0

I have a groovy script that is behaving in weird manner.My requirement is to generate a auth token by hitting server and then hitting server again to submit deployment file using the auth token. I tested two api by writing separate files, one generated token and then I manually copy that token to second file and submit file to server for deployment. When I combine this functionality in one file, then the code is not working. I use url post to generate the token and curl call to submit file.Following is my script:

import groovy.io.FileType
import groovy.json.JsonSlurper
import groovy.json.JsonOutput;
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLEngine
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509ExtendedTrustManager
import java.security.cert.CertificateException
import java.security.cert.X509Certificate

 String LINE_FEED = "\r\n";
class UnsafeTrustManager extends X509ExtendedTrustManager {

    @Override
    void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {}

    @Override
    void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {}

    @Override
    void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {}

    @Override
    void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {}

    @Override
    void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

    @Override
    void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

    @Override
    X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0]
    }

}


def upload(def auth,def nameSpace)
{

def sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, new TrustManager[]{new UnsafeTrustManager()}, null)
def sslSocketFactory = sslContext.getSocketFactory()
def postRC=""
def post
def postResponse
def auth1=""
 


post = (HttpsURLConnection) new URL("https://gateway.com:8443/tokens").openConnection();
post.setSSLSocketFactory(sslSocketFactory)

def message = '{"username":"user", "password":"pass"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));


 postRC = post.getResponseCode();
if(postRC.equals(200))
{
postResponse=post.getInputStream().getText();
def slurper = new JsonSlurper()
def resultMap = slurper.parseText(postResponse)
auth1=resultMap["authToken"]
}

def filePath = nameSpace+"/test.yaml";

def command = "curl  --location -w '%{http_code}' --request POST 'https://gateway.com:8443/cloudgateway/environments/'"+
" --header 'Content-Type: multipart/form-data'"+
" --header 'Authorization:"+auth +"\'" +
" --form 'request=@\""+filePath+"\"'"




println(" Curl command Generated for namepsace : ${nameSpace},command : ${command}")


StringBuffer out = new StringBuffer(4096)
StringBuffer err = new StringBuffer(4096)

def initialSize = 4096
def process = [ 'bash', '-c', command].execute()


process.consumeProcessOutput(out, err)
println(" Waiting curl command response for  namepsace : ${nameSpace}")
process.waitFor()

if (process.exitValue()) {
        println " erro "
        println err
       // println err
    } else {
        println " output is"
       println out
    }


}

upload("mytoken"
    ,"abc/def")

When I call upload function by passing a token to it that is generated before executing this file then it works fine.I get token by postman/(another groovy file as I mentioned in first statement).But in case I generate token in the upload api, then the curl command executes successfully but it does not give any output. The class UnsafeTrustManager is to disable SSL verification on my local.SO the curl looks like something as follow:

 curl  --location -w '%{http_code}' --request POST 'https://gateway.com:8443/environments/' --header 'Content-Type: multipart/form-data' --header 'Authorization:token' --form 'request=@"abc/def/myfile.yaml"'

Why is it happening so that if i dynamically generate token, the curl gives empty response.But if remove code to generate token and manually supply it works.Even if code to generate token is there but I use token passed in parameter, still it is not working.But the same curl if i execute on terminal it works fine.I have spent hours to debug.Can someone throw some light?

user124
  • 423
  • 2
  • 7
  • 26
  • Why do you need `bash -c` ? Why 2 different vars `auth1` and `auth`? – daggett Jul 03 '21 at 05:03
  • I took some example from stack-overflow to execute curl in groovy. auth1 is the one that i generate dynamically, if I use auth1 it does not work, and if i remove code to generate auth 1 and supply auth as a valid token then curl works fine. – user124 Jul 03 '21 at 15:05
  • sounds like you are evaluating token incorrectly. – daggett Jul 03 '21 at 17:46
  • when i run on production it works fine because it has valid certificates but on local i write some code to disable certificates, it is causing to fail but i wonder why curl has to depend on that.Token is fine.If i copy the token generated by this code and manually use that next time. works fine. Infact same curl command when executed on terminal it works fine – user124 Jul 03 '21 at 19:33
  • ok. let me suggest small improvements: `1/` instead of `consumeProcessOutput` and `waitFor` use [waitForProcessOutput](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Process.html#waitForProcessOutput(java.io.OutputStream,%20java.io.OutputStream)) `2/` try to remove `bash -c` – daggett Jul 03 '21 at 20:08

0 Answers0