diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 93cd825..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,107 +0,0 @@ -version: 2 -jobs: - build: - docker: - - image: circleci/openjdk:8-jdk - working_directory: ~/repo - environment: - JVM_OPTS: -Xmx3200m - TERM: dumb - steps: - - checkout - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle.kts" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - run: ./gradlew build - - save_cache: - paths: - - ~/.gradle - key: v1-dependencies-{{ checksum "build.gradle.kts" }} - integration-token: - machine: true - steps: - - checkout - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle.kts" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - run: docker-compose build - - run: docker-compose up -d - - run: ./gradlew publishToMavenLocal -x check - - run: ./gradlew build -x check -p integration-token - - run: docker-compose kill - - save_cache: - paths: - - ~/.gradle - key: v1-dependencies-{{ checksum "build.gradle.kts" }} - integration-tokenfile: - machine: true - steps: - - checkout - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle.kts" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - run: docker-compose build - - run: docker-compose up -d - - run: ./gradlew publishToMavenLocal -x check - - run: ./gradlew build -x check -p integration-tokenfile - - run: docker-compose kill - - save_cache: - paths: - - ~/.gradle - key: v1-dependencies-{{ checksum "build.gradle.kts" }} - publish-plugin: - docker: - - image: circleci/openjdk:8-jdk - working_directory: ~/repo - environment: - JVM_OPTS: -Xmx3200m - TERM: dumb - steps: - - checkout - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle.kts" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - run: ./gradlew versionDisplay - - run: ./gradlew publishPlugins - - save_cache: - paths: - - ~/.gradle - key: v1-dependencies-{{ checksum "build.gradle.kts" }} - -workflows: - version: 2 - all: - jobs: - - build: - filters: - tags: - only: /.*/ - - integration-token: - requires: - - build - filters: - tags: - only: /.*/ - - integration-tokenfile: - requires: - - build - filters: - tags: - only: /.*/ - - publish-plugin: - requires: - - integration-token - - integration-tokenfile - filters: - tags: - only: /.*/ - branches: - ignore: /.*/ \ No newline at end of file diff --git a/.github/workflows/pre-merge.yaml b/.github/workflows/pre-merge.yaml new file mode 100644 index 0000000..952d0b2 --- /dev/null +++ b/.github/workflows/pre-merge.yaml @@ -0,0 +1,26 @@ +name: Pre Merge Checks + +on: + push: + branches: + - main + pull_request: + branches: + - '*' + +jobs: + gradle: + runs-on: ubuntu-latest + env: + GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} + GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Cache + uses: gradle/gradle-build-action@v2.4.2 + - name: Validate + run: ./gradlew check validatePlugins --continue + - name: Integration Test + run: ./gradlew integrationTest --info + diff --git a/.github/workflows/publish-plugin.yaml b/.github/workflows/publish-plugin.yaml new file mode 100644 index 0000000..d708294 --- /dev/null +++ b/.github/workflows/publish-plugin.yaml @@ -0,0 +1,24 @@ +name: Publish to Gradle Plugin Portal + +on: + push: + tags: + - '*' + +jobs: + gradle: + runs-on: ubuntu-latest + env: + GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} + GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Cache + uses: gradle/gradle-build-action@v2.4.2 + - name: Validate + run: ./gradlew check validatePlugins --continue + - name: Integration Test + run: ./gradlew integrationTest + - name: Publish + run: ./gradlew publishPlugins diff --git a/build.gradle.kts b/build.gradle.kts index eeeab30..ddcdad8 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,10 +1,7 @@ -import net.nemerosa.versioning.tasks.VersionDisplayTask - plugins { `kotlin-dsl` - `maven-publish` - id("com.gradle.plugin-publish") version "0.18.0" - id("net.nemerosa.versioning") version "2.15.1" + alias(libs.plugins.gradlePluginPublish) + alias(libs.plugins.nemerosaVersioning) } group = "com.liftric.vault" @@ -15,23 +12,42 @@ allprojects { } else { full } + }.also { + println("version=$it") } } repositories { mavenCentral() + gradlePluginPortal() +} + +sourceSets { + val main by getting + val integrationMain by creating { + compileClasspath += main.output + runtimeClasspath += main.output + } } + dependencies { implementation(gradleApi()) implementation(kotlin("gradle-plugin")) implementation(kotlin("stdlib-jdk8")) - implementation("com.bettercloud:vault-java-driver:5.1.0") + implementation(libs.javaVaultDriver) + testImplementation(gradleTestKit()) - testImplementation("junit:junit:4.13.2") - testImplementation("com.github.stefanbirkner:system-rules:1.19.0") + testImplementation(libs.junitJupiter) + + "integrationMainImplementation"(gradleTestKit()) + "integrationMainImplementation"(libs.junitJupiter) + "integrationMainImplementation"(libs.javaVaultDriver) + "integrationMainImplementation"(libs.testContainersJUnit5) + "integrationMainImplementation"(libs.testContainersMain) } + tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" @@ -39,57 +55,44 @@ tasks { compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } - withType { - doLast { - println("[VersionDisplayTask] version=$version") - } - } - val createVersionFile by creating { - doLast { - mkdir(buildDir) - file("$buildDir/version").apply { - if (exists()) delete() - createNewFile() - writeText(project.version.toString()) - } + + val test by existing + withType { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") } + systemProperty("org.gradle.testkit.dir", gradle.gradleUserHomeDir) } - val build by existing - val publish by existing - val publishToMavenLocal by existing - listOf(build.get(), publish.get(), publishToMavenLocal.get()).forEach { it.dependsOn(createVersionFile) } - val setupPluginsLogin by creating { - // see: https://github.com/gradle/gradle/issues/1246 - val publishKey: String? = System.getenv("GRADLE_PUBLISH_KEY") - val publishSecret: String? = System.getenv("GRADLE_PUBLISH_SECRET") - if (publishKey != null && publishSecret != null) { - println("[setupPluginsLogin] seeting plugin portal credentials from env") - System.getProperties().setProperty("gradle.publish.key", publishKey) - System.getProperties().setProperty("gradle.publish.secret", publishSecret) - } + register("integrationTest") { + val integrationMain by sourceSets + description = "Runs the integration tests" + group = "verification" + testClassesDirs = integrationMain.output.classesDirs + classpath = integrationMain.runtimeClasspath + mustRunAfter(test) + useJUnitPlatform() } - val publishPlugins by existing - publishPlugins.get().dependsOn(setupPluginsLogin) } + publishing { repositories { mavenLocal() } } + gradlePlugin { + website.set("https://github.com/Liftric/vault-client-plugin") + vcsUrl.set("https://github.com/Liftric/vault-client-plugin") + testSourceSets(sourceSets["integrationMain"]) plugins { create("VaultClientPlugin") { id = "com.liftric.vault-client-plugin" displayName = "vault-client-plugin" implementationClass = "com.liftric.vault.VaultClientPlugin" description = "Read and use vault secrets in your build script" + tags.set(listOf("vault", "hashicorp", "secret")) } } } -pluginBundle { - website = "https://github.com/Liftric/vault-client-plugin" - vcsUrl = "https://github.com/Liftric/vault-client-plugin" - description = "Gradle plugin to use Vault secrets in build scripts" - tags = listOf("vault", "hashicorp", "secret") -} diff --git a/docker-compose.yml b/docker-compose.yml index fea096b..26818da 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,7 +2,7 @@ version: '3' services: vault: build: - dockerfile: vault.docker + dockerfile: vault.Dockerfile context: . environment: VAULT_DEV_ROOT_TOKEN_ID: myroottoken diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3cd8500..2fa91c5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/integration-token/build.gradle.kts b/integration-token/build.gradle.kts deleted file mode 100644 index e72039d..0000000 --- a/integration-token/build.gradle.kts +++ /dev/null @@ -1,40 +0,0 @@ -import com.liftric.vault.vault -import com.liftric.vault.GetVaultSecretTask - -plugins { - java - id("com.liftric.vault-client-plugin") // version known from buildSrc -} -vault { - vaultAddress.set("http://localhost:8200") - vaultToken.set("myroottoken") // don't do that in production code! - maxRetries.set(2) - retryIntervalMilliseconds.set(200) -} -val configTimeSecrets: Map = vault("secret/example") -tasks { - val needsSecretsConfigTime by creating { - doLast { - if (configTimeSecrets["examplestring"] != "helloworld") throw kotlin.IllegalStateException("examplestring couldn't be read") - if (configTimeSecrets["exampleint"]?.toInt() != 1337) throw kotlin.IllegalStateException("exampleint couldn't be read") - println("getting secrets succeeded!") - } - } - val needsSecrets by creating(GetVaultSecretTask::class) { - secretPath.set("secret/example") - doLast { - val secret = secret.get() - if (secret["examplestring"] != "helloworld") throw kotlin.IllegalStateException("examplestring couldn't be read") - if (secret["exampleint"]?.toInt() != 1337) throw kotlin.IllegalStateException("exampleint couldn't be read") - println("getting secret succeeded!") - } - } - val fromBuildSrc by creating { - doLast { - if (with(Configs) { secretStuff() != "helloworld:1337" }) throw kotlin.IllegalStateException("config with secret couldn't be read") - } - } - val build by existing { - dependsOn(needsSecretsConfigTime, needsSecrets, fromBuildSrc) - } -} diff --git a/integration-token/buildSrc/build.gradle.kts b/integration-token/buildSrc/build.gradle.kts deleted file mode 100644 index 7ae4eda..0000000 --- a/integration-token/buildSrc/build.gradle.kts +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - `kotlin-dsl` -} -repositories { - mavenLocal() - mavenCentral() - gradlePluginPortal() -} -dependencies { - val vaultClientPluginVersion = file("../../build/version").readText().trim() - implementation("com.liftric.vault:vault-client-plugin:$vaultClientPluginVersion") -} diff --git a/integration-token/buildSrc/src/main/kotlin/Configs.kt b/integration-token/buildSrc/src/main/kotlin/Configs.kt deleted file mode 100644 index 1661434..0000000 --- a/integration-token/buildSrc/src/main/kotlin/Configs.kt +++ /dev/null @@ -1,13 +0,0 @@ -import com.liftric.vault.GetVaultSecretTask -import org.gradle.api.Project -import org.gradle.kotlin.dsl.getByName - -object Configs { - fun Project.secretStuff(): String { - val needsSecrets: GetVaultSecretTask = tasks.getByName("needsSecrets").apply { - execute() - } - val secret = needsSecrets.secret.get() - return "${secret["examplestring"]}:${secret["exampleint"]}" - } -} diff --git a/integration-token/gradle/wrapper/gradle-wrapper.jar b/integration-token/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180..0000000 Binary files a/integration-token/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/integration-token/gradle/wrapper/gradle-wrapper.properties b/integration-token/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 84d1f85..0000000 --- a/integration-token/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/integration-token/gradlew b/integration-token/gradlew deleted file mode 100755 index 1b6c787..0000000 --- a/integration-token/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/integration-token/gradlew.bat b/integration-token/gradlew.bat deleted file mode 100644 index 107acd3..0000000 --- a/integration-token/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/integration-token/settings.gradle.kts b/integration-token/settings.gradle.kts deleted file mode 100644 index b04c4ff..0000000 --- a/integration-token/settings.gradle.kts +++ /dev/null @@ -1,15 +0,0 @@ -rootProject.name = "integration-token" -pluginManagement { - repositories { - gradlePluginPortal() - mavenLocal() - } - - resolutionStrategy { - eachPlugin { - if (requested.id.id == "com.liftric.vault-client-plugin") { - useModule("com.liftric.vault:vault-client-plugin:${requested.version}") - } - } - } -} diff --git a/integration-tokenfile/.vault-token b/integration-tokenfile/.vault-token deleted file mode 100644 index f19ac48..0000000 --- a/integration-tokenfile/.vault-token +++ /dev/null @@ -1 +0,0 @@ -myroottoken diff --git a/integration-tokenfile/build.gradle.kts b/integration-tokenfile/build.gradle.kts deleted file mode 100644 index 04dfdab..0000000 --- a/integration-tokenfile/build.gradle.kts +++ /dev/null @@ -1,27 +0,0 @@ -import com.liftric.vault.vault -import com.liftric.vault.GetVaultSecretTask - -plugins { - java - id("com.liftric.vault-client-plugin") -} -vault { - vaultAddress.set("http://localhost:8200") - vaultTokenFilePath.set("${projectDir.path}/.vault-token") // don't put the token file on the repo itself like here! - maxRetries.set(2) - retryIntervalMilliseconds.set(200) -} -tasks { - val needsSecrets by creating(GetVaultSecretTask::class) { - secretPath.set("secret/example") - doLast { - val secret = secret.get() - if (secret["examplestring"] != "helloworld") throw kotlin.IllegalStateException("examplestring couldn't be read") - if (secret["exampleint"]?.toInt() != 1337) throw kotlin.IllegalStateException("exampleint couldn't be read") - println("getting secret succeeded!") - } - } - val build by existing { - dependsOn(needsSecrets) - } -} diff --git a/integration-tokenfile/gradle/wrapper/gradle-wrapper.jar b/integration-tokenfile/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180..0000000 Binary files a/integration-tokenfile/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/integration-tokenfile/gradle/wrapper/gradle-wrapper.properties b/integration-tokenfile/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 84d1f85..0000000 --- a/integration-tokenfile/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/integration-tokenfile/gradlew b/integration-tokenfile/gradlew deleted file mode 100755 index 1b6c787..0000000 --- a/integration-tokenfile/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/integration-tokenfile/gradlew.bat b/integration-tokenfile/gradlew.bat deleted file mode 100644 index 107acd3..0000000 --- a/integration-tokenfile/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/integration-tokenfile/settings.gradle.kts b/integration-tokenfile/settings.gradle.kts deleted file mode 100644 index 0432e79..0000000 --- a/integration-tokenfile/settings.gradle.kts +++ /dev/null @@ -1,16 +0,0 @@ -rootProject.name = "integration-tokenfile" -pluginManagement { - repositories { - gradlePluginPortal() - mavenLocal() - } - - resolutionStrategy { - eachPlugin { - if (requested.id.id == "com.liftric.vault-client-plugin") { - val vaultClientPluginVersion = file("../build/version").readText().trim() - useModule("com.liftric.vault:vault-client-plugin:${vaultClientPluginVersion}") - } - } - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts index 0740375..3bbd462 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1 +1,23 @@ rootProject.name = "vault-client-plugin" + +pluginManagement { + dependencyResolutionManagement { + versionCatalogs { + create("libs") { + version("junit", "5.9.3") + version("testContainers", "1.18.3") + version("javaVaultDriver", "5.1.0") + + plugin("gradlePluginPublish", "com.gradle.plugin-publish").version("1.2.1") + plugin("nemerosaVersioning", "net.nemerosa.versioning").version("3.1.0") + + library("javaVaultDriver", "com.bettercloud", "vault-java-driver").versionRef("javaVaultDriver") + library("junitBom", "org.junit", "junit-bom").versionRef("junit") + library("junitJupiter", "org.junit.jupiter", "junit-jupiter").versionRef("junit") + library("testContainersJUnit5", "org.testcontainers", "junit-jupiter").versionRef("testContainers") + library("testContainersMain", "org.testcontainers", "testcontainers").versionRef("testContainers") + } + } + } +} + diff --git a/src/integrationMain/kotlin/com/liftric/vault/ContainerBase.kt b/src/integrationMain/kotlin/com/liftric/vault/ContainerBase.kt new file mode 100644 index 0000000..1d6e5ba --- /dev/null +++ b/src/integrationMain/kotlin/com/liftric/vault/ContainerBase.kt @@ -0,0 +1,56 @@ +package com.liftric.vault + +import com.bettercloud.vault.Vault +import com.bettercloud.vault.VaultConfig +import com.github.dockerjava.api.model.ExposedPort +import com.github.dockerjava.api.model.HostConfig +import com.github.dockerjava.api.model.PortBinding +import com.github.dockerjava.api.model.Ports +import org.testcontainers.containers.GenericContainer +import org.testcontainers.utility.DockerImageName + +abstract class ContainerBase { + companion object { + val vaultContainer: GenericContainer<*> = + GenericContainer(DockerImageName.parse("hashicorp/vault:1.13.3")) + .withEnv("VAULT_TOKEN", VAULT_TOKEN) + .withEnv("VAULT_ADDR", VAULT_ADDR) + .withCommand("server -dev -dev-root-token-id $VAULT_TOKEN") + .withCreateContainerCmdModifier { cmd -> + cmd.withHostConfig( + HostConfig().withPortBindings( + PortBinding( + Ports.Binding.bindPort(VAULT_PORT), + ExposedPort(VAULT_PORT) + ) + ) + ) + } + .withExposedPorts(VAULT_PORT) + .apply { start() } + + init { + val vault = Vault( + VaultConfig() + .address(VAULT_ADDR) + .token(VAULT_TOKEN) + .build() + ) + + vault.logical().write( + "secret/example", hashMapOf( + "examplestring" to "helloworld", + "exampleint" to 1337, + ) as Map? + ) + + vault.logical().write( + "secret/example2", hashMapOf( + "examplestring2" to "helloworld2", + "exampleint2" to 1338, + ) as Map? + ) + } + + } +} diff --git a/src/integrationMain/kotlin/com/liftric/vault/GetSecretTest.kt b/src/integrationMain/kotlin/com/liftric/vault/GetSecretTest.kt new file mode 100644 index 0000000..06e260c --- /dev/null +++ b/src/integrationMain/kotlin/com/liftric/vault/GetSecretTest.kt @@ -0,0 +1,69 @@ +package com.liftric.vault + +import org.gradle.testkit.runner.GradleRunner +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.testcontainers.junit.jupiter.Testcontainers +import java.io.File + +@Testcontainers +class GetSecretTest : ContainerBase() { + private val getSecretTestLocation = "build/getSecretTest" + + @Test + fun testGetSecretTask() { + val projectDir = File(getSecretTestLocation) + projectDir.mkdirs() + + projectDir.resolve("settings.gradle.kts").writeText("") + projectDir.resolve("build.gradle.kts").writeText( + """ +import com.liftric.vault.vault +import com.liftric.vault.GetVaultSecretTask + +plugins { + java + id("com.liftric.vault-client-plugin") +} + +group = "com.liftric.test" +version = "1.0.1" + +vault { + vaultAddress.set("$VAULT_ADDR") + vaultToken.set("$VAULT_TOKEN") + maxRetries.set(2) + retryIntervalMilliseconds.set(200) +} +tasks { + val needsSecrets by creating(GetVaultSecretTask::class) { + secretPath.set("secret/example") + doLast { + val secret = secret.get() + if (secret["examplestring"] != "helloworld") throw kotlin.IllegalStateException("examplestring couldn't be read") + if (secret["exampleint"]?.toInt() != 1337) throw kotlin.IllegalStateException("exampleint couldn't be read") + println("getting secret succeeded!") + } + } + val needsSecrets2 by creating(GetVaultSecretTask::class) { + secretPath.set("secret/example2") + doLast { + val secret = secret.get() + if (secret["examplestring2"] != "helloworld2") throw kotlin.IllegalStateException("examplestring2 couldn't be read") + if (secret["exampleint2"]?.toInt() != 1338) throw kotlin.IllegalStateException("exampleint2 couldn't be read") + println("getting secret succeeded!") + } + } +} + """ + ) + + val result = GradleRunner.create() + .withProjectDir(projectDir) + .withArguments("needsSecrets", "needsSecrets2") + .withPluginClasspath() + .build() + + assertTrue(result.output.contains("BUILD SUCCESSFUL")) + } +} diff --git a/src/integrationMain/kotlin/com/liftric/vault/GetSecretTokenFileTest.kt b/src/integrationMain/kotlin/com/liftric/vault/GetSecretTokenFileTest.kt new file mode 100644 index 0000000..09f53b7 --- /dev/null +++ b/src/integrationMain/kotlin/com/liftric/vault/GetSecretTokenFileTest.kt @@ -0,0 +1,60 @@ +package com.liftric.vault + +import org.gradle.testkit.runner.GradleRunner +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.testcontainers.junit.jupiter.Testcontainers +import java.io.File + +@Testcontainers +class GetSecretTokenFileTest : ContainerBase() { + private val getSecretTestLocation = "build/getSecretTokenFileTest" + + @Test + fun testGetSecretTokenFileTask() { + val projectDir = File(getSecretTestLocation) + projectDir.mkdirs() + + projectDir.resolve("settings.gradle.kts").writeText("") + projectDir.resolve(".vault-token").writeText(VAULT_TOKEN) + projectDir.resolve("build.gradle.kts").writeText( + """ +import com.liftric.vault.vault +import com.liftric.vault.GetVaultSecretTask + +plugins { + java + id("com.liftric.vault-client-plugin") +} +vault { + vaultAddress.set("$VAULT_ADDR") + vaultTokenFilePath.set("${projectDir.path}/.vault-token") + maxRetries.set(2) + retryIntervalMilliseconds.set(200) +} +tasks { + val needsSecrets by creating(GetVaultSecretTask::class) { + secretPath.set("secret/example") + doLast { + val secret = secret.get() + if (secret["examplestring"] != "helloworld") throw kotlin.IllegalStateException("examplestring couldn't be read") + if (secret["exampleint"]?.toInt() != 1337) throw kotlin.IllegalStateException("exampleint couldn't be read") + println("getting secret succeeded!") + } + } + val build by existing { + dependsOn(needsSecrets) + } +} + """ + ) + + val result = GradleRunner.create() + .withProjectDir(projectDir) + .withArguments("build") + .withPluginClasspath() + .build() + + assertTrue(result.output.contains("BUILD SUCCESSFUL")) + } +} diff --git a/src/integrationMain/kotlin/com/liftric/vault/testConstants.kt b/src/integrationMain/kotlin/com/liftric/vault/testConstants.kt new file mode 100644 index 0000000..a951f39 --- /dev/null +++ b/src/integrationMain/kotlin/com/liftric/vault/testConstants.kt @@ -0,0 +1,5 @@ +package com.liftric.vault + +const val VAULT_PORT = 8200 +const val VAULT_TOKEN = "myroottoken" +const val VAULT_ADDR = "http://0.0.0.0:8200" \ No newline at end of file diff --git a/src/main/kotlin/com/liftric/vault/GetVaultSecretTask.kt b/src/main/kotlin/com/liftric/vault/GetVaultSecretTask.kt index 8292a11..1e39e6f 100644 --- a/src/main/kotlin/com/liftric/vault/GetVaultSecretTask.kt +++ b/src/main/kotlin/com/liftric/vault/GetVaultSecretTask.kt @@ -53,11 +53,11 @@ open class GetVaultSecretTask : DefaultTask() { @TaskAction fun execute() { val token = determineToken(vaultToken = vaultToken.orNull, vaultTokenFilePath = vaultTokenFilePath.orNull) - val address = determinAddress(vaultAddress = vaultAddress.orNull) + val address = determineAddress(vaultAddress = vaultAddress.orNull) val maxRetries = maxRetries.getOrElse(MAX_RETRIES) val retryIntervalMilliseconds = retryIntervalMilliseconds.getOrElse(RETRY_INTERVAL_MILLI) val path = secretPath.get() - println("[vault] getting `$path` from $address") + println("[vaultFoobar] getting `$path` from $address") secret.set( VaultClient( token = token, @@ -83,7 +83,7 @@ open class GetVaultSecretTask : DefaultTask() { } } - fun determinAddress(vaultAddress: String?): String { + fun determineAddress(vaultAddress: String?): String { val finalVaultAddress = vaultAddress ?: System.getenv()[VAULT_ADDR_ENV] return finalVaultAddress?.trim() ?: error("neither `vaultAddress` nor `$VAULT_ADDR_ENV` env var provided!") } diff --git a/src/main/kotlin/com/liftric/vault/VaultClientPlugin.kt b/src/main/kotlin/com/liftric/vault/VaultClientPlugin.kt index 4447014..6fd1beb 100644 --- a/src/main/kotlin/com/liftric/vault/VaultClientPlugin.kt +++ b/src/main/kotlin/com/liftric/vault/VaultClientPlugin.kt @@ -9,13 +9,11 @@ class VaultClientPlugin : Plugin { override fun apply(project: Project) { val extension = project.extensions.create(extensionName, VaultClientExtension::class.java, project) project.tasks.withType(GetVaultSecretTask::class.java) { - project.afterEvaluate { vaultAddress.set(extension.vaultAddress) vaultToken.set(extension.vaultToken) vaultTokenFilePath.set(extension.vaultTokenFilePath) maxRetries.set(extension.maxRetries) retryIntervalMilliseconds.set(extension.retryIntervalMilliseconds) - } } } } @@ -23,23 +21,4 @@ class VaultClientPlugin : Plugin { fun Project.vault(): VaultClientExtension { return extensions.getByName(extensionName) as? VaultClientExtension ?: throw IllegalStateException("$extensionName is not of the correct type") -} - -fun Project.vault(secretPath: String): Map { - val extension: VaultClientExtension = vault() - val token = GetVaultSecretTask.determineToken( - vaultToken = extension.vaultToken.orNull, - vaultTokenFilePath = extension.vaultTokenFilePath.orNull - ) - val address = GetVaultSecretTask.determinAddress(vaultAddress = extension.vaultAddress.orNull) - val maxRetries = extension.maxRetries.getOrElse(Defaults.MAX_RETRIES) - val retryIntervalMilliseconds = extension.retryIntervalMilliseconds.getOrElse(Defaults.RETRY_INTERVAL_MILLI) - println("[vault] getting `$secretPath` from $address") - - return VaultClient( - token = token, - vaultAddress = address, - maxRetries = maxRetries, - retryIntervalMilliseconds = retryIntervalMilliseconds - ).get(secretPath) -} +} \ No newline at end of file diff --git a/src/test/kotlin/com/liftric/vault/VaultClientPluginTest.kt b/src/test/kotlin/com/liftric/vault/VaultClientPluginTest.kt index 9bd5ce6..175a185 100644 --- a/src/test/kotlin/com/liftric/vault/VaultClientPluginTest.kt +++ b/src/test/kotlin/com/liftric/vault/VaultClientPluginTest.kt @@ -1,28 +1,30 @@ package com.liftric.vault -import junit.framework.TestCase.* import org.gradle.testfixtures.ProjectBuilder -import org.junit.Rule -import org.junit.Test -import org.junit.contrib.java.lang.system.EnvironmentVariables +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path class VaultClientPluginTest { - @get:Rule - val environmentVariables = EnvironmentVariables() + private lateinit var project: org.gradle.api.Project + + @BeforeEach + fun setup(@TempDir tempDir: Path) { + project = ProjectBuilder.builder().withProjectDir(tempDir.toFile()).build() + } @Test fun testApply() { - val project = ProjectBuilder.builder().build() project.pluginManager.apply("com.liftric.vault-client-plugin") assertNotNull(project.plugins.getPlugin(VaultClientPlugin::class.java)) } @Test fun testExtension() { - val project = ProjectBuilder.builder().build() project.pluginManager.apply("com.liftric.vault-client-plugin") assertNotNull(project.vault()) } - -} +} \ No newline at end of file diff --git a/vault.Dockerfile b/vault.Dockerfile new file mode 100644 index 0000000..6f3f397 --- /dev/null +++ b/vault.Dockerfile @@ -0,0 +1,6 @@ +FROM hashicorp/vault:latest +ENV VAULT_DEV_ROOT_TOKEN_ID myroottoken +COPY vault.sh . +RUN chmod +x vault.sh +ENTRYPOINT ["/vault.sh"] +CMD [] diff --git a/vault.docker b/vault.docker deleted file mode 100644 index 966aa05..0000000 --- a/vault.docker +++ /dev/null @@ -1,14 +0,0 @@ -FROM vault -ENV VAULT_DEV_ROOT_TOKEN_ID myroottoken -#RUN /usr/local/bin/docker-entrypoint.sh server -dev & \ -# sleep 1 &&\ -# export VAULT_ADDR='http://0.0.0.0:8200' &&\ -# export VAULT_TOKEN='myroottoken' &&\ -# vault token lookup &&\ -# vault secrets enable -version=2 kv &&\ -# vault kv put secret/example examplestring=helloworld exampleint=1337 &&\ -# vault kv get secret/example -COPY vault.sh . -RUN chmod +x vault.sh -ENTRYPOINT ["/vault.sh"] -CMD []