How to prevent cypress from printing secrets in the request body? - security

So we're doing the following in our cypress tests:
login(user: SimpleUser) {
cy.request({
method: "POST",
url: `${this.apiUrl}/login`,
body: {
username: user.email,
password: "mypassword",
}
})
.should(assertStatusOk)
.then((resp) => {
...
which is pretty similar to what they suggest on their page.
However, when the login fails, it then logs to the console:
The request we sent was:
Method: POST
URL: myurl
Headers: {
"Connection": "keep-alive",
"user-agent": "myuseragent",
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"content-type": "application/json",
"content-length": mycontentlength
}
Body: {"username":"myusername","password":"mypassword"}
where the real password is logged. Can this be prevented? I've read in other threads to add the {log: false} option when doing a cy.type, but for cy.request this doesn't seem to have an impact. Any ideas how I can prevent cypress from printing the full body?

In the case of status code errors, you can add failOnStatusCode: false to the request options.
cy.request({
method: "POST",
url: `http://example.com/login`,
failOnStatusCode: false,
log: false,
body: {
username: user.email,
password: "mypassword",
}
})
.should('have.property', 'status', '200')
Then all you see is expected { Object (body, headers, ...) } to have property status of '200', but got 404.
If you have other error types than bad status code, substituute a plain fetch() for cy.request().

Related

Request Comment on Behalf not working with zendesk API

I'm making a Node application that uses Zendesk API. Users logged in and can create tickets through my application.
To create tickets, I use this configuration
var config = {
method: 'post',
url: 'url/api/v2/requests.json',
headers: {
'Authorization': 'Bearer adminToken',
'X-On-Behalf-Of': 'emailOfUser',
'Content-Type': 'application/json',
},
data: ticket
};
axios(config)
.then(function (response) {
//My code
})
With X-On-Behalf-Of I can create tickets for the user logged in with my admin token.
However, it doesn't work for updating the ticket with comments. I got a Forbidden error. Here is my code :
var config = {
method: 'put',
url: 'url/api/v2/requests/' + idTicket,
headers: {
'Authorization': 'Bearer adminToken',
'X-On-Behalf-Of': 'emailOfUser',
'Content-Type': 'application/json',
},
data: { "request": { "comment": { "body": message, "public": true, "author_id": userId } } }
};
And when I remove the X-On-Behalf-Of, the comment is publish, but with my name, the admin name, and not the user name.
Do you know a solution for that ?
Thanks
It is likely that your token is missing impersonate scope.
Example for authorization code grant:
https://{subdomain}.zendesk.com/oauth/authorizations/new?client_id=foo&redirect_uri=bar&scope=impersonate+write&response_type=code

Upload video to Cloudflare API

I am trying to upload some videos to Cloudflare Stream API. Here is official documentation and its example request using curl: https://developers.cloudflare.com/stream/uploading-videos/upload-video-file/
I am doing the request in Node.js
const uploadVideo = (video: Express.Multer.File): => {
const formData = new URLSearchParams();
formData.append('file', video);
let cloudflareResponse;
try {
cloudflareResponse = await axios.post(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/stream/copy`,
formData,
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'multipart/form-data',
//'Tus-Resumable': '1.0.0',
//'Upload-Length': '600',
//'Upload-Metadata': 'maxDurationSeconds 600'
}
}
);
} catch (e) {
console.log('Error while trying to upload video to Cloudflare API ', e);
}
}
The commented Headers I took from this article, in which the request is done in Django and I tried to replicate it https://medium.com/#berman82312/how-to-setup-cloudflare-stream-direct-creator-uploads-correctly-802c37cbfd0e
The error I am getting is a 400 and here is some of the response
config: {
url: 'https://api.cloudflare.com/client/v4/accounts/...../stream/copy',
method: 'post',
data: 'file=%5Bobject+Object%5D',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer .....',
'Tus-Resumable': '1.0.0',
'Upload-Length': '600',
'Upload-Metadata': 'maxDurationSeconds 600',
'User-Agent': 'axios/0.21.1',
'Content-Length': 24
},
data: { result: null, success: false, errors: [Array], messages: null }
I am sure something is wrong in the request and hope someone could help me spot the mistake or suggest some modifications that might help. I have been stuck with this problem for hours and on Postman I am also getting a 400 response when trying to send with form-data.

How to use axios.post method for a cURL command? (Or fix status code: 415)

We need to run the axios.post equivalent for following cURL command in nodeJS:
curl -H "Authorization: Basic ZjM4Zj...Y0MzE=" -d grant_type=refresh_token -d refresh_token=NgAagA...NUm_SHo https://accounts.spotify.com/api/token
My Approach:
axios.post("https://accounts.spotify.com/api/token", {
grant_type: 'refresh_token',
refresh_token: 'NgAagA...NUm_SHo',
header: {
Authorization: 'Basic ZjM4Zj...Y0MzE=',
}
}).then((resAxios) => {
console.log(resAxios.data)
spotifyResult = resAxios.data;
}).catch((error) => {
console.error(error)
})
Above code returns the following error in reponse:
statusCode: 415,
statusMessage: 'Unsupported Media Type'
Format:
refresh_token should be application/x-www-form-urlencoded
Authorization: Basic <base64 encoded client_id:client_secret>
Refer the 'Authorization Code Flow' for the cURL command, here:
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Feel free to provide with any other variant, i.e., instead of using axios. I preferred it, since it parses the fetched data as well. Please provide with the code to parse it with, if so. I'm a 'beginner' beginner.
Thanks to all the folks: Manuel Spigolon, zx01, Mark Stroebel, Ɓukasz Szewczak, ponury-kostek, Jakub Luczak, Gerardo Gonzalez :)
I tried this answer on this link, as provided by #zx01 in the comments to the question.
Final code, tailored to the needs:
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "refresh_token",
//grant_type: "client_credentials", //This works as well.
refresh_token: 'AQAw95rH0...CnWBE'
},
headers: {
Authorization:'Basic MWQ4Z...dhYmU=',
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
}).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
However, the following syntax doesn't seems to work.
It again returns with status code 415: Unsupported Media Type.
axios.post("https://accounts.spotify.com/api/token", null, {
params: {
grant_type: "refresh_token",
//grant_type: "client_credentials", //This doesn't work either.
refresh_token: 'AQAw95rH0...CnWBE'
},
headers: {
Authorization:'Basic MWQ4Z...dhYmU=',
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
}).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
It'd be dope if somebody could fix the above code, and reason as to why we're getting that error.
Also notice there is a quomma ',', next to the closing curly braces that packs the 'headers' property.

How do I reach request body in Strapi middleware?

I have managed to make middleware work in Strapi. But, I can't see the body in the request.
Inside /middlewares/getEmail/index.js, I Have
module.exports = (strapi) => {
return {
initialize: function (cb) {
strapi.app.use(async (ctx, next) => {
if (ctx.method === "POST" && ctx.url === "/email-leads") {
console.log(ctx);
}
await next();
});
},
};
};
and ctx request logs:
request: {
method: 'POST',
url: '/email-leads',
header: {
'content-type': 'application/json',
accept: 'application/json',
'user-agent': 'PostmanRuntime/7.26.8',
'postman-token': 'xxx',
host: 'localhost:1337',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive',
'content-length': '33'
}
},
This is the only middleware I have written on this application. In the /config/middleware.js, I have
module.exports = {
load: {
before: ["getEmail", "responseTime", "logger", "cors", "responses", "gzip"],
order: ["parser"],
after: ["router"],
},
settings: {
getEmail: {
enabled: true,
},
},
};
I read about this koa-body/unparsed.js to read the body but there's literally no body in the ctx.request. Thanks for help.
if you console.log(ctx.request.body); before await next(); line it will prints undefined because body is not loaded yet. so you have 2 option for fetching body.
Use console.log(ctx.request.body); after await next(); line
Load body from raw node request like below example
Click Here
So, I have reached a solution. Posting here in case anyone else needs it.
In config/middleware.js, I have changed the load, taking the custom middleware to after array.
load: {
before: ["responseTime", "logger", "cors", "responses", "gzip"],
after: ["parser", "router", "getEmail"],
},
I still can't see the ctx.request.body if I log ctx or ctx.request. But, if I use ctx.request.body directly, I can reach it in case the load is written as above (or custom middleware after parser).

In what format should a fetch POST request be created to access the Imagga API?

I am building a mobile application using React-Native that recommends clothing to users. I am using Imagga's API to get the colors of the clothing while excluding the background. I have tried to make a POST request using fetch from analyzing the node.js code given in the documentation:
image_file_b64 = "" + image_file_b64
//Extracting the colors from the object
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
let responseJson = await response.json()
console.log(responseJson)
However, the only output that I have received is (what is logged on the last line):
Object {
"status": Object {
"text": "Please provide content for processing.",
"type": "error",
},
}
I've worked with someone from Imagga to solve this issue, but he wasn't familiar with react native. he suggested changing the content-type to "application/x-www-form-urlencoded" or "application/x-www-form-urlencoded;charset=UTF-8", but neither have worked.
I am fairly confident that the problem is from the way that I set up my fetch. If anybody is familiar with the Imagga API, can you please identify what in the code is wrong or the mismatch in formatting between what Imagga expects and what I am giving it that results in it not thinking that I have given it input. Thanks!
the fetch body is not correct, the Content-Type that you use is JSON, why you send the string. modify it as the following, and try it.
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: {
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
I read the official API, it gives the node.js example. you can according to it and modify. If the above code is not successful, you can change the content-type to formdata
let params = {
image_base64: image_file_b64,
extract_overall_colors: 0,
};
let formData = new FromData()
formdata.append('RequestData',JSON.stringify(params))
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData)
})
this is the official api, and you can use postman software to test the request

Resources