How send a comment in a github pullRequest from jenkins/jenkinsfile - jenkins

I use the organization plugin to build the pullRequest of my github project.
During this build, I want to send a custom comment with some metric of the project to the github pullRequest.
How can I do it?

NeverMind, I found : (you need to install the http Request plugin)
def SHA1 = sh(returnStdout: true, script: "git rev-parse HEAD").trim()
def body="""{
"body": "Nice change",
"commit_id": "$SHA1",
"path": "/",
"position": 0
}"""
httpRequest authentication: '${yourCredential}', httpMode: 'POST', requestBody: body, url: 'https://api.github.com/repos/${yourOrga}/${yourRepo}/issues/${pullRequestNumber}/comments'

Not allowed to comment, but elaborating on previous answer:
httpRequest authentication: '${yourCredential}', httpMode: 'POST', requestBody: body, url: 'https://api.github.com/repos/${yourOrga}/${yourRepo}/issues/${pullRequestNumber}/comments'
$yourcredential is a name that should match a credential of type Username and password. In github you should create a token and use this.
in a pullrequest you will usually will get the url (Genericwebhook) to the issue where you can post a comment as part of the webhook payload.

Related

How to get pull requester e-mail in Jenkins

I'm using Bitbucket Push and Pull Request plugin to trigger pipeline via webhook when pull request is open or updated in
BitBucket repo.
Now I want to send a mail notification to pull requestor about the pipeline execution.
Additionally to that I want to send same kind of notification when the PR is merged to the the requester and merger.
post {
always {
emailext body: 'Test Message',
subject: 'Test Subject',
to: '${prRecipient}'
}
}
My question is how to get the e-mail address of the requestor and set it as value prRecipient in the example of the code above?
BitBucket is a server, not Cloud!
I
was able to achieve this whit emailext plugin and recipientProviders like that:
post {
always {
emailext to: "default#mail.com"
body: 'A Test EMail',
recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']],
subject: 'Test'
}
}

Is there a way to change the Content Type for a Postman OAuth 2 Client Credentials request?

I'm trying to use the built in tool to get an OAuth 2.0 token for my requests. This seems pretty straightforward when reading the documentation and I set it up like this:
The issue is that the request for the token is sent with a content type of application/x-www-form-urlencoded. So the response I'm getting from the server is a 415 Unsupported Media Type I do not see a way to change the request content-type to application/json.
Am I missing something or is the only way to create a custom pre-request script?
https://github.com/oauthjs/node-oauth2-server/issues/92
application/x-www-form-urlencoded , is the supported content-type for Oauth
https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
If you want to create , you can use pre-requisite script something like:
https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990
// Refresh the access token and set it into environment variable
pm.sendRequest({
url: pm.collectionVariables.get("zoho_accounts_endpoint") + "/oauth/v2/token",
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "client_id", value: pm.collectionVariables.get("zoho_client_id"), disabled: false},
{key: "client_secret", value: pm.collectionVariables.get("zoho_client_secret"), disabled: false},
{key: "refresh_token", value: pm.collectionVariables.get("zoho_refresh_token"), disabled: false},
{key: "grant_type", value: 'refresh_token', disabled: false}
]
}
}, function (err, res) {
pm.collectionVariables.set("zoho_access_token", 'Zoho-oauthtoken ' + res.json().access_token);
});
Change it to JSON or what ever you want and store the value to a variable and use that as bearer {{token}}

Creating tickets in Zendesk

I am new to Zendesk, but what I want is for my app to be able to create tickets in Zendesk. Basically, when a user does something in my web application, my backend application creates a ticket for a Support to look at the issue and resolve it.
Looking at the Zendesk API for creating tickets, it seems that it asks for agent username and password, but there is no agent, just a machine that is creating those tickets. So my question here is, should I use some different approach to this problem, or should I work around by creating a user for the machine with imaginary email address so that I can authenticate?
In this case, you should use the "request" endpoint, instead of the "ticket".
Here is an example that may help:
fetch('https://SUBDOMAIN.zendesk.com/api/v2/requests.json', {
method: 'post',headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json' },
body: JSON.stringify({"request": {"requester": {"name": "Anonymous customer"}, "subject": "Vlad test", "comment": {"body": "Here goes a ticket body"
}}})
}).then(res=>res.json()).then(res => console.log(res));

How to POST JSON data in body with Jenkins http-request plugin and Pipeline?

With v1.8.10 of the http-request plugin for Jenkins (I'm running 1.643), there is now support for POSTing a body in the request -- so this thread does not apply. I am wondering how to use this functionality in a Pipeline (v2.1) Groovy script? The Snippet Generator does not include this new field, so I have no example to build off of.
I have tried various ways to get the JSON data into the request body, but my Tomcat server always returns http 400 status code: The request sent by the client was syntactically incorrect.
Things I have tried:
def toJson = {
input ->
groovy.json.JsonOutput.toJson(input)
}
def body = [
displayName: [
text: "smoke test"],
description: [
text: "for smoke testing"],
genusTypeId: "type"
]
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: toJson(body), url: "https://${host}", validResponseCodes: '200'
def body = [
displayName: [
text: "smoke test"],
description: [
text: "for smoke testing"],
genusTypeId: "type"
]
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: body, url: "https://${host}", validResponseCodes: '200'
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: "{\"displayName\":{\"text\":"smoke test\"},\"description\":{\"text\":\"for smoke testing\"}, \"genusTypeId\":\"type\"}", url: "https://${host}", validResponseCodes: '200'
response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: "'{\"displayName\":{\"text\":"smoke test\"},\"description\":{\"text\":\"for smoke testing\"}, \"genusTypeId\":\"type\"'}", url: "https://${host}", validResponseCodes: '200'
Scanning the http-request library code, it seems like setting this flag should work. I don't know how Pipeline plugins / Jenkins plugins work, so I wonder if the Pipeline -> http-request code accounts for this new parameter? Can someone point me to how I can make POSTs with request bodies work with the Pipeline, or where I need to modify Pipline plugin code to make the connection?
I think this is a bug. I added https://issues.jenkins-ci.org/browse/JENKINS-36203
and the PR: https://github.com/jenkinsci/http-request-plugin/pull/15

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

I am trying to convey that the authentication/security scheme requires setting a header as follows:
Authorization: Bearer <token>
This is what I have based on the swagger documentation:
securityDefinitions:
APIKey:
type: apiKey
name: Authorization
in: header
security:
- APIKey: []
Maybe this can help:
swagger: '2.0'
info:
version: 1.0.0
title: Bearer auth example
description: >
An example for how to use Bearer Auth with OpenAPI / Swagger 2.0.
host: basic-auth-server.herokuapp.com
schemes:
- http
- https
securityDefinitions:
Bearer:
type: apiKey
name: Authorization
in: header
description: >-
Enter the token with the `Bearer: ` prefix, e.g. "Bearer abcde12345".
paths:
/:
get:
security:
- Bearer: []
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
You can copy&paste it to https://editor.swagger.io to check out the results.
There are also several examples in the Swagger Editor web with more complex security configurations which could help you.
Important: In this example, API consumers must include the "Bearer" prefix as part of the token value. For example, when using Swagger UI's "Authorize" dialog, you need to enter Bearer your_token instead of just your_token.
Bearer authentication in OpenAPI 3.0.0
OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:
openapi: 3.0.0
...
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT # optional, for documentation purposes only
security:
- bearerAuth: []
This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).
UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.
Adding Authorization header programmatically (Swagger UI 3.x)
If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x; UI 2.x used a different technique.
// index.html
const ui = SwaggerUIBundle({
url: "http://your.server.com/swagger.json",
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer xxxxxxx"
return req
}
})
Posting 2023 answer in JSON using openapi 3.0.0:
{
"openapi": "3.0.0",
...
"servers": [
{
"url": "/"
}
],
...
"paths": {
"/skills": {
"put": {
"security": [
{
"bearerAuth": []
}
],
...
},
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
}
}
Why "Accepted Answer" works... but it wasn't enough for me
This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.
But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:
this.authentications = {
'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};
There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:
this.rootGet = function(callback) { ... }
This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.
My alternative
Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.
Note: which is being discussed in
security: add support for Authorization header with Bearer
authentication scheme #583
Extensibility of security
definitions? #460
So, it's handle authentication like a standard header. On path object append an header paremeter:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: localhost
schemes:
- http
- https
paths:
/:
get:
parameters:
-
name: authorization
in: header
type: string
required: true
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
This will generate a client with a new parameter on method signature:
this.rootGet = function(authorization, callback) {
// ...
var headerParams = {
'authorization': authorization
};
// ...
}
To use this method in the right way, just pass the "full string"
// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);
And works.
By using requestInterceptor, it worked for me:
const ui = SwaggerUIBundle({
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization;
return req;
},
...
});
My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:
At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "{{.URL}}",
dom_id: '#swagger-ui',
validatorUrl: null,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
,
layout: "StandaloneLayout",
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization
return req
}
})
window.ui = ui
}
Solving this from laravel 7x ("openapi": "3.0.0"), edit your config\l5-swagger.php with the following codes
'securityDefinitions' => [
'securitySchemes' => [
'bearerAuth' => [
'type' => 'http',
'scheme' => 'bearer',
'bearerFormat' => 'JWT',
],
],
then you can add this as a security annotation for your endpoint:
*security={
*{
*"bearerAuth": {}},
*},

Resources