Skip to content

Commit

Permalink
added for s2s and bearer (#481)
Browse files Browse the repository at this point in the history
  • Loading branch information
arshinsalim authored May 6, 2022
1 parent 60581ed commit a0047a1
Show file tree
Hide file tree
Showing 8 changed files with 19 additions and 221 deletions.
5 changes: 3 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,8 @@ dependencies {
implementation group: 'io.netty', name: 'netty-buffer', version: '4.1.69.Final'
implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.2.10'
implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.10'
testImplementation ('com.github.hmcts:rd-commons-lib:v0.0.9'){

testImplementation ('com.github.hmcts:rd-commons-lib:v0.0.11'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-web'
}
implementation('io.netty:netty-codec:4.1.69.Final') {
Expand Down Expand Up @@ -489,7 +490,7 @@ dependencies {
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'
//Fix for CVE-2021-35515, CVE-2021-35516, CVE-2021-35517, CVE-2021-36090
implementation group: 'org.apache.commons', name: 'commons-compress', version: '1.21'
testImplementation 'com.github.hmcts:fortify-client:1.2.0:all'


integrationTestImplementation sourceSets.main.runtimeClasspath
integrationTestImplementation sourceSets.test.runtimeClasspath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
import org.springframework.test.context.TestPropertySource;
import uk.gov.hmcts.reform.cwrdapi.client.CaseWorkerApiClient;
import uk.gov.hmcts.reform.cwrdapi.client.FuncTestRequestHandler;
import uk.gov.hmcts.reform.cwrdapi.client.S2sClient;
import uk.gov.hmcts.reform.cwrdapi.client.response.UserProfileResponse;
import uk.gov.hmcts.reform.cwrdapi.config.Oauth2;
import uk.gov.hmcts.reform.cwrdapi.config.TestConfigProperties;
import uk.gov.hmcts.reform.cwrdapi.controllers.request.CaseWorkersProfileCreationRequest;
import uk.gov.hmcts.reform.cwrdapi.controllers.request.UserRequest;
import uk.gov.hmcts.reform.cwrdapi.idam.IdamOpenIdClient;
import uk.gov.hmcts.reform.lib.client.response.S2sClient;

import java.util.ArrayList;
import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public RequestSpecification withUnauthenticatedRequest() {
}

public RequestSpecification getMultipleAuthHeadersInternal() {
return getMultipleAuthHeaders(idamOpenIdClient.getcwdAdminOpenIdToken());
return getMultipleAuthHeaders(idamOpenIdClient.getcwdAdminOpenIdToken("cwd-admin"));
}

public RequestSpecification getMultipleAuthHeadersInternal(String role) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import java.util.Map;

import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.getS2sToken;
import static uk.gov.hmcts.reform.cwrdapi.idam.IdamOpenIdClient.crdAdminToken;
import static uk.gov.hmcts.reform.lib.idam.IdamOpenId.adminToken;

@Slf4j
@Service
Expand Down Expand Up @@ -46,10 +46,11 @@ public Response sendGet(HttpStatus httpStatus, String urlPath, String baseUrl,
.contentType(MediaType.APPLICATION_JSON_VALUE)
.baseUri(baseUrl)
.header("ServiceAuthorization", getS2sToken())
.header("Authorization", BEARER + crdAdminToken);
.header("Authorization", BEARER + adminToken);
if (!additionalHeaders.isEmpty()) {
additionalHeaders
.forEach(requestSpecification::header);

}
Response response = requestSpecification.when()
.get(urlPath);
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import uk.gov.hmcts.reform.lib.config.TestConfig;

@Getter
@Setter
@Configuration
public class TestConfigProperties {

public class TestConfigProperties implements TestConfig {

@Value("${oauth2.client.secret}")
public String clientSecret;
Expand Down Expand Up @@ -46,6 +46,9 @@ public class TestConfigProperties {
@Value("${s2s-secret}")
protected String s2sSecret;

@Value("${scope-name}")
protected String scope;

@Bean
public ObjectMapper defaultObjectMapper() {
return new ObjectMapper()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,39 +1,24 @@
package uk.gov.hmcts.reform.cwrdapi.idam;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.mifmif.common.regex.Generex;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import uk.gov.hmcts.reform.cwrdapi.config.TestConfigProperties;
import uk.gov.hmcts.reform.lib.idam.IdamOpenId;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.CREDS;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.EMAIL;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.ROLE_CWD_ADMIN;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.ROLE_CWD_SYSTEM_USER;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.generateRandomEmail;
import static uk.gov.hmcts.reform.cwrdapi.AuthorizationFunctionalTest.setEmailsTobeDeleted;

@Slf4j
public class IdamOpenIdClient {
public class IdamOpenIdClient extends IdamOpenId {

private final TestConfigProperties testConfig;

private final Gson gson = new Gson();

Expand All @@ -44,67 +29,7 @@ public class IdamOpenIdClient {
public static String cwdSystemUserToken;

public IdamOpenIdClient(TestConfigProperties testConfig) {
this.testConfig = testConfig;
}

public Map<String, String> createUser(String userRole) {

return createUser(userRole, generateRandomEmail(), "cwr-test", "cwr-test");
}

public Map<String, String> createUser(String userRole, String userEmail, String firstName, String lastName) {
//Generating a random user
String userGroup = "";
String password = generateSidamPassword();

String id = UUID.randomUUID().toString();

Role role = new Role(userRole);

List<Role> roles = new ArrayList<>();
roles.add(role);

Group group = new Group(userGroup);

User user = new User(userEmail, firstName, id, lastName, password, roles, group);

String serializedUser = gson.toJson(user);

Response createdUserResponse = null;

for (int i = 0; i < 5; i++) {
log.info("SIDAM createUser retry attempt : " + i + 1);
createdUserResponse = RestAssured
.given()
.relaxedHTTPSValidation()
.baseUri(testConfig.getIdamApiUrl())
.header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.body(serializedUser)
.post("/testing-support/accounts")
.andReturn();
if (createdUserResponse.getStatusCode() == 504) {
log.info("SIDAM createUser retry response for attempt " + i + 1 + " 504");
} else {
break;
}
}

log.info("openIdTokenResponse createUser response: " + createdUserResponse.getStatusCode());

assertThat(createdUserResponse.getStatusCode()).isEqualTo(201);
setEmailsTobeDeleted(userEmail);

Map<String, String> userCreds = new HashMap<>();
userCreds.put(EMAIL, userEmail);
userCreds.put(CREDS, password);
return userCreds;
}

public String getcwdAdminOpenIdToken() {
if (isNull(crdAdminToken)) {
crdAdminToken = getToken(ROLE_CWD_ADMIN);
}
return crdAdminToken;
super(testConfig);
}

public Map getUser(String idamId) {
Expand All @@ -121,19 +46,12 @@ public Map getUser(String idamId) {
return generatedUserResponse.getBody().as(Map.class);
}

public String getCwdSystemUserOpenIdToken() {
if (isNull(cwdSystemUserToken)) {
cwdSystemUserToken = getToken(ROLE_CWD_SYSTEM_USER);
}
return cwdSystemUserToken;
}

public String getOpenIdTokenByRole(String role) {
if (StringUtils.isNotEmpty(role)) {
if (ROLE_CWD_ADMIN.equals(role)) {
return getcwdAdminOpenIdToken();
return getcwdAdminOpenIdToken(role);
} else if (ROLE_CWD_SYSTEM_USER.equals(role)) {
return getCwdSystemUserOpenIdToken();
return getCwdSystemUserOpenIdToken(role);
} else {
return getToken(role);
}
Expand All @@ -143,39 +61,7 @@ public String getOpenIdTokenByRole(String role) {
return null;
}

public String getToken(String role) {
Map<String, String> userCreds = createUser(role);
return getOpenIdToken(userCreds.get(EMAIL), userCreds.get(CREDS));
}

public String getOpenIdToken(String userEmail, String password) {

Map<String, String> tokenParams = new HashMap<>();
tokenParams.put("grant_type", "password");
tokenParams.put("username", userEmail);
tokenParams.put("password", password);
tokenParams.put("client_id", testConfig.getClientId());
tokenParams.put("client_secret", testConfig.getClientSecret());
tokenParams.put("redirect_uri", testConfig.getOauthRedirectUrl());
tokenParams.put("scope", "openid profile roles manage-user create-user search-user");
Response openIdTokenResponse = RestAssured
.given()
.relaxedHTTPSValidation()
.baseUri(testConfig.getIdamApiUrl())
.header(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE)
.params(tokenParams)
.post("/o/token")
.andReturn();

log.info("getOpenIdToken response: " + openIdTokenResponse.getStatusCode());

assertThat(openIdTokenResponse.getStatusCode()).isEqualTo(200);

BearerTokenResponse accessTokenResponse = gson.fromJson(openIdTokenResponse.getBody()
.asString(), BearerTokenResponse.class);
return accessTokenResponse.getAccessToken();

}

public void deleteSidamUser(String email) {
try {
Expand All @@ -190,44 +76,4 @@ public void deleteSidamUser(String email) {
}
}

@AllArgsConstructor
class User {
private final String email;
private final String forename;
private final String id;
private final String surname;
private final String password;
private final List<Role> roles;
private final Group group;
}

@AllArgsConstructor
class Role {
private String code;
}

@AllArgsConstructor
class Group {
private String code;
}

@Getter
@AllArgsConstructor
class AuthorizationResponse {
private String code;
}

@Getter
@AllArgsConstructor
class BearerTokenResponse {
@SerializedName("access_token")
private String accessToken;
}

public static String generateSidamPassword() {
if (isBlank(sidamPassword)) {
sidamPassword = new Generex("([A-Z])([a-z]{4})([0-9]{4})").random();
}
return sidamPassword;
}
}
1 change: 1 addition & 0 deletions src/functionalTest/resources/application-functional.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ targetInstance: ${TEST_URL:http://localhost:8095}
s2s-url: ${S2S_URL_FOR_TESTS:http://rpe-service-auth-provider-aat.service.core-compute-aat.internal}

s2s-name: rd_caseworker_ref_api
scope-name: openid profile roles manage-user create-user search-user

idam.api.url: ${IDAM_URL:https://idam-api.aat.platform.hmcts.net}
oauth2.client.secret: ${CA_REF_OAUTH2_CLIENT_SECRET:}
Expand Down

0 comments on commit a0047a1

Please sign in to comment.