From 457d7a45797988287acdd155500b99aa2014b79d Mon Sep 17 00:00:00 2001
From: Thomas Broyer <t.broyer@ltgt.net>
Date: Sun, 24 May 2020 20:03:57 +0200
Subject: [PATCH] Add output parameters for the tool path and version

This allows calling the action multiple times in the
same job and retrieving the path and/or version in
other steps.

Fixes #65
---
 .github/workflows/workflow.yml | 11 ++--
 __tests__/verify-java.ps1      | 20 +++++++
 __tests__/verify-java.sh       | 24 ++++++++-
 action.yml                     |  5 ++
 dist/index.js                  | 96 +++++++++++++++++++++++-----------
 src/installer.ts               |  2 +
 6 files changed, 121 insertions(+), 37 deletions(-)

diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml
index dda73067..1b7aa658 100644
--- a/.github/workflows/workflow.yml
+++ b/.github/workflows/workflow.yml
@@ -35,15 +35,16 @@ jobs:
       if: runner.os == 'windows'
       run: move "${{ runner.tool_cache }}" "${{ runner.tool_cache }}.old"
     - name: Setup Java 13
+      id: setup-java
       uses: ./
       with:
         java-version: 13.0.2
     - name: Verify Java 13
       if: runner.os != 'windows'
-      run: __tests__/verify-java.sh 13.0.2
+      run: __tests__/verify-java.sh 13.0.2 "${{ steps.setup-java.outputs.path }}" "${{ steps.setup-java.outputs.version }}"
     - name: Verify Java 13 (Windows)
       if: runner.os == 'windows'
-      run: __tests__/verify-java.ps1 13.0.2
+      run: __tests__/verify-java.ps1 13.0.2 "${{ steps.setup-java.outputs.path }}" "${{ steps.setup-java.outputs.version }}"
 
   test-proxy:
     runs-on: ubuntu-latest
@@ -62,11 +63,12 @@ jobs:
     - name: Clear tool cache
       run: rm -rf $RUNNER_TOOL_CACHE/*
     - name: Setup Java 13
+      id: setup-java
       uses: ./
       with:
         java-version: 13.0.2
     - name: Verify Java 13
-      run: __tests__/verify-java.sh 13.0.2
+      run: __tests__/verify-java.sh 13.0.2 "${{ steps.setup-java.outputs.path }}" "${{ steps.setup-java.outputs.version }}"
 
   test-bypass-proxy:
     runs-on: ubuntu-latest
@@ -78,8 +80,9 @@ jobs:
     - name: Clear tool cache
       run: rm -rf $RUNNER_TOOL_CACHE/*
     - name: Setup Java 13
+      id: setup-java
       uses: ./
       with:
         java-version: 13.0.2
     - name: Verify Java 13
-      run: __tests__/verify-java.sh 13.0.2
+      run: __tests__/verify-java.sh 13.0.2 "${{ steps.setup-java.outputs.path }}" "${{ steps.setup-java.outputs.version }}"
diff --git a/__tests__/verify-java.ps1 b/__tests__/verify-java.ps1
index 9f675c89..359f2915 100644
--- a/__tests__/verify-java.ps1
+++ b/__tests__/verify-java.ps1
@@ -9,3 +9,23 @@ if (!$java_version.Contains($args[0]))
 {
   throw "Unexpected version"
 }
+
+if ($args.Count -lt 2 -or !$args[1])
+{
+  throw "Must supply java path argument"
+}
+
+if ($args[1] -ne $Env:JAVA_HOME)
+{
+  throw "Unexpected path"
+}
+
+if ($args.Count -lt 3 -or !$args[2])
+{
+  throw "Must supply java version argument"
+}
+
+if ($args[0] -ne $args[2])
+{
+  throw "Unexpected version"
+}
diff --git a/__tests__/verify-java.sh b/__tests__/verify-java.sh
index f34aba50..e0da7d3a 100755
--- a/__tests__/verify-java.sh
+++ b/__tests__/verify-java.sh
@@ -1,13 +1,33 @@
 #!/bin/sh
 
 if [ -z "$1" ]; then
-  echo "Must supply java version argument"
+  echo "::error::Must supply java version argument"
   exit 1
 fi
 
 java_version="$(java -version 2>&1)"
 echo "Found java version: $java_version"
 if [ -z "$(echo $java_version | grep --fixed-strings $1)" ]; then
-  echo "Unexpected version"
+  echo "::error::Unexpected version"
+  exit 1
+fi
+
+if [ -z "$2" ]; then
+  echo "::error::Must supply java path argument"
+  exit 1
+fi
+
+if [ "$2" != "$JAVA_HOME" ]; then
+  echo "::error::Unexpected path"
+  exit 1
+fi
+
+if [ -z "$3" ]; then
+  echo "::error::Must supply java version argument"
+  exit 1
+fi
+
+if [ "$1" != "$3" ]; then
+  echo "::error::Unexpected version"
   exit 1
 fi
diff --git a/action.yml b/action.yml
index de7711fa..d41f286a 100644
--- a/action.yml
+++ b/action.yml
@@ -36,6 +36,11 @@ inputs:
   settings-path:
     description: 'Path to where the settings.xml file will be written. Default is ~/.m2.'
     required: false
+outputs:
+  path:
+    description: 'Path to where the java environment has been installed (same as $JAVA_HOME)'
+  version:
+    description: 'Actual version of the java environment that has been installed'
 runs:
   using: 'node12'
   main: 'dist/index.js'
diff --git a/dist/index.js b/dist/index.js
index 96632653..26346063 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -3770,6 +3770,7 @@ var HttpCodes;
     HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
     HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
     HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
+    HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
     HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
     HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
     HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
@@ -3794,8 +3795,18 @@ function getProxyUrl(serverUrl) {
     return proxyUrl ? proxyUrl.href : '';
 }
 exports.getProxyUrl = getProxyUrl;
-const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect];
-const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout];
+const HttpRedirectCodes = [
+    HttpCodes.MovedPermanently,
+    HttpCodes.ResourceMoved,
+    HttpCodes.SeeOther,
+    HttpCodes.TemporaryRedirect,
+    HttpCodes.PermanentRedirect
+];
+const HttpResponseRetryCodes = [
+    HttpCodes.BadGateway,
+    HttpCodes.ServiceUnavailable,
+    HttpCodes.GatewayTimeout
+];
 const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
 const ExponentialBackoffCeiling = 10;
 const ExponentialBackoffTimeSlice = 5;
@@ -3920,18 +3931,22 @@ class HttpClient {
      */
     async request(verb, requestUrl, data, headers) {
         if (this._disposed) {
-            throw new Error("Client has already been disposed.");
+            throw new Error('Client has already been disposed.');
         }
         let parsedUrl = url.parse(requestUrl);
         let info = this._prepareRequest(verb, parsedUrl, headers);
         // Only perform retries on reads since writes may not be idempotent.
-        let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1;
+        let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
+            ? this._maxRetries + 1
+            : 1;
         let numTries = 0;
         let response;
         while (numTries < maxTries) {
             response = await this.requestRaw(info, data);
             // Check if it's an authentication challenge
-            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+            if (response &&
+                response.message &&
+                response.message.statusCode === HttpCodes.Unauthorized) {
                 let authenticationHandler;
                 for (let i = 0; i < this.handlers.length; i++) {
                     if (this.handlers[i].canHandleAuthentication(response)) {
@@ -3949,21 +3964,32 @@ class HttpClient {
                 }
             }
             let redirectsRemaining = this._maxRedirects;
-            while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1
-                && this._allowRedirects
-                && redirectsRemaining > 0) {
-                const redirectUrl = response.message.headers["location"];
+            while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
+                this._allowRedirects &&
+                redirectsRemaining > 0) {
+                const redirectUrl = response.message.headers['location'];
                 if (!redirectUrl) {
                     // if there's no location to redirect to, we won't
                     break;
                 }
                 let parsedRedirectUrl = url.parse(redirectUrl);
-                if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
-                    throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+                if (parsedUrl.protocol == 'https:' &&
+                    parsedUrl.protocol != parsedRedirectUrl.protocol &&
+                    !this._allowRedirectDowngrade) {
+                    throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
                 }
                 // we need to finish reading the response before reassigning response
                 // which will leak the open socket.
                 await response.readBody();
+                // strip authorization header if redirected to a different hostname
+                if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                    for (let header in headers) {
+                        // header names are case insensitive
+                        if (header.toLowerCase() === 'authorization') {
+                            delete headers[header];
+                        }
+                    }
+                }
                 // let's make the request with the new redirectUrl
                 info = this._prepareRequest(verb, parsedRedirectUrl, headers);
                 response = await this.requestRaw(info, data);
@@ -4014,8 +4040,8 @@ class HttpClient {
      */
     requestRawWithCallback(info, data, onResult) {
         let socket;
-        if (typeof (data) === 'string') {
-            info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
+        if (typeof data === 'string') {
+            info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
         }
         let callbackCalled = false;
         let handleResult = (err, res) => {
@@ -4028,7 +4054,7 @@ class HttpClient {
             let res = new HttpClientResponse(msg);
             handleResult(null, res);
         });
-        req.on('socket', (sock) => {
+        req.on('socket', sock => {
             socket = sock;
         });
         // If we ever get disconnected, we want the socket to timeout eventually
@@ -4043,10 +4069,10 @@ class HttpClient {
             // res should have headers
             handleResult(err, null);
         });
-        if (data && typeof (data) === 'string') {
+        if (data && typeof data === 'string') {
             req.write(data, 'utf8');
         }
-        if (data && typeof (data) !== 'string') {
+        if (data && typeof data !== 'string') {
             data.on('close', function () {
                 req.end();
             });
@@ -4073,31 +4099,34 @@ class HttpClient {
         const defaultPort = usingSsl ? 443 : 80;
         info.options = {};
         info.options.host = info.parsedUrl.hostname;
-        info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort;
-        info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
+        info.options.port = info.parsedUrl.port
+            ? parseInt(info.parsedUrl.port)
+            : defaultPort;
+        info.options.path =
+            (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
         info.options.method = method;
         info.options.headers = this._mergeHeaders(headers);
         if (this.userAgent != null) {
-            info.options.headers["user-agent"] = this.userAgent;
+            info.options.headers['user-agent'] = this.userAgent;
         }
         info.options.agent = this._getAgent(info.parsedUrl);
         // gives handlers an opportunity to participate
         if (this.handlers) {
-            this.handlers.forEach((handler) => {
+            this.handlers.forEach(handler => {
                 handler.prepareRequest(info.options);
             });
         }
         return info;
     }
     _mergeHeaders(headers) {
-        const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+        const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
         if (this.requestOptions && this.requestOptions.headers) {
             return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
         }
         return lowercaseKeys(headers || {});
     }
     _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
-        const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+        const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
         let clientHeader;
         if (this.requestOptions && this.requestOptions.headers) {
             clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
@@ -4135,7 +4164,7 @@ class HttpClient {
                     proxyAuth: proxyUrl.auth,
                     host: proxyUrl.hostname,
                     port: proxyUrl.port
-                },
+                }
             };
             let tunnelAgent;
             const overHttps = proxyUrl.protocol === 'https:';
@@ -4162,7 +4191,9 @@ class HttpClient {
             // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
             // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
             // we have to cast it to any and change it directly
-            agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false });
+            agent.options = Object.assign(agent.options || {}, {
+                rejectUnauthorized: false
+            });
         }
         return agent;
     }
@@ -4223,7 +4254,7 @@ class HttpClient {
                     msg = contents;
                 }
                 else {
-                    msg = "Failed request: (" + statusCode + ")";
+                    msg = 'Failed request: (' + statusCode + ')';
                 }
                 let err = new Error(msg);
                 // attach statusCode and body obj (if available) to the error object
@@ -4714,6 +4745,8 @@ function getJava(version, arch, jdkFile, javaPackage) {
         core.exportVariable('JAVA_HOME', toolPath);
         core.exportVariable(extendedJavaHome, toolPath);
         core.addPath(path.join(toolPath, 'bin'));
+        core.setOutput('path', toolPath);
+        core.setOutput('version', version);
     });
 }
 exports.getJava = getJava;
@@ -4917,12 +4950,10 @@ function getProxyUrl(reqUrl) {
     }
     let proxyVar;
     if (usingSsl) {
-        proxyVar = process.env["https_proxy"] ||
-            process.env["HTTPS_PROXY"];
+        proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
     }
     else {
-        proxyVar = process.env["http_proxy"] ||
-            process.env["HTTP_PROXY"];
+        proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
     }
     if (proxyVar) {
         proxyUrl = url.parse(proxyVar);
@@ -4934,7 +4965,7 @@ function checkBypass(reqUrl) {
     if (!reqUrl.hostname) {
         return false;
     }
-    let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || '';
+    let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
     if (!noProxy) {
         return false;
     }
@@ -4955,7 +4986,10 @@ function checkBypass(reqUrl) {
         upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
     }
     // Compare request host against noproxy
-    for (let upperNoProxyItem of noProxy.split(',').map(x => x.trim().toUpperCase()).filter(x => x)) {
+    for (let upperNoProxyItem of noProxy
+        .split(',')
+        .map(x => x.trim().toUpperCase())
+        .filter(x => x)) {
         if (upperReqHosts.some(x => x === upperNoProxyItem)) {
             return true;
         }
diff --git a/src/installer.ts b/src/installer.ts
index cce8fa3d..487db6ff 100644
--- a/src/installer.ts
+++ b/src/installer.ts
@@ -90,6 +90,8 @@ export async function getJava(
   core.exportVariable('JAVA_HOME', toolPath);
   core.exportVariable(extendedJavaHome, toolPath);
   core.addPath(path.join(toolPath, 'bin'));
+  core.setOutput('path', toolPath);
+  core.setOutput('version', version);
 }
 
 function getCacheVersionString(version: string) {