-
Notifications
You must be signed in to change notification settings - Fork 251
Feature/cldsrv 546 post object #5601
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KazToozs
wants to merge
23
commits into
epic/RING-45960-postObject-api
Choose a base branch
from
feature/CLDSRV-546-post-object
base: epic/RING-45960-postObject-api
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
efc79b2
CLDSRRV-546: update packages
6f82826
CLDSRRV-546: add POST object api handler
41b839c
CLDSRRV-546: add POST object action
9d9c4ae
CLDSRRV-546: update extraneous code for POST object
b740e13
CLDSRRV-546: unit test objectPOST action
6ff75db
CLDSRRV-546: functional test POST Object API
8d59e1c
fixup: update arsenal
b954a45
fixup: callPostObject error cleanup
3443d71
fixup: arsenal package update
0d40c42
fixup: additional fn test for querry in url
99b0c26
fixup: error messages for trace log in callPostObject handler
252205a
fixup: jsdoc ref in callPostObject handler
7c18326
fixup: error to string
88403e4
fixup: fn tests
7018ba1
fixup: keytoolong change callPostObject
d09a42d
fixup: arsenal package
2a7d4cf
fixup: url encode header response elements
3aadbde
fixup: fn test fixup
29ebf3f
fixup: fn test 405 not allowed error
2a41094
fixup: small fixups
cb7b4fe
fixup: update for content-type checking
95140e3
fixup: arsenal package update
92d9273
update response headers
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| const { auth, errors } = require('arsenal'); | ||
| const busboy = require('@fastify/busboy'); | ||
| const writeContinue = require('../../../utilities/writeContinue'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
| const os = require('os'); | ||
|
|
||
| // per doc: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTForms.html#HTTPPOSTFormDeclaration | ||
BourgoisMickael marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const MAX_FIELD_SIZE = 20 * 1024; // 20KB | ||
| // per doc: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html | ||
| const MAX_KEY_SIZE = 1024; | ||
|
|
||
| async function authenticateRequest(request, requestContexts, log) { | ||
| return new Promise(resolve => { | ||
| // TODO RING-45960 remove ignore for POST object here | ||
| auth.server.doAuth(request, log, (err, userInfo, authorizationResults, streamingV4Params) => | ||
| resolve({ userInfo, authorizationResults, streamingV4Params }), 's3', requestContexts); | ||
| }); | ||
| } | ||
|
|
||
| async function parseFormData(request, response, requestContexts, log) { | ||
| /* eslint-disable no-param-reassign */ | ||
| const formDataParser = busboy({ headers: request.headers }); | ||
| writeContinue(request, response); | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| request.formData = {}; | ||
| let totalFieldSize = 0; | ||
| let fileEventData = null; | ||
| let tempFileStream; | ||
| let tempFilePath; | ||
| let authResponse; | ||
| let fileWrittenPromiseResolve; | ||
| let formParserFinishedPromiseResolve; | ||
|
|
||
| const fileWrittenPromise = new Promise((res) => { fileWrittenPromiseResolve = res; }); | ||
| const formParserFinishedPromise = new Promise((res) => { formParserFinishedPromiseResolve = res; }); | ||
|
|
||
| formDataParser.on('field', (fieldname, val) => { | ||
| totalFieldSize += Buffer.byteLength(val, 'utf8'); | ||
| if (totalFieldSize > MAX_FIELD_SIZE) { | ||
| return reject(errors.MaxPostPreDataLengthExceeded); | ||
| } | ||
| const lowerFieldname = fieldname.toLowerCase(); | ||
| if (lowerFieldname === 'key') { | ||
| if (val.length > MAX_KEY_SIZE) { | ||
| return reject(errors.KeyTooLongError); | ||
| } else if (val.length === 0) { | ||
| return reject(errors.InvalidArgument | ||
| .customizeDescription('User key must have a length greater than 0.')); | ||
| } | ||
| } | ||
| request.formData[lowerFieldname] = val; | ||
| return undefined; | ||
| }); | ||
|
|
||
| formDataParser.on('file', async (fieldname, file, filename, encoding, mimetype) => { | ||
| if (fileEventData) { | ||
| file.resume(); // Resume the stream to drain and discard the file | ||
| if (tempFilePath) { | ||
| fs.unlink(tempFilePath, unlinkErr => { | ||
| if (unlinkErr) { | ||
| log.error('Failed to delete temp file', { error: unlinkErr }); | ||
| } | ||
| }); | ||
| } | ||
| return reject(errors.InvalidArgument | ||
| .customizeDescription('POST requires exactly one file upload per request.')); | ||
| } | ||
|
|
||
| fileEventData = { fieldname, file, filename, encoding, mimetype }; | ||
| if (!('key' in request.formData)) { | ||
| return reject(errors.InvalidArgument | ||
| .customizeDescription('Bucket POST must contain a field named ' | ||
| + "'key'. If it is specified, please check the order of the fields.")); | ||
| } | ||
| // Replace `${filename}` with the actual filename | ||
| request.formData.key = request.formData.key.replace('${filename}', filename); | ||
| try { | ||
| // Authenticate request before streaming file | ||
| // TODO RING-45960 auth to be properly implemented | ||
| authResponse = await authenticateRequest(request, requestContexts, log); | ||
|
|
||
| // Create a temporary file to stream the file data | ||
| // This is to finalize validation on form data before storing the file | ||
| tempFilePath = path.join(os.tmpdir(), filename); | ||
| tempFileStream = fs.createWriteStream(tempFilePath); | ||
|
|
||
| file.pipe(tempFileStream); | ||
|
|
||
| tempFileStream.on('finish', () => { | ||
| request.fileEventData = { ...fileEventData, file: tempFilePath }; | ||
| fileWrittenPromiseResolve(); | ||
| }); | ||
|
|
||
| tempFileStream.on('error', (err) => { | ||
| log.trace('Error streaming file to temporary location', { error: err.message }); | ||
| reject(errors.InternalError); | ||
| }); | ||
|
|
||
| // Wait for both file writing and form parsing to finish | ||
| return Promise.all([fileWrittenPromise, formParserFinishedPromise]) | ||
| .then(() => resolve(authResponse)) | ||
| .catch(reject); | ||
| } catch (err) { | ||
| return reject(err); | ||
| } | ||
| }); | ||
|
|
||
| formDataParser.on('finish', () => { | ||
| if (!fileEventData) { | ||
| return reject(errors.InvalidArgument | ||
| .customizeDescription('POST requires exactly one file upload per request.')); | ||
| } | ||
| return formParserFinishedPromiseResolve(); | ||
| }); | ||
|
|
||
| formDataParser.on('error', (err) => { | ||
| log.trace('Error processing form data:', { error: err.message }); | ||
| request.unpipe(formDataParser); | ||
| // Following observed AWS behaviour | ||
| reject(errors.MalformedPOSTRequest); | ||
| }); | ||
|
|
||
| request.pipe(formDataParser); | ||
| return undefined; | ||
| }); | ||
| } | ||
|
|
||
| function getFileStat(filePath, log) { | ||
| return new Promise((resolve, reject) => { | ||
| fs.stat(filePath, (err, stats) => { | ||
| if (err) { | ||
| log.trace('Error getting file size', { error: err.message }); | ||
| return reject(errors.InternalError); | ||
| } | ||
| return resolve(stats); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| async function processPostForm(request, response, requestContexts, log, callback) { | ||
| if (!request.headers || !request.headers['content-type'].includes('multipart/form-data')) { | ||
| const contentTypeError = errors.PreconditionFailed | ||
| .customizeDescription('Bucket POST must be of the enclosure-type multipart/form-data'); | ||
| return process.nextTick(callback, contentTypeError); | ||
| } | ||
| try { | ||
| const { userInfo, authorizationResults, streamingV4Params } = | ||
| await parseFormData(request, response, requestContexts, log); | ||
|
|
||
| const fileStat = await getFileStat(request.fileEventData.file, log); | ||
| request.parsedContentLength = fileStat.size; | ||
| request.fileEventData.file = fs.createReadStream(request.fileEventData.file); | ||
| if (request.formData['content-type']) { | ||
| request.headers['content-type'] = request.formData['content-type']; | ||
| } else { | ||
| request.headers['content-type'] = 'binary/octet-stream'; | ||
| } | ||
|
|
||
| const authNames = { accountName: userInfo.getAccountDisplayName() }; | ||
| if (userInfo.isRequesterAnIAMUser()) { | ||
| authNames.userName = userInfo.getIAMdisplayName(); | ||
| } | ||
| log.addDefaultFields(authNames); | ||
|
|
||
| return callback(null, userInfo, authorizationResults, streamingV4Params); | ||
| } catch (err) { | ||
| return callback(err); | ||
| } | ||
| } | ||
|
|
||
| module.exports = { | ||
| authenticateRequest, | ||
| parseFormData, | ||
| processPostForm, | ||
| getFileStat, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.