Skip to content

Commit c3e371c

Browse files
committed
wip
Signed-off-by: Richard Salac <richard.salac@broadcom.com>
1 parent 4adcfea commit c3e371c

40 files changed

Lines changed: 196 additions & 166 deletions

File tree

api-catalog-services/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ dependencies {
9191
testImplementation libs.spring.boot.starter.test
9292
testImplementation libs.spring.mock.mvc
9393
testImplementation(testFixtures(project(":apiml-common")))
94+
testImplementation(testFixtures(project(":apiml-security-common")))
9495
testImplementation libs.reactor.test
9596

9697
compileOnly libs.lombok

api-catalog-services/src/test/java/org/zowe/apiml/apicatalog/security/ApiCatalogLogoutSuccessHandlerTest.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import org.springframework.web.server.WebFilterChain;
2222
import org.zowe.apiml.security.common.config.AuthConfigurationProperties;
2323
import org.zowe.apiml.security.common.token.TokenAuthentication;
24+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2425
import reactor.test.StepVerifier;
2526

2627
import static org.junit.jupiter.api.Assertions.*;
@@ -31,8 +32,9 @@ class ApiCatalogLogoutSuccessHandlerTest {
3132

3233
@Test
3334
void testOnLogoutSuccess() {
35+
var token = JWTTestUtils.createDummyAPIMLToken("user");
3436
var request = MockServerHttpRequest.get("/logout")
35-
.header(HttpHeaders.AUTHORIZATION, "Bearer token123")
37+
.header(HttpHeaders.AUTHORIZATION, "Bearer %s".formatted(token))
3638
.build();
3739
var exchange = MockServerWebExchange.from(request);
3840
WebFilterChain mockChain = mock(WebFilterChain.class);
@@ -43,7 +45,7 @@ void testOnLogoutSuccess() {
4345

4446
StepVerifier.create(apiCatalogLogoutSuccessHandler.onLogoutSuccess(
4547
webFilterExchange,
46-
new TokenAuthentication("TEST_TOKEN_STRING")
48+
new TokenAuthentication(token)
4749
))
4850
.verifyComplete();
4951

api-catalog-services/src/test/java/org/zowe/apiml/apicatalog/staticapi/StaticDefinitionGeneratorTest.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import org.springframework.security.core.context.SecurityContextImpl;
2323
import org.springframework.test.util.ReflectionTestUtils;
2424
import org.zowe.apiml.security.common.token.TokenAuthentication;
25+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2526

2627
import java.io.IOException;
2728
import java.nio.file.FileAlreadyExistsException;
@@ -44,7 +45,7 @@ class WhenStaticDefinitionGenerationResponse {
4445

4546
@BeforeEach
4647
void setUp() {
47-
TokenAuthentication authentication = new TokenAuthentication("token");
48+
TokenAuthentication authentication = new TokenAuthentication(JWTTestUtils.createDummyAPIMLToken("user"));
4849
authentication.setAuthenticated(true);
4950
SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
5051
ReflectionTestUtils.setField(staticDefinitionGenerator, "staticApiDefinitionsDirectories", configFileLocation);
@@ -115,7 +116,7 @@ class WhenStaticDefinitionOverrideResponse {
115116

116117
@BeforeEach
117118
void setUp() {
118-
TokenAuthentication authentication = new TokenAuthentication("token");
119+
TokenAuthentication authentication = new TokenAuthentication(JWTTestUtils.createDummyAPIMLToken("user"));
119120
authentication.setAuthenticated(true);
120121
SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
121122
ReflectionTestUtils.setField(staticDefinitionGenerator, "staticApiDefinitionsDirectories", "../config/local/api-defs");

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import org.zowe.apiml.cache.EntryExpiration;
1919
import org.zowe.apiml.util.UrlUtils;
2020

21+
import java.io.Serializable;
2122
import java.util.Date;
2223
import java.util.List;
2324

@@ -27,7 +28,7 @@
2728
@Data
2829
@AllArgsConstructor
2930
@NoArgsConstructor
30-
public class QueryResponse implements EntryExpiration {
31+
public class QueryResponse implements EntryExpiration, Serializable {
3132

3233
private String domain;
3334
private String userId;

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

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@
1414
import lombok.EqualsAndHashCode;
1515
import lombok.Getter;
1616
import lombok.extern.slf4j.Slf4j;
17-
import org.apache.el.parser.Token;
1817
import org.springframework.security.authentication.AbstractAuthenticationToken;
19-
import org.springframework.security.core.parameters.P;
2018
import org.zowe.apiml.security.common.util.JwtUtils;
19+
import org.zowe.apiml.security.common.login.LoginFilter;
2120

2221
import java.io.Serial;
2322
import java.text.ParseException;
@@ -27,17 +26,18 @@
2726
* This object is added to security context after successful authentication.
2827
* Contains username and valid JWT token.
2928
*/
30-
@EqualsAndHashCode(callSuper = false)
29+
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
3130
@Slf4j
3231
public class TokenAuthentication extends AbstractAuthenticationToken {
3332

3433
@Serial
3534
//TODO: regenerate
36-
private static final long serialVersionUID = 9187160928171618141L;
35+
private static final long serialVersionUID = 82346593850419807L;
3736

3837
private static final String DOMAIN_CLAIM_NAME = "dom";
3938
private static final String SCOPES = "scopes";
4039

40+
4141
private final JWT jwt;
4242
private final JWTClaimsSet claims;
4343
private final QueryResponse queryResponse;
@@ -131,6 +131,7 @@ public QueryResponse getQueryResponse() {
131131
* @return the token that prove the username is correct
132132
*/
133133
@Override
134+
@EqualsAndHashCode.Include
134135
public String getCredentials() {
135136
return jwt.getParsedString();
136137
}
@@ -156,10 +157,10 @@ public String getPrincipal() {
156157
// }
157158

158159
@SuppressWarnings("squid:S3655")
159-
// public static TokenAuthenticationEnhanced createAuthenticatedFromHeader(String token, String authHeader) {
160-
// var loginRequest = LoginFilter.getCredentialFromAuthorizationHeader(Optional.of(authHeader));
161-
// return createAuthenticated(loginRequest.get().getUsername(), token, Type.JWT);
162-
// }
160+
public static TokenAuthentication createAuthenticatedFromHeader(String token, String authHeader) {
161+
var loginRequest = LoginFilter.getCredentialFromAuthorizationHeader(Optional.of(authHeader));
162+
return createAuthenticated(loginRequest.get().getUsername(), token, Type.JWT);
163+
}
163164

164165
public enum Type {
165166
JWT,
@@ -190,7 +191,7 @@ private QueryResponse parseQueryResponse(JWTClaimsSet claims) {
190191
private void checkUserId(String userId) {
191192
var principal = getPrincipal();
192193
if (userId == null || !userId.equalsIgnoreCase(principal)) {
193-
log.debug("Username '{}' does not match the one in token '{}'", userId, principal);
194+
log.debug("Username '{}' does not match the one in token '{}' or is null", userId, principal);
194195
throw new TokenNotValidException("Token is not valid for provided username");
195196
}
196197
}

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
import org.zowe.apiml.security.common.token.TokenAuthentication;
2424

2525
import jakarta.servlet.http.HttpServletResponse;
26+
import org.zowe.apiml.security.common.util.JWTTestUtils;
27+
2628
import java.io.IOException;
2729
import java.io.PrintWriter;
2830
import java.util.HashSet;
@@ -36,7 +38,8 @@
3638
class SuccessfulAccessTokenHandlerTest {
3739

3840
private static final String USERNAME = "user";
39-
private final TokenAuthentication dummyAuth = new TokenAuthentication(USERNAME, "TEST_TOKEN_STRING");
41+
public static final String JWT_TOKEN = JWTTestUtils.createDummyAPIMLToken(USERNAME);
42+
private final TokenAuthentication dummyAuth = new TokenAuthentication(USERNAME, JWT_TOKEN);
4043
private SuccessfulAccessTokenHandler underTest;
4144
private AccessTokenProvider accessTokenProvider;
4245
private MockHttpServletRequest httpServletRequest;
@@ -71,23 +74,23 @@ void setup() {
7174
class WhenCallingOnAuthentication {
7275
@Test
7376
void thenReturn200() throws IOException {
74-
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn("jwtToken");
77+
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn(JWT_TOKEN);
7578
executeLoginHandler();
7679

7780
assertEquals(HttpStatus.OK.value(), httpServletResponse.getStatus());
7881
}
7982

8083
@Test
8184
void givenNullExpiration_thenReturn200() throws IOException {
82-
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn("jwtToken");
85+
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn(JWT_TOKEN);
8386
executeLoginHandler();
8487

8588
assertEquals(HttpStatus.OK.value(), httpServletResponse.getStatus());
8689
}
8790

8891
@Test
8992
void givenResponseNotCommitted_thenThrowIOException() throws IOException {
90-
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn("jwtToken");
93+
when(accessTokenProvider.getToken(any(), anyInt(), any())).thenReturn(JWT_TOKEN);
9194
HttpServletResponse servletResponse = mock(HttpServletResponse.class);
9295
PrintWriter mockWriter = mock(PrintWriter.class);
9396
when(servletResponse.getWriter()).thenReturn(mockWriter);
@@ -112,7 +115,7 @@ void verifyCommons() {
112115

113116
@Test
114117
void whenProperInputs_thenRauditxIsGenerated() throws IOException {
115-
doReturn("token").when(accessTokenProvider).getToken(anyString(), anyInt(), any());
118+
doReturn(JWT_TOKEN).when(accessTokenProvider).getToken(anyString(), anyInt(), any());
116119

117120
underTest.onAuthenticationSuccess(httpServletRequest, httpServletResponse, dummyAuth);
118121

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.web.client.RestTemplate;
2626
import org.zowe.apiml.security.common.config.AuthConfigurationProperties;
2727
import org.zowe.apiml.security.common.token.TokenAuthentication;
28+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2829

2930
import static org.junit.jupiter.api.Assertions.*;
3031
import static org.mockito.ArgumentMatchers.*;
@@ -41,7 +42,7 @@ class SafResourceAccessEndpointTest {
4142
private static final String UNSUPPORTED_CLASS = "testClass";
4243
private static final String RESOURCE = "resourceTest";
4344
private static final String LEVEL = "READ";
44-
private static final Authentication authentication = new TokenAuthentication(USER_ID, "token");
45+
private static final Authentication authentication = new TokenAuthentication(USER_ID, JWTTestUtils.createDummyAPIMLToken(USER_ID));
4546

4647
@Mock
4748
private RestTemplate restTemplate;

apiml-security-common/src/test/java/org/zowe/apiml/security/common/content/BearerContentFilterTest.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
2626
import org.zowe.apiml.security.common.error.ResourceAccessExceptionHandler;
2727
import org.zowe.apiml.security.common.token.TokenAuthentication;
28+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2829

2930
import java.io.IOException;
3031
import java.util.Optional;
@@ -47,7 +48,8 @@ class BearerContentFilterTest {
4748
private final AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
4849
private final AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class);
4950
private final ResourceAccessExceptionHandler resourceAccessExceptionHandler = mock(ResourceAccessExceptionHandler.class);
50-
private final static String BEARER_AUTH = "Bearer token";
51+
public static final String JWT_TOKEN = JWTTestUtils.createDummyAPIMLToken("user");
52+
private final static String BEARER_AUTH = "Bearer %s".formatted(JWT_TOKEN);
5153

5254
private MockHttpServletRequest request;
5355
private MockHttpServletResponse response;
@@ -70,8 +72,7 @@ class WhenAuthenticate {
7072

7173
@Test
7274
void thenSuccess() throws ServletException, IOException {
73-
String token = "token";
74-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
75+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
7576
request.addHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTH);
7677

7778
bearerContentFilter.doFilter(request, response, filterChain);
@@ -89,10 +90,9 @@ class whenAuthenticateWithNoGateway {
8990

9091
@Test
9192
void thenAuthenticationFails() throws ServletException, IOException {
92-
String token = "token";
9393
RuntimeException exception = new RuntimeException("No Gateway");
9494

95-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
95+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
9696

9797
request.addHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTH);
9898
when(authenticationManager.authenticate(tokenAuthentication)).thenThrow(exception);
@@ -140,10 +140,9 @@ class WhenAuthenticate {
140140

141141
@Test
142142
void thenAuthenticationFails() throws ServletException, IOException {
143-
String token = "token";
144143
AuthenticationException exception = new BadCredentialsException("Token not valid");
145144

146-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
145+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
147146
request.addHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTH);
148147
when(authenticationManager.authenticate(tokenAuthentication)).thenThrow(exception);
149148

@@ -189,7 +188,7 @@ void thenExtractContent() {
189188
request.addHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTH);
190189
Optional<AbstractAuthenticationToken> content = bearerContentFilter.extractContent(request);
191190

192-
TokenAuthentication actualToken = new TokenAuthentication("token", TokenAuthentication.Type.JWT);
191+
TokenAuthentication actualToken = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
193192

194193
assertTrue(content.isPresent());
195194
assertEquals(actualToken, content.get());

apiml-security-common/src/test/java/org/zowe/apiml/security/common/content/CookieContentFilterTest.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.zowe.apiml.security.common.config.AuthConfigurationProperties;
2626
import org.zowe.apiml.security.common.error.ResourceAccessExceptionHandler;
2727
import org.zowe.apiml.security.common.token.TokenAuthentication;
28+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2829

2930
import java.io.IOException;
3031
import java.util.Optional;
@@ -37,6 +38,8 @@
3738

3839
class CookieContentFilterTest {
3940

41+
public static final String JWT_TOKEN = JWTTestUtils.createDummyAPIMLToken("userId");
42+
4043
private CookieContentFilter cookieContentFilter;
4144
private final AuthConfigurationProperties authConfigurationProperties = new AuthConfigurationProperties();
4245
private final MockHttpServletRequest request = new MockHttpServletRequest();
@@ -56,10 +59,8 @@ void setUp() {
5659

5760
@Test
5861
void authenticationWithValidTokenInsideCookie() throws ServletException, IOException {
59-
String token = "token";
60-
61-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
62-
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), token);
62+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
63+
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), JWT_TOKEN);
6364
request.setCookies(cookie);
6465

6566
cookieContentFilter.doFilter(request, response, filterChain);
@@ -91,11 +92,10 @@ void shouldSkipFilter() throws ServletException, IOException {
9192

9293
@Test
9394
void shouldNotAuthenticateWithBadCredentials() throws ServletException, IOException {
94-
String token = "token";
9595
AuthenticationException exception = new BadCredentialsException("Token not valid");
9696

97-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
98-
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), token);
97+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
98+
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), JWT_TOKEN);
9999
request.setCookies(cookie);
100100

101101
when(authenticationManager.authenticate(tokenAuthentication)).thenThrow(exception);
@@ -110,10 +110,9 @@ void shouldNotAuthenticateWithBadCredentials() throws ServletException, IOExcept
110110

111111
@Test
112112
void shouldNotAuthenticateWithNoGateway() throws ServletException, IOException {
113-
String token = "token";
114113
RuntimeException exception = new RuntimeException("No Gateway");
115-
TokenAuthentication tokenAuthentication = new TokenAuthentication(token, TokenAuthentication.Type.JWT);
116-
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), token);
114+
TokenAuthentication tokenAuthentication = new TokenAuthentication(JWT_TOKEN, TokenAuthentication.Type.JWT);
115+
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), JWT_TOKEN);
117116
request.setCookies(cookie);
118117

119118
when(authenticationManager.authenticate(tokenAuthentication)).thenThrow(exception);
@@ -150,7 +149,7 @@ void shouldReturnEmptyIfNoCookies() {
150149

151150
@Test
152151
void shouldExtractContent() {
153-
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), "cookie");
152+
Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), JWT_TOKEN);
154153
request.setCookies(cookie);
155154

156155
Optional<AbstractAuthenticationToken> content = cookieContentFilter.extractContent(request);

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,12 @@
2020
import org.zowe.apiml.security.common.token.TokenAuthentication;
2121

2222
import jakarta.servlet.http.Cookie;
23+
import org.zowe.apiml.security.common.util.JWTTestUtils;
2324

2425
import static org.junit.jupiter.api.Assertions.*;
2526

2627
class SuccessfulLoginHandlerTest {
27-
private final TokenAuthentication dummyAuth = new TokenAuthentication("TEST_TOKEN_STRING");
28+
private final TokenAuthentication dummyAuth = new TokenAuthentication(JWTTestUtils.createDummyAPIMLToken("user"));
2829

2930
private AuthConfigurationProperties authConfigurationProperties;
3031
private MockHttpServletRequest httpServletRequest;

0 commit comments

Comments
 (0)