Skip to content

Commit

Permalink
Merge pull request #139 from smtadmin/release-1.2.12
Browse files Browse the repository at this point in the history
Release 1.2.12
  • Loading branch information
YetAnotherMask authored Jul 26, 2023
2 parents 2b92524 + 7a28218 commit ea629a0
Show file tree
Hide file tree
Showing 8 changed files with 194 additions and 99 deletions.
6 changes: 2 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ group = 'com.siliconmtn'
* For 'release' publishing, use: version = n.n.n
*
*/
version = '1.2.11-SNAPSHOT'
//version = '1.2.11'
//version = '1.2.12-SNAPSHOT'
version = '1.2.12'

sourceCompatibility = '11'
archivesBaseName = "spacelibs-java"
Expand All @@ -53,8 +53,6 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-aop'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.security:spring-security-oauth2-client'
implementation 'org.springframework.security.oauth:spring-security-oauth2:2.5.2.RELEASE'

implementation 'org.springframework.security:spring-security-crypto:5.5.2'
implementation 'org.hibernate:hibernate-validator:7.0.1.Final'
Expand Down
34 changes: 0 additions & 34 deletions src/main/java/com/siliconmtn/pulsar/OAuthConfig.java

This file was deleted.

41 changes: 20 additions & 21 deletions src/main/java/com/siliconmtn/pulsar/PulsarAuthenticator.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import java.util.function.Supplier;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -48,16 +46,14 @@ public class PulsarAuthenticator implements Supplier<String> {

//Autowired Member Variables
protected PulsarConfig config;
protected ClientRegistrationRepository repo;

//Instance Variables
private String token;
protected ObjectMapper mapper;
protected SMTHttpConnectionManager manager;

public PulsarAuthenticator(PulsarConfig config, ClientRegistrationRepository repo) {
public PulsarAuthenticator(PulsarConfig config) {
this.config = config;
this.repo = repo;
this.manager = new SMTHttpConnectionManager();
prepareManager(this.manager);
this.mapper = new ObjectMapper();
Expand All @@ -79,7 +75,7 @@ protected void prepareManager(SMTHttpConnectionManager manager) {
*/
@Override
public String get() {
log.info("Pulsar JWT Token is being requested");
log.debug("Pulsar JWT Token is being requested");
return token;
}

Expand All @@ -93,14 +89,16 @@ public String get() {
*/
@Scheduled(cron = "${pulsar.cronSchedule:-}")
public void updateToken() {
log.info("Populating Pulsar JWT Token");
ClientRegistration reg = repo.findByRegistrationId(OAUTH_IDENTIFIER);
if(reg != null && !StringUtil.isEmpty(reg.getClientId()) && !StringUtil.isEmpty(reg.getClientSecret()) && !StringUtil.isEmpty(reg.getProviderDetails().getTokenUri())) {
retrieveNPEJWTToken(reg);
} else if (!StringUtil.isEmpty(config.getAdminJWT()) || !StringUtil.isEmpty(config.getClientJWT())) {
log.debug("Populating Pulsar JWT Token");
if(config.hasNPEAuth()) {
retrieveNPEJWTToken(config);
} else if (config.hasJWTAuth()) {
token = StringUtil.defaultString(config.getAdminJWT(), config.getClientJWT());
} else {
//Authenticator requires at least an empty string to avoid an NPE.
token = "";
}
log.info("Populated Pulsar JWT Token");
log.debug("Populated Pulsar JWT Token");
}

/**
Expand All @@ -115,20 +113,21 @@ public void updateToken() {
* --data-urlencode 'grant_type=client_credentials'
* @param reg
*/
protected void retrieveNPEJWTToken(ClientRegistration reg) {
if(reg == null) {
token = null;
protected void retrieveNPEJWTToken(PulsarConfig config) {
token = null;

if(config == null) {
return;
}
Map<String, Object> postBody = new HashMap<>();
postBody.put(CLIENT_ID, reg.getClientId());
postBody.put(CLIENT_SECRET, reg.getClientSecret());
postBody.put(SCOPE, reg.getScopes().iterator().next());
postBody.put(GRANT_TYPE, reg.getAuthorizationGrantType().getValue());
postBody.put(CLIENT_ID, config.getClientId());
postBody.put(CLIENT_SECRET, config.getClientSecret());
postBody.put(SCOPE, config.getScope());
postBody.put(GRANT_TYPE, config.getAuthorizationGrantType());

try {
byte [] data = manager.getRequestData(reg.getProviderDetails().getTokenUri(), postBody, HttpConnectionType.POST);
log.info("Received Pulsar JWT Token");
byte [] data = manager.getRequestData(config.getTokenUri(), postBody, HttpConnectionType.POST);
log.debug("Received Pulsar JWT Token");
JsonNode g = mapper.readTree(data);
token = g.get(ACCESS_TOKEN).asText();
} catch(Exception e) {
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/siliconmtn/pulsar/PulsarClientManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ protected ClientConfigurationData buildClientConfig() {
conf.setRequestTimeoutMs(1000);
conf.setOperationTimeoutMs(1000);
conf.setTlsAllowInsecureConnection(config.isTlsAllowInsecureConnection());
conf.setAuthentication(AuthenticationFactory.token(auth));
if(config.hasAuth()) {
conf.setAuthentication(AuthenticationFactory.token(auth));
}

return conf;
}
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/com/siliconmtn/pulsar/PulsarConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Map;

import org.apache.pulsar.shade.org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Configuration;
Expand Down Expand Up @@ -39,4 +40,33 @@ public class PulsarConfig {
private String cronSchedule;
private boolean tlsAllowInsecureConnection;
private Map<String, TopicConfig> topics;
private String clientId;
private String clientSecret;
private String scope;
private String tokenUri;
private String authorizationGrantType;

/**
* Helper method to check if we have a valid JWT Token Configuration
* @return
*/
public boolean hasJWTAuth() {
return !StringUtils.isEmpty(adminJWT) || !StringUtils.isEmpty(clientJWT);
}

/**
* Helper method to check if we have a valid NPE Configuration
* @return
*/
public boolean hasNPEAuth() {
return !StringUtils.isEmpty(clientId) && !StringUtils.isEmpty(clientSecret) && !StringUtils.isEmpty(tokenUri) && !StringUtils.isEmpty(scope) && !StringUtils.isEmpty(authorizationGrantType);
}

/**
* Helper method to determine if there is a valid authentication method present in config.
* @return
*/
public boolean hasAuth() {
return hasJWTAuth() || hasNPEAuth();
}
}
92 changes: 60 additions & 32 deletions src/test/java/com/siliconmtn/pulsar/PulsarAuthenticatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
Expand All @@ -17,18 +16,13 @@
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.pulsar.shade.com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;

import com.siliconmtn.io.http.SMTHttpConnectionManager;
import com.siliconmtn.io.http.SMTHttpConnectionManager.HttpConnectionType;
Expand All @@ -43,23 +37,29 @@ class PulsarAuthenticatorTest {
@Mock
PulsarConfig config;

@Mock
ClientRegistrationRepository repo;

@InjectMocks
PulsarAuthenticator auth;

@Test
void prepareManager() throws MalformedURLException {
SMTHttpConnectionManager manager = new SMTHttpConnectionManager();
auth.prepareManager(manager);
assertNotNull(manager.getSslSocketFactory());
assertTrue(manager.getRequestHeaders().containsKey(SMTHttpConnectionManager.REQUEST_PROPERTY_CONTENT_TYPE));
assertEquals(manager.getRequestHeaders().get(SMTHttpConnectionManager.REQUEST_PROPERTY_CONTENT_TYPE), "application/x-www-form-urlencoded");
assertEquals("application/x-www-form-urlencoded", manager.getRequestHeaders().get(SMTHttpConnectionManager.REQUEST_PROPERTY_CONTENT_TYPE));
}

@Test
void updateTokenNoAuth() {
when(config.hasNPEAuth()).thenReturn(false);
when(config.hasJWTAuth()).thenReturn(false);
assertDoesNotThrow(() -> auth.updateToken());
assertEquals("", auth.get());
}

@Test
void updateTokenFromConfig() {
when(config.hasNPEAuth()).thenReturn(false);
when(config.hasJWTAuth()).thenReturn(true);
String clientToken = "client";
String adminToken = "admin";
when(config.getClientJWT()).thenReturn(clientToken);
Expand All @@ -70,67 +70,95 @@ void updateTokenFromConfig() {
assertEquals(adminToken, auth.get());
}

@SuppressWarnings("unchecked")
@Test
void retrieveNPEJWTToken() throws IOException {
assertDoesNotThrow(() -> auth.retrieveNPEJWTToken(null));
assertNull(auth.get());

ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
String scope = "email";
String id = "clientId";
String secret = "clientSecret";
AuthorizationGrantType grantType = AuthorizationGrantType.CLIENT_CREDENTIALS;
String grantType = "CLIENT_CREDENTIALS";
String tokenUri = "tokenUri";
String accessToken = "token";
Map<String, String> retData = new HashMap<>();
retData.put(PulsarAuthenticator.ACCESS_TOKEN, accessToken);

byte [] data = mapper.writeValueAsBytes(retData);
SMTHttpConnectionManager manager = mock(SMTHttpConnectionManager.class);
ProviderDetails det = mock(ProviderDetails.class);
ClientRegistration reg = mock(ClientRegistration.class);
auth.manager = manager;

when(reg.getScopes()).thenReturn(Set.of(scope));
when(reg.getClientId()).thenReturn(id);
when(reg.getClientSecret()).thenReturn(secret);
when(reg.getAuthorizationGrantType()).thenReturn(grantType);
when(reg.getProviderDetails()).thenReturn(det);
when(det.getTokenUri()).thenReturn(tokenUri);
when(config.getScope()).thenReturn(scope);
when(config.getClientId()).thenReturn(id);
when(config.getClientSecret()).thenReturn(secret);
when(config.getAuthorizationGrantType()).thenReturn(grantType);
when(config.getTokenUri()).thenReturn(tokenUri);

when(manager.getRequestData(eq(tokenUri), any(Map.class), eq(HttpConnectionType.POST))).thenReturn(data);

assertDoesNotThrow(() -> auth.retrieveNPEJWTToken(reg));
assertDoesNotThrow(() -> auth.retrieveNPEJWTToken(config));

assertEquals(accessToken, auth.get());
}

@SuppressWarnings("unchecked")
@Test
void retrieveNPEJWTTokenCatchError() throws IOException {
assertDoesNotThrow(() -> auth.retrieveNPEJWTToken(null));
assertNull(auth.get());
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
String scope = "email";
String id = "clientId";
String secret = "clientSecret";
String grantType = "CLIENT_CREDENTIALS";
String tokenUri = "tokenUri";
String accessToken = "token";
Map<String, String> retData = new HashMap<>();
retData.put(PulsarAuthenticator.ACCESS_TOKEN, accessToken);

byte [] data = null;
SMTHttpConnectionManager manager = mock(SMTHttpConnectionManager.class);
auth.manager = manager;

when(config.getScope()).thenReturn(scope);
when(config.getClientId()).thenReturn(id);
when(config.getClientSecret()).thenReturn(secret);
when(config.getAuthorizationGrantType()).thenReturn(grantType);
when(config.getTokenUri()).thenReturn(tokenUri);

when(manager.getRequestData(eq(tokenUri), any(Map.class), eq(HttpConnectionType.POST))).thenReturn(data);

assertDoesNotThrow(() -> auth.retrieveNPEJWTToken(config));

assertEquals(null, auth.get());
}

@SuppressWarnings("unchecked")
@Test
void updateTokenFromOauth() throws IOException {
when(config.hasNPEAuth()).thenReturn(true);
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
String scope = "email";
String id = "clientId";
String secret = "clientSecret";
AuthorizationGrantType grantType = AuthorizationGrantType.CLIENT_CREDENTIALS;
String grantType = "CLIENT_CREDENTIALS";
String tokenUri = "tokenUri";
String accessToken = "token";
Map<String, String> retData = new HashMap<>();
retData.put(PulsarAuthenticator.ACCESS_TOKEN, accessToken);

byte [] data = mapper.writeValueAsBytes(retData);
SMTHttpConnectionManager manager = mock(SMTHttpConnectionManager.class);
ProviderDetails det = mock(ProviderDetails.class);
ClientRegistration reg = mock(ClientRegistration.class);
auth.manager = manager;
when(repo.findByRegistrationId(PulsarAuthenticator.OAUTH_IDENTIFIER)).thenReturn(reg);
when(reg.getScopes()).thenReturn(Set.of(scope));
when(reg.getClientId()).thenReturn(id);
when(reg.getClientSecret()).thenReturn(secret);
when(reg.getAuthorizationGrantType()).thenReturn(grantType);
when(reg.getProviderDetails()).thenReturn(det);
when(det.getTokenUri()).thenReturn(tokenUri);
when(config.getScope()).thenReturn(scope);
when(config.getClientId()).thenReturn(id);
when(config.getClientSecret()).thenReturn(secret);
when(config.getAuthorizationGrantType()).thenReturn(grantType);
when(config.getTokenUri()).thenReturn(tokenUri);

when(manager.getRequestData(eq(tokenUri), any(Map.class), eq(HttpConnectionType.POST))).thenReturn(data);

Expand Down
Loading

0 comments on commit ea629a0

Please sign in to comment.