How to run a Jenkins job from classic ASP? - jenkins

I have searched all over but can't find VBscript examples and all my attempts have failed. I need to run a Jenkins job from a classic ASP web page (VBScript). I can submit the job with the code below, but it returns a 403 crumb error. What I need to do is provide the user/password (which I have) for this job but I don't know how to setup the authentication for Jenkins in VBScript. I know the crumb error is due to CSRF (I read that much and can't turn that off) and hope that authentication will resolve that. Any help is much appreciated. Thanks in advance.
Dim strJenkinsURL, HttpReq
strJenkinsURL = "http://<jenkinsmaster>/job/<myjob>/buildWithParameters?token=test&Description="& strDesc &"&TestEnv="& testEnv
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.Open "POST", strJenkinsURL, False
HttpReq.Send
Response.Write "<br>Status: "& HttpReq.Status & vbNewline
Response.Write "<br>Response: "& HttpReq.responseText & vbNewline
EDIT:
Based on comments, I attempted to add the Jenkins login information but I am still getting the 403 crumb error from Jenkins. I've tried searching for solution to getting the crumb, but haven't found any VBScript examples. Here is the code and response I am trying now but I have no idea if the setRequestHeaders are correct for Jenkins and the Jenkins documentation hasn't been any help:
Dim strJenkinsURL
strJenkinsURL = "http://<jenkins master>/job/testjob/buildWithParameters?token=test&Description="& strDesc &"&TestEnv="& testEnv
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.Open "POST", strJenkinsURL, False
HttpReq.setRequestHeader "UserName", "jenkinsuser"
HttpReq.setRequestHeader "Password", "userpassword"
HttpReq.setRequestHeader "Jenkins-Crumb", "<crumbvalue>"
HttpReq.Send
Response.Write "<br>Status: "& HttpReq.Status & vbNewline
Response.Write "<br>Response: "& HttpReq.responseText & vbNewline
Status: 403
Response: HTTP ERROR 403
Problem accessing /job/testjob/buildWithParameters. Reason: No valid crumb was included in the request

For a HTTP POST request, the URL specifies the resource, i.e. strJenkinsURL = "http://<jenkinsmaster>/job/<myjob>/buildWithParameters
The parameters are added as part of the .Send command:
Dim sParams
sParams = "token=test&Description=" & strDesc & "&TestEnv=" & testEnv
HttpReq.Send(sParams)
As #Lankymart pointed out, you also need to set the appropriate headers, e.g.
HttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
HttpReq.setRequestHeader("Content-Length", CStr(Len(sParams)))

After piecing together many suggestions with some trial and error, I was finally able to get the Jenkins job to run remotely with the VBScript code below (with variables set to proper values such as strCrumb). The returned Status will be 201 for success. The Base64 functions were taken from Base64 Encode String in VBScript
Dim strJenkinsURL, strParam1, strParam2, strCrumb, strUsername, strPassword
strJenkinsURL = "https://<jenkinsURL>/job/testjob/buildWithParameters?token=test&param1="& strParam1 &"&param2="& strParam2
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.Open "POST", strJenkinsURL, False
HttpReq.setOption 2, 13056
HttpReq.setRequestHeader "Jenkins-Crumb", strCrumb
HttpReq.setRequestHeader "Authorization", "Basic "& Base64Encode(strUsername &":"& strPassword)
HttpReq.Send
Response.Write "<br>Status: "& HttpReq.Status & vbNewline
Response.Write "<br>Response: "& HttpReq.responseText & vbNewline
Function Base64Encode(sText)
Dim oXML, oNode
Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
Set oNode = oXML.CreateElement("base64")
oNode.dataType = "bin.base64"
oNode.nodeTypedValue = Stream_StringToBinary(sText)
Base64Encode = oNode.text
Set oNode = Nothing
Set oXML = Nothing
End Function
Private Function Stream_StringToBinary(Text)
Const adTypeText = 2
Const adTypeBinary = 1
Dim BinaryStream 'As New Stream
Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Type = adTypeText
BinaryStream.CharSet = "us-ascii"
BinaryStream.Open
BinaryStream.WriteText Text
BinaryStream.Position = 0
BinaryStream.Type = adTypeBinary
BinaryStream.Position = 0
Stream_StringToBinary = BinaryStream.Read
Set BinaryStream = Nothing
End Function

Related

How to send array (a text with commas) as HTTP-param using Rest Assured (Java)

I use Rest Assured framework (Java).
I need to send integer array as http-param in get request: http://example.com:8080/myservice?data_ids=11,22,33
Integer[] ids = new Integer[] {11, 22, 33};
...
RequestSpecificationImpl request = (RequestSpecificationImpl)RestAssured.given();
request.baseUri("http://example.com");
request.port(8080);
request.basePath("/myservice");
...
String ids_as_string = Arrays.toString(ids).replaceAll("\\s|[\\[]|[]]", "");
request.params("data_ids", ids_as_string);
System.out.println("Params: " + request.getRequestParams().toString());
System.out.println("URI" + request.getURI());
What I see in the console:
Params: {data_ids=11,22,33}
URI: http://example.com:8080/myservice?data_ids=11%2C22%2C33
Why do my commas transform into '%2C'?
What needs to be done to ensure that commas are passed as they should?
Disable URL encoding, simple as that
given().urlEncodingEnabled(false);
Official documentation
Verified locally,

How to neo4j server using popoto js

I am trying to run popoto js example but not working.
code:
popoto.rest.CYPHER_URL = "http://localhost:7474/db/data/transaction/commit";
popoto.rest.AUTHORIZATION = "Basic " + btoa("neo4j:password");
But the cypher url not working.
You need to change the password portion of popoto.rest.AUTHORIZATION = "Basic " + btoa("neo4j:password"); to the password of the neo4j server. This assumes that the default username is still neo4j.

Google oauth1 migration to oauth2: Invalid authorization header

I am stuck with the oauth1 migration to oauth2. I don't want to ask my users to grant contact access again, so I prefer to do migration myself but I am getting hard time figuring out why it doesn't work.
I'm getting this error from Google server:
DEBUG - << " "error" : "invalid_request",[\n]"
DEBUG - << " "error_description" : "Invalid authorization header."[\n]"
here is my code, I did almost the same thing when consuming google api, but for migration it is not working.
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getConsumerKey());
oauthParameters.setOAuthConsumerSecret(getConsumerSecret());
oauthParameters.setOAuthToken(token);
ClassPathResource cpr = new ClassPathResource("mykey.pk8");
File file = cpr.getFile();
PrivateKey privKey = getPrivateKey(file);
OAuthRsaSha1Signer signer = new OAuthRsaSha1Signer(privKey);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
String requestUrl = "https://www.googleapis.com/oauth2/v3/token";
String header = oauthHelper.getAuthorizationHeader(requestUrl, "POST", oauthParameters);
String payload = "grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&client_id="+com.app.framework.utils.OAuthHelper.OAUTH2_CLIENT_ID+"&client_secret="+com.app.framework.utils.OAuthHelper.OAUTH2_CLIENT_SECRET;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.addHeader("Authorization", header);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new ByteArrayEntity(payload.getBytes()));
String response = httpClient.execute(httpPost, new BasicResponseHandler());
After some emails exchange with #Miguel, he successfully points me to the solution.
The issue:
The OAuthHelper that GoogleOAuthHelper extends uses TwoLeggedOAuthHelper to build the base_string. The TwoLeggedOAuthHelper was not injecting 3 required parameters: client_id, client_secret and the grant_type in the base_string.
The solution:
I had to create my own classes: copy/paste code from OAuthHelper to MyOAuthHelper and from TwoLeggedOAuthHelper to MyTwoLeggedOAuthHelper. You need some declarations from GoogleOAuthHelper to resolve compilation errors.
MyOAuthHelper will call MyTwoLeggedOAuthHelper instead of TwoLeggedOAuthHelper.
Now in MyTwoLeggedOAuthHelper, around line 79, locate the
String baseString = OAuthUtil.getSignatureBaseString(baseUrl,
httpMethod,…
and add the following:
String clientId = "client_id%3DXXX123456789XXX.apps.googleusercontent.com%26";
String clientSecret = "client_secret%3DXXXX_XXXX_XX_XX%26";
String grantType = "grant_type%3Durn%253Aietf%253Aparams%253Aoauth%253Agrant-type%253Amigration%253Aoauth1%26";
baseString = StringUtils.replace(baseString, "token&", "token&" + clientId + clientSecret + grantType);
Some notes:
client_id and client_secret must be the one your backend used to get the OAUTH1 access token. Be careful with that especially if you have multiple "Client ID for web application" defined in your Google console.
Notice the crazy grant_type encoded twice.
The Google classes used are located in maven: com/google/gdata/core/1.47.1/core-1.47.1.jar
Kudos to #Miguel
Your request is failing signature verification. Please check out the responses to this related question for detailed instructions on how to construct the base string for your request and sign it.
Hope that helps!

Using REST APIs

I am new to gerrit. I am using gerrit V. 2.6 . I want to use gerrit REST APIs in my python script. But not able to figure out how to use it. I tried below code but getting errors.
curl --digest --user user:password http://server/a/changes/path/to/project~branch~change_id/rebase
getting error :
401 Authorization Required
Authorization Required
This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.
Am I missing something.??
Are you using the correct username:password combination? This isn't your network password - it is the HTTP password that gerrit generates. You can find it by going to Settings->HTTP Password. If the password box is blank, click the button to have Gerrit generate a new password.
You may try using pygerrit. https://pypi.python.org/pypi/pygerrit/0.2.1
I think it has some APIs to easily access gerrit.
As #Ramraj mentioned, you can try using pygerrit or pygerrit2.
And I provide some examples that how I use gerrit REST APIs in my python script.
Here is the code.
auth = HTTPBasicAuth(username, password)
rest = GerritRestAPI(url='http://review.xxxxxx.com:8080', auth=auth)
Query changes by change number.
info = rest.get("/changes/?q=change:{}".format(change_number))
change_id = info[0]['change_id']
subject = info[0]['subject']
Query changes by commit id.
info = rest.get("/changes/?q=commit:{}".format(commit_id))
change_id = info[0]['change_id']
subject = info[0]['subject']
Revert a change.
headers = {'content-type': 'application/json'}
query = "/changes/" + str(change_number) + "/revert"
my_data = {"message": "{}".format("Revert "+str(subject))}
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
Review a change
headers = {'content-disposition': 'attachment', 'content-type': 'application/json'}
query = "/changes/" + str(change_number) + "/revisions/current/review"
my_data = { "labels": {"Code-Review": "+2", "Verified": "+1"} }
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)

Sending Post Data through a HTTP Request POST

I am trying to post data from a Textarea to a classic ASP script that updates the MS SQL on the local machine then posts to a PHP script on another server. However doing the below does not work, as it will cut off the data for the textarea. It has special characters in it for HTML and other data.
So my question is, how do I pass this data through a POST using ASP Classic?
I have been searching all day, so hopefully someone can enlighten me, thanks!
strUrl = "http://www.example.com/index.php"
requestData = request("request")
requestData2 = request("request2")
strData = "request=" & requestData & "&request2=" & requestData2
postHTML (strUrl, strData)
function postHTML (strUrl, strData)
Set xmlHttp = Server.Createobject("MSXML2.ServerXMLHTTP")
xmlHttp.Open "POST", strUrl, False
xmlHttp.setRequestHeader "User-Agent", "asp httprequest"
xmlHttp.setRequestHeader "content-type", "application/x-www-form-urlencoded"
xmlHttp.Send strData
postHTML = xmlHttp.responseText
xmlHttp.abort()
set xmlHttp = Nothing
end function
For example if an & is in the requestdata2, anything after that & is truncated, because it is thinking it is starting a new string. But I want to be able to pass this along.
Only Solution I can think of as of right now: do a string replace for special characters such as = and & and restore them with another string replace on the php server. This however is not what I want to accomplish this task. I would like the correct way of sending a post.
You need to URL encode the parameter values, so change this line...
strData = "request=" & requestData & "&request2=" & requestData2
...to...
strData = "request=" & Server.UrlEncode(requestData) & "&request2=" & Server.UrlEncode(requestData2)
The receiving server should automatically decode the values.

Resources