How to verify file type for multipart/form data upload in vertx? - vert.x

I have a multipart/form with file upload in my Vert.x web application.
The issue I am running into is that I can only seem to validate the type of the uploaded file after having the request go through Vertx's BodyHandler.
Now I can validate the type after it went through, but the BodyHandler has already uploaded the file at this point in time. On a similair issue it was stated that you should check the content-type with your own handler before the BodyHandler, but this always returns an empty formAttributes.
I've tried creating my own handler:
public void handle(RoutingContext context) {
context.request().setExpectMultipart(true);
MultiMap attributes = context.request().formAttributes();
System.out.println(attributes);
context.next();
}
But attributes is always empty, so I can't verify the content-type of the file uploaded.
After it passes through the BodyHandler into my other handler it works fine:
MultiMap attributes = context.request().formAttributes();
Set<FileUpload> uploads = context.fileUploads();
for (FileUpload file : uploads
) {
System.out.println(file.contentType());
// This returns image/jpeg
}
context.response().end();
But as I stated above, the file is already uploaded when it has passed through the BodyHandler.
Here is the code for the handlers:
router.post("/api/someendpoint").handler(new FileTypeHandler());
router.post("/api/someendpoint").handler(BodyHandler.create()
.setUploadsDirectory("static/images")
.setBodyLimit(MB * 1));
router.post("/api/someendpoint").handler(new EndPointHandler());
How can I verify the type of a file being uploaded before it passes through the BodyHandler, so that I can reject any other file upload except an image?

Related

mocking a request with a payload using wiremock

I'm currently trying to mock external server using Wiremock.
One of my external server endpoint takes a payload.
This endpoint is defined as follow :
def sendRequestToMockServer(payload: String) = {
for {
request_entity <- Marshal(payload).to[RequestEntity]
response <- Http().singleRequest(
HttpRequest(
method = HttpMethods.GET,
uri = "http://localhost:9090/login",
entity = request_entity
)
)
} yield {
response
}
}
To mock this endpoint using Wiremock, I have written the following code :
stubFor(
get(urlEqualTo("/login"))
.willReturn(
aResponse()
.withHeader("Content-Type","application/json")
.withBodyFile("wireMockResponse.json")
.withStatus(200)
)
.withRequestBody(matchingJsonPath("requestBody.json"))
)
where I Have defined the request body in the requestBody.json file.
But when I run tests , I keep getting an error indicating that the requested Url is not found.
I'm thinking that the error is related to this line withRequestBody(matchingJsonPath("requestBody.json")), because when I comment it the error disappear.
Any suggestions on how to work around this?
matchingJsonPath does not populate a file at a provided filepath, but instead evaluates the JsonPath provided. See documentation.
I'm not entirely sure there is a way to provide the request body as a .json file. If you copy the contents of the file into the withRequest(equalToJson(_yourJsonHere_)), does it work? If it does, you could get the file contents as a JSON string above the definition and provide it to the function (or I guess, make a function to return a JSON string from a .json file).
Additionally, you could make a custom request matcher that does the parsing for you. I think I'd recommend this only if the above does not work.

Intercept and edit multipart form-data POST request body in Browser

I've got a site that accepts file uploads which are sent as multipart/form-data within a POST request. To verify that the upload, which shows the filename afterwards, is secured against XSS I want to upload a file which contains HTML Tags in the filename.
This is actually harder than I expected. I can't create a file containing < on my filesystem (Windows). Also, I don't know a way to change the filename of the file input element inside the DOM before the upload (which is what I would do with normal/hidden inputs). So I thought about editing the POST body before it's uploaded, but I don't know how. Popular extensions (I recall Tamper Data, Tamper Dev) only let me change headers. I guess this is due to the plugin system of Chrome, which is the Browser I use.
So, what's the simplest way of manipulating the POST requests body? I could craft the entire request using cUrl, but I also need state, lots of additional parameters and session data etc. which gets quite complex... A simple way within the Browser would ne nice.
So, while this is not a perfect solution, it is at least a way to recreate and manipulate the form submit using FormData and fetch. It is not as generic as I'd like it to be, but it works in that case. Just use this code in the devtools to submit the form with the altered filename:
let formElement = document.querySelector('#idForm'); // get the form element
let oldForm = new FormData(formElement);
let newForm = new FormData;
// copy the FormData entry by entry
for (var pair of oldForm.entries()) {
console.log(pair[0]+': '+pair[1]);
if(typeof(pair[1]) == 'object' && pair[1].name) {
// alter the filename if it's a file
newForm.append(pair[0],pair[1],'yourNewFilename.txt');
} else {
newForm.append(pair[0],pair[1]);
}
}
// Log the new FormData
for (var pair of newForm.entries()) {
console.log(pair[0]+': ');
console.log(pair[1]);
}
// Submit it
fetch(formElement.action, {
method: formElement.method,
body: newForm
});
I'd still appreciate other approaches.

Filepicker.io Javascript API Remove

Trying to use the remove function after the pick function and file is not being removed. (from here https://www.filepicker.com/documentation/file_ingestion/javascript_api/remove?v=v2)
selectFileMedium: function () {
filepicker.pick({
cropRatio: 24/13,
mimetype: 'image/*',
imageDim: [1440, 780]
}, function (Blob) {
InnerThis.uploadMediumImage(Blob.url, Blob.filename);
filepicker.remove(Blob);
});
}
Am I doing this correct?
Blob object return url property which is unificated url of uploaded file eg:
https://www.filepicker.io/api/file/AQgF2U68SNmJDpDXlOdg
However since v2 dialog version there is crop UI avaliable. If user crop file as a response it return the uploaded file url with appended Rest convert parameters:
https://www.filepicker.io/api/file/AQgF2U68SNmJDpDXlOdg/convert?crop=100,200,200,300
filepicker.remove dose not deal with it. Some temporary workaround would be to strip url from '/convert' part just before remove it. However it should be solved on library side.

Fiddler Script - SaveResponseBody()

I want to save all png images that are loaded along with some webpage into a separate folder.
I am using below code with in Fiddler Script [CustomRules.js].
static function OnBeforeResponse(oSession: Session)
{
if(oSession.url.EndsWith(".png"))
{
oSession.SaveResponseBody();
}
//Actual content of OnBeforeResponse function.
}
Problem here is, I was unable to find any image got saved within Program files/Documents.
Where do “SaveResponseBody()” will save the HTTP Response Body?
Can we give our own custom folder?
My Fiddler version is (v4.4.5.6)
The default SaveResponseBody() method saves the files to your \Documents\Fiddler2\Captures\ folder. If you want to use a different name, use the overload that accepts a filename. You should check the Response's status code is 200 to ensure that you're not trying to save off HTTP/304 responses which won't contain a body. Also, rather than looking at the URL, you probably want to check the response's type.
So you end up with something like this:
if ((oSession.responseCode == 200) &&
oSession.oResponse.headers.ExistsAndContains("Content-Type", "image/png"))
{
SaveResponseBody("C:\\temp\\" + oSession.SuggestedFilename);
}
Note: The manual way of doing this would be to go to the QuickExec box below the Web Sessions list, type select png and hit Enter, then click File > Export > Selected Sessions > Raw Files.

How to see the request variables or files sent from the phonegap to MVC asp.net Controller

I have done coding
public JSONResult media(HttpPostedFileBase file)
{
=====done with some code===
}
Here i m getting the file as null always.
Note:
file is the file submitted from the Phonegap's JSON method.
My question is :
Is there any mechanism for the decoding the encoded multipart file before reading?
Got it :)
Use the request params for getting the file input and changed the method as
public JSONResult media()
added request.files and stored in HTTPcollectionfile base and got the same file information posted in the PhonegapAPI