diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e5993bc311..d8972ac82b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -117,14 +117,14 @@ jobs: echo ${{ env.SECURITY_PLUGIN_VERSION_ONLY_NUMBER }} echo ${{ env.TEST_QUALIFIER }} - - run: ./gradlew clean assemble && test -s ./build/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION }}.jar + - run: ./gradlew clean assemble && test -s ./build/distributions/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION }}.zip - - run: ./gradlew clean assemble -Dbuild.snapshot=false && test -s ./build/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_NO_SNAPSHOT }}.jar + - run: ./gradlew clean assemble -Dbuild.snapshot=false && test -s ./build/distributions/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_NO_SNAPSHOT }}.zip - - run: ./gradlew clean assemble -Dbuild.snapshot=false -Dbuild.version_qualifier=${{ env.TEST_QUALIFIER }} && test -s ./build/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_ONLY_NUMBER }}-${{ env.TEST_QUALIFIER }}.jar + - run: ./gradlew clean assemble -Dbuild.snapshot=false -Dbuild.version_qualifier=${{ env.TEST_QUALIFIER }} && test -s ./build/distributions/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_ONLY_NUMBER }}-${{ env.TEST_QUALIFIER }}.zip - - run: ./gradlew clean assemble -Dbuild.version_qualifier=${{ env.TEST_QUALIFIER }} && test -s ./build/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_ONLY_NUMBER }}-${{ env.TEST_QUALIFIER }}-SNAPSHOT.jar + - run: ./gradlew clean assemble -Dbuild.version_qualifier=${{ env.TEST_QUALIFIER }} && test -s ./build/distributions/opensearch-security-${{ env.SECURITY_PLUGIN_VERSION_ONLY_NUMBER }}-${{ env.TEST_QUALIFIER }}-SNAPSHOT.zip - name: List files in the build directory if there was an error - run: ls -al ./build/ + run: ls -al ./build/distributions/ if: failure() diff --git a/build.gradle b/build.gradle index 5a66d36b6d..7d2526a0ac 100644 --- a/build.gradle +++ b/build.gradle @@ -9,79 +9,221 @@ * GitHub history for details. */ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +buildscript { + ext { + opensearch_version = System.getProperty("opensearch.version", "2.1.0-SNAPSHOT") + isSnapshot = "true" == System.getProperty("build.snapshot", "true") + buildVersionQualifier = System.getProperty("build.version_qualifier", "") + + // 2.0.0-rc1-SNAPSHOT -> 2.0.0.0-rc1-SNAPSHOT + version_tokens = opensearch_version.tokenize('-') + opensearch_build = version_tokens[0] + '.0' + if (buildVersionQualifier) { + opensearch_build += "-${buildVersionQualifier}" + } + if (isSnapshot) { + opensearch_build += "-SNAPSHOT" + } + } + + repositories { + mavenCentral() + mavenLocal() + maven { url "https://plugins.gradle.org/m2/" } + maven { url "https://aws.oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://d1nvenhzbhpy0q.cloudfront.net/snapshots/lucene/" } + } + + dependencies { + classpath "org.opensearch.gradle:build-tools:${opensearch_version}" + } +} plugins { id 'java' - id 'maven-publish' + id 'idea' id 'jacoco' + id 'maven-publish' + id 'com.diffplug.spotless' version '5.11.0' id 'checkstyle' - id "com.gorylenko.gradle-git-properties" version "2.3.2" - id 'org.gradle.crypto.checksum' version '1.1.0' + id 'nebula.ospackage' version "8.3.0" + id "org.gradle.test-retry" version "1.3.1" +} - // Plugin prints gradle task graph, use following command: ./gradlew tiTree build - id 'org.barfuin.gradle.taskinfo' version '1.0.5' +allprojects { + group = "org.opensearch" + version = opensearch_build +} - id "nebula.ospackage" version "9.0.0" - id "com.google.osdetector" version "1.7.0" - id "org.gradle.test-retry" version "1.3.1" - id "com.diffplug.spotless" version "6.5.0" +apply plugin: 'opensearch.opensearchplugin' +apply plugin: 'opensearch.pluginzip' + +licenseFile = rootProject.file('LICENSE.txt') +noticeFile = rootProject.file('NOTICE.txt') + +spotless { + java { + // note: you can use an empty string for all the imports you didn't specify explicitly, and '\\#` prefix for static imports + importOrder('java', 'javax', '', 'com.amazon', 'org.opensearch', '\\#') + } +} + +java.sourceCompatibility = JavaVersion.VERSION_11 +java.targetCompatibility = JavaVersion.VERSION_11 + +licenseHeaders.enabled = true + +// The following check that have never be enabled in security +dependencyLicenses.enabled = false +thirdPartyAudit.enabled = false +loggerUsageCheck.enabled = false +forbiddenApisMain.enabled = false +forbiddenApisTest.enabled = false +filepermissions.enabled = false +forbiddenPatterns.enabled = false +testingConventions.enabled = false +// Conflicts between runtime kafka-clients:3.0.1 & testRuntime kafka-clients:3.0.1:test +jarHell.enabled = false + +test { + include '**/*.class' + maxParallelForks = 8 + jvmArgs += "-Xmx3072m" + if (JavaVersion.current() > JavaVersion.VERSION_1_8) { + jvmArgs += "--add-opens=java.base/java.io=ALL-UNNAMED" + } + retry { + failOnPassedAfterRetry = false + maxRetries = 5 + } + jacoco { + excludes = [ + "com.sun.jndi.dns.*", + "com.sun.security.sasl.gsskerb.*", + "java.sql.*", + "javax.script.*", + "org.jcp.xml.dsig.internal.dom.*", + "sun.nio.cs.ext.*", + "sun.security.ec.*", + "sun.security.jgss.*", + "sun.security.pkcs11.*", + "sun.security.smartcardio.*", + "sun.util.resources.provider.*" + ] + } } -import org.gradle.crypto.checksum.Checksum -import java.text.SimpleDateFormat +task copyExtraTestResources(dependsOn: testClasses) { + copy { + from 'src/test/resources' + into 'build/testrun/test/src/test/resources' + } +} +tasks.test.dependsOn(copyExtraTestResources) + +jacoco { + reportsDirectory = file("$buildDir/reports/jacoco") +} + +jacocoTestReport { + reports { + xml.required = true + } +} + +checkstyle { + configFile file("checkstyle/sun_checks.xml") +} + +opensearchplugin { + name 'opensearch-security' + description 'Provide access control related features for OpenSearch' + classname 'org.opensearch.security.OpenSearchSecurityPlugin' +} + +// This requires an additional Jar not published as part of build-tools +loggerUsageCheck.enabled = false + +// No need to validate pom, as we do not upload to maven/sonatype +validateNebulaPom.enabled = false + +publishing { + publications { + pluginZip(MavenPublication) { publication -> + pom { + name = "opensearch-security" + description = "Provide access control related features for OpenSearch" + licenses { + license { + name = "The Apache License, Version 2.0" + url = "http://www.apache.org/licenses/LICENSE-2.0.txt" + } + } + developers { + developer { + name = "OpenSearch" + url = "https://github.com/opensearch-project/security" + } + } + } + } + } +} repositories { - mavenLocal() - maven { url "https://aws.oss.sonatype.org/content/repositories/snapshots" } mavenCentral() + mavenLocal() maven { url "https://plugins.gradle.org/m2/" } + maven { url "https://aws.oss.sonatype.org/content/repositories/snapshots" } maven { url "https://d1nvenhzbhpy0q.cloudfront.net/snapshots/lucene/" } } -ext { - isSnapshot = "true" == System.getProperty("build.snapshot", "true") - opensearch_version = System.getProperty("opensearch.version", "2.1.0-SNAPSHOT") - buildVersionQualifier = System.getProperty("build.version_qualifier", "") - version_tokens = opensearch_version.tokenize('-') - opensearch_build = version_tokens[0] + '.0' - if (buildVersionQualifier) { - opensearch_build += "-${buildVersionQualifier}" - opensearch_build_nosnapshot = opensearch_build +tasks.withType(Checkstyle) { + showViolations true + reports { + ignoreFailures = false } - if (isSnapshot) { - opensearch_build += "-SNAPSHOT" +} + +tasks.withType(JavaCompile) { + configure(options) { + options.encoding = 'UTF-8' + options.compilerArgs << '-Xlint:removal' << '-Werror' + } +} + +tasks.test.finalizedBy(jacocoTestReport) // report is always generated after tests run +tasks.jacocoTestReport.dependsOn(test) // tests are required to run before generating the report + + +allprojects { + tasks.withType(Javadoc).all { enabled = false } +} + +bundlePlugin { + from('plugin-security.policy') + from('config') { + into 'config' + } + from('tools') { + into 'tools' } } configurations.all { resolutionStrategy { force 'commons-codec:commons-codec:1.14' - force 'org.apache.santuario:xmlsec:2.2.3' - force 'org.cryptacular:cryptacular:1.2.4' - force 'net.minidev:json-smart:2.4.7' - force 'commons-cli:commons-cli:1.3.1' - force 'org.apache.httpcomponents:httpcore:4.4.12' - force "org.apache.commons:commons-lang3:3.4" - force "org.springframework:spring-core:5.3.20" - force "com.google.guava:guava:30.0-jre" + force 'org.slf4j:slf4j-api:1.7.30' + force 'org.scala-lang:scala-library:2.13.8' + force 'commons-io:commons-io:2.11.0' + force "com.fasterxml.jackson:jackson-bom:${versions.jackson}" + force "com.fasterxml.jackson.core:jackson-core:${versions.jackson}" + force "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:${versions.jackson}" + force "com.fasterxml.jackson.core:jackson-databind:${versions.jackson_databind}" + force 'io.netty:netty-buffer:4.1.73.Final' + force 'io.netty:netty-common:4.1.73.Final' + force 'io.netty:netty-handler:4.1.73.Final' + force 'io.netty:netty-transport:4.1.73.Final' } } @@ -96,22 +238,76 @@ dependencies { implementation 'org.ldaptive:ldaptive:1.2.3' implementation 'org.apache.httpcomponents:httpclient-cache:4.5.13' implementation 'io.jsonwebtoken:jjwt-api:0.10.8' - implementation("org.apache.cxf:cxf-rt-rs-security-jose:3.4.5") { + implementation('org.apache.cxf:cxf-rt-rs-security-jose:3.4.5') { exclude(group: 'jakarta.activation', module: 'jakarta.activation-api') } implementation 'com.github.wnameless:json-flattener:0.5.0' implementation 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4' - implementation 'org.apache.kafka:kafka-clients:3.0.0' + implementation 'org.apache.kafka:kafka-clients:3.0.1' implementation 'com.onelogin:java-saml:2.5.0' + implementation 'com.onelogin:java-saml-core:2.5.0' + + runtimeOnly 'net.minidev:accessors-smart:2.4.7' + + runtimeOnly 'org.apache.cxf:cxf-core:3.4.5' + implementation 'org.apache.cxf:cxf-rt-rs-json-basic:3.4.5' + runtimeOnly 'org.apache.cxf:cxf-rt-security:3.4.5' + + runtimeOnly 'com.sun.activation:jakarta.activation:1.2.2' + runtimeOnly 'com.eclipsesource.minimal-json:minimal-json:0.9.5' + runtimeOnly 'commons-codec:commons-codec:1.14' + runtimeOnly 'org.cryptacular:cryptacular:1.2.4' + runtimeOnly 'com.google.errorprone:error_prone_annotations:2.3.4' + runtimeOnly 'com.sun.istack:istack-commons-runtime:3.0.12' + runtimeOnly 'jakarta.xml.bind:jakarta.xml.bind-api:2.3.3' + runtimeOnly 'org.ow2.asm:asm:9.1' + + testImplementation 'org.apache.camel:camel-xmlsecurity:3.14.2' + + implementation 'net.shibboleth.utilities:java-support:7.5.1' + implementation 'org.opensaml:opensaml-core:3.4.5' + implementation 'org.opensaml:opensaml-security-impl:3.4.5' + implementation 'org.opensaml:opensaml-security-api:3.4.5' + implementation 'org.opensaml:opensaml-xmlsec-api:3.4.5' + implementation 'org.opensaml:opensaml-xmlsec-impl:3.4.5' + implementation 'org.opensaml:opensaml-saml-api:3.4.5' implementation ('org.opensaml:opensaml-saml-impl:3.4.5') { exclude(group: 'org.apache.velocity', module: 'velocity') } + testImplementation 'org.opensaml:opensaml-messaging-impl:3.4.5' + implementation 'org.opensaml:opensaml-messaging-api:3.4.5' + runtimeOnly 'org.opensaml:opensaml-profile-api:3.4.5' + runtimeOnly 'org.opensaml:opensaml-soap-api:3.4.5' + runtimeOnly 'org.opensaml:opensaml-soap-impl:3.4.5' + implementation 'org.opensaml:opensaml-storage-api:3.4.5' implementation 'commons-lang:commons-lang:2.4' implementation 'commons-collections:commons-collections:3.2.2' implementation 'com.jayway.jsonpath:json-path:2.4.0' implementation 'org.apache.httpcomponents:httpclient:4.5.13' + implementation 'org.apache.httpcomponents:httpclient:4.5.13' + implementation 'net.minidev:json-smart:2.4.7' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.10.8' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.10.8' + runtimeOnly 'com.google.guava:failureaccess:1.0.1' + runtimeOnly 'org.apache.commons:commons-text:1.2' + runtimeOnly 'org.glassfish.jaxb:jaxb-runtime:2.3.4' + runtimeOnly 'com.google.j2objc:j2objc-annotations:1.3' + runtimeOnly 'com.google.code.findbugs:jsr305:3.0.2' + runtimeOnly 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava' + runtimeOnly 'org.lz4:lz4-java:1.7.1' + runtimeOnly 'io.dropwizard.metrics:metrics-core:3.1.2' + runtimeOnly 'org.slf4j:slf4j-api:1.7.30' + runtimeOnly 'org.xerial.snappy:snappy-java:1.1.8.1' + runtimeOnly 'org.codehaus.woodstox:stax2-api:4.2.1' + runtimeOnly 'org.glassfish.jaxb:txw2:2.3.4' + runtimeOnly 'com.fasterxml.woodstox:woodstox-core:6.2.6' + runtimeOnly 'org.apache.ws.xmlschema:xmlschema-core:2.2.5' + runtimeOnly 'org.apache.santuario:xmlsec:2.2.3' + runtimeOnly 'com.github.luben:zstd-jni:1.5.0-2' + runtimeOnly 'org.checkerframework:checker-qual:3.5.0' + + + implementation 'org.apache.commons:commons-lang3:3.4' testImplementation "org.opensearch.plugin:reindex-client:${opensearch_version}" testImplementation "org.opensearch:opensearch-ssl-config:${opensearch_version}" testImplementation "org.opensearch.plugin:percolator-client:${opensearch_version}" @@ -120,75 +316,42 @@ dependencies { testImplementation "org.opensearch.plugin:aggs-matrix-stats-client:${opensearch_version}" testImplementation 'org.apache.logging.log4j:log4j-core:2.17.1' testImplementation 'commons-io:commons-io:2.7' - testImplementation 'org.hamcrest:hamcrest-all:1.3' - testImplementation 'junit:junit:4.13.1' - testImplementation 'org.apache.httpcomponents:fluent-hc:4.5.13' - testImplementation 'org.mockito:mockito-core:2.23.0' - testImplementation 'org.springframework.kafka:spring-kafka-test:2.8.6' testImplementation 'javax.servlet:servlet-api:2.5' testImplementation 'com.unboundid:unboundid-ldapsdk:4.0.9' testImplementation 'com.github.stephenc.jcip:jcip-annotations:1.0-1' - testImplementation 'org.apache.kafka:kafka_2.13:2.8.1' - testImplementation 'org.apache.kafka:kafka_2.13:2.8.1:test' - testImplementation 'org.apache.kafka:kafka-clients:2.8.1:test' - compileOnly "org.opensearch:opensearch:${opensearch_version}" -} - -group = 'org.opensearch' -version = opensearch_build - -description = 'OpenSearch Security' - - -java.sourceCompatibility = JavaVersion.VERSION_11 -java.targetCompatibility = JavaVersion.VERSION_11 - -tasks.register('testsJar', Jar) { - archiveClassifier = 'tests' - from(sourceSets.test.output) -} - -publishing { - publications { - maven(MavenPublication) { - from(components.java) - artifact(testsJar) - } + testImplementation 'com.unboundid:unboundid-ldapsdk:4.0.9' + testImplementation 'javax.servlet:servlet-api:2.5' + testImplementation 'org.apache.httpcomponents:fluent-hc:4.5.13' + testImplementation 'org.apache.kafka:kafka_2.13:3.0.1' + testImplementation 'org.apache.kafka:kafka_2.13:3.0.1:test' + testImplementation 'org.apache.kafka:kafka-clients:3.0.1:test' + testImplementation 'org.springframework.kafka:spring-kafka-test:2.8.6' + testImplementation 'org.springframework:spring-beans:5.3.20' + testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + // JUnit build requirement + testCompileOnly 'org.apiguardian:apiguardian-api:1.0.0' + // Kafka test execution + testRuntimeOnly 'org.springframework.retry:spring-retry:1.3.3' + testRuntimeOnly ('org.springframework:spring-core:5.3.21') { + exclude(group:'org.springframework', module: 'spring-jcl' ) } -} + testRuntimeOnly 'org.scala-lang:scala-library:2.13.8' + testRuntimeOnly 'com.yammer.metrics:metrics-core:2.2.0' + testRuntimeOnly 'com.typesafe.scala-logging:scala-logging_3:3.9.5' + testRuntimeOnly 'org.apache.zookeeper:zookeeper:3.6.3' + testRuntimeOnly 'org.apache.kafka:kafka-metadata:3.0.1' + testRuntimeOnly 'org.apache.kafka:kafka-storage:3.0.1' -tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' -} -static def getTimestamp() { - def df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") - df.setTimeZone(TimeZone.getTimeZone("UTC")) - return df.format(new Date()) -} -static def gitCommitId() { - def cmd = "git rev-parse HEAD" - def proc = cmd.execute() - return proc.text.trim() + implementation "com.fasterxml.jackson.core:jackson-annotations:${versions.jackson}" + implementation "com.fasterxml.jackson.core:jackson-databind:${versions.jackson_databind}" + + compileOnly "org.opensearch:opensearch:${opensearch_version}" } jar { - manifest { - attributes( - "Manifest-Version": "1.0", - "Created-By": "Gradle ${gradle.gradleVersion}", - "Build-Jdk": "${System.properties['java.version']}", - "Implementation-Title": "OpenSearch Security", - "Implementation-Version": archiveVersion, - "Implementation-Vendor-Id": "org.opensearch", - "Implementation-URL": "https://github.com/opensearch-project/security", - "Build-Time": getTimestamp(), - "Built-By": "OpenSearch Security Plugin", - "git-sha1": gitCommitId() - ) - } - libsDirName = '.' into '', { from 'NOTICE.txt', "THIRD-PARTY.txt", "LICENSE" @@ -196,101 +359,17 @@ jar { processResources { exclude("KEYS") } +} +tasks.register('testsJar', Jar) { + archiveClassifier = 'tests' + from(sourceSets.test.output) } testsJar { - manifest { - attributes( - "Manifest-Version": "1.0", - "Created-By": "Gradle ${gradle.gradleVersion}", - "Build-Jdk": "${System.properties['java.version']}", - "Implementation-Title": "OpenSearch Security", - "Implementation-Version": archiveVersion, - "Implementation-Vendor-Id": "org.opensearch", - "Implementation-URL": "https://github.com/opensearch-project/security", - "Build-Time": getTimestamp(), - "Built-By": "OpenSearch Security Plugin", - "git-sha1": gitCommitId() - ) - } - libsDirName = '.' } - -test { - maxParallelForks = 3 - jvmArgs += "-Xmx3072m" - if (JavaVersion.current() > JavaVersion.VERSION_1_8) { - jvmArgs += "--add-opens=java.base/java.io=ALL-UNNAMED" - } - retry { - failOnPassedAfterRetry = false - maxFailures = 30 - maxRetries = 5 - } - jacoco { - excludes = [ - "com.sun.jndi.dns.*", - "com.sun.security.sasl.gsskerb.*", - "java.sql.*", - "javax.script.*", - "org.jcp.xml.dsig.internal.dom.*", - "sun.nio.cs.ext.*", - "sun.security.ec.*", - "sun.security.jgss.*", - "sun.security.pkcs11.*", - "sun.security.smartcardio.*", - "sun.util.resources.provider.*" - ] - } -} - -gitProperties { - keys = [ - 'git.branch', - 'git.build.version', - 'git.closest.tag.commit.count', - 'git.closest.tag.name', - 'git.commit.id', - 'git.commit.id.abbrev', - 'git.commit.id.describe', - 'git.commit.message.full', - 'git.commit.message.short', - 'git.commit.time', - 'git.dirty', - 'git.remote.origin.url', - 'git.tags', - 'git.total.commit.count' - ] -} - -// copied from: org.opensearch.gradle.dependencies.CompileOnlyResolvePlugin -project.getConfigurations().all { Configuration configuration -> - if (configuration.getName().equals(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME)) { - NamedDomainObjectProvider resolvableCompileOnly = project.getConfigurations().register('resolveableCompileOnly'); - resolvableCompileOnly.configure { c -> - c.setCanBeResolved(true); - c.setCanBeConsumed(false); - c.extendsFrom(configuration); - }; - } -}; - -task bundle(dependsOn: jar, type: Zip) { - from configurations.runtimeClasspath - project.configurations.getByName('resolveableCompileOnly') - from project.jar - from 'plugin-security.policy' - from 'plugin-descriptor.properties' - from('securityconfig') { - into 'config/' - } - from('tools') { - into 'tools/' - } -} - task bundleSecurityAdminStandalone(dependsOn: jar, type: Zip) { archiveClassifier = 'securityadmin-standalone' from(configurations.runtimeClasspath) { @@ -302,10 +381,11 @@ task bundleSecurityAdminStandalone(dependsOn: jar, type: Zip) { from('tools') { into 'tools/' } - from('securityconfig') { + from('config') { into 'deps/securityconfig' } } + task bundleSecurityAdminStandaloneTarGz(dependsOn: jar, type: Tar) { archiveClassifier = 'securityadmin-standalone' archiveExtension = 'tar.gz' @@ -319,110 +399,90 @@ task bundleSecurityAdminStandaloneTarGz(dependsOn: jar, type: Tar) { from('tools') { into 'tools/' } - from('securityconfig') { + from('config') { into 'deps/securityconfig' } } -task createPluginDescriptor() { - List descriptorProperties = [ - "description=Provide access control related features for OpenSearch", - "version=${version}", - "name=opensearch-security", - "classname=org.opensearch.security.OpenSearchSecurityPlugin", - "java.version=${java.targetCompatibility}", - "opensearch.version=${version_tokens[0]}", - ] - - new File("plugin-descriptor.properties").text = descriptorProperties.join ("\n") -} -bundle.doLast() { - new File("plugin-descriptor.properties").delete() -} - -tasks.assemble.dependsOn(bundle) -tasks.bundle.dependsOn(createPluginDescriptor) - -clean { - delete 'data/' +buildRpm { + arch = 'NOARCH' + addParentDirs = false + archiveName "${packageName}-${version}.rpm" } - -task createChecksums(type: Checksum) { - files = bundle.outputs.files - outputDir = new File(project.buildDir, "distributions") - algorithm = Checksum.Algorithm.SHA512 +buildDeb { + arch = 'all' + archiveName "${packageName}-${version}.deb" } -tasks.assemble.finalizedBy(createChecksums) - -jacoco { - reportsDirectory = file("$buildDir/reports/jacoco") -} -jacocoTestReport { - reports { - xml.required = true +publishing { + publications { + maven(MavenPublication) { + from(components.java) + artifact(testsJar) + } } } -tasks.test.finalizedBy(jacocoTestReport) // report is always generated after tests run -tasks.jacocoTestReport.dependsOn(test) // tests are required to run before generating the report +// This is afterEvaluate because the bundlePlugin ZIP task is updated afterEvaluate and changes the ZIP name to match the plugin name +afterEvaluate { + ospackage { + packageName = "${name}" + release = isSnapshot ? "0.1" : '1' + version = "${project.version}" - "-SNAPSHOT" -checkstyle { - configFile file("config/checkstyle/sun_checks.xml") -} + into '/usr/share/opensearch/plugins' + from(zipTree(bundlePlugin.archivePath)) { + into opensearchplugin.name + } -tasks.withType(Checkstyle) { - showViolations true - reports { - ignoreFailures = false + user 'root' + permissionGroup 'root' + fileMode 0644 + dirMode 0755 + + requires('opensearch', versions.opensearch, EQUAL) + packager = 'Amazon' + vendor = 'Amazon' + os = 'LINUX' + prefix '/usr' + + license 'ASL-2.0' + maintainer 'OpenSearch ' + url 'https://opensearch.org/downloads.html' + summary ''' + Security plugin for OpenSearch. + Reference documentation can be found at https://opensearch.org/docs/latest/. + '''.stripIndent().replace('\n', ' ').trim() } -} -tasks.withType(JavaCompile) { - configure(options) { - options.compilerArgs << '-Xlint:removal' << '-Werror' + buildRpm { + arch = 'NOARCH' + dependsOn 'assemble' + finalizedBy 'renameRpm' + task renameRpm(type: Copy) { + from("$buildDir/distributions") + into("$buildDir/distributions") + include archiveName + rename archiveName, "${packageName}-${version}.rpm" + doLast { delete file("$buildDir/distributions/$archiveName") } + } } -} - -spotless { - java { - // note: you can use an empty string for all the imports you didn't specify explicitly, and '\\#` prefix for static imports - importOrder('java', 'javax', '', 'com.amazon', 'org.opensearch', '\\#') - } -} -buildRpm { - arch = 'NOARCH' - addParentDirs = false - archiveName "${packageName}-${version}.rpm" -} -buildDeb { - arch = 'all' - archiveName "${packageName}-${version}.deb" -} - -allprojects { - // add a collection to track failedTests - ext.failedTests = [] - - // add a testlistener to all tasks of type Test - tasks.withType(Test) { - afterTest { TestDescriptor descriptor, TestResult result -> - if(result.resultType == org.gradle.api.tasks.testing.TestResult.ResultType.FAILURE){ - failedTests << ["${descriptor.className}::${descriptor.name}"] - } + buildDeb { + arch = 'all' + dependsOn 'assemble' + finalizedBy 'renameDeb' + task renameDeb(type: Copy) { + from("$buildDir/distributions") + into("$buildDir/distributions") + include archiveName + rename archiveName, "${packageName}-${version}.deb" + doLast { delete file("$buildDir/distributions/$archiveName") } } } - // print out tracked failed tests when the build has finished - gradle.buildFinished { - if(!failedTests.empty){ - println "Failed tests for ${project.name}:" - failedTests.each { failedTest -> - println failedTest - } - println "" - } + task buildPackages(type: GradleBuild) { + tasks = ['build', 'buildRpm', 'buildDeb'] } } diff --git a/config/checkstyle/sun_checks.xml b/checkstyle/sun_checks.xml similarity index 94% rename from config/checkstyle/sun_checks.xml rename to checkstyle/sun_checks.xml index e4c0e03341..099c8d39a5 100644 --- a/config/checkstyle/sun_checks.xml +++ b/checkstyle/sun_checks.xml @@ -194,22 +194,14 @@ - + - - - - - - - - - + diff --git a/securityconfig/action_groups.yml b/config/action_groups.yml similarity index 100% rename from securityconfig/action_groups.yml rename to config/action_groups.yml diff --git a/securityconfig/allowlist.yml b/config/allowlist.yml similarity index 100% rename from securityconfig/allowlist.yml rename to config/allowlist.yml diff --git a/securityconfig/audit.yml b/config/audit.yml similarity index 100% rename from securityconfig/audit.yml rename to config/audit.yml diff --git a/securityconfig/config.yml b/config/config.yml similarity index 100% rename from securityconfig/config.yml rename to config/config.yml diff --git a/securityconfig/internal_users.yml b/config/internal_users.yml similarity index 100% rename from securityconfig/internal_users.yml rename to config/internal_users.yml diff --git a/securityconfig/nodes_dn.yml b/config/nodes_dn.yml similarity index 100% rename from securityconfig/nodes_dn.yml rename to config/nodes_dn.yml diff --git a/securityconfig/opensearch.yml.example b/config/opensearch.yml.example similarity index 100% rename from securityconfig/opensearch.yml.example rename to config/opensearch.yml.example diff --git a/securityconfig/roles.yml b/config/roles.yml similarity index 100% rename from securityconfig/roles.yml rename to config/roles.yml diff --git a/securityconfig/roles_mapping.yml b/config/roles_mapping.yml similarity index 100% rename from securityconfig/roles_mapping.yml rename to config/roles_mapping.yml diff --git a/securityconfig/tenants.yml b/config/tenants.yml similarity index 100% rename from securityconfig/tenants.yml rename to config/tenants.yml diff --git a/securityconfig/whitelist.yml b/config/whitelist.yml similarity index 100% rename from securityconfig/whitelist.yml rename to config/whitelist.yml diff --git a/src/main/java/org/opensearch/security/dlic/rest/api/MigrateApiAction.java b/src/main/java/org/opensearch/security/dlic/rest/api/MigrateApiAction.java index 7ea87cba09..6c973f3557 100644 --- a/src/main/java/org/opensearch/security/dlic/rest/api/MigrateApiAction.java +++ b/src/main/java/org/opensearch/security/dlic/rest/api/MigrateApiAction.java @@ -27,7 +27,7 @@ import org.opensearch.action.bulk.BulkResponse; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.support.WriteRequest.RefreshPolicy; -import org.opensearch.action.support.master.AcknowledgedResponse; +import org.opensearch.action.support.clustermanager.AcknowledgedResponse; import org.opensearch.client.Client; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.cluster.service.ClusterService; diff --git a/src/main/java/org/opensearch/security/dlic/rest/api/WhitelistApiAction.java b/src/main/java/org/opensearch/security/dlic/rest/api/WhitelistApiAction.java index 1928bbdf7a..6f55a2d762 100644 --- a/src/main/java/org/opensearch/security/dlic/rest/api/WhitelistApiAction.java +++ b/src/main/java/org/opensearch/security/dlic/rest/api/WhitelistApiAction.java @@ -9,7 +9,6 @@ * GitHub history for details. */ - package org.opensearch.security.dlic.rest.api; import java.nio.file.Path; diff --git a/src/main/java/org/opensearch/security/securityconf/DynamicConfigFactory.java b/src/main/java/org/opensearch/security/securityconf/DynamicConfigFactory.java index e735c82b45..d812bd7bbb 100644 --- a/src/main/java/org/opensearch/security/securityconf/DynamicConfigFactory.java +++ b/src/main/java/org/opensearch/security/securityconf/DynamicConfigFactory.java @@ -184,7 +184,6 @@ public void onChange(Map> typeToConfig) { " whitelist " + whitelistingSetting.getImplementingClass() + " with " + whitelistingSetting.getCEntries().size() + " entries\n" + " allowlist " + allowlistingSetting.getImplementingClass() + " with " + allowlistingSetting.getCEntries().size() + " entries\n"; log.debug(logmsg); - } final DynamicConfigModel dcm; diff --git a/src/main/java/org/opensearch/security/ssl/util/CertFileProps.java b/src/main/java/org/opensearch/security/ssl/util/CertFileProps.java index 018d922c6c..3e86ec5ede 100644 --- a/src/main/java/org/opensearch/security/ssl/util/CertFileProps.java +++ b/src/main/java/org/opensearch/security/ssl/util/CertFileProps.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; diff --git a/src/main/java/org/opensearch/security/ssl/util/CertFromFile.java b/src/main/java/org/opensearch/security/ssl/util/CertFromFile.java index 7383ae8290..d3cb62efe0 100644 --- a/src/main/java/org/opensearch/security/ssl/util/CertFromFile.java +++ b/src/main/java/org/opensearch/security/ssl/util/CertFromFile.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.File; diff --git a/src/main/java/org/opensearch/security/ssl/util/CertFromKeystore.java b/src/main/java/org/opensearch/security/ssl/util/CertFromKeystore.java index 4591ace69c..f2395a350a 100644 --- a/src/main/java/org/opensearch/security/ssl/util/CertFromKeystore.java +++ b/src/main/java/org/opensearch/security/ssl/util/CertFromKeystore.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.IOException; diff --git a/src/main/java/org/opensearch/security/ssl/util/CertFromTruststore.java b/src/main/java/org/opensearch/security/ssl/util/CertFromTruststore.java index 8ca7e500a7..86dae8da50 100644 --- a/src/main/java/org/opensearch/security/ssl/util/CertFromTruststore.java +++ b/src/main/java/org/opensearch/security/ssl/util/CertFromTruststore.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.IOException; diff --git a/src/main/java/org/opensearch/security/ssl/util/CertificateValidator.java b/src/main/java/org/opensearch/security/ssl/util/CertificateValidator.java index 4ab0760fc4..81d625126b 100644 --- a/src/main/java/org/opensearch/security/ssl/util/CertificateValidator.java +++ b/src/main/java/org/opensearch/security/ssl/util/CertificateValidator.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; // diff --git a/src/main/java/org/opensearch/security/ssl/util/KeystoreProps.java b/src/main/java/org/opensearch/security/ssl/util/KeystoreProps.java index 9d79f28916..37fa6b791b 100644 --- a/src/main/java/org/opensearch/security/ssl/util/KeystoreProps.java +++ b/src/main/java/org/opensearch/security/ssl/util/KeystoreProps.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.File; diff --git a/src/main/java/org/opensearch/security/tools/SecurityAdmin.java b/src/main/java/org/opensearch/security/tools/SecurityAdmin.java index 6360f508b3..4839524552 100644 --- a/src/main/java/org/opensearch/security/tools/SecurityAdmin.java +++ b/src/main/java/org/opensearch/security/tools/SecurityAdmin.java @@ -89,7 +89,7 @@ import org.opensearch.action.get.GetResponse; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.support.WriteRequest.RefreshPolicy; -import org.opensearch.action.support.master.AcknowledgedResponse; +import org.opensearch.action.support.clustermanager.AcknowledgedResponse; import org.opensearch.client.Request; import org.opensearch.client.RequestOptions; import org.opensearch.client.Response; diff --git a/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java b/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java index f391ee4a8a..2e4b659841 100644 --- a/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java @@ -26,15 +26,12 @@ import com.google.common.io.BaseEncoding; import io.jsonwebtoken.JwtBuilder; -import io.jsonwebtoken.JwtParser; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import org.apache.http.HttpHeaders; import org.junit.Assert; import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.internal.util.reflection.FieldSetter; import org.opensearch.common.settings.Settings; import org.opensearch.security.user.AuthCredentials; @@ -148,15 +145,12 @@ public void testBearerWrongPosition() throws Exception { public void testBasicAuthHeader() throws Exception { Settings settings = Settings.builder().put("signing_key", BaseEncoding.base64().encode(secretKeyBytes)).build(); HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null); - JwtParser jwtParser = Mockito.spy(JwtParser.class); - FieldSetter.setField(jwtAuth, HTTPJwtAuthenticator.class.getDeclaredField("jwtParser"), jwtParser); String basicAuth = BaseEncoding.base64().encode("user:password".getBytes(StandardCharsets.UTF_8)); Map headers = Collections.singletonMap(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); AuthCredentials credentials = jwtAuth.extractCredentials(new FakeRestRequest(headers, Collections.emptyMap()), null); Assert.assertNull(credentials); - Mockito.verifyZeroInteractions(jwtParser); } @Test diff --git a/src/test/java/com/amazon/dlic/auth/http/saml/MockSamlIdpServer.java b/src/test/java/com/amazon/dlic/auth/http/saml/MockSamlIdpServer.java index 8ceb44aeab..9b2a2f1854 100644 --- a/src/test/java/com/amazon/dlic/auth/http/saml/MockSamlIdpServer.java +++ b/src/test/java/com/amazon/dlic/auth/http/saml/MockSamlIdpServer.java @@ -87,7 +87,6 @@ import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; -import org.apache.xml.security.utils.EncryptionConstants; import org.joda.time.DateTime; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.XMLObjectBuilderFactory; @@ -516,7 +515,8 @@ private String createSamlAuthResponse(AuthnRequest authnRequest) { private Encrypter getEncrypter() { KeyEncryptionParameters kek = new KeyEncryptionParameters(); - kek.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); + // Algorithm from https://santuario.apache.org/Java/api/constant-values.html#org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15 + kek.setAlgorithm("http://www.w3.org/2001/04/xmlenc#rsa-1_5"); kek.setEncryptionCredential(new BasicX509Credential(spSignatureCertificate)); Encrypter encrypter = new Encrypter( new DataEncryptionParameters(),kek); encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE); diff --git a/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java b/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java index d9f2bd607a..e4711bb504 100644 --- a/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java +++ b/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java @@ -25,18 +25,19 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.cluster.ClusterConfiguration; +import org.opensearch.security.test.helper.cluster.ClusterHelper; import org.opensearch.security.test.helper.rest.RestHelper; public class AdvancedSecurityMigrationTests extends SingleClusterTest { @Before public void setupBefore() { - System.setProperty("security.default_init.dir", new File("./src/test/resources/security_passive").getAbsolutePath()); + ClusterHelper.updateDefaultDirectory(new File(TEST_RESOURCE_RELATIVE_PATH + "security_passive").getAbsolutePath()); } @After public void cleanupAfter() { - System.setProperty("security.default_init.dir", new File("./securityconfig").getAbsolutePath()); + ClusterHelper.resetSystemProperties(); } /** diff --git a/src/test/java/org/opensearch/security/ConfigTests.java b/src/test/java/org/opensearch/security/ConfigTests.java index cd7c21b892..8d7ebf8003 100644 --- a/src/test/java/org/opensearch/security/ConfigTests.java +++ b/src/test/java/org/opensearch/security/ConfigTests.java @@ -42,6 +42,7 @@ import org.opensearch.security.securityconf.impl.v7.RoleMappingsV7; import org.opensearch.security.securityconf.impl.v7.RoleV7; import org.opensearch.security.securityconf.impl.v7.TenantV7; +import org.opensearch.security.test.SingleClusterTest; public class ConfigTests { @@ -76,26 +77,27 @@ public void testMigrate() throws Exception { public void testParseSg67Config() throws Exception { check("./legacy/securityconfig_v6/action_groups.yml", CType.ACTIONGROUPS); - check("./securityconfig/action_groups.yml", CType.ACTIONGROUPS); + check("./action_groups.yml", CType.ACTIONGROUPS); check("./legacy/securityconfig_v6/config.yml", CType.CONFIG); - check("./securityconfig/config.yml", CType.CONFIG); + check("./config.yml", CType.CONFIG); check("./legacy/securityconfig_v6/roles.yml", CType.ROLES); - check("./securityconfig/roles.yml", CType.ROLES); + check("./roles.yml", CType.ROLES); check("./legacy/securityconfig_v6/internal_users.yml", CType.INTERNALUSERS); - check("./securityconfig/internal_users.yml", CType.INTERNALUSERS); + check("./internal_users.yml", CType.INTERNALUSERS); check("./legacy/securityconfig_v6/roles_mapping.yml", CType.ROLESMAPPING); - check("./securityconfig/roles_mapping.yml", CType.ROLESMAPPING); + check("./roles_mapping.yml", CType.ROLESMAPPING); - check("./securityconfig/tenants.yml", CType.TENANTS); + check("./tenants.yml", CType.TENANTS); } private void check(String file, CType cType) throws Exception { - JsonNode jsonNode = YAML.readTree(FileUtils.readFileToString(new File(file), "UTF-8")); + final String adjustedFilePath = SingleClusterTest.TEST_RESOURCE_RELATIVE_PATH + file; + JsonNode jsonNode = YAML.readTree(FileUtils.readFileToString(new File(adjustedFilePath), "UTF-8")); int configVersion = 1; System.out.println("%%%%%%%% THIS IS A LINE OF INTEREST %%%%%%%"); if(jsonNode.get("_meta") != null) { @@ -116,7 +118,8 @@ private void check(String file, CType cType) throws Exception { } private SecurityDynamicConfiguration load(String file, CType cType) throws Exception { - JsonNode jsonNode = YAML.readTree(FileUtils.readFileToString(new File(file), "UTF-8")); + final String adjustedFilePath = SingleClusterTest.TEST_RESOURCE_RELATIVE_PATH + file; + JsonNode jsonNode = YAML.readTree(FileUtils.readFileToString(new File(adjustedFilePath), "UTF-8")); int configVersion = 1; System.out.println("%%%%%%%% THIS IS A LINE OF INTEREST LOAD: CONFIG VERSION: %%%%%%%"); diff --git a/src/test/java/org/opensearch/security/InitializationIntegrationTests.java b/src/test/java/org/opensearch/security/InitializationIntegrationTests.java index f5285bec22..090b1ece75 100644 --- a/src/test/java/org/opensearch/security/InitializationIntegrationTests.java +++ b/src/test/java/org/opensearch/security/InitializationIntegrationTests.java @@ -54,6 +54,7 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.DynamicSecurityConfig; import org.opensearch.security.test.SingleClusterTest; +import org.opensearch.security.test.helper.cluster.ClusterHelper; import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; @@ -194,9 +195,8 @@ public void testDefaultConfig() throws Exception { @Test public void testInvalidDefaultConfig() throws Exception { - String defaultInitDirectory = System.getProperty("security.default_init.dir"); try { - System.setProperty("security.default_init.dir", new File("./src/test/resources/invalid_config").getAbsolutePath()); + final String defaultInitDirectory = ClusterHelper.updateDefaultDirectory(new File(TEST_RESOURCE_RELATIVE_PATH + "invalid_config").getAbsolutePath()); final Settings settings = Settings.builder() .put(ConfigConstants.SECURITY_ALLOW_DEFAULT_INIT_SECURITYINDEX, true) .build(); @@ -205,17 +205,13 @@ public void testInvalidDefaultConfig() throws Exception { Thread.sleep(10000); Assert.assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode()); - System.setProperty("security.default_init.dir", defaultInitDirectory); + ClusterHelper.updateDefaultDirectory(defaultInitDirectory); restart(Settings.EMPTY, null, settings, false); rh = nonSslRestHelper(); Thread.sleep(10000); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode()); } finally { - if (defaultInitDirectory != null) { - System.setProperty("security.default_init.dir", defaultInitDirectory); - } else { - System.clearProperty("security.default_init.dir"); - } + ClusterHelper.resetSystemProperties(); } } diff --git a/src/test/java/org/opensearch/security/IntegrationTests.java b/src/test/java/org/opensearch/security/IntegrationTests.java index 8e74e033be..985ea826b6 100644 --- a/src/test/java/org/opensearch/security/IntegrationTests.java +++ b/src/test/java/org/opensearch/security/IntegrationTests.java @@ -26,7 +26,6 @@ package org.opensearch.security; -import java.lang.Thread.UncaughtExceptionHandler; import java.util.TreeSet; import com.fasterxml.jackson.databind.JsonNode; @@ -63,17 +62,7 @@ public class IntegrationTests extends SingleClusterTest { @Test - public void testSearchScroll() throws Exception { - - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - - @Override - public void uncaughtException(Thread t, Throwable e) { - e.printStackTrace(); - - } - }); - + public void testSearchScroll() throws Exception { final Settings settings = Settings.builder() .putList(ConfigConstants.SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists") .build(); diff --git a/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java b/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java index 9ddff6414c..1f9668c641 100644 --- a/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java +++ b/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security; import com.google.common.collect.ImmutableMap; diff --git a/src/test/java/org/opensearch/security/RolesValidationIntegTest.java b/src/test/java/org/opensearch/security/RolesValidationIntegTest.java index ba36653fe8..86168c0c14 100644 --- a/src/test/java/org/opensearch/security/RolesValidationIntegTest.java +++ b/src/test/java/org/opensearch/security/RolesValidationIntegTest.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security; import java.nio.file.Path; diff --git a/src/test/java/org/opensearch/security/SecurityAdminTests.java b/src/test/java/org/opensearch/security/SecurityAdminTests.java index 18e6397ad7..0de30943de 100644 --- a/src/test/java/org/opensearch/security/SecurityAdminTests.java +++ b/src/test/java/org/opensearch/security/SecurityAdminTests.java @@ -56,8 +56,7 @@ public void testSecurityAdmin() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-nhnv"); @@ -89,8 +88,7 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -109,8 +107,7 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("--diagnose"); argsAsList.add("-nhnv"); @@ -129,8 +126,7 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-nhnv"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -159,8 +155,7 @@ public void testSecurityAdminV6Update() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("./legacy/securityconfig_v6").getAbsolutePath()); + addDirectoryPath(argsAsList, new File("./legacy/securityconfig_v6").getAbsolutePath()); argsAsList.add("-nhnv"); @@ -196,8 +191,7 @@ public void testSecurityAdminRegularUpdate() throws Exception { argsAsList.add(String.valueOf(clusterInfo.httpPort)); argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-nhnv"); @@ -235,7 +229,7 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); argsAsList.add("-f"); - argsAsList.add(new File("./securityconfig/config.yml").getAbsolutePath()); + argsAsList.add(new File(TEST_RESOURCE_RELATIVE_PATH + "config.yml").getAbsolutePath()); argsAsList.add("-t"); argsAsList.add("config"); argsAsList.add("-nhnv"); @@ -254,7 +248,7 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); argsAsList.add("-f"); - argsAsList.add(new File("./securityconfig/roles_mapping.yml").getAbsolutePath()); + argsAsList.add(new File(TEST_RESOURCE_RELATIVE_PATH + "roles_mapping.yml").getAbsolutePath()); argsAsList.add("-t"); argsAsList.add("rolesmapping"); argsAsList.add("-nhnv"); @@ -273,7 +267,7 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); argsAsList.add("-f"); - argsAsList.add(new File("./securityconfig/tenants.yml").getAbsolutePath()); + argsAsList.add(new File(TEST_RESOURCE_RELATIVE_PATH + "tenants.yml").getAbsolutePath()); argsAsList.add("-t"); argsAsList.add("tenants"); argsAsList.add("-nhnv"); @@ -313,7 +307,7 @@ public void testSecurityAdminSingularV6Updates() throws Exception { argsAsList.add("-cn"); argsAsList.add(clusterInfo.clustername); argsAsList.add("-f"); - argsAsList.add(new File("./legacy/securityconfig_v6/config.yml").getAbsolutePath()); + argsAsList.add(new File(TEST_RESOURCE_RELATIVE_PATH + "legacy/securityconfig_v6/config.yml").getAbsolutePath()); argsAsList.add("-t"); argsAsList.add("config"); argsAsList.add("-nhnv"); @@ -420,8 +414,7 @@ public void testSecurityAdminReloadInvalidConfig() throws Exception { @Test public void testSecurityAdminValidateConfig() throws Exception { List argsAsList = new ArrayList<>(); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-vc"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -429,7 +422,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-f"); - argsAsList.add(new File("src/test/resources/roles.yml").getAbsolutePath()); + argsAsList.add(new File(PROJECT_ROOT_RELATIVE_PATH + "src/test/resources/roles.yml").getAbsolutePath()); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -437,7 +430,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-f"); - argsAsList.add(new File("./src/main/resources/static_config/static_roles.yml").getAbsolutePath()); + argsAsList.add(new File(PROJECT_ROOT_RELATIVE_PATH + "src/main/resources/static_config/static_roles.yml").getAbsolutePath()); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -445,7 +438,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-f"); - argsAsList.add(new File("./src/main/resources/static_config/static_action_groups.yml").getAbsolutePath()); + argsAsList.add(new File(PROJECT_ROOT_RELATIVE_PATH + "src/main/resources/static_config/static_action_groups.yml").getAbsolutePath()); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -453,7 +446,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-f"); - argsAsList.add(new File("./src/main/resources/static_config/static_tenants.yml").getAbsolutePath()); + argsAsList.add(new File(PROJECT_ROOT_RELATIVE_PATH + "src/main/resources/static_config/static_tenants.yml").getAbsolutePath()); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); @@ -461,7 +454,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-f"); - argsAsList.add(new File("src/test/resources/roles.yml").getAbsolutePath()); + argsAsList.add(TEST_RESOURCE_ABSOLUTE_PATH + "roles.yml"); argsAsList.add("-vc"); argsAsList.add("-t"); argsAsList.add("config"); @@ -471,23 +464,21 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList = new ArrayList<>(); argsAsList.add("-ks"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + argsAsList.add(TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); Assert.assertNotEquals(0, returnCode); argsAsList = new ArrayList<>(); - argsAsList.add("-cd"); - argsAsList.add(new File("./legacy/securityconfig_v6").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH + "legacy/securityconfig_v6"); argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); Assert.assertNotEquals(0, returnCode); argsAsList = new ArrayList<>(); - argsAsList.add("-cd"); - argsAsList.add(new File("./legacy/securityconfig_v6").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH + "legacy/securityconfig_v6"); argsAsList.add("-vc"); argsAsList.add("6"); @@ -495,12 +486,16 @@ public void testSecurityAdminValidateConfig() throws Exception { Assert.assertEquals(0, returnCode); argsAsList = new ArrayList<>(); - argsAsList.add("-cd"); - argsAsList.add(new File("src/test/resources/").getAbsolutePath()); + addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); argsAsList.add("-vc"); argsAsList.add("8"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); Assert.assertNotEquals(0, returnCode); } + + private void addDirectoryPath(final List args, final String path) { + args.add("-cd"); + args.add(path); + } } diff --git a/src/test/java/org/opensearch/security/SnapshotRestoreTests.java b/src/test/java/org/opensearch/security/SnapshotRestoreTests.java index 6c92788748..03d1128bfe 100644 --- a/src/test/java/org/opensearch/security/SnapshotRestoreTests.java +++ b/src/test/java/org/opensearch/security/SnapshotRestoreTests.java @@ -26,16 +26,9 @@ package org.opensearch.security; -import java.util.Arrays; -import java.util.Collection; - import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; import org.opensearch.action.admin.cluster.repositories.put.PutRepositoryRequest; import org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest; @@ -52,18 +45,8 @@ import org.opensearch.security.test.helper.cluster.ClusterConfiguration; import org.opensearch.security.test.helper.rest.RestHelper; -@RunWith(Parameterized.class) public class SnapshotRestoreTests extends SingleClusterTest { - - @Parameters - public static Collection data() { - return Arrays.asList(new ClusterConfiguration[] { - ClusterConfiguration.DEFAULT - }); - } - - @Parameter - public ClusterConfiguration currentClusterConfig; + private ClusterConfiguration currentClusterConfig = ClusterConfiguration.DEFAULT; @Test public void testSnapshotEnableSecurityIndexRestore() throws Exception { diff --git a/src/test/java/org/opensearch/security/TracingTests.java b/src/test/java/org/opensearch/security/TracingTests.java index 6021bb6241..4c7e0472ce 100644 --- a/src/test/java/org/opensearch/security/TracingTests.java +++ b/src/test/java/org/opensearch/security/TracingTests.java @@ -26,8 +26,6 @@ package org.opensearch.security; -import java.lang.Thread.UncaughtExceptionHandler; - import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Ignore; @@ -239,16 +237,6 @@ public void testHTTPTraceNoSource() throws Exception { @Test public void testHTTPSingle() throws Exception { - - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - - @Override - public void uncaughtException(Thread t, Throwable e) { - e.printStackTrace(); - - } - }); - final Settings settings = Settings.builder() .putList(ConfigConstants.SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists") .build(); @@ -305,16 +293,6 @@ public void uncaughtException(Thread t, Throwable e) { @Test public void testSearchScroll() throws Exception { - - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - - @Override - public void uncaughtException(Thread t, Throwable e) { - e.printStackTrace(); - - } - }); - final Settings settings = Settings.builder() .putList(ConfigConstants.SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists") .build(); diff --git a/src/test/java/org/opensearch/security/TransportUserInjectorIntegTest.java b/src/test/java/org/opensearch/security/TransportUserInjectorIntegTest.java index 6a96c02926..065b99146b 100644 --- a/src/test/java/org/opensearch/security/TransportUserInjectorIntegTest.java +++ b/src/test/java/org/opensearch/security/TransportUserInjectorIntegTest.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security; import java.nio.file.Path; diff --git a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java index 79f9108518..a88baef90f 100644 --- a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java @@ -183,13 +183,12 @@ public void testSourceFilterMsearch() throws Exception { " }" + "}"+System.lineSeparator(); - TestAuditlogImpl.clear(); - HttpResponse response = rh.executePostRequest("_msearch?pretty", search, encodeBasicHeader("admin", "admin")); - assertNotContains(response, "*exception*"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Thread.sleep(1500); + TestAuditlogImpl.doThenWaitForMessages(() -> { + HttpResponse response = rh.executePostRequest("_msearch?pretty", search, encodeBasicHeader("admin", "admin")); + assertNotContains(response, "*exception*"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + }, 2); System.out.println(TestAuditlogImpl.sb.toString()); - Assert.assertTrue("Was "+TestAuditlogImpl.messages.size(), TestAuditlogImpl.messages.size() == 2); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("COMPLIANCE_DOC_READ")); Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("Salary")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("Gender")); diff --git a/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java b/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java index 7c38bc952c..49dd3b38b2 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java @@ -11,9 +11,6 @@ package org.opensearch.security.auditlog.impl; -import java.lang.Thread.UncaughtExceptionHandler; - -import net.jcip.annotations.NotThreadSafe; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; @@ -35,7 +32,6 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -@NotThreadSafe public class TracingTests extends SingleClusterTest { @Override @@ -215,16 +211,6 @@ public void testHTTPTrace() throws Exception { @Test public void testHTTPSingle() throws Exception { - - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - - @Override - public void uncaughtException(Thread t, Throwable e) { - e.printStackTrace(); - - } - }); - final Settings settings = Settings.builder() .putList(ConfigConstants.SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists") .build(); @@ -281,16 +267,6 @@ public void uncaughtException(Thread t, Throwable e) { @Test public void testSearchScroll() throws Exception { - - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - - @Override - public void uncaughtException(Thread t, Throwable e) { - e.printStackTrace(); - - } - }); - final Settings settings = Settings.builder() .putList(ConfigConstants.SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists") .build(); diff --git a/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java b/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java index 03ee1b16b5..ea9ce18e3d 100644 --- a/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java +++ b/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java @@ -11,9 +11,11 @@ package org.opensearch.security.auditlog.sink; +import java.lang.Thread.UncaughtExceptionHandler; import java.time.Duration; import java.util.Arrays; import java.util.Properties; +import java.util.Random; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; @@ -21,7 +23,6 @@ import org.junit.ClassRule; import org.junit.Test; import org.springframework.kafka.test.rule.EmbeddedKafkaRule; -import scala.util.Random; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.yaml.YamlXContent; @@ -32,40 +33,54 @@ public class KafkaSinkTest extends AbstractAuditlogiUnitTest { - @ClassRule - public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1, true, 1, "compliance"); + @ClassRule + public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1, true, 1, "compliance") { + // Prevents test exceptions from randomized runner, see https://bit.ly/3y17IkI + private UncaughtExceptionHandler currentHandler; + @Override + public void before() { + currentHandler = Thread.getDefaultUncaughtExceptionHandler(); + super.before(); + } - @Test - public void testKafka() throws Exception { - String configYml = FileHelper.loadFile("auditlog/endpoints/sink/configuration_kafka.yml"); - configYml = configYml.replace("_RPLC_BOOTSTRAP_SERVERS_",embeddedKafka.getEmbeddedKafka().getBrokersAsString()); - Settings.Builder settingsBuilder = Settings.builder().loadFromSource(configYml, YamlXContent.yamlXContent.type()); - try(KafkaConsumer consumer = createConsumer()) { - consumer.subscribe(Arrays.asList("compliance")); + @Override + public void after() { + super.after(); + Thread.setDefaultUncaughtExceptionHandler(currentHandler); + } + }; - Settings settings = settingsBuilder.put("path.home", ".").build(); - SinkProvider provider = new SinkProvider(settings, null, null, null); - AuditLogSink sink = provider.getDefaultSink(); - try { - Assert.assertEquals(KafkaSink.class, sink.getClass()); - boolean success = sink.doStore(MockAuditMessageFactory.validAuditMessage(AuditCategory.MISSING_PRIVILEGES)); - Assert.assertTrue(success); - ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); - Assert.assertEquals(1, records.count()); - } finally { - sink.close(); - } - } + @Test + public void testKafka() throws Exception { + String configYml = FileHelper.loadFile("auditlog/endpoints/sink/configuration_kafka.yml"); + configYml = configYml.replace("_RPLC_BOOTSTRAP_SERVERS_",embeddedKafka.getEmbeddedKafka().getBrokersAsString()); + Settings.Builder settingsBuilder = Settings.builder().loadFromSource(configYml, YamlXContent.yamlXContent.type()); + try(KafkaConsumer consumer = createConsumer()) { + consumer.subscribe(Arrays.asList("compliance")); - } + Settings settings = settingsBuilder.put("path.home", ".").build(); + SinkProvider provider = new SinkProvider(settings, null, null, null); + AuditLogSink sink = provider.getDefaultSink(); + try { + Assert.assertEquals(KafkaSink.class, sink.getClass()); + boolean success = sink.doStore(MockAuditMessageFactory.validAuditMessage(AuditCategory.MISSING_PRIVILEGES)); + Assert.assertTrue(success); + ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); + Assert.assertEquals(1, records.count()); + } finally { + sink.close(); + } + } - private KafkaConsumer createConsumer() { - Properties props = new Properties(); - props.put("bootstrap.servers", embeddedKafka.getEmbeddedKafka().getBrokersAsString()); - props.put("auto.offset.reset", "earliest"); - props.put("group.id", "mygroup"+System.currentTimeMillis()+"_"+new Random().nextDouble()); - props.put("key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"); - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - return new KafkaConsumer<>(props); - } + } + + private KafkaConsumer createConsumer() { + Properties props = new Properties(); + props.put("bootstrap.servers", embeddedKafka.getEmbeddedKafka().getBrokersAsString()); + props.put("auto.offset.reset", "earliest"); + props.put("group.id", "mygroup"+System.currentTimeMillis()+"_"+new Random().nextDouble()); + props.put("key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"); + props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + return new KafkaConsumer<>(props); + } } diff --git a/src/test/java/org/opensearch/security/auth/UserInjectorTest.java b/src/test/java/org/opensearch/security/auth/UserInjectorTest.java index cfde2c89de..09bc1653a4 100644 --- a/src/test/java/org/opensearch/security/auth/UserInjectorTest.java +++ b/src/test/java/org/opensearch/security/auth/UserInjectorTest.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.auth; import java.util.Arrays; diff --git a/src/test/java/org/opensearch/security/ccstest/CrossClusterMinimalRoundtripSearchTests.java b/src/test/java/org/opensearch/security/ccstest/CrossClusterMinimalRoundtripSearchTests.java new file mode 100644 index 0000000000..292a0d38d8 --- /dev/null +++ b/src/test/java/org/opensearch/security/ccstest/CrossClusterMinimalRoundtripSearchTests.java @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.ccstest; + +public class CrossClusterMinimalRoundtripSearchTests extends CrossClusterSearchTests { + @Override + protected boolean ccsMinimizeRoundtrips() { return true; } +} diff --git a/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java b/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java index 13f0629d7e..246e159c5a 100644 --- a/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java +++ b/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java @@ -30,10 +30,6 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; import org.opensearch.OpenSearchSecurityException; import org.opensearch.action.admin.cluster.health.ClusterHealthRequest; @@ -70,7 +66,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -@RunWith(Parameterized.class) public class CrossClusterSearchTests extends AbstractSecurityUnitTest { private final ClusterHelper cl1 = new ClusterHelper("crl1_n"+num.incrementAndGet()+"_f"+System.getProperty("forkno")+"_t"+System.nanoTime()); @@ -80,9 +75,7 @@ public class CrossClusterSearchTests extends AbstractSecurityUnitTest { private RestHelper rh1; private RestHelper rh2; - //default is true - @Parameter - public boolean ccsMinimizeRoundtrips; + protected boolean ccsMinimizeRoundtrips() { return false; }; private static class ClusterTransportClientSettings extends Tuple { @@ -103,12 +96,6 @@ public Settings transportClientSettings() { } } - - @Parameters - public static Object[] parameters() { - return new Object[] { Boolean.FALSE, Boolean.TRUE }; - } - private void setupCcs() throws Exception { setupCcs(new DynamicSecurityConfig()); } @@ -188,7 +175,7 @@ public void testCcs() throws Exception { HttpResponse ccs = null; System.out.println("###################### query 1"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("nagilum","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("crl1")); @@ -197,20 +184,20 @@ public void testCcs() throws Exception { System.out.println("###################### query 4"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:xx,xx/xx/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("nagilum","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:xx,xx/xx/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum","nagilum")); System.out.println(ccs.getBody()); //TODO fix exception nesting //Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, ccs.getStatusCode()); //Assert.assertTrue(ccs.getBody().contains("Can not filter indices; index cross_cluster_two:xx exists but there is also a remote cluster named: cross_cluster_two")); System.out.println("###################### query 5"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:abcnonext/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("nagilum","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:abcnonext/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("index_not_found_exception")); System.out.println("###################### query 6"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("nagilum","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("security_exception")); @@ -251,34 +238,34 @@ public void testCcsNonadmin() throws Exception { HttpResponse ccs = null; System.out.println("###################### query 1"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); System.out.println("###################### query 2"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); System.out.println("###################### query 3"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); System.out.println("###################### query 4"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); System.out.println("###################### query 5"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); @@ -287,7 +274,7 @@ public void testCcsNonadmin() throws Exception { "{}"+System.lineSeparator()+ "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator(); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest("cross_cluster_two:twitter,twitter/_msearch?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, msearchBody, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest("cross_cluster_two:twitter,twitter/_msearch?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), msearchBody, encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); @@ -296,35 +283,35 @@ public void testCcsNonadmin() throws Exception { "{}"+System.lineSeparator()+ "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator(); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest("cross_cluster_two:twitter/_msearch?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, msearchBody, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest("cross_cluster_two:twitter/_msearch?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), msearchBody, encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_all/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_all/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); @@ -338,54 +325,54 @@ public void testCcsNonadmin() throws Exception { Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); //TODO: Change for 25.0 to be forbidden (Indices options) - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); System.out.println("#### Alias both"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("notexist,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("notexist,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); //TODO Fix for 25.0 to resolve coordalias (Indices options) - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("crusherw","crusherw")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("crusherw","crusherw")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); @@ -422,33 +409,33 @@ public void testCcsNonadminDnfof() throws Exception { HttpResponse ccs = null; System.out.println("###################### query 1"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); System.out.println("###################### query 2"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); System.out.println("###################### query 3"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("twutter")); System.out.println("###################### query 4"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); System.out.println("###################### query 5"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); @@ -470,47 +457,47 @@ public void testCcsNonadminDnfof() throws Exception { System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_all/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_all/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); System.out.println("#####*"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*,*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:*,*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); //wildcard in remote cluster names - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*cross*:*twit*,*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*cross*:*twit*,*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,t*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter,t*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:*/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); @@ -524,47 +511,47 @@ public void testCcsNonadminDnfof() throws Exception { Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); //TODO: Change for 25.0 to be forbidden (Indices options) - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("*:/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("worf","worf")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("worf","worf")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("crusherw","crusherw")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("crusherw","crusherw")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); } @@ -587,7 +574,7 @@ public void testCcsEmptyCoord() throws Exception { HttpResponse ccs = null; System.out.println("###################### query 1"); - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("twitter","nagilum")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("twitter","nagilum")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("security_exception")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterMinimalRoundtripSearchTests.java b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterMinimalRoundtripSearchTests.java new file mode 100644 index 0000000000..86b97c1afe --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterMinimalRoundtripSearchTests.java @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.dlsfls; + +public class DlsFlsCrossClusterMinimalRoundtripSearchTests extends DlsFlsCrossClusterSearchTest { + @Override + protected boolean ccsMinimizeRoundtrips() { return true; } +} diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterSearchTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterSearchTest.java index eeee724f6d..d44d5b4f6e 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterSearchTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsFlsCrossClusterSearchTest.java @@ -15,10 +15,6 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.support.WriteRequest.RefreshPolicy; @@ -33,7 +29,6 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -@RunWith(Parameterized.class) public class DlsFlsCrossClusterSearchTest extends AbstractSecurityUnitTest { private final ClusterHelper cl1 = new ClusterHelper("crl1_n"+num.incrementAndGet()+"_f"+System.getProperty("forkno")+"_t"+System.nanoTime()); @@ -41,14 +36,7 @@ public class DlsFlsCrossClusterSearchTest extends AbstractSecurityUnitTest { private ClusterInfo cl1Info; private ClusterInfo cl2Info; - //default is true - @Parameter - public boolean ccsMinimizeRoundtrips; - - @Parameters - public static Object[] parameters() { - return new Object[] { Boolean.FALSE, Boolean.TRUE }; - } + protected boolean ccsMinimizeRoundtrips() { return false; }; @Override protected String getResourceFolder() { @@ -122,7 +110,7 @@ public void testCcs() throws Exception { System.out.println("###################### query 1"); //on coordinating cluster - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("human_resources_trainee", "password")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("human_resources_trainee", "password")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("crl1")); @@ -179,7 +167,7 @@ public void testCcsDifferentConfig() throws Exception { System.out.println("###################### query 1"); //on coordinating cluster - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("human_resources_trainee", "password")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("human_resources_trainee", "password")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertFalse(ccs.getBody().contains("crl1")); @@ -259,7 +247,7 @@ public void testCcsDifferentConfigBoth() throws Exception { System.out.println("###################### query 1"); //on coordinating cluster - ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources,humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips, encodeBasicHeader("human_resources_trainee", "password")); + ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest("cross_cluster_two:humanresources,humanresources/_search?pretty&ccs_minimize_roundtrips="+ccsMinimizeRoundtrips(), encodeBasicHeader("human_resources_trainee", "password")); System.out.println(ccs.getBody()); Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); Assert.assertTrue(ccs.getBody().contains("crl1")); diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AccountApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AccountApiTest.java index 05bdbc1f66..c1840524c9 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AccountApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AccountApiTest.java @@ -11,13 +11,10 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -29,26 +26,18 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class AccountApiTest extends AbstractRestApiUnitTest { - private final String BASE_ENDPOINT; - private final String ENDPOINT; - - - public AccountApiTest(String endpoint){ - BASE_ENDPOINT = endpoint; - ENDPOINT = BASE_ENDPOINT + "account"; + private final String BASE_ENDPOINT; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/", - PLUGINS_PREFIX + "/api/" - ); + public AccountApiTest(){ + BASE_ENDPOINT = getEndpointPrefix() + "/api/"; + ENDPOINT = getEndpointPrefix() + "/api/account"; } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiTest.java index b4c3fdf2ae..09efae9fbe 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiTest.java @@ -13,13 +13,10 @@ import java.util.List; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -27,24 +24,16 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class ActionGroupsApiTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public ActionGroupsApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/actiongroups", - PLUGINS_PREFIX + "/api/actiongroups" - ); + public ActionGroupsApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api/actiongroups"; } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java index c5949515e5..c5e0a61d2f 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java @@ -30,8 +30,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.DefaultObjectMapper; @@ -45,31 +43,23 @@ import static org.junit.Assert.assertTrue; import static org.opensearch.security.DefaultObjectMapper.readTree; import static org.opensearch.security.DefaultObjectMapper.writeValueAsString; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class AuditApiActionTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - private final String CONFIG_ENDPOINT; - // admin cred with roles in test yml files final Header adminCredsHeader = encodeBasicHeader("sarek", "sarek"); // non-admin final Header nonAdminCredsHeader = encodeBasicHeader("random", "random"); - public AuditApiActionTest(String endpoint){ - ENDPOINT = endpoint; - CONFIG_ENDPOINT = ENDPOINT + "/config"; + private final String ENDPOINT; + private final String CONFIG_ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/audit", - PLUGINS_PREFIX + "/api/audit" - ); + public AuditApiActionTest(){ + ENDPOINT = getEndpointPrefix() + "/api/audit"; + CONFIG_ENDPOINT = ENDPOINT + "/config"; } @Rule diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/DashboardsInfoActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/DashboardsInfoActionTest.java index a5841c42c0..c6af253f95 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/DashboardsInfoActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/DashboardsInfoActionTest.java @@ -11,35 +11,24 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class DashboardsInfoActionTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public DashboardsInfoActionTest(String endpoint) { - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpoint() { + return PLUGINS_PREFIX + "/dashboardsinfo"; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/kibanainfo", - PLUGINS_PREFIX + "/dashboardsinfo" - ); + public DashboardsInfoActionTest(){ + ENDPOINT = getEndpoint(); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/FlushCacheApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/FlushCacheApiTest.java index 3c42f020c6..ad0a4eea14 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/FlushCacheApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/FlushCacheApiTest.java @@ -11,70 +11,58 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class FlushCacheApiTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public FlushCacheApiTest(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/cache", - PLUGINS_PREFIX + "/api/cache" - ); - } - - @Test - public void testFlushCache() throws Exception { - - setup(); - - // Only DELETE is allowed for flush cache - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = true; - - // GET - HttpResponse response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); - Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.get("message"), "Method GET not supported for this action."); - - // PUT - response = rh.executePutRequest(ENDPOINT, "{}", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.get("message"), "Method PUT not supported for this action."); - - // POST - response = rh.executePostRequest(ENDPOINT, "{}", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.get("message"), "Method POST not supported for this action."); - - // DELETE - response = rh.executeDeleteRequest(ENDPOINT, new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.get("message"), "Cache flushed successfully."); - - } + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } + public FlushCacheApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api/cache"; + } + + @Test + public void testFlushCache() throws Exception { + + setup(); + + // Only DELETE is allowed for flush cache + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = true; + + // GET + HttpResponse response = rh.executeGetRequest(ENDPOINT); + Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); + Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.get("message"), "Method GET not supported for this action."); + + // PUT + response = rh.executePutRequest(ENDPOINT, "{}", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.get("message"), "Method PUT not supported for this action."); + + // POST + response = rh.executePostRequest(ENDPOINT, "{}", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.get("message"), "Method POST not supported for this action."); + + // DELETE + response = rh.executeDeleteRequest(ENDPOINT, new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.get("message"), "Cache flushed successfully."); + + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java index abdc9d143d..237e75a79a 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java @@ -12,86 +12,76 @@ package org.opensearch.security.dlic.rest.api; import com.fasterxml.jackson.databind.JsonNode; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.DefaultObjectMapper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class GetConfigurationApiTest extends AbstractRestApiUnitTest { - private final String ENDPOINT; - - public GetConfigurationApiTest(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); - } - - @Test - public void testGetConfiguration() throws Exception { - - setup(); - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = true; - - // wrong config name -> bad request - HttpResponse response = null; - - // test that every config is accessible - // config - response = rh.executeGetRequest(ENDPOINT + "/securityconfig"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals( - settings.getAsBoolean("config.dynamic.authc.authentication_domain_basic_internal.http_enabled", false), - true); - Assert.assertNull(settings.get("_opendistro_security_meta.type")); - - // internalusers - response = rh.executeGetRequest(ENDPOINT + "/internalusers"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("other.hash")); - Assert.assertNull(settings.get("_opendistro_security_meta.type")); - - // roles - response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - JsonNode jnode = DefaultObjectMapper.readTree(response.getBody()); - Assert.assertEquals(jnode.get("opendistro_security_all_access").get("cluster_permissions").get(0).asText(), "cluster:*"); - Assert.assertNull(settings.get("_opendistro_security_meta.type")); - - // roles - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0), "starfleet"); - Assert.assertNull(settings.get("_opendistro_security_meta.type")); - - // action groups - response = rh.executeGetRequest(ENDPOINT + "/actiongroups"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.getAsList("ALL.allowed_actions").get(0), "indices:*"); - Assert.assertTrue(settings.hasValue("INTERNAL.allowed_actions")); - Assert.assertNull(settings.get("_opendistro_security_meta.type")); - } + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } + + public GetConfigurationApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; + } + + @Test + public void testGetConfiguration() throws Exception { + + setup(); + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = true; + + // wrong config name -> bad request + HttpResponse response = null; + + // test that every config is accessible + // config + response = rh.executeGetRequest(ENDPOINT + "/securityconfig"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals( + settings.getAsBoolean("config.dynamic.authc.authentication_domain_basic_internal.http_enabled", false), + true); + Assert.assertNull(settings.get("_opendistro_security_meta.type")); + + // internalusers + response = rh.executeGetRequest(ENDPOINT + "/internalusers"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.get("admin.hash")); + Assert.assertEquals("", settings.get("other.hash")); + Assert.assertNull(settings.get("_opendistro_security_meta.type")); + + // roles + response = rh.executeGetRequest(ENDPOINT + "/roles"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + JsonNode jnode = DefaultObjectMapper.readTree(response.getBody()); + Assert.assertEquals(jnode.get("opendistro_security_all_access").get("cluster_permissions").get(0).asText(), "cluster:*"); + Assert.assertNull(settings.get("_opendistro_security_meta.type")); + + // roles + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0), "starfleet"); + Assert.assertNull(settings.get("_opendistro_security_meta.type")); + + // action groups + response = rh.executeGetRequest(ENDPOINT + "/actiongroups"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(settings.getAsList("ALL.allowed_actions").get(0), "indices:*"); + Assert.assertTrue(settings.hasValue("INTERNAL.allowed_actions")); + Assert.assertNull(settings.get("_opendistro_security_meta.type")); + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java index d0c00612d3..257732f129 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java @@ -11,101 +11,91 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.security.DefaultObjectMapper; import org.opensearch.security.support.SecurityJsonNode; import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class IndexMissingTest extends AbstractRestApiUnitTest { - private final String ENDPOINT; - - public IndexMissingTest(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); - } - - @Test - public void testGetConfiguration() throws Exception { - // don't setup index for this test - init = false; - setup(); - - // test with no Security index at all - testHttpOperations(); - - } - - protected void testHttpOperations() throws Exception { - - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = true; - - // GET configuration - HttpResponse response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - String errorString = response.getBody(); - System.out.println(errorString); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); - - // GET roles - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); - - // GET rolesmapping - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); - - // GET actiongroups - response = rh.executeGetRequest(ENDPOINT + "/actiongroups/READ"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); - - // GET internalusers - response = rh.executeGetRequest(ENDPOINT + "/internalusers/picard"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); - - // PUT request - response = rh.executePutRequest(ENDPOINT + "/actiongroups/READ", FileHelper.loadFile("restapi/actiongroup_read.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - - // DELETE request - response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); - - // setup index now - initialize(this.clusterHelper, this.clusterInfo); - - // GET configuration - response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - SecurityJsonNode securityJsonNode = new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())); - Assert.assertEquals("OPENDISTRO_SECURITY_CLUSTER_ALL", securityJsonNode.get("opendistro_security_admin").get("cluster_permissions").get(0).asString()); - - } + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } + + public IndexMissingTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; + } + + @Test + public void testGetConfiguration() throws Exception { + // don't setup index for this test + init = false; + setup(); + + // test with no Security index at all + testHttpOperations(); + + } + + protected void testHttpOperations() throws Exception { + + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = true; + + // GET configuration + HttpResponse response = rh.executeGetRequest(ENDPOINT + "/roles"); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + String errorString = response.getBody(); + System.out.println(errorString); + Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + + // GET roles + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + errorString = response.getBody(); + Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + + // GET rolesmapping + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + errorString = response.getBody(); + Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + + // GET actiongroups + response = rh.executeGetRequest(ENDPOINT + "/actiongroups/READ"); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + errorString = response.getBody(); + Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + + // GET internalusers + response = rh.executeGetRequest(ENDPOINT + "/internalusers/picard"); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + errorString = response.getBody(); + Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + + // PUT request + response = rh.executePutRequest(ENDPOINT + "/actiongroups/READ", FileHelper.loadFile("restapi/actiongroup_read.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + + // DELETE request + response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); + Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + + // setup index now + initialize(this.clusterHelper, this.clusterInfo); + + // GET configuration + response = rh.executeGetRequest(ENDPOINT + "/roles"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + SecurityJsonNode securityJsonNode = new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())); + Assert.assertEquals("OPENDISTRO_SECURITY_CLUSTER_ALL", securityJsonNode.get("opendistro_security_admin").get("cluster_permissions").get(0).asString()); + + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java index 6296bb4e6b..f72375600c 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java @@ -18,14 +18,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -39,27 +36,18 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; - -@RunWith(Parameterized.class) public class NodesDnApiTest extends AbstractRestApiUnitTest { private HttpResponse response; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private final String ENDPOINT; - - public NodesDnApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); + public NodesDnApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; } private JsonNode asJsonNode(T t) throws Exception { diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java index 9ca0f4378b..96027e6f8d 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java @@ -11,12 +11,9 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -25,254 +22,246 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class RoleBasedAccessTest extends AbstractRestApiUnitTest { + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } + + public RoleBasedAccessTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; + } + + @Test + public void testActionGroupsApi() throws Exception { + + setupWithRestRoles(); + + rh.sendAdminCertificate = false; + + // worf and sarek have access, worf has some endpoints disabled + + // ------ GET ------ + + // --- Allowed Access --- + + // legacy user API, accessible for worf, single user + HttpResponse response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertTrue(settings.get("admin.hash") != null); + Assert.assertEquals("", settings.get("admin.hash")); + + // new user API, accessible for worf, single user + response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertTrue(settings.get("admin.hash") != null); + + // legacy user API, accessible for worf, get complete config + response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.get("admin.hash")); + Assert.assertEquals("", settings.get("sarek.hash")); + Assert.assertEquals("", settings.get("worf.hash")); + + // new user API, accessible for worf + response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.get("admin.hash")); + Assert.assertEquals("", settings.get("sarek.hash")); + Assert.assertEquals("", settings.get("worf.hash")); + + // legacy user API, accessible for worf, get complete config, no trailing slash + response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.get("admin.hash")); + Assert.assertEquals("", settings.get("sarek.hash")); + Assert.assertEquals("", settings.get("worf.hash")); + + // new user API, accessible for worf, get complete config, no trailing slash + response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.get("admin.hash")); + Assert.assertEquals("", settings.get("sarek.hash")); + Assert.assertEquals("", settings.get("worf.hash")); + + // roles API, GET accessible for worf + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("", settings.getAsList("opendistro_security_all_access.users").get(0), "nagilum"); + Assert.assertEquals("", settings.getAsList("opendistro_security_role_starfleet_library.backend_roles").get(0), "starfleet*"); + Assert.assertEquals("", settings.getAsList("opendistro_security_zdummy_all.users").get(0), "bug108"); + + + // Deprecated get configuration API, acessible for sarek + // response = rh.executeGetRequest("_opendistro/_security/api/configuration/internalusers", encodeBasicHeader("sarek", "sarek")); + // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + // Assert.assertEquals("", settings.get("admin.hash")); + // Assert.assertEquals("", settings.get("sarek.hash")); + // Assert.assertEquals("", settings.get("worf.hash")); + + // Deprecated get configuration API, acessible for sarek + // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("sarek", "sarek")); + // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + // Assert.assertEquals("", settings.getAsList("ALL").get(0), "indices:*"); + // Assert.assertEquals("", settings.getAsList("OPENDISTRO_SECURITY_CLUSTER_MONITOR").get(0), "cluster:monitor/*"); + // new format for action groups + // Assert.assertEquals("", settings.getAsList("CRUD.permissions").get(0), "READ_UT"); + + // configuration API, not accessible for worf +// response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("worf", "worf")); +// Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); +// Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CONFIGURATION")); + + // cache API, not accessible for worf since it's disabled globally + response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); + + // cache API, not accessible for sarek since it's disabled globally + response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("sarek", "sarek")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); + + // Admin user has no eligible role at all + response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); + + // Admin user has no eligible role at all + response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); + + // Admin user has no eligible role at all + response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); + + // Admin user has no eligible role at all + response = rh.executeGetRequest(ENDPOINT + "/roles", encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); + + // --- DELETE --- + + // Admin user has no eligible role at all + response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); + + // Worf, has access to internalusers API, able to delete + response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'other' deleted")); + + // Worf, has access to internalusers API, user "other" deleted now + response = rh.executeGetRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'other' not found")); + + // Worf, has access to roles API, get captains role + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertEquals(new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())).getDotted("opendistro_security_role_starfleet_captains.cluster_permissions").get(0).asString(), "cluster:monitor*"); + + // Worf, has access to roles API, able to delete + response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); + + // Worf, has access to roles API, captains role deleted now + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' not found")); + + // Worf, has no DELETE access to rolemappings API + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // Worf, has no DELETE access to rolemappings API, legacy endpoint + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // --- PUT --- + + // admin, no access + response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/roles_captains_tenants.json"), encodeBasicHeader("admin", "admin")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // worf, restore role starfleet captains + response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + + // starfleet role present again + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertEquals(new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())).getDotted("opendistro_security_role_starfleet_captains.index_permissions").get(0).get("allowed_actions").get(0).asString(), "blafasel"); + + // Try the same, but now with admin certificate + rh.sendAdminCertificate = true; + + // admin + response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("la", "lu")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertTrue(settings.get("admin.hash") != null); + Assert.assertEquals("", settings.get("admin.hash")); + + // worf and config + // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("bla", "fasel")); + // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // cache + response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("wrong", "wrong")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // -- test user, does not have any endpoints disabled, but has access to API, i.e. full access + + rh.sendAdminCertificate = false; + + // GET actiongroups + // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("test", "test")); + // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + response = rh.executeGetRequest("_opendistro/_security/api/actiongroups", encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // clear cache - globally disabled, has to fail + response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // PUT roles + response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // GET captions role + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - private final String ENDPOINT; - - public RoleBasedAccessTest(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); - } - - @Test - public void testActionGroupsApi() throws Exception { - - setupWithRestRoles(); - - rh.sendAdminCertificate = false; - - // worf and sarek have access, worf has some endpoints disabled - - // ------ GET ------ - - // --- Allowed Access --- - - // legacy user API, accessible for worf, single user - HttpResponse response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertTrue(settings.get("admin.hash") != null); - Assert.assertEquals("", settings.get("admin.hash")); - - // new user API, accessible for worf, single user - response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertTrue(settings.get("admin.hash") != null); - - // legacy user API, accessible for worf, get complete config - response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); - - // new user API, accessible for worf - response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); - - // legacy user API, accessible for worf, get complete config, no trailing slash - response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); - - // new user API, accessible for worf, get complete config, no trailing slash - response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); - - // roles API, GET accessible for worf - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.getAsList("opendistro_security_all_access.users").get(0), "nagilum"); - Assert.assertEquals("", settings.getAsList("opendistro_security_role_starfleet_library.backend_roles").get(0), "starfleet*"); - Assert.assertEquals("", settings.getAsList("opendistro_security_zdummy_all.users").get(0), "bug108"); - - - // Deprecated get configuration API, acessible for sarek - // response = rh.executeGetRequest("_opendistro/_security/api/configuration/internalusers", encodeBasicHeader("sarek", "sarek")); - // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - // Assert.assertEquals("", settings.get("admin.hash")); - // Assert.assertEquals("", settings.get("sarek.hash")); - // Assert.assertEquals("", settings.get("worf.hash")); - - // Deprecated get configuration API, acessible for sarek - // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("sarek", "sarek")); - // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - // Assert.assertEquals("", settings.getAsList("ALL").get(0), "indices:*"); - // Assert.assertEquals("", settings.getAsList("OPENDISTRO_SECURITY_CLUSTER_MONITOR").get(0), "cluster:monitor/*"); - // new format for action groups - // Assert.assertEquals("", settings.getAsList("CRUD.permissions").get(0), "READ_UT"); - - // configuration API, not accessible for worf -// response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("worf", "worf")); -// Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); -// Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CONFIGURATION")); - - // cache API, not accessible for worf since it's disabled globally - response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); - - // cache API, not accessible for sarek since it's disabled globally - response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("sarek", "sarek")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); - - // Admin user has no eligible role at all - response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); - - // Admin user has no eligible role at all - response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); - - // Admin user has no eligible role at all - response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); - - // Admin user has no eligible role at all - response = rh.executeGetRequest(ENDPOINT + "/roles", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); - - // --- DELETE --- - - // Admin user has no eligible role at all - response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); - - // Worf, has access to internalusers API, able to delete - response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'other' deleted")); - - // Worf, has access to internalusers API, user "other" deleted now - response = rh.executeGetRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'other' not found")); - - // Worf, has access to roles API, get captains role - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertEquals(new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())).getDotted("opendistro_security_role_starfleet_captains.cluster_permissions").get(0).asString(), "cluster:monitor*"); - - // Worf, has access to roles API, able to delete - response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); - - // Worf, has access to roles API, captains role deleted now - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' not found")); - - // Worf, has no DELETE access to rolemappings API - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // Worf, has no DELETE access to rolemappings API, legacy endpoint - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // --- PUT --- - - // admin, no access - response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/roles_captains_tenants.json"), encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // worf, restore role starfleet captains - response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - - // starfleet role present again - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertEquals(new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())).getDotted("opendistro_security_role_starfleet_captains.index_permissions").get(0).get("allowed_actions").get(0).asString(), "blafasel"); - - // Try the same, but now with admin certificate - rh.sendAdminCertificate = true; - - // admin - response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("la", "lu")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertTrue(settings.get("admin.hash") != null); - Assert.assertEquals("", settings.get("admin.hash")); - - // worf and config - // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("bla", "fasel")); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // cache - response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("wrong", "wrong")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // -- test user, does not have any endpoints disabled, but has access to API, i.e. full access - - rh.sendAdminCertificate = false; - - // GET actiongroups - // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("test", "test")); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - response = rh.executeGetRequest("_opendistro/_security/api/actiongroups", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // clear cache - globally disabled, has to fail - response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // PUT roles - response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // GET captions role - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + // Delete captions role + response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); - // Delete captions role - response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); + // GET captions role + response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - // GET captions role - response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - } + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiTest.java index 016ba4903a..8dc18f5043 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiTest.java @@ -14,13 +14,10 @@ import java.util.List; import com.fasterxml.jackson.databind.JsonNode; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -30,27 +27,18 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class RolesApiTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public RolesApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); + public RolesApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; } - @Test public void testPutRole() throws Exception { @@ -285,10 +273,10 @@ public void testRolesApi() throws Exception { FileHelper.loadFile("restapi/roles_complete_invalid.json"), new Header[0]); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); -// rh.sendAdminCertificate = true; -// response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", -// FileHelper.loadFile("restapi/roles_multiple.json"), new Header[0]); -// Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); +// rh.sendAdminCertificate = true; +// response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", +// FileHelper.loadFile("restapi/roles_multiple.json"), new Header[0]); +// Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); response = rh.executePutRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", FileHelper.loadFile("restapi/roles_multiple_2.json"), new Header[0]); diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiTest.java index f09d7284ee..2d1f10736d 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiTest.java @@ -13,13 +13,10 @@ import java.util.List; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -27,412 +24,404 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class RolesMappingApiTest extends AbstractRestApiUnitTest { + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } - private final String ENDPOINT; + public RolesMappingApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; + } - public RolesMappingApiTest(String endpoint){ - ENDPOINT = endpoint; - } + @Test + public void testRolesMappingApi() throws Exception { + + setup(); - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); - } + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = true; - @Test - public void testRolesMappingApi() throws Exception { + // check rolesmapping exists, old config api + HttpResponse response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - setup(); + // check rolesmapping exists, new API + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getContentType(), response.isJsonContentType()); - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = true; - - // check rolesmapping exists, old config api - HttpResponse response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // check rolesmapping exists, new API - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getContentType(), response.isJsonContentType()); - - // Superadmin should be able to see hidden rolesmapping - Assert.assertTrue(response.getBody().contains("opendistro_security_hidden")); - - // Superadmin should be able to see reserved rolesmapping - Assert.assertTrue(response.getBody().contains("opendistro_security_reserved")); - - - // -- GET - - // GET opendistro_security_role_starfleet, exists - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getContentType(), response.isJsonContentType()); - Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("starfleet", settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0)); - Assert.assertEquals("captains", settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(1)); - Assert.assertEquals("*.starfleetintranet.com", settings.getAsList("opendistro_security_role_starfleet.hosts").get(0)); - Assert.assertEquals("nagilum", settings.getAsList("opendistro_security_role_starfleet.users").get(0)); - - // GET, rolesmapping does not exist - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/nothinghthere", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // GET, new URL endpoint in security - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getContentType(), response.isJsonContentType()); - - // GET, new URL endpoint in security - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getContentType(), response.isJsonContentType()); - - // Super admin should be able to describe particular hidden rolemapping - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("\"hidden\":true")); - - // create index - setupStarfleetIndex(); - - // add user picard, role captains initially maps to - // opendistro_security_role_starfleet_captains and opendistro_security_role_starfleet - addUserWithPassword("picard", "picard", new String[] { "captains" }, HttpStatus.SC_CREATED); - checkWriteAccess(HttpStatus.SC_CREATED, "picard", "picard", "sf", "_doc", 1); - - // TODO: only one doctype allowed for ES6 - //checkWriteAccess(HttpStatus.SC_CREATED, "picard", "picard", "sf", "_doc", 1); - - // --- DELETE - - rh.sendAdminCertificate = true; - - // Non-existing role - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/idonotexist", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // read only role - // SuperAdmin can delete read only role - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // hidden role - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertTrue(response.getBody().contains("'opendistro_security_internal' deleted.")); - - // remove complete role mapping for opendistro_security_role_starfleet_captains - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - response = rh.executeGetRequest(ENDPOINT + "/configuration/rolesmapping"); - rh.sendAdminCertificate = false; - - // now picard is only in opendistro_security_role_starfleet, which has write access to - // public, but not to _doc - checkWriteAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); - - // TODO: only one doctype allowed for ES6 - // checkWriteAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); - - // remove also opendistro_security_role_starfleet, poor picard has no mapping left - rh.sendAdminCertificate = true; - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - rh.sendAdminCertificate = false; - checkAllSfForbidden(); - - rh.sendAdminCertificate = true; - - // --- PUT - - // put with empty mapping, must fail - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", "", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.PAYLOAD_MANDATORY.getMessage(), settings.get("reason")); - - // put new configuration with invalid payload, must fail - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_not_parseable.json"), new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.BODY_NOT_PARSEABLE.getMessage(), settings.get("reason")); - - // put new configuration with invalid keys, must fail - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_invalid_keys.json"), new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.INVALID_CONFIGURATION.getMessage(), settings.get("reason")); - Assert.assertTrue(settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("theusers")); - Assert.assertTrue( - settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("thebackendroles")); - Assert.assertTrue(settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("thehosts")); - - // wrong datatypes - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_backendroles_captains_single_wrong_datatype.json"), new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); - Assert.assertTrue(settings.get("backend_roles").equals("Array expected")); - Assert.assertTrue(settings.get("hosts") == null); - Assert.assertTrue(settings.get("users") == null); - - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_hosts_single_wrong_datatype.json"), new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); - Assert.assertTrue(settings.get("hosts").equals("Array expected")); - Assert.assertTrue(settings.get("backend_roles") == null); - Assert.assertTrue(settings.get("users") == null); - - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_users_picard_single_wrong_datatype.json"), new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); - Assert.assertTrue(settings.get("hosts").equals("Array expected")); - Assert.assertTrue(settings.get("users").equals("Array expected")); - Assert.assertTrue(settings.get("backend_roles").equals("Array expected")); - - // Read only role mapping - // SuperAdmin can add read only roles - mappings - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", - FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); - - // hidden role, allowed for super admin - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", - FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); - - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); - - // -- PATCH - // PATCH on non-existing resource - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/imnothere", "[{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // PATCH read only resource, must be forbidden - // SuperAdmin can patch read-only resource - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\"] }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - - // PATCH hidden resource, must be not found, can be found by super admin - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", "[{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ " + - "\"foo\", \"bar\" ] }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - - // PATCH value of hidden flag, must fail with validation error - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", "[{ \"op\": \"add\", \"path\": \"/hidden\", \"value\": true }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertTrue(response.getBody().matches(".*\"invalid_keys\"\\s*:\\s*\\{\\s*\"keys\"\\s*:\\s*\"hidden\"\\s*\\}.*")); - - // PATCH - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", "[{ \"op\": \"add\", \"path\": \"/backend_roles/-\", \"value\": \"spring\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - List permissions = settings.getAsList("opendistro_security_role_vulcans.backend_roles"); - Assert.assertNotNull(permissions); - Assert.assertTrue(permissions.contains("spring")); - - // -- PATCH on whole config resource - // PATCH on non-existing resource - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/imnothere/a\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - - // PATCH read only resource, must be forbidden - // SuperAdmin can patch read only resource - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_starfleet_library/description\", \"value\": \"foo\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - - // PATCH hidden resource, must be bad request - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_internal/a\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - - // PATCH value of hidden flag, must fail with validation error - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_vulcans/hidden\", \"value\": true }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertTrue(response.getBody().matches(".*\"invalid_keys\"\\s*:\\s*\\{\\s*\"keys\"\\s*:\\s*\"hidden\"\\s*\\}.*")); - - // PATCH - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/bulknew1\", \"value\": { \"backend_roles\":[\"vulcanadmin\"]} }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/bulknew1", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - permissions = settings.getAsList("bulknew1.backend_roles"); - Assert.assertNotNull(permissions); - Assert.assertTrue(permissions.contains("vulcanadmin")); - - // PATCH delete - rh.sendAdminCertificate = true; - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"remove\", \"path\": \"/bulknew1\"}]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/bulknew1", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - - // mapping with several backend roles, one of the is captain - deleteAndputNewMapping("rolesmapping_backendroles_captains_list.json"); - checkAllSfAllowed(); - - // mapping with one backend role, captain - deleteAndputNewMapping("rolesmapping_backendroles_captains_single.json"); - checkAllSfAllowed(); - - // mapping with several users, one is picard - deleteAndputNewMapping("rolesmapping_users_picard_list.json"); - checkAllSfAllowed(); - - // just user picard - deleteAndputNewMapping("rolesmapping_users_picard_single.json"); - checkAllSfAllowed(); - - // hosts - deleteAndputNewMapping("rolesmapping_hosts_list.json"); - checkAllSfAllowed(); - - // hosts - deleteAndputNewMapping("rolesmapping_hosts_single.json"); - checkAllSfAllowed(); - - // full settings, access - deleteAndputNewMapping("rolesmapping_all_access.json"); - checkAllSfAllowed(); - - // full settings, no access - deleteAndputNewMapping("rolesmapping_all_noaccess.json"); - checkAllSfForbidden(); - - } - - private void checkAllSfAllowed() throws Exception { - rh.sendAdminCertificate = false; - checkReadAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); - checkWriteAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); - } - - private void checkAllSfForbidden() throws Exception { - rh.sendAdminCertificate = false; - checkReadAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); - checkWriteAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); - } - - private HttpResponse deleteAndputNewMapping(String fileName) throws Exception { - rh.sendAdminCertificate = true; - HttpResponse response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - FileHelper.loadFile("restapi/"+fileName), new Header[0]); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); - rh.sendAdminCertificate = false; - return response; - } - - @Test - public void testRolesMappingApiForNonSuperAdmin() throws Exception { - - setupWithRestRoles(); - - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = false; - rh.sendHTTPClientCredentials = true; - - HttpResponse response; - - // Delete read only roles mapping - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library" , new Header[0]); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // Put read only roles mapping - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", - FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // Patch single read only roles mapping - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // Patch multiple read only roles mapping - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_starfleet_library/description\", \"value\": \"foo\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - - // GET, rolesmapping is hidden, allowed for super admin - response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // Delete hidden roles mapping - response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal" , new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // Put hidden roles mapping - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", - FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // Patch hidden roles mapping - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - // Patch multiple hidden roles mapping - response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_internal/description\", \"value\": \"foo\" }]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); - - } - - @Test - public void checkNullElementsInArray() throws Exception{ - setup(); - rh.keystore = "restapi/kirk-keystore.jks"; - rh.sendAdminCertificate = true; - - String body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_users.json"); - HttpResponse response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - body, new Header[0]); - Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); - - body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_backend_roles.json"); - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - body, new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); - - body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_hosts.json"); - response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", - body, new Header[0]); - settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); - } + // Superadmin should be able to see hidden rolesmapping + Assert.assertTrue(response.getBody().contains("opendistro_security_hidden")); + + // Superadmin should be able to see reserved rolesmapping + Assert.assertTrue(response.getBody().contains("opendistro_security_reserved")); + + + // -- GET + + // GET opendistro_security_role_starfleet, exists + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getContentType(), response.isJsonContentType()); + Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals("starfleet", settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0)); + Assert.assertEquals("captains", settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(1)); + Assert.assertEquals("*.starfleetintranet.com", settings.getAsList("opendistro_security_role_starfleet.hosts").get(0)); + Assert.assertEquals("nagilum", settings.getAsList("opendistro_security_role_starfleet.users").get(0)); + + // GET, rolesmapping does not exist + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/nothinghthere", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // GET, new URL endpoint in security + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getContentType(), response.isJsonContentType()); + + // GET, new URL endpoint in security + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getContentType(), response.isJsonContentType()); + + // Super admin should be able to describe particular hidden rolemapping + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("\"hidden\":true")); + + // create index + setupStarfleetIndex(); + + // add user picard, role captains initially maps to + // opendistro_security_role_starfleet_captains and opendistro_security_role_starfleet + addUserWithPassword("picard", "picard", new String[] { "captains" }, HttpStatus.SC_CREATED); + checkWriteAccess(HttpStatus.SC_CREATED, "picard", "picard", "sf", "_doc", 1); + + // TODO: only one doctype allowed for ES6 + //checkWriteAccess(HttpStatus.SC_CREATED, "picard", "picard", "sf", "_doc", 1); + + // --- DELETE + + rh.sendAdminCertificate = true; + + // Non-existing role + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/idonotexist", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // read only role + // SuperAdmin can delete read only role + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // hidden role + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + Assert.assertTrue(response.getBody().contains("'opendistro_security_internal' deleted.")); + + // remove complete role mapping for opendistro_security_role_starfleet_captains + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + response = rh.executeGetRequest(ENDPOINT + "/configuration/rolesmapping"); + rh.sendAdminCertificate = false; + + // now picard is only in opendistro_security_role_starfleet, which has write access to + // public, but not to _doc + checkWriteAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); + + // TODO: only one doctype allowed for ES6 + // checkWriteAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); + + // remove also opendistro_security_role_starfleet, poor picard has no mapping left + rh.sendAdminCertificate = true; + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + rh.sendAdminCertificate = false; + checkAllSfForbidden(); + + rh.sendAdminCertificate = true; + + // --- PUT + + // put with empty mapping, must fail + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", "", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.PAYLOAD_MANDATORY.getMessage(), settings.get("reason")); + + // put new configuration with invalid payload, must fail + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_not_parseable.json"), new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.BODY_NOT_PARSEABLE.getMessage(), settings.get("reason")); + + // put new configuration with invalid keys, must fail + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_invalid_keys.json"), new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.INVALID_CONFIGURATION.getMessage(), settings.get("reason")); + Assert.assertTrue(settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("theusers")); + Assert.assertTrue( + settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("thebackendroles")); + Assert.assertTrue(settings.get(AbstractConfigurationValidator.INVALID_KEYS_KEY + ".keys").contains("thehosts")); + + // wrong datatypes + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_backendroles_captains_single_wrong_datatype.json"), new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); + Assert.assertTrue(settings.get("backend_roles").equals("Array expected")); + Assert.assertTrue(settings.get("hosts") == null); + Assert.assertTrue(settings.get("users") == null); + + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_hosts_single_wrong_datatype.json"), new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); + Assert.assertTrue(settings.get("hosts").equals("Array expected")); + Assert.assertTrue(settings.get("backend_roles") == null); + Assert.assertTrue(settings.get("users") == null); + + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_users_picard_single_wrong_datatype.json"), new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.WRONG_DATATYPE.getMessage(), settings.get("reason")); + Assert.assertTrue(settings.get("hosts").equals("Array expected")); + Assert.assertTrue(settings.get("users").equals("Array expected")); + Assert.assertTrue(settings.get("backend_roles").equals("Array expected")); + + // Read only role mapping + // SuperAdmin can add read only roles - mappings + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", + FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + + // hidden role, allowed for super admin + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", + FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + + // -- PATCH + // PATCH on non-existing resource + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/imnothere", "[{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // PATCH read only resource, must be forbidden + // SuperAdmin can patch read-only resource + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\"] }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + + // PATCH hidden resource, must be not found, can be found by super admin + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", "[{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ " + + "\"foo\", \"bar\" ] }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + + // PATCH value of hidden flag, must fail with validation error + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", "[{ \"op\": \"add\", \"path\": \"/hidden\", \"value\": true }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertTrue(response.getBody().matches(".*\"invalid_keys\"\\s*:\\s*\\{\\s*\"keys\"\\s*:\\s*\"hidden\"\\s*\\}.*")); + + // PATCH + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", "[{ \"op\": \"add\", \"path\": \"/backend_roles/-\", \"value\": \"spring\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_vulcans", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + List permissions = settings.getAsList("opendistro_security_role_vulcans.backend_roles"); + Assert.assertNotNull(permissions); + Assert.assertTrue(permissions.contains("spring")); + + // -- PATCH on whole config resource + // PATCH on non-existing resource + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/imnothere/a\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + + // PATCH read only resource, must be forbidden + // SuperAdmin can patch read only resource + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_starfleet_library/description\", \"value\": \"foo\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + + // PATCH hidden resource, must be bad request + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_internal/a\", \"value\": [ \"foo\", \"bar\" ] }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + + // PATCH value of hidden flag, must fail with validation error + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_vulcans/hidden\", \"value\": true }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertTrue(response.getBody().matches(".*\"invalid_keys\"\\s*:\\s*\\{\\s*\"keys\"\\s*:\\s*\"hidden\"\\s*\\}.*")); + + // PATCH + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/bulknew1\", \"value\": { \"backend_roles\":[\"vulcanadmin\"]} }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/bulknew1", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + permissions = settings.getAsList("bulknew1.backend_roles"); + Assert.assertNotNull(permissions); + Assert.assertTrue(permissions.contains("vulcanadmin")); + + // PATCH delete + rh.sendAdminCertificate = true; + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"remove\", \"path\": \"/bulknew1\"}]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/bulknew1", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + + // mapping with several backend roles, one of the is captain + deleteAndputNewMapping("rolesmapping_backendroles_captains_list.json"); + checkAllSfAllowed(); + + // mapping with one backend role, captain + deleteAndputNewMapping("rolesmapping_backendroles_captains_single.json"); + checkAllSfAllowed(); + + // mapping with several users, one is picard + deleteAndputNewMapping("rolesmapping_users_picard_list.json"); + checkAllSfAllowed(); + + // just user picard + deleteAndputNewMapping("rolesmapping_users_picard_single.json"); + checkAllSfAllowed(); + + // hosts + deleteAndputNewMapping("rolesmapping_hosts_list.json"); + checkAllSfAllowed(); + + // hosts + deleteAndputNewMapping("rolesmapping_hosts_single.json"); + checkAllSfAllowed(); + + // full settings, access + deleteAndputNewMapping("rolesmapping_all_access.json"); + checkAllSfAllowed(); + + // full settings, no access + deleteAndputNewMapping("rolesmapping_all_noaccess.json"); + checkAllSfForbidden(); + + } + + private void checkAllSfAllowed() throws Exception { + rh.sendAdminCertificate = false; + checkReadAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); + checkWriteAccess(HttpStatus.SC_OK, "picard", "picard", "sf", "_doc", 1); + } + + private void checkAllSfForbidden() throws Exception { + rh.sendAdminCertificate = false; + checkReadAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); + checkWriteAccess(HttpStatus.SC_FORBIDDEN, "picard", "picard", "sf", "_doc", 1); + } + + private HttpResponse deleteAndputNewMapping(String fileName) throws Exception { + rh.sendAdminCertificate = true; + HttpResponse response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + new Header[0]); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + FileHelper.loadFile("restapi/"+fileName), new Header[0]); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + rh.sendAdminCertificate = false; + return response; + } + + @Test + public void testRolesMappingApiForNonSuperAdmin() throws Exception { + + setupWithRestRoles(); + + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = false; + rh.sendHTTPClientCredentials = true; + + HttpResponse response; + + // Delete read only roles mapping + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library" , new Header[0]); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // Put read only roles mapping + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", + FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // Patch single read only roles mapping + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_library", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // Patch multiple read only roles mapping + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_role_starfleet_library/description\", \"value\": \"foo\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + + // GET, rolesmapping is hidden, allowed for super admin + response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // Delete hidden roles mapping + response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal" , new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // Put hidden roles mapping + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", + FileHelper.loadFile("restapi/rolesmapping_all_access.json"), new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // Patch hidden roles mapping + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping/opendistro_security_internal", "[{ \"op\": \"add\", \"path\": \"/description\", \"value\": \"foo\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + // Patch multiple hidden roles mapping + response = rh.executePatchRequest(ENDPOINT + "/rolesmapping", "[{ \"op\": \"add\", \"path\": \"/opendistro_security_internal/description\", \"value\": \"foo\" }]", new Header[0]); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + + } + + @Test + public void checkNullElementsInArray() throws Exception{ + setup(); + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendAdminCertificate = true; + + String body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_users.json"); + HttpResponse response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + body, new Header[0]); + Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); + + body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_backend_roles.json"); + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + body, new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); + + body = FileHelper.loadFile("restapi/rolesmapping_null_array_element_hosts.json"); + response = rh.executePutRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet_captains", + body, new Header[0]); + settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + Assert.assertEquals(AbstractConfigurationValidator.ErrorType.NULL_ARRAY_ELEMENT.getMessage(), settings.get("reason")); + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java index 9883a74d1d..4e8808e811 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java @@ -11,55 +11,44 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class SecurityApiAccessTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public SecurityApiAccessTest(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/internalusers", - PLUGINS_PREFIX + "/api/internalusers" - ); - } - - @Test - public void testRestApi() throws Exception { - - setup(); - - // test with no cert, must fail - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest(ENDPOINT).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(ENDPOINT, - encodeBasicHeader("admin", "admin")) - .getStatusCode()); - - // test with non-admin cert, must fail - rh.keystore = "restapi/node-0-keystore.jks"; - rh.sendAdminCertificate = true; - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest(ENDPOINT).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(ENDPOINT, - encodeBasicHeader("admin", "admin")) - .getStatusCode()); - - } + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; + } + + public SecurityApiAccessTest(){ + ENDPOINT = getEndpointPrefix() + "/api/internalusers"; + } + + @Test + public void testRestApi() throws Exception { + + setup(); + + // test with no cert, must fail + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, + rh.executeGetRequest(ENDPOINT).getStatusCode()); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, + rh.executeGetRequest(ENDPOINT, + encodeBasicHeader("admin", "admin")) + .getStatusCode()); + + // test with non-admin cert, must fail + rh.keystore = "restapi/node-0-keystore.jks"; + rh.sendAdminCertificate = true; + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, + rh.executeGetRequest(ENDPOINT).getStatusCode()); + Assert.assertEquals(HttpStatus.SC_FORBIDDEN, + rh.executeGetRequest(ENDPOINT, + encodeBasicHeader("admin", "admin")) + .getStatusCode()); + + } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigApiTest.java index 9338e3bc33..f5742cfecd 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigApiTest.java @@ -11,13 +11,10 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.DefaultObjectMapper; @@ -25,24 +22,16 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class SecurityConfigApiTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public SecurityConfigApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); + public SecurityConfigApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityHealthActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityHealthActionTest.java index f0145a0cb1..54aeb6d8a1 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityHealthActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityHealthActionTest.java @@ -11,34 +11,24 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class SecurityHealthActionTest extends AbstractRestApiUnitTest { - private final String ENDPOINT; - - public SecurityHealthActionTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "", - PLUGINS_PREFIX + "" - ); + public SecurityHealthActionTest(){ + ENDPOINT = getEndpointPrefix(); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityInfoActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityInfoActionTest.java index 10de3b495a..0743cd4d95 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityInfoActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityInfoActionTest.java @@ -11,34 +11,24 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class SecurityInfoActionTest extends AbstractRestApiUnitTest { - private final String ENDPOINT; - - public SecurityInfoActionTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/authinfo", - PLUGINS_PREFIX + "/authinfo" - ); + public SecurityInfoActionTest(){ + ENDPOINT = getEndpointPrefix() + "/authinfo"; } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java index 8986f40fec..01004faba7 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java @@ -11,45 +11,34 @@ package org.opensearch.security.dlic.rest.api; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class TenantInfoActionTest extends AbstractRestApiUnitTest { private String payload = "{\"hosts\":[],\"users\":[\"sarek\"]," + "\"backend_roles\":[\"starfleet*\",\"ambassador\"],\"and_backend_roles\":[],\"description\":\"Migrated " + "from v6\"}"; - private final String BASE_ENDPOINT; - private final String ENDPOINT; - - - public TenantInfoActionTest(String endpoint){ - BASE_ENDPOINT = endpoint; - ENDPOINT = BASE_ENDPOINT + "/tenantinfo"; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX, - PLUGINS_PREFIX - ); + public TenantInfoActionTest(){ + BASE_ENDPOINT = getEndpointPrefix(); + ENDPOINT = getEndpointPrefix() + "/tenantinfo"; } + @Test - public void testTenantInfoAPI() throws Exception { + public void testTenantInfoAPIAccess() throws Exception { Settings settings = Settings.builder().put(ConfigConstants.SECURITY_UNSUPPORTED_RESTAPI_ALLOW_SECURITYCONFIG_MODIFICATION, true).build(); setup(settings); @@ -65,11 +54,18 @@ public void testTenantInfoAPI() throws Exception { rh.sendHTTPClientCredentials = true; response = rh.executeGetRequest(ENDPOINT); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + } + @Test + public void testTenantInfoAPIUpdate() throws Exception { + Settings settings = Settings.builder().put(ConfigConstants.SECURITY_UNSUPPORTED_RESTAPI_ALLOW_SECURITYCONFIG_MODIFICATION, true).build(); + setup(settings); + rh.keystore = "restapi/kirk-keystore.jks"; + rh.sendHTTPClientCredentials = true; rh.sendAdminCertificate = true; //update security config - response = rh.executePatchRequest(BASE_ENDPOINT + "/api/securityconfig", "[{\"op\": \"add\",\"path\": \"/config/dynamic/kibana/opendistro_role\"," + + RestHelper.HttpResponse response = rh.executePatchRequest(BASE_ENDPOINT + "/api/securityconfig", "[{\"op\": \"add\",\"path\": \"/config/dynamic/kibana/opendistro_role\"," + "\"value\": \"opendistro_security_internal\"}]", new Header[0]); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/UserApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/UserApiTest.java index 622b202833..e81e42c25c 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/UserApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/UserApiTest.java @@ -14,14 +14,11 @@ import java.net.URLEncoder; import java.util.List; -import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.message.BasicHeader; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentType; @@ -31,24 +28,16 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class UserApiTest extends AbstractRestApiUnitTest { - - private final String ENDPOINT; - - public UserApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); + public UserApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java index 84d804e575..b5c0d98fc2 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java @@ -11,19 +11,15 @@ package org.opensearch.security.dlic.rest.api; - import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.JsonNode; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.DefaultObjectMapper; @@ -40,14 +36,12 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; /** * Testing class to verify that {@link WhitelistApiAction} works correctly. * Check {@link SecurityRestFilter} for extra tests for whitelisting functionality. */ -@RunWith(Parameterized.class) public class WhitelistApiTest extends AbstractRestApiUnitTest { private RestHelper.HttpResponse response; @@ -57,19 +51,13 @@ public class WhitelistApiTest extends AbstractRestApiUnitTest { */ private final Header adminCredsHeader = encodeBasicHeader("admin_all_access", "admin_all_access"); private final Header nonAdminCredsHeader = encodeBasicHeader("sarek", "sarek"); - - private final String ENDPOINT; - - public WhitelistApiTest(String endpoint){ - ENDPOINT = endpoint; + private final String ENDPOINT; + protected String getEndpointPrefix() { + return PLUGINS_PREFIX; } - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api", - PLUGINS_PREFIX + "/api" - ); + public WhitelistApiTest(){ + ENDPOINT = getEndpointPrefix() + "/api"; } /** diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAccountApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAccountApiTests.java new file mode 100644 index 0000000000..a48a7d2e3a --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAccountApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.AccountApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyAccountApiTests extends AccountApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyActionGroupsApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyActionGroupsApiTests.java new file mode 100644 index 0000000000..9aa4b70c77 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyActionGroupsApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.ActionGroupsApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyActionGroupsApiTests extends ActionGroupsApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAuditApiActionTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAuditApiActionTests.java new file mode 100644 index 0000000000..4d97da8bbb --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyAuditApiActionTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.AuditApiActionTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyAuditApiActionTests extends AuditApiActionTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyDashboardsInfoActionTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyDashboardsInfoActionTests.java new file mode 100644 index 0000000000..a9baec37bd --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyDashboardsInfoActionTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.DashboardsInfoActionTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyDashboardsInfoActionTests extends DashboardsInfoActionTest { + @Override + protected String getEndpoint() { + return LEGACY_OPENDISTRO_PREFIX + "/kibanainfo"; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyFlushCacheApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyFlushCacheApiTests.java new file mode 100644 index 0000000000..ab09a6e2f2 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyFlushCacheApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.FlushCacheApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyFlushCacheApiTests extends FlushCacheApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyGetConfigurationApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyGetConfigurationApiTests.java new file mode 100644 index 0000000000..cca6739733 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyGetConfigurationApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.GetConfigurationApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyGetConfigurationApiTests extends GetConfigurationApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyIndexMissingTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyIndexMissingTests.java new file mode 100644 index 0000000000..0680aa2c2e --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyIndexMissingTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.IndexMissingTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyIndexMissingTests extends IndexMissingTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyNodesDnApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyNodesDnApiTests.java new file mode 100644 index 0000000000..22237ece3f --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyNodesDnApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.NodesDnApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyNodesDnApiTests extends NodesDnApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRoleBasedAccessTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRoleBasedAccessTests.java new file mode 100644 index 0000000000..c9f421058c --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRoleBasedAccessTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.RoleBasedAccessTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyRoleBasedAccessTests extends RoleBasedAccessTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesApiTests.java new file mode 100644 index 0000000000..b4ec33a2d5 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.RolesApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyRolesApiTests extends RolesApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesMappingApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesMappingApiTests.java new file mode 100644 index 0000000000..c659fb57bc --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyRolesMappingApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.RolesMappingApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyRolesMappingApiTests extends RolesMappingApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityApiAccessTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityApiAccessTests.java new file mode 100644 index 0000000000..72b6086c1e --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityApiAccessTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.SecurityApiAccessTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacySecurityApiAccessTests extends SecurityApiAccessTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityConfigApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityConfigApiTests.java new file mode 100644 index 0000000000..fd03e7248a --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityConfigApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.SecurityConfigApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacySecurityConfigApiTests extends SecurityConfigApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityHealthActionTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityHealthActionTests.java new file mode 100644 index 0000000000..470db0a526 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityHealthActionTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.SecurityHealthActionTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacySecurityHealthActionTests extends SecurityHealthActionTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityInfoActionTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityInfoActionTests.java new file mode 100644 index 0000000000..8480787423 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacySecurityInfoActionTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.SecurityInfoActionTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacySecurityInfoActionTests extends SecurityInfoActionTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyTenantInfoActionTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyTenantInfoActionTests.java new file mode 100644 index 0000000000..1f2ac9a77d --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyTenantInfoActionTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.TenantInfoActionTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyTenantInfoActionTests extends TenantInfoActionTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyUserApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyUserApiTests.java new file mode 100644 index 0000000000..5753688097 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyUserApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.UserApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyUserApiTests extends UserApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyWhitelistApiTests.java b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyWhitelistApiTests.java new file mode 100644 index 0000000000..3ae501f9a4 --- /dev/null +++ b/src/test/java/org/opensearch/security/dlic/rest/api/legacy/LegacyWhitelistApiTests.java @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.dlic.rest.api.legacy; + +import org.opensearch.security.dlic.rest.api.WhitelistApiTest; + +import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; + +public class LegacyWhitelistApiTests extends WhitelistApiTest { + @Override + protected String getEndpointPrefix() { + return LEGACY_OPENDISTRO_PREFIX; + } +} diff --git a/src/test/java/org/opensearch/security/filter/SecurityFilterTest.java b/src/test/java/org/opensearch/security/filter/SecurityFilterTest.java index 98b46a6548..9430450875 100644 --- a/src/test/java/org/opensearch/security/filter/SecurityFilterTest.java +++ b/src/test/java/org/opensearch/security/filter/SecurityFilterTest.java @@ -36,9 +36,11 @@ import org.opensearch.security.support.WildcardMatcher; import org.opensearch.threadpool.ThreadPool; -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -84,7 +86,7 @@ public void testImmutableIndicesWildcardMatcher() { mock(IndexResolverReplacer.class), mock(XFFResolver.class) ); - assertEquals(expected, filter.getImmutableIndicesMatcher()); + assertThat(expected, equalTo(filter.getImmutableIndicesMatcher())); } @SuppressWarnings("unchecked") @@ -117,8 +119,8 @@ public void testUnexepectedCausesAreNotSendToCallers() { final ArgumentCaptor cap = ArgumentCaptor.forClass(OpenSearchSecurityException.class); verify(listener).onFailure(cap.capture()); - assertNull(cap.getValue().getCause(), "The cause should never be included as it will leak to callers"); - assertFalse(cap.getValue().getMessage().contains("ABC!"), "Make sure the cause exception wasn't toStringed in the method"); + assertThat("The cause should never be included as it will leak to callers", cap.getValue().getCause(), nullValue()); + assertThat("Make sure the cause exception wasn't toStringed in the method", cap.getValue().getMessage(), not(containsString("ABC!"))); verifyNoMoreInteractions(auditLog, listener); } diff --git a/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java b/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java index 2b87974f9f..245127995e 100644 --- a/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java +++ b/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.securityconf.impl.v6; import com.fasterxml.jackson.databind.JsonNode; diff --git a/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java b/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java index 0ec6e6a4e6..92af5aeebd 100644 --- a/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java +++ b/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.securityconf.impl.v7; import com.fasterxml.jackson.databind.JsonNode; diff --git a/src/test/java/org/opensearch/security/ssl/SecuritySSLCertsInfoActionTests.java b/src/test/java/org/opensearch/security/ssl/SecuritySSLCertsInfoActionTests.java index 1f1f5e7d41..c9618e6463 100644 --- a/src/test/java/org/opensearch/security/ssl/SecuritySSLCertsInfoActionTests.java +++ b/src/test/java/org/opensearch/security/ssl/SecuritySSLCertsInfoActionTests.java @@ -19,8 +19,6 @@ import net.minidev.json.JSONObject; import org.junit.Assert; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.opensearch.common.settings.Settings; import org.opensearch.security.ssl.util.SSLConfigConstants; @@ -32,22 +30,7 @@ import static org.opensearch.security.OpenSearchSecurityPlugin.LEGACY_OPENDISTRO_PREFIX; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -@RunWith(Parameterized.class) public class SecuritySSLCertsInfoActionTests extends SingleClusterTest { - private final String ENDPOINT; - - public SecuritySSLCertsInfoActionTests(String endpoint){ - ENDPOINT = endpoint; - } - - @Parameterized.Parameters - public static Iterable endpoints() { - return ImmutableList.of( - LEGACY_OPENDISTRO_PREFIX + "/api/ssl/certs", - PLUGINS_PREFIX + "/api/ssl/certs" - ); - } - private final List> NODE_CERT_DETAILS = ImmutableList.of( ImmutableMap.of( "issuer_dn", "CN=Example Com Inc. Signing CA,OU=Example Com Inc. Signing CA,O=Example Com Inc.,DC=example,DC=com", @@ -57,8 +40,17 @@ public static Iterable endpoints() { "not_after","2028-05-02T14:37:09Z" )); + @Test + public void testCertInfo_Legacy_Pass() throws Exception { + certInfo_Pass(LEGACY_OPENDISTRO_PREFIX + "/api/ssl/certs"); + } + @Test public void testCertInfo_Pass() throws Exception { + certInfo_Pass(PLUGINS_PREFIX + "/api/ssl/certs"); + } + + public void certInfo_Pass(final String endpoint) throws Exception { initTestCluster(); final RestHelper rh = restHelper(); rh.enableHTTPClientSSL = true; @@ -66,15 +58,24 @@ public void testCertInfo_Pass() throws Exception { rh.sendAdminCertificate = true; rh.keystore = "kirk-keystore.jks"; - final RestHelper.HttpResponse transportInfoRestResponse = rh.executeGetRequest(ENDPOINT); + final RestHelper.HttpResponse transportInfoRestResponse = rh.executeGetRequest(endpoint); JSONObject expectedJsonResponse = new JSONObject(); expectedJsonResponse.appendField("http_certificates_list", NODE_CERT_DETAILS); expectedJsonResponse.appendField("transport_certificates_list", NODE_CERT_DETAILS); Assert.assertEquals(expectedJsonResponse.toString(), transportInfoRestResponse.getBody()); } + @Test + public void testCertInfoFail_Legacy_NonAdmin() throws Exception { + certInfoFail_NonAdmin(LEGACY_OPENDISTRO_PREFIX + "/api/ssl/certs"); + } + @Test public void testCertInfoFail_NonAdmin() throws Exception { + certInfoFail_NonAdmin(PLUGINS_PREFIX + "/api/ssl/certs"); + } + + public void certInfoFail_NonAdmin(final String endpoint) throws Exception { initTestCluster(); final RestHelper rh = restHelper(); rh.enableHTTPClientSSL = true; @@ -82,7 +83,7 @@ public void testCertInfoFail_NonAdmin() throws Exception { rh.sendAdminCertificate = true; rh.keystore = "spock-keystore.jks"; - final RestHelper.HttpResponse transportInfoRestResponse = rh.executeGetRequest(ENDPOINT); + final RestHelper.HttpResponse transportInfoRestResponse = rh.executeGetRequest(endpoint); Assert.assertEquals(401, transportInfoRestResponse.getStatusCode()); // Forbidden for non-admin Assert.assertEquals("Unauthorized", transportInfoRestResponse.getStatusReason()); } diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java index 825094871a..383c60147c 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.FileNotFoundException; diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java index 354d1bc09d..0a2cac18b5 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.IOException; diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java index 0f0b5e8867..ed0f0ac252 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java @@ -1,3 +1,14 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + package org.opensearch.security.ssl.util; import java.io.IOException; diff --git a/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java b/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java index 8ff27b9e84..1400b0d401 100644 --- a/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java @@ -87,7 +87,7 @@ public void testConnectionSSLNotAvailableIOException() throws Exception { SSLConnectionTestResult result = connectionTestUtil.testConnection(); verifyClientHelloSend(); - Mockito.verifyZeroInteractions(inputStreamReader); + Mockito.verifyNoInteractions(inputStreamReader); verifyOpenSearchPingSend(); Mockito.verify(socket, Mockito.times(2)).close(); Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.SSL_NOT_AVAILABLE, result); @@ -149,7 +149,7 @@ public void testConnectionOpenSearchPingFailedIOException() throws Exception { verifyClientHelloSend(); verifyOpenSearchPingSend(); - Mockito.verifyZeroInteractions(inputStream); + Mockito.verifyNoInteractions(inputStream); Mockito.verify(socket, Mockito.times(2)).close(); Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.OPENSEARCH_PING_FAILED, result); } diff --git a/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java b/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java index 3b9b821165..c5c3172855 100644 --- a/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java +++ b/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java @@ -38,6 +38,9 @@ import javax.net.ssl.SSLContext; +import com.carrotsearch.randomizedtesting.RandomizedTest; +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; import io.netty.handler.ssl.OpenSsl; import org.apache.http.Header; import org.apache.http.HttpHost; @@ -78,7 +81,14 @@ import org.opensearch.security.test.helper.rules.SecurityTestWatcher; import org.opensearch.threadpool.ThreadPool; -public abstract class AbstractSecurityUnitTest { +/* + * There are real thread leaks during test execution, not all threads are + * properly waited on or interupted. While this normally doesn't create test + * failures, retries mitigate this. Remove this attribute to explore these + * issues. + */ +@ThreadLeakScope(Scope.NONE) +public abstract class AbstractSecurityUnitTest extends RandomizedTest { protected static final AtomicLong num = new AtomicLong(); protected static boolean withRemoteCluster; diff --git a/src/test/java/org/opensearch/security/test/SingleClusterTest.java b/src/test/java/org/opensearch/security/test/SingleClusterTest.java index 39d0b595fc..0c2f3bfc07 100644 --- a/src/test/java/org/opensearch/security/test/SingleClusterTest.java +++ b/src/test/java/org/opensearch/security/test/SingleClusterTest.java @@ -26,6 +26,7 @@ package org.opensearch.security.test; +import java.io.File; import java.util.List; import org.junit.After; @@ -40,6 +41,10 @@ public abstract class SingleClusterTest extends AbstractSecurityUnitTest { + public static final String TEST_RESOURCE_RELATIVE_PATH = "../../resources/test/"; + public static final String TEST_RESOURCE_ABSOLUTE_PATH = new File(TEST_RESOURCE_RELATIVE_PATH).getAbsolutePath() + "/"; + public static final String PROJECT_ROOT_RELATIVE_PATH = "../../../"; + private static final int DEFAULT_CLUSTER_MANAGER_NODE_NUM = 3; private static final int DEFAULT_FIRST_DATA_NODE_NUM = 2; diff --git a/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java b/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java index 72360a5712..ab6bc9d236 100644 --- a/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java +++ b/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java @@ -49,7 +49,7 @@ import org.opensearch.action.admin.cluster.node.info.NodesInfoRequest; import org.opensearch.action.admin.cluster.node.info.NodesInfoResponse; import org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest; -import org.opensearch.action.support.master.AcknowledgedResponse; +import org.opensearch.action.support.clustermanager.AcknowledgedResponse; import org.opensearch.client.Client; import org.opensearch.cluster.health.ClusterHealthStatus; import org.opensearch.cluster.node.DiscoveryNodeRole; @@ -61,6 +61,7 @@ import org.opensearch.node.Node; import org.opensearch.node.PluginAwareNode; import org.opensearch.security.test.NodeSettingsSupplier; +import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.cluster.ClusterConfiguration.NodeSettings; import org.opensearch.security.test.helper.network.SocketUtils; import org.opensearch.transport.TransportInfo; @@ -68,8 +69,23 @@ public final class ClusterHelper { static { + resetSystemProperties(); + } + + /** Resets all system properties associated with a cluster */ + public static void resetSystemProperties() { System.setProperty("opensearch.enforce.bootstrap.checks", "true"); - System.setProperty("security.default_init.dir", new File("./securityconfig").getAbsolutePath()); + updateDefaultDirectory(new File( SingleClusterTest.PROJECT_ROOT_RELATIVE_PATH + "config").getAbsolutePath()); + } + + /** + * Update the default directory used by the security plugin + * NOTE: this setting is system wide, use ClusterHelper.resetSystemProperties() to restore the original state + * + * @return the previous value if one was set, otherwise null + */ + public static String updateDefaultDirectory(final String newValue) { + return System.setProperty("security.default_init.dir", newValue); } protected final Logger log = LogManager.getLogger(ClusterHelper.class);