jenkins http request, variables on requestbody - jenkins

I am using httprequest plugin on jenkis to work with API. I am trying to insert a variable on the requesbody but the variable is not resolved. It is considering the variable as a string.
timestamps {
node () {
def console_api = 'https://example.com/zyx'
def console_address = 'example.com'
stage ('download ') {
httpRequest authentication: 'sa', httpMode: 'POST', ignoreSslErrors: true, outputFile: 'output.yaml', requestBody: ''' {
"consoleAddr": "${console_address}",
}''', responseHandle: 'NONE', url: "${console_api}/api/v1/daemonset.yaml", wrapAsMultipart: false
I need consoleAddr to be resolved to example.com on the http request body.

Related

"Only absolute URLs are supported" When fetch webhooks Nextjs

Im trying to fetch an webhooks url using Environment Variables.
here is my code
const url = process.env.WEBHOOK_URL;
const response = await fetch(
`${url}` ,
{
body: JSON.stringify({
name,
email,
message,
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}
);
But the error show up "Only absolute URLs are supported"
please help! Thank you

Groovy representation of Notification plugin in Jenkinsfile

How to represent the Notifications Endpoint section of the Jenkins job configuration in a Jenkinsfile (in the form of a groovy script) ? I have installed the Notification plugin but I am not sure how I would use that.
In my jenkins pipeline I did the following:
pipeline {
// ..
stages {
stage('Notify') {
script {
def build = currentBuild // global variable in pipeline -> https://opensource.triology.de/jenkins/pipeline-syntax/globals#currentBuild
def targetUrl = "http://some-url?{some-query-params}"
def buildUrl = build.absoluteUrl
def buildNumber = build.number
def buildStatus = build.currentResult
httpRequest url: targetUrl, contentType: 'APPLICATION_JSON', httpMode: 'POST', responseHandle: 'NONE', timeout: 30, requestBody: """
{
"name": "${args.serviceName}",
"build": {
"full_url": "${buildUrl}",
"number": "${buildNumber}",
"phase": "FINISHED",
"status": "${buildStatus}"
}
}
"""
}
}

Nock how to mock put request

My real codes like:
fetch(hostname+ '/api/save', {
method: "put",
credentials: "include",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({a: 'b'})
})
nock like:
nock(hostname)
.put('/api/save')
.reply(200);
the hostname includes port, but it's random port in the test. I've checked the log, the real url and test url are same. But I don't know why it doesn't match???

Unable to send xml response with serverless framework

I'm working with twilio in which when call comes to my twilio number it invokes webhook, I'm using lambda function as webhook,
twilio expects xml(formerly called twiml) response from webhook and i'm unable to send xml response from lambda function
I'm using serverless framework
here is my code
function:
module.exports.voice = (event, context, callback) => {
console.log("event", JSON.stringify(event))
var twiml = new VoiceResponse();
twiml.say({ voice: 'alice' }, 'Hello, What type of podcast would you like to listen? ');
twiml.say({ voice: 'alice' }, 'Please record your response after the beep. Press any key to finish.');
twiml.record({
transcribe: true,
transcribeCallback: '/voice/transcribe',
maxLength: 10
});
console.log("xml: ", twiml.toString())
context.succeed({
body: twiml.toString()
});
};
yml:
service: aws-nodejs
provider:
name: aws
runtime: nodejs6.10
timeout: 10
iamRoleStatements:
- Effect: "Allow"
Action: "*"
Resource: "*"
functions:
voice:
handler: handler.voice
events:
- http:
path: voice
method: post
integration: lambda
response:
headers:
Content-Type: "'application/xml'"
template: $input.path("$")
statusCodes:
200:
pattern: '.*' # JSON response
template:
application/xml: $input.path("$.body") # XML return object
headers:
Content-Type: "'application/xml'"
Response:
please let me know if I'm making some mistake in code
also created an issue on github
Thanks,
Inzamam Malik
You don't need to mess with serverless.yml so much. Here is the simple way:
In serverless.yml...
functions:
voice:
handler: handler.voice
events:
- http:
path: voice
method: post
(response, headers, Content-Type, template, and statusCodes are not necessary)
Then you can just set the statusCode and Content-Type in your function.
So delete this part...
context.succeed({
body: twiml.toString()
});
... and replace it with:
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/xml',
},
body: twiml.toString(),
};
callback(null, response);
Lambda proxy integration (which is the default) assembles it into a proper response.
Personally I find this way simpler and more readable.
you need your lambda to be a "proxy" type, so you set the body property.
but just try to do
context.succeed(twiml.toString());
that will send the "string" as result directly
or use the callback param:
function(event, context, callback) {
callback(null, twiml.toString())
}
As mentioned by #UXDart, you'll not be able to do this using the standard integration. You should setup a proxy integration with Lambda like here -http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-nodejs
This will work better with what you are trying to do, return xml through api gateway.
Change your serverless.yml to this:
service: aws-nodejs
provider:
name: aws
runtime: nodejs6.10
timeout: 10
iamRoleStatements:
- Effect: "Allow"
Action: "*"
Resource: "*"
functions:
voice:
handler: handler.voice
events:
- http:
path: voice
method: post
integration: lambda
response:
headers:
Content-Type: "'application/xml'"
template: $input.path("$")
statusCodes:
200:
pattern: '' # Default response method
template:
# Your script returns json, so match it here
application/json: $input.path("$.body")
headers:
Content-Type: "'application/xml'"
Got mine to work with this.
events:
- http:
path: call/receive
method: post
integration: lambda
response:
headers:
Content-Type: "'application/xml'"
template: $input.path("$")
statusCodes:
200:
pattern: ''
template:
application/json: $input.path("$")
headers:
Content-Type: "'application/xml'"
and
callback(null, twiml.toString());
It works for me.
webhook:
handler: webhook.webhook
events:
- http:
path: webhook
method: get
cors: true
integration: lambda
response:
headers:
Content-Type: "'application/xml'"
template: $input.path("$")
statusCodes:
200:
pattern: '' # Default response method
template:
# Your script returns json, so match it here
application/json: $input.path("$.body")
headers:
Content-Type: "'application/xml'"
Checkout the twilio serverless example here: https://github.com/serverless/examples/tree/master/aws-node-twilio-send-text-message

Rails Can't verify CSRF token authenticity ajax with X-CSRF-TOKEN header

I try to register a service worker endpoint in my database but when I send my post data with fetch the app raise an error.
I want to keep the csrf verification. Do you see something wrong ?
var ready;
ready = function(){
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function(sub) {
console.log('endpoint:', sub.endpoint);
console.log(sub);
var token = $('meta[name=csrf-token]').attr('content')
console.log(token);
return fetch('/register_endpoint', {
method: 'post',
headers: {
'Content-type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({
endpoint: sub.endpoint,
authenticity_token: token
})
});
});
}).catch(function(err) {
console.log('Erreur -> ', err);
});
}
};
$(document).ready(ready);
$(document).on('page:load',ready);
thanks
The problem is that the session cookie is not being sent if credentials is not specified as an option within fetch.
credentials has 3 possible values:
omit -> Doesn't send cookies
same-origin -> Only send cookies if the URL is on the same origin as the calling script
include -> Always send cookies, even for cross-origin calls
So this should probably work:
return fetch('/register_endpoint', {
method: 'post',
headers: {
'Content-type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({endpoint: sub.endpoint}),
credentials: 'same-origin'
})
Here more info about the native fetch api.
$ajax or fetch Both works in your case.
let token = function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))};
$.ajax({ url: URL,
type: 'POST',
beforeSend: token,
data: 'someData=' + someData,
success: function(response) {
$('#someDiv').html(response);
}
});
Or:
return fetch( URL, {
method: 'post',
headers: {
'Content-type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({endpoint: sub.endpoint}),
credentials: 'same-origin'
})
This is also not working for me so I have override this verified_request? method CsrfToken
class ApplicationController < ActionController::Base
protect_from_forgery
skip_before_action :verify_authenticity_token, if: :verified_request?
protected
def verified_request?
return true if request.get?
if respond_to?(:valid_authenticity_token?, true)
super || valid_authenticity_token?(session, URI.unescape(request.headers['X-CSRF-TOKEN'] || "") )
else
super || form_authenticity_token == URI.unescape(request.headers['X-CSRF-TOKEN'] || "")
end
end
end

Resources