Skip to content

Commit 261da3c

Browse files
committed
tests and cleanup
Signed-off-by: Richard Salac <richard.salac@broadcom.com>
1 parent 6286fbc commit 261da3c

11 files changed

Lines changed: 86 additions & 45 deletions

File tree

apiml-security-common/src/main/java/org/zowe/apiml/security/common/token/TokenAuthentication.java

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import lombok.EqualsAndHashCode;
1515
import lombok.Getter;
1616
import lombok.extern.slf4j.Slf4j;
17+
import org.apache.commons.lang3.StringUtils;
1718
import org.springframework.security.authentication.AbstractAuthenticationToken;
1819
import org.zowe.apiml.security.common.util.JwtUtils;
1920
import org.zowe.apiml.security.common.login.LoginFilter;
@@ -36,7 +37,6 @@ public class TokenAuthentication extends AbstractAuthenticationToken {
3637
private static final String DOMAIN_CLAIM_NAME = "dom";
3738
private static final String SCOPES = "scopes";
3839

39-
4040
@Getter
4141
private final JWT jwt;
4242
private final JWTClaimsSet claims;
@@ -51,15 +51,6 @@ public enum Type {
5151
OIDC
5252
}
5353

54-
public TokenAuthentication(String tokenString) {
55-
this(tokenString, (Type) null);
56-
}
57-
58-
public TokenAuthentication(String userId, String tokenString) {
59-
this(tokenString);
60-
checkUserId(userId);
61-
}
62-
6354
public TokenAuthentication(String tokenString, Type type) {
6455
super(Collections.emptyList());
6556

@@ -73,28 +64,33 @@ public TokenAuthentication(String tokenString, Type type) {
7364
}
7465
}
7566

67+
public TokenAuthentication(String tokenString) {
68+
this(tokenString, Type.JWT);
69+
}
70+
7671
public TokenAuthentication(String userId, String tokenString, Type type) {
7772
this(tokenString, type);
7873
checkUserId(userId);
7974
}
8075

81-
82-
public static TokenAuthentication createAuthenticated(String tokenString, Type type) {
76+
public static TokenAuthentication createAuthenticated(String tokenString, Type type) {
8377
var tokenAuthentication = new TokenAuthentication(tokenString, type);
8478
tokenAuthentication.setAuthenticated(true);
8579
return tokenAuthentication;
8680
}
8781

88-
public static TokenAuthentication createAuthenticated(String tokenString, String type) {
89-
return createAuthenticated(tokenString, Type.valueOf(type));
90-
}
91-
9282
public static TokenAuthentication createAuthenticated(String userId, String token, Type type) {
9383
var tokenAuthentication = new TokenAuthentication(userId, token, type);
9484
tokenAuthentication.setAuthenticated(true);
9585
return tokenAuthentication;
9686
}
9787

88+
@SuppressWarnings("squid:S3655")
89+
public static TokenAuthentication createAuthenticatedFromHeader(String token, String authHeader) {
90+
var loginRequest = LoginFilter.getCredentialFromAuthorizationHeader(Optional.of(authHeader));
91+
return createAuthenticated(loginRequest.get().getUsername(), token, Type.JWT);
92+
}
93+
9894
public boolean isExpired() {
9995
return queryResponse.isExpired();
10096
}
@@ -128,10 +124,14 @@ public String getPrincipal() {
128124
return queryResponse.getUserId();
129125
}
130126

131-
@SuppressWarnings("squid:S3655")
132-
public static TokenAuthentication createAuthenticatedFromHeader(String token, String authHeader) {
133-
var loginRequest = LoginFilter.getCredentialFromAuthorizationHeader(Optional.of(authHeader));
134-
return createAuthenticated(loginRequest.get().getUsername(), token, Type.JWT);
127+
@Override
128+
public void setAuthenticated(boolean authenticated) {
129+
if (authenticated && isExpired()) {
130+
throw new TokenExpireException(
131+
"Unable to set authentication as true because the token ...%s expired on %s"
132+
.formatted(StringUtils.right(jwt.getParsedString(), 15), getExpiration()));
133+
}
134+
super.setAuthenticated(authenticated);
135135
}
136136

137137
private QueryResponse parseQueryResponse(JWTClaimsSet claims) {

apiml-security-common/src/test/java/org/zowe/apiml/gateway/security/login/SuccessfulAccessTokenHandlerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class SuccessfulAccessTokenHandlerTest {
3939

4040
private static final String USERNAME = "user";
4141
public static final String JWT_TOKEN = JWTTestUtils.createDummyAPIMLToken(USERNAME);
42-
private final TokenAuthentication dummyAuth = new TokenAuthentication(USERNAME, JWT_TOKEN);
42+
private final TokenAuthentication dummyAuth = new TokenAuthentication(JWT_TOKEN);
4343
private SuccessfulAccessTokenHandler underTest;
4444
private AccessTokenProvider accessTokenProvider;
4545
private MockHttpServletRequest httpServletRequest;

apiml-security-common/src/test/java/org/zowe/apiml/security/common/auth/saf/SafResourceAccessEndpointTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class SafResourceAccessEndpointTest {
4242
private static final String UNSUPPORTED_CLASS = "testClass";
4343
private static final String RESOURCE = "resourceTest";
4444
private static final String LEVEL = "READ";
45-
private static final Authentication authentication = new TokenAuthentication(USER_ID, JWTTestUtils.createDummyAPIMLToken(USER_ID));
45+
private static final Authentication authentication = new TokenAuthentication(JWTTestUtils.createDummyAPIMLToken(USER_ID));
4646

4747
@Mock
4848
private RestTemplate restTemplate;

apiml-security-common/src/test/java/org/zowe/apiml/security/common/token/TokenAuthenticationTest.java

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,68 @@
1313
import org.junit.jupiter.api.Test;
1414
import org.zowe.apiml.security.common.util.JWTTestUtils;
1515

16-
import static org.junit.jupiter.api.Assertions.assertEquals;
17-
import static org.junit.jupiter.api.Assertions.assertTrue;
16+
import static org.junit.jupiter.api.Assertions.*;
1817
import static org.zowe.apiml.security.common.token.TokenAuthentication.Type.JWT;
1918

2019
class TokenAuthenticationTest {
2120

2221
public static final String USERNAME = "user";
2322
public static final String JWT_TOKEN = JWTTestUtils.createDummyAPIMLToken(USERNAME);
23+
public static final String EXPIRED_JWT_TOKEN = JWTTestUtils.createDummyJwtToken(USERNAME, "APIML", -100_000L);
2424

2525
@Test
2626
void testCreateAuthenticated() {
27-
TokenAuthentication ta = TokenAuthentication.createAuthenticated(USERNAME, JWT_TOKEN, JWT);
28-
assertEquals(USERNAME, ta.getPrincipal());
29-
assertEquals(JWT_TOKEN, ta.getCredentials());
30-
assertEquals(JWT, ta.getType());
31-
assertTrue(ta.isAuthenticated());
27+
var ta = TokenAuthentication.createAuthenticated(USERNAME, JWT_TOKEN, JWT);
28+
validateTokenAuthentication(ta, JWT_TOKEN, true);
3229
}
3330

3431
@Test
3532
void testCreateAuthenticatedFromHeader() {
36-
TokenAuthentication ta = TokenAuthentication.createAuthenticatedFromHeader(JWT_TOKEN, "Basic dXNlcjpwYXNzd29yZA==");
37-
assertEquals("user", ta.getPrincipal());
38-
assertEquals(JWT_TOKEN, ta.getCredentials());
39-
assertTrue(ta.isAuthenticated());
33+
var ta = TokenAuthentication.createAuthenticatedFromHeader(JWT_TOKEN, "Basic dXNlcjpwYXNzd29yZA==");
34+
validateTokenAuthentication(ta, JWT_TOKEN, true);
35+
}
36+
37+
@Test
38+
void testAuthenticationFalseByDefault() {
39+
var ta = new TokenAuthentication(JWT_TOKEN);
40+
validateTokenAuthentication(ta, JWT_TOKEN, false);
41+
}
42+
43+
@Test
44+
void testExceptionThrownOnUnparsableToken() {
45+
assertThrows(TokenNotValidException.class, () -> new TokenAuthentication("unparsableToken"));
46+
}
47+
48+
@Test
49+
void testExpiredTokenDoesNotFailParsing() {
50+
var ta = new TokenAuthentication(EXPIRED_JWT_TOKEN);
51+
validateTokenAuthentication(ta, EXPIRED_JWT_TOKEN, false);
52+
}
53+
54+
@Test
55+
void testSettingAuthenticationTrueWithExpiredTokenFails() {
56+
var ta = new TokenAuthentication(EXPIRED_JWT_TOKEN);
57+
assertThrows(TokenExpireException.class, () -> ta.setAuthenticated(true));
58+
}
59+
60+
@Test
61+
void testSettingAuthenticationFalseWithExpiredTokenSucceeds() {
62+
var ta = new TokenAuthentication(EXPIRED_JWT_TOKEN);
63+
ta.setAuthenticated(false);
64+
65+
validateTokenAuthentication(ta, EXPIRED_JWT_TOKEN, false);
66+
}
67+
68+
@Test
69+
void testUsernameNotMatchingTokenFails() {
70+
assertThrows(TokenNotValidException.class, () -> TokenAuthentication.createAuthenticated("someUser", JWT_TOKEN, JWT));
71+
}
72+
73+
private void validateTokenAuthentication(TokenAuthentication ta, String jwt, boolean isAuthenticated) {
74+
assertEquals(USERNAME, ta.getPrincipal());
75+
assertEquals(jwt, ta.getCredentials());
76+
assertEquals(JWT, ta.getType());
77+
assertEquals(isAuthenticated, ta.isAuthenticated());
4078
}
4179

4280
}

apiml-security-common/src/testFixtures/java/org/zowe/apiml/security/common/util/JWTTestUtils.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,21 @@ public static String createToken(String username, String domain, String ltpaToke
5555
.compact();
5656
}
5757

58-
public static String createDummyJwtToken(String username, String issuer) {
58+
public static String createDummyJwtToken(String username, String issuer, long expiration) {
5959
long now = System.currentTimeMillis();
60-
long expiration = now + 100_000L;
6160
return Jwts.builder()
6261
.subject(username)
6362
.issuedAt(new Date(now))
64-
.expiration(new Date(expiration))
63+
.expiration(new Date(now + expiration))
6564
.issuer(issuer)
6665
.id(UUID.randomUUID().toString())
6766
.compact();
6867
}
6968

69+
public static String createDummyJwtToken(String username, String issuer) {
70+
return createDummyJwtToken(username, issuer, 100_000L);
71+
}
72+
7073
public static String createDummyAPIMLToken(String username) {
7174
return createDummyJwtToken(username, "APIML");
7275
}

zaas-service/src/test/java/org/zowe/apiml/zaas/security/login/saf/ZosAuthenticationProviderTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ void validAuthenticationOnOnValidCredentials() {
5858
String validJwtToken = JWTTestUtils.createDummyAPIMLToken(VALID_USERID);
5959
when(mockService.createJwtToken(anyString(), anyString(), any())).thenReturn(validJwtToken);
6060
when(mockService.createTokenAuthentication(VALID_USERID, validJwtToken))
61-
.thenReturn(new TokenAuthentication(VALID_USERID, validJwtToken));
61+
.thenReturn(new TokenAuthentication(validJwtToken));
6262

6363
Authentication authentication = provider.authenticate(VALID_TOKEN);
6464
assertThat(VALID_USERID, is(authentication.getPrincipal()));

zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/QueryFilterTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class QueryFilterTest {
4242
private MockHttpServletResponse httpServletResponse;
4343
private QueryFilter queryFilter;
4444

45-
private final String VALID_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJNZSIsImRvbSI6InRoaXMuY29tIiwibHRwYSI6Imx0cGFUb2tlbiIsImlhdCI6MTU1NDg4MzMzNCwiZXhwIjoxNTU0OTY5NzM0LCJpc3MiOiJBUElNTCIsImp0aSI6IjNkMzU3M2VhLWMxMzktNGE5Yy1iZDU5LWVjYmIyMmM0ZDcxZCJ9.bLe_d3b3bZC-K5K49fj1aHL_xDWMPsAgwKkrfewOrHhrxVL6lSphpGx52b8YvjaMUkFpVO12jCEDoYC1JLaQhQ";
45+
private final String VALID_TOKEN = JWTTestUtils.createDummyJwtToken("me", "APIML");
4646

4747
@Mock
4848
private AuthenticationSuccessHandler authenticationSuccessHandler;

zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/SuccessfulQueryHandlerTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ void setup() {
123123
@Test
124124
void shouldSetResponseParameters() throws Exception {
125125
httpServletResponse = new MockHttpServletResponse();
126-
TokenAuthentication tokenAuthentication = new TokenAuthentication(USER, jwtToken);
126+
TokenAuthentication tokenAuthentication = new TokenAuthentication(jwtToken);
127127
httpServletResponse.setStatus(HttpStatus.EXPECTATION_FAILED.value());
128128
assertNotEquals(HttpStatus.OK.value(), httpServletResponse.getStatus());
129129

@@ -137,7 +137,7 @@ void shouldSetResponseParameters() throws Exception {
137137
@Test
138138
void shouldWriteModelToBody() throws Exception {
139139
httpServletResponse = new MockHttpServletResponse();
140-
TokenAuthentication tokenAuthentication = new TokenAuthentication(USER, jwtToken);
140+
TokenAuthentication tokenAuthentication = new TokenAuthentication(jwtToken);
141141

142142
successfulQueryHandler.onAuthenticationSuccess(httpServletRequest, httpServletResponse, tokenAuthentication);
143143

zaas-service/src/test/java/org/zowe/apiml/zaas/security/refresh/SuccessfulRefreshHandlerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ void unknownTypeOfAuthenticationDoesntDoAnything() throws ServletException, IOEx
6565

6666
@Test
6767
void tokenTypeOfAuthenticationIssuesToken() throws ServletException, IOException {
68-
Authentication auth = new TokenAuthentication("USER", TOKEN);
68+
Authentication auth = new TokenAuthentication(TOKEN);
6969
underTest.onAuthenticationSuccess(request, response, auth);
7070
verify(authenticationService, atLeastOnce()).invalidateJwtToken(TOKEN, true);
7171
assertThat(response.getStatus(), is(HttpStatus.NO_CONTENT.value()));

zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/TokenCreationServiceTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ void setUp() {
8282
void givenZosmfIsUnavailable_whenTokenIsRequested_thenTokenCreatedByApiMlIsReturned() {
8383
when(providers.isZosfmUsed()).thenReturn(false);
8484
when(authenticationService.createJwtToken(eq(VALID_USER_ID), any(), any())).thenReturn(VALID_APIML_TOKEN);
85-
when(authenticationService.createTokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN)).thenReturn(new TokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN));
85+
when(authenticationService.createTokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN)).thenReturn(new TokenAuthentication(VALID_APIML_TOKEN));
8686

8787
String jwtToken = underTest.createJwtTokenWithoutCredentials(VALID_USER_ID);
8888
assertThat(jwtToken, is(VALID_APIML_TOKEN));
@@ -92,7 +92,7 @@ void givenZosmfIsUnavailable_whenTokenIsRequested_thenTokenCreatedByApiMlIsRetur
9292
void givenZosmfIsntPresentBecauseOfError_whenTokenIsRequested_shouldReturnTokenCreatedByApiMl() {
9393
when(providers.isZosfmUsed()).thenThrow(new AuthenticationServiceException("zOSMF id invalid"));
9494
when(authenticationService.createJwtToken(eq(VALID_USER_ID), any(), any())).thenReturn(VALID_APIML_TOKEN);
95-
when(authenticationService.createTokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN)).thenReturn(new TokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN));
95+
when(authenticationService.createTokenAuthentication(VALID_USER_ID, VALID_APIML_TOKEN)).thenReturn(new TokenAuthentication(VALID_APIML_TOKEN));
9696

9797
String jwtToken = underTest.createJwtTokenWithoutCredentials(VALID_USER_ID);
9898
assertThat(jwtToken, is(VALID_APIML_TOKEN));
@@ -103,7 +103,7 @@ void givenZosmfIsAvailable_whenTokenIsRequested_thenTokenCreatedByZosmfIsReturne
103103
when(providers.isZosmfAvailable()).thenReturn(true);
104104
when(providers.isZosfmUsed()).thenReturn(true);
105105
when(passTicketService.generate(VALID_USER_ID, VALID_ZOSMF_APPLID)).thenReturn(PASSTICKET);
106-
when(zosmfAuthenticationProvider.authenticate(any())).thenReturn(new TokenAuthentication(VALID_USER_ID, VALID_ZOSMF_TOKEN));
106+
when(zosmfAuthenticationProvider.authenticate(any())).thenReturn(new TokenAuthentication(VALID_ZOSMF_TOKEN));
107107

108108
String jwtToken = underTest.createJwtTokenWithoutCredentials(VALID_USER_ID);
109109
assertThat(jwtToken, is(VALID_ZOSMF_TOKEN));

0 commit comments

Comments
 (0)