Commit 31e86c39 authored by Aman Verma's avatar Aman Verma
Browse files

merging with master

parents cc986f08 a6e2d3f0
Pipeline #61732 passed with stages
in 29 minutes and 51 seconds
......@@ -18,20 +18,6 @@ The following software have components provided under the terms of this license:
- AMQP 1.0 JMS Spring Boot Starter (from https://repo1.maven.org/maven2/org/amqphub/spring/amqp-10-jms-spring-boot-starter)
- ASM based accessors helper used by json-smart (from )
- ASM based accessors helper used by json-smart (from )
- AWS Event Stream (from https://github.com/awslabs/aws-eventstream-java)
- AWS Java SDK :: AWS Core (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Annotations (from https://repo1.maven.org/maven2/software/amazon/awssdk/annotations)
- AWS Java SDK :: Auth (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Core :: Protocols :: AWS Json Protocol (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Core :: Protocols :: Protocol Core (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: HTTP Client Interface (from https://repo1.maven.org/maven2/software/amazon/awssdk/http-client-spi)
- AWS Java SDK :: HTTP Clients :: Apache (from https://repo1.maven.org/maven2/software/amazon/awssdk/apache-client)
- AWS Java SDK :: HTTP Clients :: Netty Non-Blocking I/O (from https://repo1.maven.org/maven2/software/amazon/awssdk/netty-nio-client)
- AWS Java SDK :: Profiles (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Regions (from https://repo1.maven.org/maven2/software/amazon/awssdk/regions)
- AWS Java SDK :: SDK Core (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Services :: AWS Simple Systems Management (SSM) (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK :: Utilities (from https://repo1.maven.org/maven2/software/amazon/awssdk/utils)
- AWS Java SDK for AWS Amplify (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK for AWS App Mesh (from https://aws.amazon.com/sdkforjava)
- AWS Java SDK for AWS AppSync (from https://aws.amazon.com/sdkforjava)
......@@ -327,7 +313,7 @@ The following software have components provided under the terms of this license:
- FindBugs-jsr305 (from http://findbugs.sourceforge.net/)
- Google APIs Client Library for Java (from https://repo1.maven.org/maven2/com/google/api-client/google-api-client)
- Google App Engine extensions to the Google HTTP Client Library for Java. (from https://repo1.maven.org/maven2/com/google/http-client/google-http-client-appengine)
- Google Cloud Core (from https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-core)
- Google Cloud Core (from https://github.com/googleapis/java-core)
- Google Cloud Core HTTP (from https://github.com/googleapis/java-core)
- Google Cloud Core gRPC (from https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-core-grpc)
- Google Cloud Datastore (from https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-datastore)
......@@ -364,19 +350,20 @@ The following software have components provided under the terms of this license:
- JSON Web Token support for the JVM (from https://repo1.maven.org/maven2/io/jsonwebtoken/jjwt)
- JSON library from Android SDK (from http://developer.android.com/sdk)
- JSONassert (from https://github.com/skyscreamer/JSONassert)
- JSR107 API and SPI (from https://github.com/jsr107/jsr107spec)
- Jackson 2 extensions to the Google HTTP Client Library for Java. (from https://repo1.maven.org/maven2/com/google/http-client/google-http-client-jackson2)
- Jackson dataformat: CBOR (from http://github.com/FasterXML/jackson-dataformats-binary)
- Jackson dataformat: CBOR (from http://github.com/FasterXML/jackson-dataformats-binary)
- Jackson datatype: JSR310 (from https://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-jsr310)
- Jackson datatype: JSR310 (from http://wiki.fasterxml.com/JacksonModuleJSR310)
- Jackson datatype: Joda (from https://github.com/FasterXML/jackson-datatype-joda)
- Jackson datatype: jdk8 (from https://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-jdk8)
- Jackson module: JAXB Annotations (from https://github.com/FasterXML/jackson-modules-base)
- Jackson module: Afterburner (from https://github.com/FasterXML/jackson-modules-base)
- Jackson module: Old JAXB Annotations (javax.xml.bind) (from https://github.com/FasterXML/jackson-modules-base)
- Jackson-annotations (from http://github.com/FasterXML/jackson)
- Jackson-core (from https://github.com/FasterXML/jackson-core)
- Jackson-dataformat-Smile (from http://wiki.fasterxml.com/JacksonForSmile)
- Jackson-dataformat-XML (from https://github.com/FasterXML/jackson-dataformat-xml)
- Jackson-dataformat-YAML (from https://github.com/FasterXML/jackson-dataformats-text)
- Jackson-module-Afterburner (from http://wiki.fasterxml.com/JacksonHome)
- Jackson-module-parameter-names (from https://repo1.maven.org/maven2/com/fasterxml/jackson/module/jackson-module-parameter-names)
- Jakarta Bean Validation API (from https://beanvalidation.org)
- Jakarta Expression Language Implementation (from https://projects.eclipse.org/projects/ee4j.el)
......@@ -424,8 +411,6 @@ The following software have components provided under the terms of this license:
- Microsoft Azure Netty HTTP Client Library (from https://github.com/Azure/azure-sdk-for-java)
- Microsoft Azure SDK for SQL API of Azure Cosmos DB Service (from https://github.com/Azure/azure-sdk-for-java)
- Mockito (from http://www.mockito.org)
- Netty Reactive Streams HTTP support (from https://repo1.maven.org/maven2/com/typesafe/netty/netty-reactive-streams-http)
- Netty Reactive Streams Implementation (from https://repo1.maven.org/maven2/com/typesafe/netty/netty-reactive-streams)
- Netty/Buffer (from https://repo1.maven.org/maven2/io/netty/netty-buffer)
- Netty/Codec (from https://repo1.maven.org/maven2/io/netty/netty-codec)
- Netty/Codec/DNS (from https://repo1.maven.org/maven2/io/netty/netty-codec-dns)
......@@ -495,6 +480,8 @@ The following software have components provided under the terms of this license:
- Spring WebFlux (from https://github.com/spring-projects/spring-framework)
- T-Digest (from https://github.com/tdunning/t-digest)
- TypeTools (from http://github.com/jhalterman/typetools/)
- Vavr (from http://vavr.io)
- Vavr Match (from http://vavr.io)
- Woodstox (from https://github.com/FasterXML/woodstox)
- Zipkin Core Library (from https://repo1.maven.org/maven2/io/zipkin/zipkin2/zipkin)
- Zipkin Reporter Brave (from https://repo1.maven.org/maven2/io/zipkin/reporter2/zipkin-reporter-brave)
......@@ -503,17 +490,14 @@ The following software have components provided under the terms of this license:
- aggs-matrix-stats (from https://github.com/elastic/elasticsearch)
- asm (from http://asm.ow2.io/)
- asm (from http://asm.ow2.io/)
- aws-ssm-java-caching-client (from https://github.com/awslabs/aws-ssm-java-caching-client)
- boto3 (from https://github.com/boto/boto3)
- botocore (from https://github.com/boto/botocore)
- cli (from https://github.com/elastic/elasticsearch)
- com.google.api.grpc:proto-google-cloud-datastore-v1 (from https://github.com/googleapis/googleapis)
- compiler (from http://github.com/spullara/mustache.java)
- core (from https://github.com/elastic/elasticsearch)
- datastore-v1-proto-client (from https://repo1.maven.org/maven2/com/google/cloud/datastore/datastore-v1-proto-client)
- elasticsearch-cli (from https://github.com/elastic/elasticsearch)
- elasticsearch-core (from https://github.com/elastic/elasticsearch)
- elasticsearch-geo (from https://github.com/elastic/elasticsearch)
- elasticsearch-secure-sm (from https://github.com/elastic/elasticsearch)
- elasticsearch-x-content (from https://github.com/elastic/elasticsearch)
- error-prone annotations (from https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations)
- error-prone annotations (from https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations)
- google-auth (from https://github.com/googleapis/google-auth-library-python)
......@@ -550,7 +534,7 @@ The following software have components provided under the terms of this license:
- okhttp-urlconnection (from https://github.com/square/okhttp)
- org.apiguardian:apiguardian-api (from https://github.com/apiguardian-team/apiguardian)
- org.opentest4j:opentest4j (from https://github.com/ota4j-team/opentest4j)
- org.xmlunit:xmlunit-core (from http://www.xmlunit.org/)
- org.xmlunit:xmlunit-core (from https://www.xmlunit.org/)
- parent-join (from https://github.com/elastic/elasticsearch)
- project ':json-path' (from https://github.com/jayway/JsonPath)
- proto-google-cloud-logging-v2 (from https://repo1.maven.org/maven2/com/google/api/grpc/proto-google-cloud-logging-v2)
......@@ -559,10 +543,19 @@ The following software have components provided under the terms of this license:
- proto-google-iam-v1 (from https://github.com/googleapis/java-iam/proto-google-iam-v1)
- rank-eval (from https://github.com/elastic/elasticsearch)
- requests (from https://requests.readthedocs.io)
- resilience4j (from https://resilience4j.readme.io)
- resilience4j (from https://resilience4j.readme.io)
- resilience4j (from https://resilience4j.readme.io)
- resilience4j (from https://github.com/resilience4j/resilience4j)
- resilience4j (from https://resilience4j.readme.io)
- resilience4j (from https://github.com/resilience4j/resilience4j)
- resilience4j (from https://resilience4j.readme.io)
- resilience4j (from https://resilience4j.readme.io)
- rest (from https://github.com/elastic/elasticsearch)
- rest (from https://github.com/elastic/elasticsearch)
- rest-high-level (from https://github.com/elastic/elasticsearch)
- rxjava (from https://github.com/ReactiveX/RxJava)
- secure-sm (from https://github.com/elastic/elasticsearch)
- server (from https://github.com/elastic/elasticsearch)
- spring-boot (from https://spring.io/projects/spring-boot)
- spring-boot (from https://spring.io/projects/spring-boot)
......@@ -578,6 +571,7 @@ The following software have components provided under the terms of this license:
- spring-boot-starter (from https://spring.io/projects/spring-boot)
- spring-boot-starter-actuator (from https://spring.io/projects/spring-boot)
- spring-boot-starter-actuator (from https://spring.io/projects/spring-boot)
- spring-boot-starter-aop (from https://spring.io/projects/spring-boot)
- spring-boot-starter-json (from https://spring.io/projects/spring-boot)
- spring-boot-starter-json (from https://spring.io/projects/spring-boot)
- spring-boot-starter-logging (from https://spring.io/projects/spring-boot)
......@@ -595,15 +589,15 @@ The following software have components provided under the terms of this license:
- spring-boot-test (from https://spring.io/projects/spring-boot)
- spring-boot-test-autoconfigure (from https://spring.io/projects/spring-boot)
- spring-boot-test-autoconfigure (from https://spring.io/projects/spring-boot)
- spring-security-config (from https://spring.io/projects/spring-security)
- spring-security-config (from https://spring.io/projects/spring-security)
- spring-security-core (from https://spring.io/projects/spring-security)
- spring-security-core (from https://spring.io/projects/spring-security)
- spring-security-oauth2-core (from https://spring.io/projects/spring-security)
- spring-security-oauth2-jose (from https://spring.io/projects/spring-security)
- spring-security-oauth2-resource-server (from https://spring.io/projects/spring-security)
- spring-security-web (from https://spring.io/projects/spring-security)
- spring-security-web (from https://spring.io/projects/spring-security)
- spring-security-config (from http://spring.io/spring-security)
- spring-security-config (from http://spring.io/spring-security)
- spring-security-core (from http://spring.io/spring-security)
- spring-security-core (from http://spring.io/spring-security)
- spring-security-oauth2-core (from http://spring.io/spring-security)
- spring-security-oauth2-jose (from http://spring.io/spring-security)
- spring-security-oauth2-resource-server (from http://spring.io/spring-security)
- spring-security-web (from http://spring.io/spring-security)
- spring-security-web (from http://spring.io/spring-security)
- springfox-core (from https://github.com/springfox/springfox)
- springfox-schema (from https://github.com/springfox/springfox)
- springfox-spi (from https://github.com/springfox/springfox)
......@@ -616,6 +610,7 @@ The following software have components provided under the terms of this license:
- swagger-models (from https://repo1.maven.org/maven2/io/swagger/swagger-models)
- tomcat-embed-core (from http://tomcat.apache.org/)
- tomcat-embed-websocket (from https://tomcat.apache.org/)
- x-content (from https://github.com/elastic/elasticsearch)
========================================================================
BSD-2-Clause
......@@ -732,6 +727,7 @@ EPL-1.0
========================================================================
The following software have components provided under the terms of this license:
- AspectJ Weaver (from https://www.eclipse.org/aspectj/)
- JUnit Jupiter (Aggregator) (from https://junit.org/junit5/)
- JUnit Jupiter (Aggregator) (from https://junit.org/junit5/)
- JUnit Jupiter API (from https://junit.org/junit5/)
......@@ -945,8 +941,8 @@ The following software have components provided under the terms of this license:
- msal (from https://github.com/AzureAD/microsoft-authentication-library-for-python)
- msal4j (from https://github.com/AzureAD/microsoft-authentication-library-for-java)
- msal4j-persistence-extension (from https://github.com/AzureAD/microsoft-authentication-extensions-for-java)
- spring-security-core (from https://spring.io/projects/spring-security)
- spring-security-core (from https://spring.io/projects/spring-security)
- spring-security-core (from http://spring.io/spring-security)
- spring-security-core (from http://spring.io/spring-security)
========================================================================
MPL-1.1
......@@ -1019,7 +1015,6 @@ public-domain
The following software have components provided under the terms of this license:
- AOP alliance (from http://aopalliance.sourceforge.net)
- AWS Java SDK :: SDK Core (from https://aws.amazon.com/sdkforjava)
- AWS SDK for Java - Models (from https://aws.amazon.com/sdkforjava)
- Asynchronous Http Client (from https://repo1.maven.org/maven2/org/asynchttpclient/async-http-client)
- Guava: Google Core Libraries for Java (from https://repo1.maven.org/maven2/com/google/guava/guava)
......
......@@ -31,7 +31,7 @@
<groupId>org.opengroup.osdu</groupId>
<artifactId>os-schema</artifactId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>os-schema</name>
<description>os schema service </description>
......
......@@ -18,7 +18,7 @@
<parent>
<artifactId>os-schema</artifactId>
<groupId>org.opengroup.osdu</groupId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
......@@ -35,7 +35,7 @@
<dependency>
<groupId>org.opengroup.osdu</groupId>
<artifactId>os-schema-core</artifactId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
</dependency>
<!-- AWS managed packages -->
<dependency>
......@@ -67,7 +67,7 @@
<dependency>
<groupId>org.opengroup.osdu.core.aws</groupId>
<artifactId>os-core-lib-aws</artifactId>
<version>0.11.0-SNAPSHOT</version>
<version>0.11.0</version>
</dependency>
<dependency>
......
......@@ -18,21 +18,21 @@
<parent>
<artifactId>os-schema</artifactId>
<groupId>org.opengroup.osdu</groupId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>os-schema-azure</artifactId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
<description>Azure related implementation staff.</description>
<packaging>jar</packaging>
<properties>
<azure.version>2.1.7</azure.version>
<osdu.corelibazure.version>0.10.1</osdu.corelibazure.version>
<osdu.oscorecommon.version>0.11.0-rc4</osdu.oscorecommon.version>
<osdu.os-schema-core.version>0.10.0-SNAPSHOT</osdu.os-schema-core.version>
<osdu.corelibazure.version>0.11.0</osdu.corelibazure.version>
<osdu.oscorecommon.version>0.11.0</osdu.oscorecommon.version>
<osdu.os-schema-core.version>0.11.0-SNAPSHOT</osdu.os-schema-core.version>
<mockito.version>1.10.19</mockito.version>
<cucumber.version>5.4.0</cucumber.version>
<nimbus-jose-jwt-azure.version>8.20.2</nimbus-jose-jwt-azure.version>
......
......@@ -11,6 +11,10 @@ import java.util.Map;
@Component
public class AuthorizationServiceForServicePrincipalImpl implements IAuthorizationServiceForServicePrincipal {
private final String AAD_issuer_v1 = "https://sts.windows.net";
private final String AAD_issuer_v2 = "https://login.microsoftonline.com";
enum UserType {
REGULAR_USER,
GUEST_USER,
......@@ -26,14 +30,24 @@ public class AuthorizationServiceForServicePrincipalImpl implements IAuthorizati
}
final UserPrincipal userPrincipal = (UserPrincipal) principal;
String issuer = userPrincipal.getClaim("iss").toString();
UserType type = getType(userPrincipal);
if (type == UserType.SERVICE_PRINCIPAL) {
if (type == UserType.SERVICE_PRINCIPAL && issuedByAAD(issuer)) {
return true;
}
return false;
}
/***
* Check that issuer string startswith accepted prefix of AAD issuer url (V1 or V2).
* @param issuer claim for "issuer"
* @return true if issuer startswith V1 url or V2 url
*/
private boolean issuedByAAD(String issuer) {
return issuer.startsWith(AAD_issuer_v1) || issuer.startsWith(AAD_issuer_v2);
}
/**
* The internal method to get the user principal.
*
......
......@@ -15,7 +15,7 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@ConditionalOnProperty(value = "azure.istio.auth.enabled", havingValue = "true", matchIfMissing = true)
public class AADSecurityConfigWithIstioEnabled extends WebSecurityConfigurerAdapter {
@Autowired
private AADAppRoleStatelessAuthenticationFilter appRoleAuthFilter;
private AzureIstioSecurityFilter azureIstioSecurityFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
......@@ -37,6 +37,6 @@ public class AADSecurityConfigWithIstioEnabled extends WebSecurityConfigurerAdap
"/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(appRoleAuthFilter, UsernamePasswordAuthenticationFilter.class);
.addFilterBefore(azureIstioSecurityFilter, UsernamePasswordAuthenticationFilter.class);
}
}
package org.opengroup.osdu.schema.security;
import com.azure.spring.autoconfigure.aad.UserPrincipal;
import com.nimbusds.jwt.JWTClaimsSet;
import net.minidev.json.JSONArray;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Base64;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static org.springframework.util.StringUtils.hasText;
@Component
@ConditionalOnProperty(value = "azure.istio.auth.enabled", havingValue = "true", matchIfMissing = true)
public class AzureIstioSecurityFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureIstioSecurityFilter.class);
private static final String X_ISTIO_CLAIMS_PAYLOAD = "x-payload";
private static final JSONArray DEFAULT_ROLE_CLAIM = new JSONArray().appendElement("USER");
private static final String ROLE_PREFIX = "ROLE_";
/**
* Filter logic.
* @param servletRequest Request object.
* @param servletResponse Response object.
* @param filterChain Filter Chain object.
* @throws IOException
* @throws ServletException
*/
@Override
protected void doFilterInternal(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final FilterChain filterChain) throws ServletException, IOException {
final String istioPayload = servletRequest.getHeader(X_ISTIO_CLAIMS_PAYLOAD);
LOGGER.debug("Received headers list: {}", Collections.list(servletRequest.getHeaderNames()));
try {
if (hasText(istioPayload)) {
JWTClaimsSet claimsSet = JWTClaimsSet.parse(new String(Base64.getDecoder().decode(istioPayload)));
final JSONArray roles = Optional.ofNullable((JSONArray) claimsSet.getClaims().get("roles"))
.filter(r -> !r.isEmpty())
.orElse(DEFAULT_ROLE_CLAIM);
// By default the authenticated is set to true as part PreAuthenticatedAuthenticationToken constructor.
SecurityContextHolder
.getContext()
.setAuthentication(
new PreAuthenticatedAuthenticationToken(
new UserPrincipal(null,null, claimsSet),
null,
rolesToGrantedAuthorities(roles)
));
} else {
SecurityContextHolder
.getContext()
.setAuthentication(
new PreAuthenticatedAuthenticationToken(
null, null, null
));
}
} catch (ParseException ex) {
LOGGER.error("Failed to initialize UserPrincipal.", ex);
throw new AppException(500, "Unable to parse claims in istio payload", ex.getMessage());
}
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* To return roles.
* @param roles Request Object.
* @return set representation of roles.
*/
protected Set<SimpleGrantedAuthority> rolesToGrantedAuthorities(final JSONArray roles) {
return roles.stream()
.filter(Objects::nonNull)
.map(s -> new SimpleGrantedAuthority(ROLE_PREFIX + s))
.collect(Collectors.toSet());
}
}
......@@ -21,8 +21,8 @@ AUTHORIZE_API_KEY=${entitlements_service_api_key}
# Azure AD configuration, commented below settings to disable AAD AuthN,
# Uncomment it In the Istio AUTHN disabled Scenario
azure.activedirectory.client-id=${aad_client_id}
azure.activedirectory.AppIdUri=api://${azure.activedirectory.client-id}
# azure.activedirectory.client-id=${aad_client_id}
# azure.activedirectory.AppIdUri=api://${azure.activedirectory.client-id}
azure.activedirectory.session-stateless=true
# Azure CosmosDB configuration
......
package org.opengroup.osdu.schema.provider.azure.service.serviceimpl;
import com.azure.spring.autoconfigure.aad.UserPrincipal;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import com.nimbusds.jwt.JWTClaimsSet;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.impl.DefaultClaims;
import io.jsonwebtoken.impl.DefaultJws;
import lombok.Getter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.schema.azure.service.serviceimpl.AuthorizationServiceForServicePrincipalImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AuthorizationServiceForServicePrincipalImplTest {
@Mock
private Authentication auth;
@Mock
private SecurityContext securityContext;
@InjectMocks
private AuthorizationServiceForServicePrincipalImpl authorizationService;
@Before
public void setup() {
securityContext = Mockito.mock(SecurityContext.class);
auth = Mockito.mock(Authentication.class);
}
private UserPrincipal createAADUserPrincipal(String claimName, String claimValue, String issuer) {
final JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder()
//.subject("subject")
.claim(claimName, claimValue)
.issuer(issuer)
.build();
final JWSObject jwsObject = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).build(),
new Payload(jwtClaimsSet.toString()));
return new UserPrincipal("token", jwsObject, jwtClaimsSet);
}
private DummyAuthToken createSAuthToken(final String email, final String appcode) {
final Map<String, Object> map = new HashMap<>();
map.put("email", email);
map.put("appcode", appcode);
map.put("iss", "sauth-preview.slb.com");
Jws<Claims> jws = new DefaultJws<>(null, new DefaultClaims(map), null);
return new DummyAuthToken(jws);
}
private void createSAuthTokenSetSecurityContext(final String email, final String appcode) {
DummyAuthToken dummyAuthToken = createSAuthToken(email, appcode);
SecurityContextHolder.setContext(securityContext);
when(securityContext.getAuthentication()).thenReturn(auth);
when(auth.getPrincipal()).thenReturn(dummyAuthToken);
}
private UserPrincipal createAADUserPrincipalSetSecurityContext(String claimName, String claimValue, String issuer) {
UserPrincipal dummyAADPrincipal = createAADUserPrincipal(claimName, claimValue, issuer);
SecurityContextHolder.setContext(securityContext);
when(securityContext.getAuthentication()).thenReturn(auth);
when(auth.getPrincipal()).thenReturn(dummyAADPrincipal);
return dummyAADPrincipal;
}
@Test
public void shouldReturnFalseWhenSAuthTokenIsSetInContext() {
createSAuthTokenSetSecurityContext("email", null);
assertFalse(authorizationService.isDomainAdminServiceAccount());
}
@Test
public void shouldReturnTrueWhenAADTokenIsSetInContext_AndIssuerIsAAD() {
createAADUserPrincipalSetSecurityContext(TestUtils.APPID, TestUtils.getAppId(), TestUtils.getAadIssuer());
assertTrue(authorizationService.isDomainAdminServiceAccount());
}
@Test
public void shouldReturnTrueWhenAADTokenIsSetInContext_AndIssuerIsAADV2() {
createAADUserPrincipalSetSecurityContext(TestUtils.APPID, TestUtils.getAppId(), TestUtils.getAadIssuerV2());
assertTrue(authorizationService.isDomainAdminServiceAccount());
}
@Test
public void shouldReturnFalseWhenAADTokenIsSetInContext_AndIssuerIsNotAAD() {
createAADUserPrincipalSetSecurityContext(TestUtils.APPID, TestUtils.getAppId(), TestUtils.getNonAadIssuer());
assertFalse(authorizationService.isDomainAdminServiceAccount());
}
@Getter
public class DummyAuthToken {
private final Jws<Claims> jws;
public DummyAuthToken(Jws<Claims> jws) {
this.jws = jws;
}
public <T> T getClaim(String claim, Class<T> type) {
return jws.getBody().get(claim, type);
}
public String getIssuer() {
return jws.getBody().getIssuer();
}
}
}
package org.opengroup.osdu.schema.provider.azure.service.serviceimpl;
public class TestUtils {
private static final String appId = "1234";
public static final String APPID = "appid";
public static final String aadIssuer = "https://sts.windows.net";
public static final String aadIssuerV2 = "https://login.microsoftonline.com";
public static final String nonAadIssuer = "https://login.abc.com";
public static String getAppId() {return appId;}
public static String getAadIssuer() {return aadIssuer;}
public static String getAadIssuerV2() {return aadIssuerV2;}
public static String getNonAadIssuer() {return nonAadIssuer;}
}
......@@ -3,7 +3,7 @@
<parent>
<groupId>org.opengroup.osdu</groupId>
<artifactId>os-schema</artifactId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
......@@ -29,7 +29,7 @@
<dependency>
<groupId>org.opengroup.osdu</groupId>
<artifactId>os-schema-core</artifactId>
<version>0.10.0-SNAPSHOT</version>
<version>0.11.0-SNAPSHOT</version>
</dependency>
<dependency>
......
......@@ -3,7 +3,7 @@
<parent>
<groupId>org.opengroup.osdu</groupId>