├── gradle.properties ├── settings.gradle ├── docs └── resources │ ├── summary.png │ └── bamboo_test_results.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .github ├── dependabot.yml └── workflows │ ├── publish.yaml │ ├── build.yaml │ └── codeql-analysis.yml ├── src ├── main │ └── java │ │ └── com │ │ └── bisnode │ │ └── opa │ │ ├── configuration │ │ ├── ExecutableMode.java │ │ ├── OpaExtension.java │ │ ├── DefaultOpaExtension.java │ │ └── OpaPlatform.java │ │ ├── package-info.java │ │ ├── process │ │ ├── ProcessExecutionResult.java │ │ ├── ProcessConfiguration.java │ │ ├── OpaTestProcess.java │ │ └── OpaOutputConsumer.java │ │ ├── StopOpaTask.java │ │ ├── OpaPluginUtils.java │ │ ├── DownloadOpaTask.java │ │ ├── TestRegoCoverageTask.java │ │ ├── OpaPlugin.java │ │ ├── TestRegoTask.java │ │ └── StartOpaTask.java ├── testFunctional │ └── java │ │ └── com │ │ └── bisnode │ │ └── test │ │ ├── OpaPluginFunctionalTestUtils.java │ │ └── PluginFunctionalTest.java └── test │ ├── java │ └── com │ │ └── bisnode │ │ └── opa │ │ ├── OpaPluginTestUtils.java │ │ ├── configuration │ │ └── DefaultOpaConfigurationTest.java │ │ ├── OpaPluginTest.java │ │ ├── StopOpaTaskTest.java │ │ ├── StartOpaTaskTest.java │ │ ├── TestRegoCoverageTaskTest.java │ │ ├── OpaIOTest.java │ │ └── TestRegoTaskTest.java │ └── resources │ └── opa-test-output.json ├── .gitignore ├── CHANGELOG.md ├── gradlew.bat ├── README.md ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── config └── checkstyle │ └── checkstyle.xml ├── gradlew └── LICENSE /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.warning.mode=all -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'opa-gradle-plugin' 2 | 3 | -------------------------------------------------------------------------------- /docs/resources/summary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bisnode/opa-gradle-plugin/HEAD/docs/resources/summary.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bisnode/opa-gradle-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /docs/resources/bamboo_test_results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bisnode/opa-gradle-plugin/HEAD/docs/resources/bamboo_test_results.png -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/configuration/ExecutableMode.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.configuration; 2 | 3 | public enum ExecutableMode { 4 | LOCAL, DOWNLOAD 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/package-info.java: -------------------------------------------------------------------------------- 1 | @ParametersAreNonnullByDefault 2 | package com.bisnode.opa; 3 | 4 | import javax.annotation.ParametersAreNonnullByDefault; 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | .idea_modules/ 4 | /build/ 5 | !gradle-wrapper.jar 6 | .gradletasknamecache 7 | out/ 8 | atlassian-ide-plugin.xml 9 | *.class 10 | *.log 11 | *.jar 12 | *.war 13 | *.nar 14 | *.ear 15 | *.zip 16 | *.tar.gz 17 | *.rar 18 | hs_err_pid* 19 | 20 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/process/ProcessExecutionResult.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.process; 2 | 3 | public class ProcessExecutionResult { 4 | private final String output; 5 | private final int exitCode; 6 | 7 | ProcessExecutionResult(String output, int exitCode) { 8 | this.output = output; 9 | this.exitCode = exitCode; 10 | } 11 | 12 | public String getOutput() { 13 | return output; 14 | } 15 | 16 | public int getExitCode() { 17 | return exitCode; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: publish 2 | on: 3 | push: 4 | tags: 5 | - '[0-9]+.[0-9]+.[0-9]+' 6 | 7 | jobs: 8 | publish: 9 | name: Publish plugin 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up JDK 11 14 | uses: actions/setup-java@v1 15 | with: 16 | java-version: '11.x.x' 17 | - uses: eskatos/gradle-command-action@v1 18 | with: 19 | arguments: publishPlugins -Dgradle.publish.key=${{ secrets.GRADLE_PUBLISH_KEY }} -Dgradle.publish.secret=${{ secrets.GRADLE_PUBLISH_SECRET }} 20 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/configuration/OpaExtension.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.configuration; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | @SuppressWarnings("unused") 6 | public interface OpaExtension { 7 | 8 | ExecutableMode getMode(); 9 | void setMode(ExecutableMode mode); 10 | 11 | String getLocation(); 12 | void setLocation(String location); 13 | 14 | @Nullable String getVersion(); 15 | void setVersion(String version); 16 | 17 | String getSrcDir(); 18 | void setSrcDir(String srcDir); 19 | 20 | String getTestDir(); 21 | void setTestDir(String testDir); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/StopOpaTask.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.DefaultTask; 4 | import org.gradle.api.tasks.TaskAction; 5 | 6 | public class StopOpaTask extends DefaultTask { 7 | 8 | public StopOpaTask() { 9 | setGroup("opa"); 10 | setDescription("Stops the OPA server started by the startOpa task."); 11 | } 12 | 13 | @TaskAction 14 | public void stopOpa() { 15 | boolean result = OpaPluginUtils.stopOpaProcess(getProject()); 16 | if (getLogger().isDebugEnabled()) { 17 | getLogger().debug(result ? "OPA stopped" : "Did not find OPA process to stop or the process is hanging"); 18 | } 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/process/ProcessConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.process; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ProcessConfiguration { 7 | private final String location; 8 | private final String srcLocation; 9 | private final String testSrcLocation; 10 | 11 | public ProcessConfiguration(String location, String srcLocation, String testSrcLocation) { 12 | this.location = location; 13 | this.srcLocation = srcLocation; 14 | this.testSrcLocation = testSrcLocation; 15 | } 16 | 17 | List getCommandArgs() { 18 | return Arrays.asList(location, "test", "--format=json", srcLocation, testSrcLocation); 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return String.join(" ", getCommandArgs()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/testFunctional/java/com/bisnode/test/OpaPluginFunctionalTestUtils.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.test; 2 | 3 | final class OpaPluginFunctionalTestUtils { 4 | 5 | private OpaPluginFunctionalTestUtils() { 6 | } 7 | 8 | static String getRegoPolicy() { 9 | return "package test\n" + 10 | "\n" + 11 | "default allow = false"; 12 | } 13 | 14 | static String getRegoPolicyTest() { 15 | return "package test\n" + 16 | "\n" + 17 | "test_allow_is_false {\n" + 18 | " not allow\n" + 19 | "}"; 20 | } 21 | 22 | static String getRegoPolicyTestFail() { 23 | return "package test\n" + 24 | "\n" + 25 | "test_allow_is_false {\n" + 26 | " allow\n" + 27 | "}"; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: [push] 3 | 4 | jobs: 5 | build: 6 | name: Build plugin 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - name: Set up JDK 11 11 | uses: actions/setup-java@v1 12 | with: 13 | java-version: '11.x.x' 14 | - name: Download opa 15 | run: wget -O opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64 16 | - name: Install opa 17 | run: sudo mv opa /usr/local/bin/ && sudo chmod +x /usr/local/bin/opa 18 | - name: Build plugin 19 | run: ./gradlew build jacocoTestReport 20 | - uses: actions/upload-artifact@v1 21 | with: 22 | name: opa-gradle-plugin 23 | path: build/libs 24 | - uses: codecov/codecov-action@v3.1.4 25 | with: 26 | token: ${{secrets.CODECOV_TOKEN}} 27 | file: ./build/reports/jacoco/test/jacocoTestReport.xml 28 | name: opa-gradle-plugin 29 | 30 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/OpaPluginTestUtils.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | final class OpaPluginTestUtils { 4 | 5 | private OpaPluginTestUtils() { 6 | } 7 | 8 | static String getRegoPolicy() { 9 | return "package test\n" + 10 | "\n" + 11 | "default allow = false"; 12 | } 13 | 14 | static String getRegoPolicyTest() { 15 | return "package test\n" + 16 | "\n" + 17 | "test_allow_is_false {\n" + 18 | " not allow\n" + 19 | "}"; 20 | } 21 | 22 | static String getManyRegoPolicyTests() { 23 | StringBuilder regoTestsBuilder = new StringBuilder(); 24 | for (int i = 0; i < 300; i++) { 25 | regoTestsBuilder.append("\n"); 26 | regoTestsBuilder.append("test_allow_is_false_" + i + " {\n"); 27 | regoTestsBuilder.append(" not allow\n"); 28 | regoTestsBuilder.append("}"); 29 | } 30 | 31 | return "package test\n" + regoTestsBuilder; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/configuration/DefaultOpaConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.configuration; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.testfixtures.ProjectBuilder; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | 10 | public class DefaultOpaConfigurationTest { 11 | 12 | private Project project; 13 | 14 | @BeforeEach 15 | public void before() { 16 | project = ProjectBuilder.builder().build(); 17 | project.getPluginManager().apply("com.bisnode.opa"); 18 | } 19 | 20 | @Test 21 | public void allConfigurationSettingsReturnExpectedValues() { 22 | DefaultOpaExtension configuration = new DefaultOpaExtension(); 23 | 24 | configuration.setLocation("/tmp/location"); 25 | configuration.setSrcDir("/tmp/src"); 26 | configuration.setTestDir("/tmp/test"); 27 | 28 | assertEquals("/tmp/location", configuration.getLocation()); 29 | assertEquals("/tmp/src", configuration.getSrcDir()); 30 | assertEquals("/tmp/test", configuration.getTestDir()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/OpaPluginTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.testfixtures.ProjectBuilder; 5 | 6 | import org.junit.jupiter.api.AfterEach; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertTrue; 11 | 12 | public class OpaPluginTest { 13 | 14 | private Project project; 15 | 16 | @BeforeEach 17 | public void before() { 18 | project = ProjectBuilder.builder().build(); 19 | project.getPluginManager().apply("com.bisnode.opa"); 20 | } 21 | 22 | @AfterEach 23 | public void after() { 24 | OpaPluginUtils.stopOpaProcess(project); 25 | } 26 | 27 | @Test 28 | public void opaPluginAddsOpaStartTaskToProject() { 29 | assertTrue(project.getTasks().getByName("startOpa") instanceof StartOpaTask); 30 | } 31 | 32 | @Test 33 | public void opaPluginAddsOpaStopTaskToProject() { 34 | assertTrue(project.getTasks().getByName("stopOpa") instanceof StopOpaTask); 35 | } 36 | 37 | @Test 38 | public void opaPluginAddsTestRegoTaskToProject() { 39 | assertTrue(project.getTasks().getByName("testRego") instanceof TestRegoTask); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/OpaPluginUtils.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.api.plugins.ExtraPropertiesExtension.UnknownPropertyException; 5 | 6 | import javax.annotation.Nullable; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | final class OpaPluginUtils { 12 | 13 | private OpaPluginUtils() { 14 | } 15 | 16 | static boolean stopOpaProcess(Project project) { 17 | try { 18 | @Nullable Object object = project.getExtensions().getExtraProperties().get("opaProcess"); 19 | if (object instanceof Process) { 20 | Process process = (Process) object; 21 | process.destroy(); 22 | return process.waitFor(5, TimeUnit.SECONDS); 23 | } 24 | } catch (UnknownPropertyException | InterruptedException ignored) { 25 | } 26 | return false; 27 | } 28 | 29 | static String toAbsoluteProjectPath(Project project, String pathComponent) { 30 | Path path = Paths.get(pathComponent); 31 | return path.isAbsolute() ? 32 | path.toString() : 33 | Paths.get(project.getRootDir().getPath(), pathComponent).toString(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/process/OpaTestProcess.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.process; 2 | 3 | import org.gradle.tooling.TestExecutionException; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.util.stream.Collectors; 8 | 9 | public class OpaTestProcess { 10 | 11 | private final File rootDir; 12 | private final ProcessConfiguration command; 13 | 14 | public OpaTestProcess(File rootDir, ProcessConfiguration command) { 15 | this.rootDir = rootDir; 16 | this.command = command; 17 | } 18 | 19 | public ProcessExecutionResult execute() { 20 | try { 21 | Process process = new ProcessBuilder() 22 | .directory(rootDir) 23 | .command(command.getCommandArgs()) 24 | .start(); 25 | 26 | OpaOutputConsumer opaOutputConsumer = new OpaOutputConsumer(process); 27 | opaOutputConsumer.spawn(); 28 | String testResultFromOpa = opaOutputConsumer.readAllLines().stream().collect(Collectors.joining()); 29 | int exitCode = process.waitFor(); 30 | return new ProcessExecutionResult(testResultFromOpa, exitCode); 31 | } catch (IOException | InterruptedException e) { 32 | throw new TestExecutionException("Failed to start OPA process for tests", e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/configuration/DefaultOpaExtension.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.configuration; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | public class DefaultOpaExtension implements OpaExtension { 6 | 7 | private ExecutableMode mode = ExecutableMode.LOCAL; 8 | private String location = "opa"; 9 | @Nullable private String version; 10 | private String srcDir = "src/main/rego"; 11 | private String testDir = "src/test/rego"; 12 | 13 | @Override 14 | public ExecutableMode getMode() { 15 | return mode; 16 | } 17 | 18 | @Override 19 | public void setMode(ExecutableMode mode) { 20 | this.mode = mode; 21 | } 22 | 23 | @Override 24 | public String getLocation() { 25 | return location; 26 | } 27 | 28 | @Override 29 | public void setLocation(String location) { 30 | this.location = location; 31 | } 32 | 33 | @Override 34 | public @Nullable String getVersion() { 35 | return version; 36 | } 37 | 38 | @Override 39 | public void setVersion(String version) { 40 | this.version = version; 41 | } 42 | 43 | @Override 44 | public String getSrcDir() { 45 | return srcDir; 46 | } 47 | 48 | @Override 49 | public void setSrcDir(String srcDir) { 50 | this.srcDir = srcDir; 51 | } 52 | 53 | @Override 54 | public String getTestDir() { 55 | return testDir; 56 | } 57 | 58 | @Override 59 | public void setTestDir(String testDir) { 60 | this.testDir = testDir; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/StopOpaTaskTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.testfixtures.ProjectBuilder; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import javax.annotation.Nullable; 9 | import java.io.IOException; 10 | 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | import static org.junit.jupiter.api.Assertions.assertFalse; 13 | import static org.junit.jupiter.api.Assertions.assertNotNull; 14 | import static org.junit.jupiter.api.Assertions.assertTrue; 15 | 16 | public class StopOpaTaskTest { 17 | 18 | private Project project; 19 | 20 | @BeforeEach 21 | public void before() { 22 | project = ProjectBuilder.builder().build(); 23 | project.getPluginManager().apply("com.bisnode.opa"); 24 | } 25 | 26 | @Test 27 | public void taskIsInOpaGroup() { 28 | StopOpaTask task = (StopOpaTask) project.getTasks().getByName("stopOpa"); 29 | assertEquals("opa", task.getGroup()); 30 | } 31 | 32 | @Test 33 | public void taskStopsOpaProcess() throws IOException { 34 | Process process = new ProcessBuilder().directory(project.getRootDir()).command("opa", "run", "-s").start(); 35 | project.getExtensions().getExtraProperties().set("opaProcess", process); 36 | 37 | assertTrue(process.isAlive()); 38 | 39 | StopOpaTask task = (StopOpaTask) project.getTasks().getByName("stopOpa"); 40 | task.stopOpa(); 41 | 42 | @Nullable Object object = project.getExtensions().getExtraProperties().get("opaProcess"); 43 | assertTrue(object instanceof Process); 44 | Process opaProcess = (Process) object; 45 | 46 | assertNotNull(opaProcess); 47 | assertFalse(opaProcess.isAlive()); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master, ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [master] 9 | schedule: 10 | - cron: '0 6 * * 4' 11 | 12 | jobs: 13 | analyze: 14 | name: Analyze 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v2 20 | with: 21 | # We must fetch at least the immediate parents so that if this is 22 | # a pull request then we can checkout the head. 23 | fetch-depth: 2 24 | 25 | # If this run was triggered by a pull request event, then checkout 26 | # the head of the pull request instead of the merge commit. 27 | - run: git checkout HEAD^2 28 | if: ${{ github.event_name == 'pull_request' }} 29 | 30 | # Initializes the CodeQL tools for scanning. 31 | - name: Initialize CodeQL 32 | uses: github/codeql-action/init@v1 33 | # Override language selection by uncommenting this and choosing your languages 34 | # with: 35 | # languages: go, javascript, csharp, python, cpp, java 36 | 37 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 38 | # If this step fails, then you should remove it and run the build manually (see below) 39 | - name: Autobuild 40 | uses: github/codeql-action/autobuild@v1 41 | 42 | # ℹ️ Command-line programs to run using the OS shell. 43 | # 📚 https://git.io/JvXDl 44 | 45 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 46 | # and modify them (or add more) to build your code if your project 47 | # uses a compiled language 48 | 49 | #- run: | 50 | # make bootstrap 51 | # make release 52 | 53 | - name: Perform CodeQL Analysis 54 | uses: github/codeql-action/analyze@v1 55 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/DownloadOpaTask.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.net.URL; 7 | import java.nio.channels.Channels; 8 | import java.nio.channels.ReadableByteChannel; 9 | 10 | import com.bisnode.opa.configuration.OpaPlatform; 11 | import org.gradle.api.DefaultTask; 12 | import org.gradle.api.file.RegularFileProperty; 13 | import org.gradle.api.provider.Property; 14 | import org.gradle.api.tasks.Input; 15 | import org.gradle.api.tasks.OutputFile; 16 | import org.gradle.api.tasks.TaskAction; 17 | 18 | public abstract class DownloadOpaTask extends DefaultTask { 19 | 20 | public static final String TASK_BASE_NAME = "downloadOpa"; 21 | 22 | @Input 23 | public abstract Property getVersion(); 24 | 25 | @OutputFile 26 | public abstract RegularFileProperty getOutputFile(); 27 | 28 | public DownloadOpaTask() { 29 | setGroup("opa"); 30 | setDescription("Download OPA"); 31 | } 32 | 33 | @TaskAction 34 | public void downloadOpa() throws IOException { 35 | final String downloadUrl = OpaPlatform.getPlatform().getDownloadUrl(getVersion().get()); 36 | getLogger().info("Retrieving OPA executable from " + downloadUrl); 37 | final File targetFile = getOutputFile().getAsFile().get(); 38 | getLogger().info("Saving OPA executable to " + targetFile.getAbsolutePath()); 39 | try (FileOutputStream output = new FileOutputStream(targetFile); 40 | ReadableByteChannel input = Channels.newChannel(new URL(downloadUrl).openStream())) { 41 | output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); 42 | } 43 | if (!targetFile.setReadable(true) || !targetFile.setExecutable(true)) { 44 | throw new IllegalStateException("Unable to set permissions on OPA executable"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/configuration/OpaPlatform.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.configuration; 2 | 3 | import java.nio.file.Path; 4 | 5 | public enum OpaPlatform { 6 | 7 | MAC_OS_AMD64("darwin_amd64", ""), 8 | LINUX_AMD64("linux_amd64_static", ""), 9 | WINDOWS_AMD64("windows_amd64", ".exe"); 10 | 11 | private final String platformQualifier; 12 | private final String executableExtension; 13 | 14 | OpaPlatform(final String platformQualifier, final String executableExtension) { 15 | this.platformQualifier = platformQualifier; 16 | this.executableExtension = executableExtension; 17 | } 18 | 19 | public String getDownloadUrl(final String opaVersion) { 20 | return String.format("https://openpolicyagent.org/downloads/v%s/opa_%s%s", 21 | opaVersion, 22 | platformQualifier, 23 | executableExtension); 24 | } 25 | 26 | public Path getExecutablePath(final Path rootPath, final String version) { 27 | return rootPath.resolve("opa").resolve(version).resolve(String.format("opa%s", executableExtension)); 28 | } 29 | 30 | public static OpaPlatform getPlatform() { 31 | final String osName = System.getProperty("os.name"); 32 | final String osArch = System.getProperty("os.arch"); 33 | if (osName.contains("win")) { 34 | if (osArch.equals("amd64")) { 35 | return WINDOWS_AMD64; 36 | } 37 | } else if (osName.contains("Mac")) { 38 | if (osArch.equals("x86_64") || osArch.equals("aarch64")) { 39 | return MAC_OS_AMD64; 40 | } 41 | } else if (osName.contains("Linux")) { 42 | if (osArch.equals("amd64")) { 43 | return LINUX_AMD64; 44 | } 45 | } 46 | throw new IllegalStateException(String.format("Unsupported combination of OS/arch: %s/%s", 47 | osName, 48 | osArch)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/StartOpaTaskTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.configuration.OpaExtension; 4 | import org.gradle.api.Project; 5 | import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder; 6 | import org.gradle.testfixtures.ProjectBuilder; 7 | import org.junit.jupiter.api.AfterEach; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | 11 | import javax.annotation.Nullable; 12 | import java.io.IOException; 13 | import java.util.Objects; 14 | 15 | import static org.junit.jupiter.api.Assertions.assertEquals; 16 | import static org.junit.jupiter.api.Assertions.assertTrue; 17 | 18 | public class StartOpaTaskTest { 19 | 20 | private Project project; 21 | 22 | @BeforeEach 23 | public void before() { 24 | project = ProjectBuilder.builder().build(); 25 | project.getPluginManager().apply("com.bisnode.opa"); 26 | } 27 | 28 | @AfterEach 29 | public void after() { 30 | OpaPluginUtils.stopOpaProcess(project); 31 | } 32 | 33 | @Test 34 | public void taskIsInOpaGroup() { 35 | StartOpaTask task = (StartOpaTask) project.getTasks().getByName("startOpa"); 36 | assertEquals("opa", task.getGroup()); 37 | } 38 | 39 | @Test 40 | public void opaPluginStartTaskSavesProcessInExtProperties() throws IOException { 41 | OpaExtension extension = Objects.requireNonNull(project.getExtensions().findByType( 42 | OpaExtension.class), "opa extension"); 43 | extension.setSrcDir(getPathToTmpFolder()); 44 | 45 | StartOpaTask startOpaTask = (StartOpaTask) project.getTasks().getByName("startOpa"); 46 | startOpaTask.startOpa(); 47 | 48 | @Nullable Object object = project.getExtensions().getExtraProperties().get("opaProcess"); 49 | assertTrue(object instanceof Process); 50 | } 51 | 52 | private String getPathToTmpFolder() throws IOException { 53 | TemporaryFolder tmpdir = new TemporaryFolder(); 54 | tmpdir.create(); 55 | return tmpdir.getRoot().getAbsolutePath(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | [//]: # (## [Unreleased]) 8 | [//]: # (### Added) 9 | [//]: # (### Changed) 10 | [//]: # (### Removed) 11 | 12 | ## [0.3.1] - 2020-11-23 13 | ### Changed 14 | - GH-28 OPA process' output is now consumed and logged on info level, so the subprocess doesn't hang anymore 15 | - startOpa task now waits for OPA server to initialize 16 | - enabled test in `StopOpaTaskTest` 17 | - for now, tests rely on `opa` in `$PATH` 18 | 19 | ## [0.3.0] - 2020-07-16 20 | ### Added 21 | - GH-15 Make testRego task output `opa -v`-like summary when invoked with `--info` 22 | 23 | ### Changed 24 | - Refactor TestRegoTask 25 | - GH-18 Use dedicated library to output JUnit XML 26 | 27 | ## [0.2.1] - 2020-06-14 28 | ### Changed 29 | - GH-14 Fix "Failed to read input stream" bug that was triggered on non-empty test-results directory. 30 | 31 | ## [0.2.0] - 2020-06-09 32 | ### Changed 33 | - Complete rewrite of the `testRego` task, now not just failing the build on test failures or errors but actually translating the test results into formats recognizable both by Gradle and by CI/CD systems by exporing the test results into JUnit XML reports. This allows for OPA/Rego tests to be both tested and reported like any other Gradle tests. 34 | - Task configuration may now override "base" configuration (like `srcDir` and `testDir`) on a per task basis. 35 | - Tons of internal improvements, tests and fixes. 36 | 37 | ## [0.1.1] - 2019-11-14 38 | ### Added 39 | - Install/usage instructions to README now that plugin has been approved for 40 | [plugin.gradle.org](https://plugins.gradle.org/plugin/com.bisnode.opa). 41 | 42 | ### Changed 43 | - Fixed `opa` configuration object which would always use default values regardless of provided config. 44 | 45 | ## [0.1.0] - 2019-11-13 46 | ### Added 47 | - First release, including task `testRego`, `testRegoCoverage`, `startOpa`, `stopOpa`. 48 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/TestRegoCoverageTaskTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.api.Task; 5 | import org.gradle.testfixtures.ProjectBuilder; 6 | 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import java.io.ByteArrayInputStream; 11 | import java.io.File; 12 | import java.io.IOException; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | 16 | import static com.bisnode.opa.OpaPluginTestUtils.getRegoPolicy; 17 | import static com.bisnode.opa.OpaPluginTestUtils.getRegoPolicyTest; 18 | import static com.bisnode.opa.OpaPluginUtils.toAbsoluteProjectPath; 19 | import static java.nio.charset.StandardCharsets.UTF_8; 20 | import static org.junit.jupiter.api.Assertions.assertTrue; 21 | import static org.junit.jupiter.api.Assertions.assertEquals; 22 | 23 | public class TestRegoCoverageTaskTest { 24 | 25 | private Project project; 26 | 27 | @BeforeEach 28 | public void before() { 29 | project = ProjectBuilder.builder().build(); 30 | project.getPluginManager().apply("com.bisnode.opa"); 31 | } 32 | 33 | @Test 34 | public void canAddTaskToProject() { 35 | Task task = project.getTasks().getByName("testRegoCoverage"); 36 | assertTrue(task instanceof TestRegoCoverageTask); 37 | } 38 | 39 | @Test 40 | public void taskIsInOpaGroup() { 41 | TestRegoCoverageTask task = (TestRegoCoverageTask) project.getTasks().getByName("testRegoCoverage"); 42 | assertEquals("opa", task.getGroup()); 43 | } 44 | 45 | @Test 46 | public void taskGeneratesTestReport() throws IOException { 47 | TestRegoCoverageTask task = (TestRegoCoverageTask) project.getTasks().getByName("testRegoCoverage"); 48 | 49 | Path tmpDir = Files.createTempDirectory("rego"); 50 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), tmpDir.resolve("policy.rego")); 51 | Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), tmpDir.resolve("policy_test.rego")); 52 | 53 | task.setSrcDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 54 | task.setTestDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 55 | task.testRegoCoverage(); 56 | 57 | String reportFile = project.getRootDir() + "/build/reports/opa/opa-coverage.json"; 58 | assertTrue(new File(reportFile).exists()); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/process/OpaOutputConsumer.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.process; 2 | 3 | import org.gradle.api.logging.Logger; 4 | import org.gradle.api.logging.Logging; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.concurrent.BlockingQueue; 12 | import java.util.concurrent.LinkedBlockingQueue; 13 | 14 | import static java.nio.charset.StandardCharsets.UTF_8; 15 | 16 | // GH-47 17 | public class OpaOutputConsumer { 18 | 19 | private static final String POISON_PILL = "DONE_CONSUMING_OUTPUT"; 20 | private static final Logger log = Logging.getLogger(OpaOutputConsumer.class); 21 | 22 | private final Process opaProcess; 23 | private final BlockingQueue outputFromProcess; 24 | 25 | public OpaOutputConsumer(Process opaProcess) { 26 | this.opaProcess = opaProcess; 27 | this.outputFromProcess = new LinkedBlockingQueue<>(); 28 | } 29 | 30 | /** 31 | * Consumes OPA output in another thread and enqueues each consumed line into a queue. 32 | */ 33 | public void spawn() { 34 | new Thread(() -> { 35 | try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this.opaProcess.getInputStream(), UTF_8))) { 36 | String line; 37 | while ((line = bufferedReader.readLine()) != null) { 38 | outputFromProcess.put(line); 39 | } 40 | outputFromProcess.put(POISON_PILL); 41 | } catch (IOException e) { 42 | if (!"Stream closed".equals(e.getMessage())) { 43 | log.warn("IOException while reading OPA's stdout", e); 44 | } 45 | } catch (InterruptedException e) { 46 | log.error("Unable to read from OPA's stdout", e); 47 | } 48 | }).start(); 49 | } 50 | 51 | /** 52 | * Reads the next output line from OPA 53 | * 54 | * @return Next output line from OPA, or null if there's no more output 55 | */ 56 | public String readLine() { 57 | try { 58 | String line = outputFromProcess.take(); 59 | if (line.equals(POISON_PILL)) { 60 | return null; 61 | } 62 | return line; 63 | } catch (InterruptedException e) { 64 | log.error("Unable to read from OPA output buffer", e); 65 | } 66 | return null; 67 | } 68 | 69 | /** 70 | * Reads all output line from OPA, blocks until the OPA process ends the stream 71 | * 72 | * @return All outputs lines from OPA 73 | */ 74 | public List readAllLines() { 75 | List allOutput = new ArrayList<>(); 76 | String line; 77 | while ((line = readLine()) != null) { 78 | allOutput.add(line); 79 | } 80 | return allOutput; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/TestRegoCoverageTask.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.configuration.OpaExtension; 4 | import org.gradle.api.DefaultTask; 5 | import org.gradle.api.tasks.InputDirectory; 6 | import org.gradle.api.tasks.TaskAction; 7 | 8 | import javax.annotation.Nullable; 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.nio.file.Files; 13 | import java.nio.file.Paths; 14 | import java.util.Arrays; 15 | import java.util.List; 16 | import java.util.Objects; 17 | import java.util.Optional; 18 | 19 | import static java.nio.charset.StandardCharsets.UTF_8; 20 | 21 | public abstract class TestRegoCoverageTask extends DefaultTask { 22 | 23 | public TestRegoCoverageTask() { 24 | setGroup("opa"); 25 | setDescription( 26 | "Run OPA tests in testDir of any policies provided in srcDir, saving the coverage report from the run." 27 | ); 28 | } 29 | 30 | @Nullable 31 | private String srcDir; 32 | @Nullable 33 | private String testDir; 34 | 35 | @TaskAction 36 | public void testRegoCoverage() { 37 | OpaExtension extension = Objects.requireNonNull(getProject().getExtensions().findByType( 38 | OpaExtension.class), "opa extension"); 39 | String location = extension.getLocation(); 40 | 41 | String src = Optional.ofNullable(srcDir).orElse(extension.getSrcDir()); 42 | String test = Optional.ofNullable(testDir).orElse(extension.getTestDir()); 43 | 44 | List command = Arrays.asList(location, "test", src, test, "--coverage"); 45 | 46 | try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { 47 | getProject().exec(execSpec -> { 48 | getLogger().debug("Running command {}", String.join(" ", command)); 49 | execSpec.commandLine(command); 50 | execSpec.setStandardOutput(outputStream); 51 | }); 52 | 53 | String opaReportsPath = getProject().getBuildDir() + "/reports/opa"; 54 | String output = new String(outputStream.toByteArray(), UTF_8); 55 | if (new File(opaReportsPath).mkdirs()) { 56 | Files.write(Paths.get(opaReportsPath + "/opa-coverage.json"), output.getBytes(UTF_8)); 57 | } 58 | } catch (IOException e) { 59 | getLogger().error("Failed writing coverage report", e); 60 | throw new RuntimeException(e); 61 | } 62 | } 63 | 64 | @InputDirectory 65 | public String getSrcDir() { 66 | return Optional.ofNullable(srcDir) 67 | .orElse(getProject().getExtensions().getByType(OpaExtension.class).getSrcDir()); 68 | } 69 | 70 | @InputDirectory 71 | public String getTestDir() { 72 | return Optional.ofNullable(testDir) 73 | .orElse(getProject().getExtensions().getByType(OpaExtension.class).getTestDir()); 74 | } 75 | 76 | public void setSrcDir(String srcDir) { 77 | this.srcDir = srcDir; 78 | } 79 | 80 | public void setTestDir(String testDir) { 81 | this.testDir = testDir; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/OpaIOTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.configuration.OpaExtension; 4 | import org.gradle.api.Project; 5 | import org.gradle.internal.impldep.org.apache.http.client.methods.CloseableHttpResponse; 6 | import org.gradle.internal.impldep.org.apache.http.client.methods.HttpGet; 7 | import org.gradle.internal.impldep.org.apache.http.impl.client.CloseableHttpClient; 8 | import org.gradle.internal.impldep.org.apache.http.impl.client.HttpClients; 9 | import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder; 10 | import org.gradle.testfixtures.ProjectBuilder; 11 | import org.junit.jupiter.api.AfterEach; 12 | import org.junit.jupiter.api.BeforeEach; 13 | import org.junit.jupiter.api.Test; 14 | 15 | import javax.annotation.Nullable; 16 | import java.io.BufferedReader; 17 | import java.io.IOException; 18 | import java.io.InputStreamReader; 19 | import java.util.Objects; 20 | 21 | import static org.junit.jupiter.api.Assertions.assertFalse; 22 | import static org.junit.jupiter.api.Assertions.assertNotNull; 23 | import static org.junit.jupiter.api.Assertions.assertTrue; 24 | 25 | public class OpaIOTest { 26 | private Project project; 27 | 28 | @BeforeEach 29 | public void before() { 30 | project = ProjectBuilder.builder().build(); 31 | project.getPluginManager().apply("com.bisnode.opa"); 32 | } 33 | 34 | @AfterEach 35 | public void after() { 36 | OpaPluginUtils.stopOpaProcess(project); 37 | } 38 | 39 | //GH-28 40 | @Test 41 | void shouldNotHangOnOPAOutputBufferOverflow() throws IOException { 42 | //given 43 | OpaExtension extension = Objects.requireNonNull(project.getExtensions().findByType( 44 | OpaExtension.class), "opa extension"); 45 | extension.setSrcDir(getPathToTmpFolder()); 46 | 47 | StartOpaTask startOpaTask = (StartOpaTask) project.getTasks().getByName("startOpa"); 48 | //when 49 | startOpaTask.startOpa(); 50 | // Trial and error has shown that output buffer overflows after ~160 calls 51 | try (CloseableHttpClient client = HttpClients.createDefault()) { 52 | for (int i = 0; i < 170; i++) executeCallToOPA(client); 53 | } 54 | StopOpaTask task = (StopOpaTask) project.getTasks().getByName("stopOpa"); 55 | task.stopOpa(); 56 | //then 57 | @Nullable Object object = project.getExtensions().getExtraProperties().get("opaProcess"); 58 | assertTrue(object instanceof Process); 59 | Process opaProcess = (Process) object; 60 | assertNotNull(opaProcess); 61 | assertFalse(opaProcess.isAlive()); 62 | } 63 | 64 | private String getPathToTmpFolder() throws IOException { 65 | TemporaryFolder tmpdir = new TemporaryFolder(); 66 | tmpdir.create(); 67 | return tmpdir.getRoot().getAbsolutePath(); 68 | } 69 | 70 | private void executeCallToOPA(CloseableHttpClient client) throws IOException { 71 | CloseableHttpResponse execute = client.execute(new HttpGet("http://localhost:8181/api/v1/data/example")); 72 | // This output also has to be consumed to avoid hanging 73 | try (BufferedReader br = new BufferedReader(new InputStreamReader(execute.getEntity().getContent()))) { 74 | while (br.readLine() != null) { 75 | // noop 76 | } 77 | } 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/OpaPlugin.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.HashSet; 6 | import java.util.List; 7 | import java.util.Set; 8 | 9 | import com.bisnode.opa.configuration.DefaultOpaExtension; 10 | import com.bisnode.opa.configuration.ExecutableMode; 11 | import com.bisnode.opa.configuration.OpaExtension; 12 | import com.bisnode.opa.configuration.OpaPlatform; 13 | import org.gradle.api.Plugin; 14 | import org.gradle.api.Project; 15 | import org.gradle.api.Task; 16 | import org.gradle.api.tasks.TaskContainer; 17 | import org.gradle.api.tasks.TaskProvider; 18 | 19 | @SuppressWarnings("unused") 20 | public class OpaPlugin implements Plugin { 21 | 22 | @Override 23 | public void apply(Project project) { 24 | project.getExtensions().create(OpaExtension.class, "opa", DefaultOpaExtension.class); 25 | 26 | TaskContainer tasks = project.getTasks(); 27 | List addedTasks = new ArrayList<>(); 28 | addedTasks.add(tasks.create("startOpa", StartOpaTask.class)); 29 | addedTasks.add(tasks.create("stopOpa", StopOpaTask.class)); 30 | addedTasks.add(tasks.create("testRego", TestRegoTask.class)); 31 | addedTasks.add(tasks.create("testRegoCoverage", TestRegoCoverageTask.class)); 32 | 33 | project.afterEvaluate(currentProject -> applyToRootProject(currentProject, addedTasks)); 34 | } 35 | 36 | private void applyToRootProject(Project project, List dependentTasks) { 37 | OpaExtension opaExtension = project.getExtensions().findByType(OpaExtension.class); 38 | if (opaExtension == null) { 39 | return; 40 | } 41 | if (!ExecutableMode.DOWNLOAD.equals(opaExtension.getMode())) { 42 | return; 43 | } 44 | String version = opaExtension.getVersion(); 45 | if (version == null || version.trim().isEmpty()) { 46 | throw new IllegalStateException("You must specify OPA version in DOWNLOAD mode"); 47 | } 48 | 49 | // When the current plugin is executed in a subproject, 50 | // the root project may (or may not) have been executed. 51 | // We need different strategies to apply depending on root project state 52 | Project rootProject = project.getRootProject(); 53 | if (rootProject.getState().getExecuted()) { 54 | applyDownloadTask(rootProject, version, dependentTasks); 55 | } else { 56 | rootProject.afterEvaluate(root -> applyDownloadTask(root, version, dependentTasks)); 57 | } 58 | } 59 | 60 | private synchronized void applyDownloadTask(Project project, String version, List dependentTasks) { 61 | final String taskName = String.format("%s_%s", DownloadOpaTask.TASK_BASE_NAME, version); 62 | final File opaExecutable = OpaPlatform.getPlatform().getExecutablePath(project.getBuildDir().toPath(), version).toFile(); 63 | Set downloadTasks = project.getTasksByName(taskName, false); 64 | if (downloadTasks.isEmpty()) { 65 | final TaskProvider downloadTask = project.getTasks().register(taskName, DownloadOpaTask.class); 66 | downloadTask.configure(task -> { 67 | task.getVersion().set(version); 68 | task.getOutputFile().set(opaExecutable); 69 | }); 70 | downloadTasks = new HashSet<>(); 71 | downloadTasks.add(downloadTask.get()); 72 | } 73 | downloadTasks.forEach(downloadTask -> dependentTasks.forEach(task -> { 74 | task.dependsOn(downloadTask); 75 | final OpaExtension opaExtension = task.getExtensions().findByType(OpaExtension.class); 76 | if (opaExtension != null) { 77 | opaExtension.setLocation(opaExecutable.getParent()); 78 | } 79 | })); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/com/bisnode/opa/TestRegoTaskTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import org.gradle.api.Project; 4 | import org.gradle.api.Task; 5 | import org.gradle.testfixtures.ProjectBuilder; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.io.ByteArrayInputStream; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.nio.file.Files; 13 | import java.nio.file.Path; 14 | import java.time.Duration; 15 | 16 | import static com.bisnode.opa.OpaPluginTestUtils.getManyRegoPolicyTests; 17 | import static com.bisnode.opa.OpaPluginTestUtils.getRegoPolicy; 18 | import static com.bisnode.opa.OpaPluginTestUtils.getRegoPolicyTest; 19 | import static com.bisnode.opa.OpaPluginUtils.toAbsoluteProjectPath; 20 | import static java.nio.charset.StandardCharsets.UTF_8; 21 | import static org.junit.jupiter.api.Assertions.assertEquals; 22 | import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; 23 | import static org.junit.jupiter.api.Assertions.assertTrue; 24 | 25 | public class TestRegoTaskTest { 26 | 27 | private Project project; 28 | 29 | @BeforeEach 30 | public void before() { 31 | project = ProjectBuilder.builder().build(); 32 | project.getPluginManager().apply("com.bisnode.opa"); 33 | } 34 | 35 | @Test 36 | public void canAddTaskToProject() { 37 | Task task = project.getTasks().getByName("testRego"); 38 | assertTrue(task instanceof TestRegoTask); 39 | } 40 | 41 | @Test 42 | public void taskIsInOpaGroup() { 43 | TestRegoTask task = (TestRegoTask) project.getTasks().getByName("testRego"); 44 | assertEquals("opa", task.getGroup()); 45 | } 46 | 47 | @Test 48 | public void opaPluginStartTestTaskSaves() throws IOException { 49 | TestRegoTask task = (TestRegoTask) project.getTasks().getByName("testRego"); 50 | 51 | Path tmpDir = Files.createTempDirectory("rego"); 52 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), tmpDir.resolve("policy.rego")); 53 | Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), tmpDir.resolve("policy_test.rego")); 54 | 55 | task.setSrcDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 56 | task.setTestDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 57 | 58 | task.testRego(); 59 | 60 | String targetReport = project.getBuildDir().getAbsolutePath() + "/test-results/opa/TEST-opa-tests.xml"; 61 | 62 | assertTrue(new File(targetReport).exists()); 63 | } 64 | 65 | @Test 66 | public void taskUsesDefaultSrcDirIfNoneProvided() { 67 | TestRegoTask task = (TestRegoTask) project.getTasks().getByName("testRego"); 68 | 69 | assertEquals("src/main/rego", task.getSrcDir()); 70 | } 71 | 72 | @Test 73 | public void taskUsesDefaultTestDirIfNoneProvided() { 74 | TestRegoTask task = (TestRegoTask) project.getTasks().getByName("testRego"); 75 | 76 | assertEquals("src/test/rego", task.getTestDir()); 77 | } 78 | 79 | 80 | @Test 81 | public void opaPluginStartTestTaskShouldNotHangForManyPolicyTests() throws IOException { 82 | TestRegoTask task = (TestRegoTask) project.getTasks().getByName("testRego"); 83 | 84 | Path tmpDir = Files.createTempDirectory("rego"); 85 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), tmpDir.resolve("policy.rego")); 86 | Files.copy(new ByteArrayInputStream(getManyRegoPolicyTests().getBytes(UTF_8)), tmpDir.resolve("policy_test.rego")); 87 | 88 | task.setSrcDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 89 | task.setTestDir(toAbsoluteProjectPath(project, tmpDir.toAbsolutePath().toString())); 90 | 91 | assertTimeoutPreemptively(Duration.ofSeconds(10), () -> { 92 | task.testRego(); 93 | }); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open Policy Agent plugin for Gradle 2 | ![](https://github.com/Bisnode/opa-gradle-plugin/workflows/build/badge.svg) 3 | [![Total alerts](https://img.shields.io/lgtm/alerts/g/Bisnode/opa-gradle-plugin.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Bisnode/opa-gradle-plugin/alerts/) 4 | [![Language grade: Java](https://img.shields.io/lgtm/grade/java/g/Bisnode/opa-gradle-plugin.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Bisnode/opa-gradle-plugin/context:java) 5 | [![codecov](https://codecov.io/gh/Bisnode/opa-gradle-plugin/branch/master/graph/badge.svg)](https://codecov.io/gh/Bisnode/opa-gradle-plugin) 6 | [![Version](https://img.shields.io/maven-metadata/v/https/plugins.gradle.org/m2/com/bisnode/opa/opa-gradle-plugin/maven-metadata.xml.svg?label=gradle)](https://plugins.gradle.org/plugin/com.bisnode.opa) 7 | 8 | Plugin adding various tasks to help out integrating Open Policy Agent (OPA) in Gradle builds. 9 | 10 | ## Install 11 | 12 | Simply add the plugin to your build.gradle `plugins` declaration: 13 | 14 | [![Version](https://img.shields.io/maven-metadata/v/https/plugins.gradle.org/m2/com/bisnode/opa/opa-gradle-plugin/maven-metadata.xml.svg?label=gradle)](https://plugins.gradle.org/plugin/com.bisnode.opa) 15 | 16 | ``` 17 | plugins { 18 | id 'com.bisnode.opa' version '' 19 | } 20 | ``` 21 | For legacy versions of Gradle, see instructions in the 22 | [Gradle plugin directory](https://plugins.gradle.org/plugin/com.bisnode.opa). 23 | 24 | **Prerequisites**: OPA installed on same machine as the tasks are run, either on `$PATH` or pointed out by the 25 | `location` configuration attribute (see Configuration below). 26 | 27 | ## Configuration 28 | 29 | The following configuration properties are made available by the plugin: 30 | ``` 31 | opa { 32 | location = 'path/opa/executable' // default: use opa on $PATH 33 | srcDir = 'path/to/rego/src' // default: src/main/rego 34 | testDir = 'path/to/rego/tests/' // default: src/test/rego 35 | } 36 | ``` 37 | 38 | ## Tasks 39 | 40 | The plugin adds the following tasks: 41 | * `testRego` - Runs `opa test {srcDir} {testDir}` (see below). 42 | * `testRegoCoverage` - Runs `opa test {srcDir} {testDir} --coverage` saving report in `build/report/opa` directory. 43 | * `startOpa` - Start OPA in background for subsequent tasks like integration tests. 44 | * `stopOpa` - Stop OPA process started by `startOpa`. 45 | 46 | ### testRego 47 | 48 | The `testRego` task runs the unit tests found in `testDir` with all policies provided in `srcDir`. If not provided, 49 | these directories default to `src/main/rego` (rego policies) and `src/test/rego` (rego tests) respectively. 50 | 51 | When invoked with `--info` output similar to `--info` is printed to console. 52 | 53 | Example: 54 | ![Example testRego output](docs/resources/summary.png?raw=true) 55 | 56 | #### JUnit XML test results 57 | 58 | The `testRego` task automatically converts the OPA test command output into JUnit XML and writes the output to the 59 | `build/tests-results/opa` directory. This enables any tool or system (such as CI/CD servers) that knows how to parse 60 | JUnit test results to include the OPA test results when handling test outcomes, like when compiling test reports. 61 | 62 | Example test report output in Atlassian Bamboo: 63 | ![Example test report output](docs/resources/bamboo_test_results.png?raw=true) 64 | 65 | ### Run Rego tests 66 | 67 | To integrate policy tests into your regular Gradle pipeline you may add the `testRego` and/or `testRegoCoverage` tasks 68 | as dependencies of the `check` task: 69 | ``` 70 | check.dependsOn(testRego, testRegoCoverage) 71 | ``` 72 | 73 | ### Run OPA for integration tests 74 | 75 | Just start/stop OPA before/after your test suite like this: 76 | ``` 77 | integrationTest.dependsOn startOpa 78 | integrationTest.finalizedBy stopOpa 79 | ``` 80 | 81 | ## Contribution 82 | 83 | Interested in contributing? Please, start by reading [this document](https://github.com/Bisnode/opa-gradle-plugin/blob/master/CONTRIBUTING.md). 84 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/TestRegoTask.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.configuration.OpaExtension; 4 | import com.bisnode.opa.process.OpaTestProcess; 5 | import com.bisnode.opa.process.ProcessConfiguration; 6 | import com.bisnode.opa.process.ProcessExecutionResult; 7 | import com.bisnode.opa.testformats.junit.JUnitXml; 8 | import com.bisnode.opa.testformats.opa.OpaVerboseSummary; 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import org.gradle.api.DefaultTask; 11 | import org.gradle.api.tasks.InputDirectory; 12 | import org.gradle.api.tasks.TaskAction; 13 | import org.gradle.tooling.TestExecutionException; 14 | 15 | import javax.annotation.Nullable; 16 | import java.io.IOException; 17 | import java.nio.file.Files; 18 | import java.nio.file.Path; 19 | import java.nio.file.Paths; 20 | import java.util.Optional; 21 | 22 | public class TestRegoTask extends DefaultTask { 23 | 24 | public TestRegoTask() { 25 | setGroup("opa"); 26 | setDescription("Run OPA tests in testDir of any policies provided in srcDir"); 27 | } 28 | 29 | @Nullable 30 | private String srcDir; 31 | @Nullable 32 | private String testDir; 33 | 34 | @TaskAction 35 | public void testRego() { 36 | ProcessConfiguration processConfiguration = new ProcessConfiguration(getLocation(), getSrcDir(), getTestDir()); 37 | getLogger().debug("Running command {}", processConfiguration); 38 | ProcessExecutionResult processExecutionResult = new OpaTestProcess(getProject().getRootDir(), processConfiguration).execute(); 39 | 40 | writeToFile(testResultsPath(), asJUnitXml(processExecutionResult)); 41 | 42 | getLogger().info(asOpaVerbose(processExecutionResult)); 43 | 44 | if (processExecutionResult.getExitCode() != 0) { 45 | throw new TestExecutionException(processExecutionResult.getOutput()); 46 | } 47 | } 48 | 49 | private Path testResultsPath() { 50 | return Paths.get(getProject().getBuildDir().getAbsolutePath() + "/test-results/opa/TEST-opa-tests.xml"); 51 | } 52 | 53 | private void writeToFile(Path filePath, String output) { 54 | try { 55 | Files.createDirectories(filePath.getParent()); 56 | Files.write(filePath, output.getBytes()); 57 | } catch (IOException e) { 58 | throw new TestExecutionException("Could not write to file " + filePath.toString(), e); 59 | } 60 | } 61 | 62 | private String asOpaVerbose(ProcessExecutionResult processExecutionResult) { 63 | try { 64 | OpaTestResults opaTestResults = OpaTestResults.fromJson(processExecutionResult.getOutput()); 65 | return OpaVerboseSummary.of(opaTestResults).summary(); 66 | } catch (JsonProcessingException e) { 67 | throw new TestExecutionException("Could not parse test command output", e); 68 | } 69 | } 70 | 71 | private String asJUnitXml(ProcessExecutionResult processExecutionResult) { 72 | try { 73 | OpaTestResults opaTestResults = OpaTestResults.fromJson(processExecutionResult.getOutput()); 74 | return JUnitXml.from(opaTestResults).asXmlString(); 75 | } catch (JsonProcessingException e) { 76 | throw new TestExecutionException("Could not parse test command output", e); 77 | } 78 | } 79 | 80 | @InputDirectory 81 | public String getSrcDir() { 82 | return Optional.ofNullable(srcDir) 83 | .orElse(getProject().getExtensions().getByType(OpaExtension.class).getSrcDir()); 84 | } 85 | 86 | @InputDirectory 87 | public String getTestDir() { 88 | return Optional.ofNullable(testDir) 89 | .orElse(getProject().getExtensions().getByType(OpaExtension.class).getTestDir()); 90 | } 91 | 92 | private String getLocation() { 93 | return getProject().getExtensions().getByType(OpaExtension.class).getLocation(); 94 | } 95 | 96 | public void setSrcDir(String srcDir) { 97 | this.srcDir = srcDir; 98 | } 99 | 100 | public void setTestDir(String testDir) { 101 | this.testDir = testDir; 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/StartOpaTask.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.configuration.OpaExtension; 4 | import com.bisnode.opa.process.OpaOutputConsumer; 5 | import org.gradle.api.DefaultTask; 6 | import org.gradle.api.tasks.TaskAction; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.io.InputStreamReader; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.Objects; 15 | import java.util.concurrent.CountDownLatch; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.stream.Collectors; 18 | 19 | import static java.nio.charset.StandardCharsets.UTF_8; 20 | 21 | public class StartOpaTask extends DefaultTask { 22 | 23 | public StartOpaTask() { 24 | setGroup("opa"); 25 | setDescription( 26 | "Starts OPA in background to allow for subsequent tasks to query it (for integration tests or such). " + 27 | "NOTE that you'll need to run the opaStop task to stop OPA after starting it with this task." 28 | ); 29 | } 30 | 31 | @TaskAction 32 | public void startOpa() { 33 | OpaExtension extension = Objects.requireNonNull(getProject().getExtensions().findByType( 34 | OpaExtension.class), "opa extension"); 35 | String location = extension.getLocation(); 36 | String srcDir = extension.getSrcDir(); 37 | 38 | String srcAbsolutePath = OpaPluginUtils.toAbsoluteProjectPath(getProject(), srcDir); 39 | getLogger().debug("Starting OPA from {} with srcDir set to {}", "opa".equals(location) ? "$PATH" : location, srcDir); 40 | Process process = runProcess(getProject().getRootDir(), buildCommand(location, srcAbsolutePath)); 41 | 42 | storeOpaProcessInProject(process); 43 | OpaOutputConsumer outputConsumer = new OpaOutputConsumer(process); 44 | waitForOpaInit(outputConsumer); 45 | } 46 | 47 | private List buildCommand(String location, String srcAbsolutePath) { 48 | getLogger().debug("Absolute path of src directory determined to be {}", srcAbsolutePath); 49 | return Arrays.asList(location, "run", "-s", srcAbsolutePath); 50 | } 51 | 52 | private Process runProcess(File rootDir, List command) { 53 | getLogger().debug("Running command {}", String.join(" ", command)); 54 | try { 55 | return new ProcessBuilder() 56 | .directory(rootDir) 57 | .command(command) 58 | .redirectErrorStream(true) 59 | .start(); 60 | } catch (IOException e) { 61 | throw new RuntimeException(e); 62 | } 63 | } 64 | 65 | private void storeOpaProcessInProject(Process process) { 66 | if (process.isAlive()) { 67 | getLogger().debug("Storing running opa process in ext.opaProcess"); 68 | getProject().getExtensions().getExtraProperties().set("opaProcess", process); 69 | } else { 70 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), UTF_8))) { 71 | getLogger().error("{}", reader.lines().collect(Collectors.joining("\n"))); 72 | } catch (IOException e) { 73 | getLogger().error("Failed to start OPA and failed to read error stream", e); 74 | } 75 | throw new RuntimeException("Failed to start OPA"); 76 | } 77 | } 78 | 79 | private void waitForOpaInit(OpaOutputConsumer outputConsumer) { 80 | outputConsumer.spawn(); 81 | CountDownLatch serverInitializationLatch = new CountDownLatch(1); 82 | 83 | new Thread(() -> { 84 | String line; 85 | while ((line = outputConsumer.readLine()) != null) { 86 | if (line.contains("Initializing server")) { 87 | serverInitializationLatch.countDown(); 88 | } 89 | getLogger().info("[OPA] {}", line); 90 | } 91 | }).start(); 92 | 93 | try { 94 | if (!serverInitializationLatch.await(5, TimeUnit.SECONDS)) { 95 | throw new RuntimeException("OPA failed to initialize"); 96 | } 97 | } catch (InterruptedException e) { 98 | throw new RuntimeException(e); 99 | } 100 | } 101 | 102 | 103 | } 104 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | ### Welcome 4 | 5 | First off, thank you for considering contributing to Opa Gradle Plugin. It's people like you that make this code such a great plugin. 6 | 7 | Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests. 8 | 9 | ### What we are looking for 10 | 11 | Opa Gradle Plugin is an open source project, and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be incorporated into Opa Gradle Plugin itself. 12 | 13 | # Ground Rules 14 | 15 | Responsibilities 16 | * Ensure cross-platform compatibility for every change that's accepted. Windows, Mac, Debian & Ubuntu Linux. 17 | * Create issues for any major changes and enhancements that you wish to make. Discuss things transparently and get community feedback. 18 | * Keep feature versions as small as possible, preferably one new feature per version. 19 | * Be welcoming to newcomers and encourage diverse new contributors from all backgrounds. See the [Code of Conduct](https://github.com/Bisnode/opa-gradle-plugin/blob/master/CODE_OF_CONDUCT.md). 20 | 21 | # Getting started 22 | 23 | As a rule of thumb, changes are obvious fixes if they do not introduce any new functionality or creative thinking. As long as the change does not affect functionality, some likely examples include the following: 24 | * Spelling / grammar fixes 25 | * Typo correction, white space and formatting changes 26 | * Comment clean up 27 | * Bug fixes that change default return values or error codes stored in constants 28 | * Adding logging messages or debugging output 29 | * Changes to ‘metadata’ files like .gitignore, build scripts, etc. 30 | * Moving source files from one directory or package to another 31 | 32 | For something that is bigger than a few line fix: 33 | 34 | 1. Create your own fork of the code 35 | 2. Do the changes in your fork 36 | 3. If you like the change and think the project could use it 37 | * Be sure you have followed the code style for the project. 38 | * Note the Code of Conduct. 39 | * Send a pull request. 40 | 41 | 42 | # How to report a bug 43 | 44 | If you find a security vulnerability, do NOT open an issue. Email [maintainers](nights-watch@bisnode.com) instead. 45 | 46 | 47 | Any security issues should be submitted directly to [maintainers](nights-watch@bisnode.com) 48 | In order to determine whether you are dealing with a security issue, ask yourself these two questions: 49 | * Can I access something that's not mine, or something I shouldn't have access to? 50 | * Can I disable something for other people? 51 | 52 | If the answer to either of those two questions are "yes", then you're probably dealing with a security issue. Note that even if you answer "no" to both questions, you may still be dealing with a security issue, so if you're unsure, just [email us](nights-watch@bisnode.com). 53 | 54 | When filing an issue, make sure to answer these five questions: 55 | 56 | 1. What version of OPA/Java/Gradle are you using? 57 | 2. What operating system and processor architecture are you using? 58 | 3. What did you do? 59 | 4. What did you expect to see? 60 | 5. What did you see instead? 61 | 62 | # How to report a Feature Request 63 | If you find yourself wishing for a feature that doesn't exist in Opa Gradle Plugin, you are probably not alone. There are bound to be others out there with similar needs. Many of the features that Opa Gradle Plugin has today have been added because our users saw the need. Open an issue on our issues list on GitHub which describes the feature you would like to see, why you need it, and how it should work. 64 | 65 | # Code review process 66 | 67 | The core team looks at Pull Requests as fast as possible. If there is a need, we can arrange a meeting and elaborate on implementation details. 68 | After feedback has been given we expect responses within two weeks. After two weeks we may close the pull request if it isn't showing any activity. 69 | 70 | ## Code, commit message and labeling conventions 71 | 72 | ### Commit message convention 73 | 74 | Please do not provide nondeterministic messages to commits like: "fix vol2", "another fix". 75 | From maintainers point of view, there should be one commit for one Pull Request. 76 | Perhaps the best idea is to squash commits before merge. 77 | 78 | ### Labeling convention 79 | 80 | [1] [StandardIssueLabels](https://github.com/wagenet/StandardIssueLabels#standardissuelabels) 81 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [this email](nights-watch@bisnode.com). 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html), 118 | version 2.0. 119 | -------------------------------------------------------------------------------- /config/checkstyle/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /src/test/resources/opa-test-output.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "location": { 4 | "file": "tbac-policy-test.rego", 5 | "row": 5, 6 | "col": 1 7 | }, 8 | "package": "data.kubernetes.authz", 9 | "name": "test_any_input_with_a_non_regular_user_is_no_opinion", 10 | "duration": 1118113 11 | }, 12 | { 13 | "location": { 14 | "file": "tbac-policy-test.rego", 15 | "row": 13, 16 | "col": 1 17 | }, 18 | "package": "data.kubernetes.authz", 19 | "name": "test_any_input_with_modifying_verb_is_denied", 20 | "duration": 767167 21 | }, 22 | { 23 | "location": { 24 | "file": "tbac-policy-test.rego", 25 | "row": 22, 26 | "col": 1 27 | }, 28 | "package": "data.kubernetes.authz", 29 | "name": "test_any_input_with_modifying_verb_not_exec_is_denied_reason_message", 30 | "duration": 1498551 31 | }, 32 | { 33 | "location": { 34 | "file": "tbac-policy-test.rego", 35 | "row": 33, 36 | "col": 1 37 | }, 38 | "package": "data.kubernetes.authz", 39 | "name": "test_create_exec_allowed_if_member_of_team", 40 | "duration": 444361 41 | }, 42 | { 43 | "location": { 44 | "file": "tbac-policy-test.rego", 45 | "row": 50, 46 | "col": 1 47 | }, 48 | "package": "data.kubernetes.authz", 49 | "name": "test_create_exec_not_allowed_if_not_member_of_team", 50 | "duration": 589920 51 | }, 52 | { 53 | "location": { 54 | "file": "tbac-policy-test.rego", 55 | "row": 67, 56 | "col": 1 57 | }, 58 | "package": "data.kubernetes.authz", 59 | "name": "test_any_input_with_empty_or_unknown_verb_is_denied", 60 | "duration": 472691 61 | }, 62 | { 63 | "location": { 64 | "file": "tbac-policy-test.rego", 65 | "row": 74, 66 | "col": 1 67 | }, 68 | "package": "data.kubernetes.authz", 69 | "name": "test_input_with_no_resource_name_is_defined", 70 | "duration": 764679 71 | }, 72 | { 73 | "location": { 74 | "file": "tbac-policy-test.rego", 75 | "row": 83, 76 | "col": 1 77 | }, 78 | "package": "data.kubernetes.authz", 79 | "name": "test_input_with_no_resource_name_is_defined_reason_message", 80 | "duration": 1038786 81 | }, 82 | { 83 | "location": { 84 | "file": "tbac-policy-test.rego", 85 | "row": 92, 86 | "col": 1 87 | }, 88 | "package": "data.kubernetes.authz", 89 | "name": "test_input_with_no_group_is_denied", 90 | "duration": 433926 91 | }, 92 | { 93 | "location": { 94 | "file": "tbac-policy-test.rego", 95 | "row": 96, 96 | "col": 1 97 | }, 98 | "package": "data.kubernetes.authz", 99 | "name": "test_input_with_no_matching_group_is_denied", 100 | "duration": 490681 101 | }, 102 | { 103 | "location": { 104 | "file": "tbac-policy-test.rego", 105 | "row": 101, 106 | "col": 1 107 | }, 108 | "package": "data.kubernetes.authz", 109 | "name": "test_input_with_no_bisnode_email_is_denied", 110 | "duration": 377743 111 | }, 112 | { 113 | "location": { 114 | "file": "tbac-policy-test.rego", 115 | "row": 105, 116 | "col": 1 117 | }, 118 | "package": "data.kubernetes.authz", 119 | "name": "test_input_with_non_default_namespace", 120 | "duration": 362833 121 | }, 122 | { 123 | "location": { 124 | "file": "tbac-policy-test.rego", 125 | "row": 109, 126 | "col": 1 127 | }, 128 | "package": "data.kubernetes.authz", 129 | "name": "test_input_with_non_default_namespace_reason_message", 130 | "duration": 477337 131 | }, 132 | { 133 | "location": { 134 | "file": "tbac-policy-test.rego", 135 | "row": 115, 136 | "col": 1 137 | }, 138 | "package": "data.kubernetes.authz", 139 | "name": "test_input_with_team_matching_resource_owner_modifying_action", 140 | "fail": true, 141 | "duration": 600281 142 | }, 143 | { 144 | "location": { 145 | "file": "tbac-policy-test.rego", 146 | "row": 126, 147 | "col": 1 148 | }, 149 | "package": "data.kubernetes.authz", 150 | "name": "test_input_with_team_not_matching_resource_owner_modifying_action", 151 | "duration": 862539 152 | }, 153 | { 154 | "location": { 155 | "file": "tbac-policy-test.rego", 156 | "row": 137, 157 | "col": 1 158 | }, 159 | "package": "data.kubernetes.authz", 160 | "name": "test_input_with_team_not_matching_resource_owner_modifying_action_reason_message", 161 | "duration": 706323 162 | }, 163 | { 164 | "location": { 165 | "file": "tbac-policy-test.rego", 166 | "row": 149, 167 | "col": 1 168 | }, 169 | "package": "data.kubernetes.authz", 170 | "name": "test_input_with_team_matching_deployment_owner_delete_action", 171 | "fail": true, 172 | "duration": 1289212 173 | }, 174 | { 175 | "location": { 176 | "file": "tbac-policy-test.rego", 177 | "row": 167, 178 | "col": 1 179 | }, 180 | "package": "data.kubernetes.authz", 181 | "name": "test_input_with_team_matching_deployment_owner_variations_delete_action", 182 | "fail": true, 183 | "duration": 532151 184 | }, 185 | { 186 | "location": { 187 | "file": "tbac-policy-test.rego", 188 | "row": 185, 189 | "col": 1 190 | }, 191 | "package": "data.kubernetes.authz", 192 | "name": "test_input_with_team_matching_pod_owner_delete_action", 193 | "fail": true, 194 | "duration": 583905 195 | }, 196 | { 197 | "location": { 198 | "file": "tbac-policy-test.rego", 199 | "row": 203, 200 | "col": 1 201 | }, 202 | "package": "data.kubernetes.authz", 203 | "name": "test_input_single_matching_team_is_allowed", 204 | "fail": true, 205 | "duration": 558076 206 | }, 207 | { 208 | "location": { 209 | "file": "tbac-policy-test.rego", 210 | "row": 226, 211 | "col": 1 212 | }, 213 | "package": "data.kubernetes.authz", 214 | "name": "test_input_one_of_many_team_is_allowed", 215 | "fail": true, 216 | "duration": 578959 217 | }, 218 | { 219 | "location": { 220 | "file": "tbac-policy-test.rego", 221 | "row": 250, 222 | "col": 1 223 | }, 224 | "package": "data.kubernetes.authz", 225 | "name": "test_division_by_zero", 226 | "error": { 227 | "code": "eval_builtin_error", 228 | "message": "div: divide by zero", 229 | "location": { 230 | "file": "tbac-policy-test.rego", 231 | "row": 251, 232 | "col": 40 233 | } 234 | }, 235 | "duration": 294354 236 | } 237 | ] 238 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | if ! command -v java >/dev/null 2>&1 134 | then 135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 136 | 137 | Please set the JAVA_HOME variable in your environment to match the 138 | location of your Java installation." 139 | fi 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | 201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 203 | 204 | # Collect all arguments for the java command; 205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 206 | # shell script including quotes and variable substitutions, so put them in 207 | # double quotes to make sure that they get re-expanded; and 208 | # * put everything else in single quotes, so that it's not re-expanded. 209 | 210 | set -- \ 211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 212 | -classpath "$CLASSPATH" \ 213 | org.gradle.wrapper.GradleWrapperMain \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020-2021 Bisnode 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/testFunctional/java/com/bisnode/test/PluginFunctionalTest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.test; 2 | 3 | import com.bisnode.opa.configuration.ExecutableMode; 4 | import com.bisnode.opa.configuration.OpaPlatform; 5 | import org.gradle.testkit.runner.BuildResult; 6 | import org.gradle.testkit.runner.BuildTask; 7 | import org.gradle.testkit.runner.GradleRunner; 8 | import org.gradle.testkit.runner.TaskOutcome; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.junit.jupiter.api.io.TempDir; 12 | import org.w3c.dom.Document; 13 | import org.xml.sax.SAXException; 14 | 15 | import javax.annotation.Nullable; 16 | import javax.xml.parsers.DocumentBuilder; 17 | import javax.xml.parsers.DocumentBuilderFactory; 18 | import javax.xml.parsers.ParserConfigurationException; 19 | import java.io.ByteArrayInputStream; 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.io.StringWriter; 23 | import java.nio.file.Files; 24 | import java.nio.file.Path; 25 | import java.nio.file.Paths; 26 | import java.nio.file.StandardOpenOption; 27 | import java.util.Objects; 28 | import java.util.function.Function; 29 | 30 | import static com.bisnode.test.OpaPluginFunctionalTestUtils.getRegoPolicy; 31 | import static com.bisnode.test.OpaPluginFunctionalTestUtils.getRegoPolicyTest; 32 | import static com.bisnode.test.OpaPluginFunctionalTestUtils.getRegoPolicyTestFail; 33 | import static java.nio.charset.StandardCharsets.UTF_8; 34 | import static org.junit.jupiter.api.Assertions.assertEquals; 35 | import static org.junit.jupiter.api.Assertions.assertNotNull; 36 | import static org.junit.jupiter.api.Assertions.assertTrue; 37 | 38 | @SuppressWarnings({"DuplicatedCode", "VisibilityModifier"}) 39 | public class PluginFunctionalTest { 40 | 41 | @TempDir 42 | File tmpDir; 43 | 44 | private File buildFile; 45 | 46 | @BeforeEach 47 | public void setup() throws IOException { 48 | String buildFileContent = "plugins {\n" + 49 | " id 'com.bisnode.opa'\n" + 50 | "}\n"; 51 | 52 | buildFile = new File(tmpDir, "build.gradle"); 53 | Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8)); 54 | } 55 | 56 | @Test 57 | public void testRunningSuccessfulTestProducesJUnitXMLOutput() throws IOException { 58 | String directory = tmpDir.getAbsolutePath(); 59 | 60 | Path path = Paths.get(directory); 61 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego")); 62 | Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), path.resolve("policy_test.rego")); 63 | 64 | Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND); 65 | 66 | BuildResult result = prepareRunner(new StringWriter(), "testRego").build(); 67 | @Nullable BuildTask task = result.task(":testRego"); 68 | 69 | assertEquals(1, result.getTasks().size()); 70 | assertNotNull(task); 71 | assertEquals(TaskOutcome.SUCCESS, task.getOutcome()); 72 | assertNotNull(path.toFile()); 73 | assertNotNull(path.toFile().listFiles()); 74 | 75 | Path testResultPath = path.resolve("build/test-results/opa"); 76 | assertNotNull(testResultPath.toFile()); 77 | assertTrue(testResultPath.toFile().exists()); 78 | 79 | Path opaJunitXMLReportPath = testResultPath.resolve("TEST-opa-tests.xml"); 80 | assertNotNull(opaJunitXMLReportPath.toFile()); 81 | assertTrue(opaJunitXMLReportPath.toFile().exists()); 82 | 83 | Document document = readXmlDocument(opaJunitXMLReportPath.toFile()); 84 | 85 | Function attributes = attributeRetriever(document); 86 | 87 | assertEquals("1", attributes.apply("tests")); 88 | assertEquals("0", attributes.apply("errors")); 89 | assertEquals("0", attributes.apply("failures")); 90 | } 91 | 92 | @Test 93 | public void testRunningTestWithExistingReportsDirectoryWorks() throws IOException { 94 | String directory = tmpDir.getAbsolutePath(); 95 | 96 | Path path = Paths.get(directory); 97 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego")); 98 | Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), path.resolve("policy_test.rego")); 99 | 100 | Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND); 101 | 102 | Files.createDirectories(buildFile.toPath().getParent().resolve("build/test-results/opa")); 103 | 104 | BuildResult result = prepareRunner(new StringWriter(), "testRego").build(); 105 | @Nullable BuildTask task = result.task(":testRego"); 106 | 107 | assertEquals(1, result.getTasks().size()); 108 | assertNotNull(task); 109 | assertEquals(TaskOutcome.SUCCESS, task.getOutcome()); 110 | assertNotNull(path.toFile()); 111 | assertNotNull(path.toFile().listFiles()); 112 | 113 | Path testResultPath = path.resolve("build/test-results/opa"); 114 | assertNotNull(testResultPath.toFile()); 115 | assertTrue(testResultPath.toFile().exists()); 116 | 117 | Path opaJunitXMLReportPath = testResultPath.resolve("TEST-opa-tests.xml"); 118 | assertNotNull(opaJunitXMLReportPath.toFile()); 119 | assertTrue(opaJunitXMLReportPath.toFile().exists()); 120 | 121 | Document document = readXmlDocument(opaJunitXMLReportPath.toFile()); 122 | 123 | Function attributes = attributeRetriever(document); 124 | 125 | assertEquals("1", attributes.apply("tests")); 126 | assertEquals("0", attributes.apply("errors")); 127 | assertEquals("0", attributes.apply("failures")); 128 | } 129 | 130 | @Test 131 | public void testRunningFailingTestProducesJUnitXMLOutput() throws IOException { 132 | String directory = tmpDir.getAbsolutePath(); 133 | 134 | Path path = Paths.get(directory); 135 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego")); 136 | Files.copy(new ByteArrayInputStream(getRegoPolicyTestFail().getBytes(UTF_8)), path.resolve("policy_test.rego")); 137 | 138 | Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND); 139 | 140 | BuildResult result = prepareRunner(new StringWriter(), "testRego").buildAndFail(); 141 | @Nullable BuildTask task = result.task(":testRego"); 142 | 143 | assertEquals(1, result.getTasks().size()); 144 | assertNotNull(task); 145 | assertEquals(TaskOutcome.FAILED, task.getOutcome()); 146 | assertNotNull(path.toFile()); 147 | assertNotNull(path.toFile().listFiles()); 148 | 149 | Path testResultPath = path.resolve("build/test-results/opa"); 150 | assertNotNull(testResultPath.toFile()); 151 | assertTrue(testResultPath.toFile().exists()); 152 | 153 | Path opaJunitXMLReportPath = testResultPath.resolve("TEST-opa-tests.xml"); 154 | assertNotNull(opaJunitXMLReportPath.toFile()); 155 | assertTrue(opaJunitXMLReportPath.toFile().exists()); 156 | 157 | Document document = readXmlDocument(opaJunitXMLReportPath.toFile()); 158 | 159 | Function attributes = attributeRetriever(document); 160 | 161 | assertEquals("1", attributes.apply("tests")); 162 | assertEquals("0", attributes.apply("errors")); 163 | assertEquals("1", attributes.apply("failures")); 164 | } 165 | 166 | @Test 167 | public void testProvidingTaskPropertiesOverridesDefaults() throws IOException { 168 | String directory = tmpDir.getAbsolutePath(); 169 | Path path = Paths.get(directory); 170 | Path policyDirPath = path.resolve("policy"); 171 | File policyDir = new File(policyDirPath.toString()); 172 | assert policyDir.mkdir(); 173 | 174 | Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), policyDirPath.resolve("policy.rego")); 175 | Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), policyDirPath.resolve("policy_test.rego")); 176 | 177 | String buildFileContent = getOpaBlockConfig("/tmp") + "\n\n" + 178 | "testRego {\n" + 179 | " srcDir '" + policyDirPath.toAbsolutePath() + "'\n" + 180 | " testDir '" + policyDirPath.toAbsolutePath() + "'\n" + 181 | "}"; 182 | 183 | Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND); 184 | 185 | BuildResult result = prepareRunner(new StringWriter(), "testRego").build(); 186 | @Nullable BuildTask task = result.task(":testRego"); 187 | 188 | assertEquals(1, result.getTasks().size()); 189 | assertNotNull(task); 190 | assertEquals(TaskOutcome.SUCCESS, task.getOutcome()); 191 | assertNotNull(path.toFile()); 192 | assertNotNull(path.toFile().listFiles()); 193 | 194 | Path testResultPath = path.resolve("build/test-results/opa"); 195 | assertNotNull(testResultPath.toFile()); 196 | assertTrue(testResultPath.toFile().exists()); 197 | 198 | Path opaJunitXMLReportPath = testResultPath.resolve("TEST-opa-tests.xml"); 199 | assertNotNull(opaJunitXMLReportPath.toFile()); 200 | assertTrue(opaJunitXMLReportPath.toFile().exists()); 201 | 202 | Document document = readXmlDocument(opaJunitXMLReportPath.toFile()); 203 | 204 | Function attributes = attributeRetriever(document); 205 | 206 | assertEquals("1", attributes.apply("tests")); 207 | assertEquals("0", attributes.apply("errors")); 208 | assertEquals("0", attributes.apply("failures")); 209 | } 210 | 211 | @Test 212 | public void testRunningTestRegoCoverageTaskWithoutArgumentsWork() throws IOException { 213 | String directory = tmpDir.getAbsolutePath(); 214 | String buildFileContent = "opa {\n" + 215 | " srcDir '" + directory + "'\n" + 216 | " testDir '" + directory + "'\n" + 217 | "}"; 218 | Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND); 219 | 220 | BuildResult result = prepareRunner(new StringWriter(), "testRegoCoverage").build(); 221 | @Nullable BuildTask task = result.task(":testRegoCoverage"); 222 | 223 | assertEquals(1, result.getTasks().size()); 224 | assertNotNull(task); 225 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(task).getOutcome()); 226 | } 227 | 228 | @Test 229 | public void testRunningTestWithDownloadModeWorks() throws IOException { 230 | String directory = tmpDir.getAbsolutePath(); 231 | String buildFileContent = "opa {\n" + 232 | " mode '" + ExecutableMode.DOWNLOAD + "'\n" + 233 | " version '0.54.0'\n" + 234 | " srcDir '" + directory + "'\n" + 235 | " testDir '" + directory + "'\n" + 236 | "}"; 237 | Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND); 238 | 239 | BuildResult result = prepareRunner(new StringWriter(), "testRegoCoverage").build(); 240 | @Nullable BuildTask task = result.task(":testRegoCoverage"); 241 | @Nullable BuildTask downloadTask = result.task(":downloadOpa_0.54.0"); 242 | 243 | assertEquals(2, result.getTasks().size()); 244 | assertNotNull(task); 245 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(task).getOutcome()); 246 | assertNotNull(downloadTask); 247 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(downloadTask).getOutcome()); 248 | assertTrue(Files.exists(OpaPlatform.getPlatform().getExecutablePath(tmpDir.toPath().resolve("build"), "0.54.0"))); 249 | } 250 | 251 | @Test 252 | public void testDownloadModeInMultiModuleWorks() throws IOException { 253 | Files.delete(buildFile.toPath()); 254 | String settingFileContent = "include 'module1', 'module2'"; 255 | File settingFile = new File(tmpDir, "settings.gradle"); 256 | Files.write(settingFile.toPath(), settingFileContent.getBytes(UTF_8)); 257 | String subBuildFileContent = "plugins {\n" + 258 | " id 'com.bisnode.opa'\n" + 259 | "}\n\n" + 260 | "opa {\n" + 261 | " mode '" + ExecutableMode.DOWNLOAD + "'\n" + 262 | " version '0.54.0'\n" + 263 | " srcDir 'src'\n" + 264 | " testDir 'test'\n" + 265 | "}"; 266 | File module1Directory = new File(tmpDir, "module1"); 267 | Files.createDirectories(module1Directory.toPath().resolve("src")); 268 | Files.createDirectories(module1Directory.toPath().resolve("test")); 269 | File module1BuildFile = new File(module1Directory, "build.gradle"); 270 | Files.write(module1BuildFile.toPath(), subBuildFileContent.getBytes(UTF_8)); 271 | File module2Directory = new File(tmpDir, "module2"); 272 | Files.createDirectories(module2Directory.toPath().resolve("src")); 273 | Files.createDirectories(module2Directory.toPath().resolve("test")); 274 | File module2BuildFile = new File(module2Directory, "build.gradle"); 275 | Files.write(module2BuildFile.toPath(), subBuildFileContent.getBytes(UTF_8)); 276 | 277 | BuildResult result = prepareRunner(new StringWriter(), "testRegoCoverage").build(); 278 | @Nullable BuildTask taskModule1 = result.task(":module1:testRegoCoverage"); 279 | @Nullable BuildTask taskModule2 = result.task(":module2:testRegoCoverage"); 280 | @Nullable BuildTask downloadTask = result.task(":downloadOpa_0.54.0"); 281 | 282 | assertEquals(3, result.getTasks().size()); 283 | assertNotNull(taskModule1); 284 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(taskModule1).getOutcome()); 285 | assertNotNull(taskModule2); 286 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(taskModule2).getOutcome()); 287 | assertNotNull(downloadTask); 288 | assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(downloadTask).getOutcome()); 289 | assertTrue(Files.exists(OpaPlatform.getPlatform().getExecutablePath(tmpDir.toPath().resolve("build"), "0.54.0"))); 290 | } 291 | 292 | private GradleRunner prepareRunner(StringWriter writer, String... tasks) { 293 | return GradleRunner.create() 294 | .withProjectDir(tmpDir) 295 | .forwardStdOutput(writer) 296 | .forwardStdError(writer) 297 | .withPluginClasspath() 298 | .withArguments(tasks); 299 | } 300 | 301 | private static String getOpaBlockConfig(String directory) { 302 | return "opa {\n" + 303 | " srcDir '" + directory + "'\n" + 304 | " testDir '" + directory + "'\n" + 305 | "}"; 306 | } 307 | 308 | private static Document readXmlDocument(File file) { 309 | try { 310 | DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 311 | DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 312 | 313 | return documentBuilder.parse(file); 314 | } catch (ParserConfigurationException | SAXException | IOException e) { 315 | throw new RuntimeException(e); 316 | } 317 | } 318 | 319 | private static Function attributeRetriever(Document document) { 320 | return attribute -> document.getElementsByTagName("testsuites") 321 | .item(0) 322 | .getAttributes() 323 | .getNamedItem(attribute) 324 | .getNodeValue(); 325 | } 326 | 327 | } 328 | --------------------------------------------------------------------------------