Lua socket HTTP getting connection refused - sockets

I'm trying to create a function that creates an issue to a Github repository using Lua socket.http, but I'm getting connection refused everytime. The documentation for socket is a bit unclear and I couldn't find more helpful information on why is the request getting refused every time. I tried the following:
local config = {
token = "oauth token from github"
}
local http, ltn12 = require("socket.http"), require("ltn12")
local payload = '{"title": "Test", "body": "Test body", "labels": ["bug"]}'
local response, status, headers, line = http.request("https://api.github.com/repos/<username>/<repository>/issues?access_token=" .. config.token, payload)
So I checked again how to do and there is a second form to do a request. I'm trying the following:
local response = {}
local _, status, headers, line = http.request{
url = "https://api.github.com/repos/<username>/<repository>/issues",
sink = ltn12.sink.table(response),
method = "POST",
headers = {
["Authorization"] = "token " .. config.token,
["Content-Length"] = payload:len()
},
source = ltn12.source.string(payload)
}
According to socket documentation, this should make POST request to the URL sending the payload as body. If I print(status) it prints connection refused.
I'm ignoring the first return value as it always is 1.
I tried manually issuing the request using curl:
curl -H "Authorization: token <oauth token from github>" https://api.github.com/repos/<username>/<repository>/issues -XPOST -d '{"title": "Test", "body": "{"title": "Test", "body": "Test body", "labels": ["bug"]}'
And it posted the issue properly. I still can't figure it out what is happening that the connection is getting refused.

Related

Receiving 404 when trying to edit a datasource despite being able to retrieve it's details

I have a datasource created in Grafana and attempting to update it to refresh the bearer token for auth access.
However, I'm receiving a 404 Not Found error from the grafana api when making a request to localhost:3000/api/datasources/uid/:uid with a uid just received from the datasources/name api - attempting to update as per the documentation https://grafana.com/docs/grafana/latest/developers/http_api/data_source/#update-an-existing-data-source
I'm using the grafana opensource docker container with the Infinity plugin.
docker run -d -p 3000:3000 --name=grafana -e "GF_INSTALL_PLUGINS=yesoreyeram-infinity-datasource" grafana/grafana-oss
I'm able to create a datasource via the api, just can't update an existing one.
My code is:-
grafana_api_token = '<my api token>'
new_access_token = '<my new bearer token>'
my_data_source = 'my_data_source'
grafana_header = {"authorization": f"Bearer {grafana_api_token}", "content-type":"application/json;charset=UTF-8"}
grafana_datasource_url = f"http://localhost:3000/api/datasources/name/{my_data_source}"
firebolt_datasource_resp = get(url=grafana_datasource_url, headers=grafana_header)
full_datasource = loads(firebolt_datasource_resp.content.decode("utf-8"))
datasource_uid = full_datasource["uid"]
update_token_url = f"http://localhost:3000/api/datasources/uid/{datasource_uid}"
new_data = {"id": full_datasource["id"],
"uid": full_datasource["uid"],
"orgId": full_datasource["orgId"],
"name": "new_data_source",
"type": full_datasource["type"],
"access": full_datasource["access"],
"url": full_datasource["url"],
"user": full_datasource["user"],
"database": full_datasource["database"],
"basicAuth": full_datasource["basicAuth"],
"basicAuthUser": full_datasource["basicAuthUser"],
"withCredentials": full_datasource["withCredentials"],
"isDefault": full_datasource["isDefault"],
"jsonData": full_datasource["jsonData"],
"secureJsonData": {
"bearerToken": new_access_token
}
}
update_bearer_token_resp = post(url=update_token_url, data=dumps(new_data), headers=grafana_header)
Oh, oh, oh, idiot mode. Using post rather than put. Doh.

pythonanywhere is not updating mongoDB

#app.route('/signup', methods=['POST'])
def signup():
info = request.args
if info["password"] == info["password2"] and info["name"] and info["email"] and info["password"] and info["password2"]:
password = os.getenv("password")
link = 'mongodb+srv://yakov:' + password + '#cluster0.irzzw.mongodb.net/myAuctionDB?retryWrites=true&w=majority'
client = MongoClient(link)
db = client.get_database('myAuctionDB')
users = db.users
users.insert_one({
'name': info["name"],
'email': info["email"],
'password': info["password"],
'sales': [],
'offers': [],
'saved': []
})
return jsonify({"status": "ok", "message": " welcome to {} {} ".format(info["name"], info["email"])})
else:
return jsonify({"status": "error", "message": "you are missing some arguments"})
this is my code, it works when i run it locally from my computer.
i saved it on a host called pythonanywhere, and the code works, but it does not insert the json to mongoDB, it gives me this error "500 Internal Server Error".
this is the response when i run it locally:
this is the response of the same code when i run it through pythonanywhere:
Using a free acount in pythonanywhere, does not allow to connect to mongodb atlas, so when it runs on pythonanywhere, it does not connect to the database, and does not work

K6 Get reqeust result in error against specific endpoint URL

I am new to K6 and is trying to use the tool to perform a Get request by verifying an API.
When the script is executed I get a warning that terminates the scrip. As far as my understanding is that this error is somewhat related to Go (if I have understood it correctly).
The result that I want to achieve is to be able to execute the Get request to the endpoint URL, but would appreciate any kind of feedback if I have done any incorrectly or should try an other approach.
Script:
import http from "k6/http";
import { check } from "k6";
export default function () {
var url =
"https://endpoint.example.to.cloud/api/reports/v1/SMOKETESTC6KP6NWX";
var headerParam = {
headers: {
"Content-Type": "application/json",
},
};
const response = http.get(url, headerParam);
check(response, {
"Response status reciving a 200 response ": (r) => r.status === 200,
});
let body = JSON.parse(response.body);
}
Output:
WARN[0000] Request Failed error="Get \"https://endpoint.example.to.cloud/api/reports/v1/SMOKETESTC6KP6NWX\": x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0"
Changing URL endpoint:
If i change the URL endpoint (mockup url) like below, there will be no errors:
...
var url = "https://run.mocky.io/v3/16fa8113-57e0-4e47-99b9-b5c55da93d71";
...
Updated solution to run this locally:
In order to run this locally i had to add the certification and key:
Example:
export let options = {
...
tlsAuth: [
{
cert: open(`${__ENV.Certificate}`),
key: open(`${__ENV.Key}`),
},
],
};
In addition populate the execute command with --insecure-skip-tls-verify
Example:
k6 run -e Certificate=/home/cert/example_certification.crt -e Key=/home/cert/certification/example_key.key -e example.js --insecure-skip-tls-verify
k6 is written in Go, and the latest versions of Go have a breaking change in how they handle X.509 certificates: https://golang.org/doc/go1.15#commonname
As it says in the error message, you can temporarily allow the old behavior by setting a GODEBUG=x509ignoreCN=0 environment variable, but that will likely stop working in a few months with Go 1.17. Using the insecureSkipTLSVerify k6 option might also work, I haven't checked, but as the name implies, that stops any TLS verification and is insecure.
So the real solution is to re-generate your server-side certificate properly.

Jfrog REST API Jenkins Groovy status code: 404, reason phrase: Not Found

I have a Groovy script which is run in the Jenkins script console. The script uses the JFrog Rest API to run some queries. One of which returns: status code: 404, reason phrase: Not Found
CURL:
$ curl -X GET -H "X-JFrog-Art-Api:APIKey" https://OU.jfrog.io/OU/api/storage/test-repository/docker-log-gen/1.12/manifest.json?properties
{
"properties" : { ... },
"uri" : "https://OU.jfrog.io/artifactory/api/storage/test-repository/docker-log-gen/1.12/manifest.json"
}
WGET
$ wget --header="X-JFrog-Art-Api:APIKey" https://OU.jfrog.io/OU/api/storage/test-repository/docker-log-gen/1.12/manifest.json?properties
--2020-01-14 13:12:16-- https://OU.jfrog.io/OU/api/storage/test-repository/docker-log-gen/1.12/manifest.json?properties
HTTP request sent, awaiting response... 200 OK
Jenkins Groovy
def restClient = new RESTClient('https://OU.jfrog.io')
restClient.headers['X-JFrog-Art-Api'] = 'APIKey'
println(restClient.get(path: '/OU/api/storage/test-repository/docker-log-gen/1.12/manifest.json?properties', requestContentType: 'text/plain') )
groovyx.net.http.HttpResponseException: status code: 404, reason phrase: Not Found
Other rest calls (api/docker) are made prior to this one in the script and return successfully. I am unable to identify a cause for this response, as shown the command-line calls return the expected JSON.
Please help.
The part after the first question mark is not the URI path component.
println(restClient.get(path: '/OU/api/storage/test-repository/docker-log-gen/1.12/manifest.json', query: ['properties': ''] , requestContentType: 'text/plain').data.text )
{
"properties" : { ... },
"uri" : "https://OU.jfrog.io/artifactory/api/storage/test-repository/docker-log-gen/1.12/manifest.json"
}

Make POST request with alamofire

I my swift app . I want to create a request POST with alamofire
The request
$ curl \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-X POST -d '{ "user": { "email": "user#example.com", "password": "1234" } }' \
http://localhost:3000/users/sign_in
My code
let crendetials = ["user": ["email": "bolo#me.com", "password": "PASSWORD"]]
var postsEndpoint: String = "http://localhost:3000/users/sign_in"
Alamofire.request(.POST, postsEndpoint, parameters: crendetials, encoding: .JSON)
.responseJSON { (request, response, data, error) in
if let anError = error
{
// got an error in getting the data, need to handle it
println("error calling POST on /users/sign_in")
println(error)
}
else if let data: AnyObject = data
{
// handle the results as JSON, without a bunch of nested if loops
let post = JSON(data)
// to make sure it posted, print the results
println(data)
}
}
I have got this error
request: <NSMutableURLRequest: 0x170208be0> { URL: http://localhost:3000/users/sign_in } || response: nil || object: Optional(<>) || error: Optional(Error Domain=NSURLErrorDomain Code=-1004 "The operation couldn’t be completed. (NSURLErrorDomain error -1004.)" UserInfo=0x1740f6900 {NSErrorFailingURLStringKey=http://localhost:3000/users/sign_in, NSErrorFailingURLKey=http://localhost:3000/users/sign_in, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSUnderlyingError=0x17405c500 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1004.)"})
If you're testing with a real iPhone, you should change the host from localhost to your Mac's ip address and make sure you iPhone and Mac in the same wireless network.
If you're testing with a simulator, it should work. Maybe you can change localhost to 127.0.0.1.
The error is due to wrong url. You can test in Safari in your device to see if it works.