Skip to content
This repository has been archived by the owner on Oct 28, 2024. It is now read-only.

Fix build status and adjust Vault #1074

Merged
merged 18 commits into from
Apr 21, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 2 additions & 25 deletions src/test/groovy/BuildStatusTests.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -19,51 +19,28 @@ import org.junit.Before
import org.junit.After
import org.junit.Test
import static org.junit.Assert.assertTrue
import com.sun.net.httpserver.HttpServer
import com.sun.net.httpserver.HttpContext
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler

class BuildStatusTests extends ApmBasePipelineTest {


// Build a small test server
def i = new InetSocketAddress('localhost', 9999)
def HttpServer ws = HttpServer.create(i, 100)
HttpContext job_status_context = ws.createContext("/buildStatus/text")


@Override
@Before
void setUp() throws Exception {
super.setUp()
script = loadScript('vars/buildStatus.groovy')
job_status_context.setHandler({ exchange ->
String response = "Success"
exchange.responseHeaders.set("Content-Type", "text/plain;charset=utf-8")
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
exchange.Send
});
ws.start()
}

@After
void tearDown() throws Exception {
ws.stop(0)
}

@Test
void test() throws Exception {
helper.registerAllowedMethod("httpRequest", [Map.class], { "Success" })
def result = script.call(host: 'localhost:9999', job: ['apm-agent-java', 'apm-agent-java-mbp', 'master'], ssl: false)
assertTrue("Success" == result)
assertJobStatusSuccess()
}

@Test
void testBoolSuccess() throws Exception {
helper.registerAllowedMethod("httpRequest", [Map.class], { "Success" })
def result = script.call(host: 'localhost:9999', job: ['apm-agent-java', 'apm-agent-java-mbp', 'master'], return_boolean: true, ssl: false)
assertTrue(result)
}
Expand Down
12 changes: 11 additions & 1 deletion src/test/groovy/GetVaultSecretStepTests.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,19 @@ class GetVaultSecretStepTests extends ApmBasePipelineTest {
assertTrue(assertMethodCallContainsPattern('error', 'getVaultSecret: Unable to get the secret.'))
}

@Test
void testReadSecretWrapperWithParams() throws Exception {
script.readSecretWrapperWithParams('dummy-role-id', 'dummy-secret-id') {
// TODO
}
printCallStack()
assertTrue(assertMethodCallContainsPattern('withCredentials', '[{credentialsId=vault-addr, variable=VAULT_ADDR}, {credentialsId=dummy-role-id, variable=VAULT_ROLE_ID}, {credentialsId=dummy-secret-id, variable=VAULT_SECRET_ID}]'))
assertJobStatusSuccess()
}

@Test
void testReadSecretWrapper() throws Exception {
script.readSecretWrapper {
script.readSecretWrapper() {
// TODO
}
printCallStack()
Expand Down
29 changes: 2 additions & 27 deletions vars/buildStatus.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,7 @@ buildStatus(
**/

import java.net.URL
import java.net.HttpURLConnection

import java.io.BufferedReader
import java.io.InputStreamReader


private static String makeRequest(URL url) throws IOException {
// URL url = new URL("${baseUrl}/${path}")
HttpURLConnection con = (HttpURLConnection)url.openConnection()
con.setRequestMethod("GET")
con.setRequestProperty("User-Agent", "Jenkins Build Status/1.0")
int responseCode = con.getResponseCode()

InputStreamReader isr = new InputStreamReader(con.getInputStream())
BufferedReader brd = new BufferedReader(isr)
if (responseCode == HttpURLConnection.HTTP_OK) {
String inputLine
StringBuffer response = new StringBuffer()
while ((inputLine = brd.readLine()) != null) {
response.append(inputLine)
}
brd.close()
return response.toString()
} else {
raise IOException("Failure to connect to Jenkins instance")
}
}

private static URL constructURL(String host, ArrayList job, boolean ssl) throws Exception {
String delim = "%2F"
Expand All @@ -71,7 +45,8 @@ def call(Map args = [:]) {
def job = args.get('job', [])
def return_boolean = args.get('return_boolean', false)
def ssl = args.get('ssl', true)
def result = makeRequest(constructURL(host, job, ssl))
def to_url = constructURL(host, job, ssl).toString()
def result = httpRequest(url: to_url)
if (return_boolean){
if (result == "Success") {
return true
Expand Down
24 changes: 20 additions & 4 deletions vars/getVaultSecret.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ import net.sf.json.JSONObject
*/
def call(Map args = [:]){
def secret = args.containsKey('secret') ? args.secret : error("getVaultSecret: No valid secret to looking for.")
return readSecret(secret)
def role_id = args.containsKey('role_id') ? args.role_id : 'vault-role-id'
def secret_id = args.containsKey('secret_id') ? args.secret_id : 'vault-secret-id'
return readSecret(secret, role_id, secret_id)
}

/**
Expand All @@ -39,13 +41,13 @@ def call(secret) {
error("getVaultSecret: No valid secret to looking for.")
}
secret = 'secret/apm-team/ci/' + secret
return readSecret(secret)
return readSecret(secret, 'vault-role-id', 'vault-secret-id')
}

def readSecret(secret) {
def readSecret(secret, role_id, secret_id) {
def props = null
log(level: 'INFO', text: 'getVaultSecret: Getting secrets')
readSecretWrapper() {
readSecretWrapperWithParams(role_id, secret_id) {
// When running in the CI with multiple parallel stages
// the access could be considered as a DDOS attack. Let's sleep a bit if it fails.
retryWithSleep(retries: 3, seconds: 5, backoff: true) {
Expand All @@ -58,6 +60,20 @@ def readSecret(secret) {
return props
}

def readSecretWrapperWithParams(role_id, secret_id, body) {
cachedout marked this conversation as resolved.
Show resolved Hide resolved
withCredentials([
string(credentialsId: 'vault-addr', variable: 'VAULT_ADDR'),
string(credentialsId: role_id, variable: 'VAULT_ROLE_ID'),
string(credentialsId: secret_id, variable: 'VAULT_SECRET_ID')]) {
withEnv([
"VAULT_AUTH_METHOD=approle", //Used by Ansible Vault modules
"VAULT_AUTHTYPE=approle" //Used by Ansible Vault modules
]){
body()
}
}
}

def readSecretWrapper(body) {
withCredentials([
string(credentialsId: 'vault-addr', variable: 'VAULT_ADDR'),
Expand Down
5 changes: 4 additions & 1 deletion vars/withSecretVault.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@ def call(Map args = [:], Closure body) {
def pass_variable = args?.pass_var_name
def pass_key = args.containsKey('pass_key') ? args.pass_key : 'password'

def role_id = args.containsKey('role_id') ? args.role_id : 'vault-role-id'
def secret_id = args.containsKey('secret_id') ? args.secret_id : 'vault-secret-id'

if (!secret || !user_variable || !pass_variable) {
error "withSecretVault: Missing variables"
}

def props = getVaultSecret(secret: secret)
def props = getVaultSecret(secret: secret, role_id: role_id, secret_id: secret_id)
if(props?.errors){
error "withSecretVault: Unable to get credentials from the vault: " + props.errors.toString()
}
Expand Down