Commit 47d48000 authored by Rucha Deshpande's avatar Rucha Deshpande
Browse files

Update Push Listener


commit 883c5719 
Author: Rucha Deshpande <deshruch@amazon.com> 
Date: Wed Oct 21 2020 15:54:38 GMT-0500 (Central Daylight Time) 

    Update Push Listener
parent 965c00b4
Pipeline #12768 passed with stages
in 17 minutes and 28 seconds
......@@ -13,17 +13,17 @@
// limitations under the License.
package org.opengroup.osdu.register.provider.aws.pushApi;
import com.amazonaws.services.sns.message.*;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.base.Strings;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.ConfirmSubscriptionRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.Hashing;
import org.opengroup.osdu.core.aws.sns.AmazonSNSConfig;
import org.opengroup.osdu.core.common.cryptographic.ISignatureService;
import org.opengroup.osdu.core.common.cryptographic.SignatureServiceException;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.opengroup.osdu.register.provider.aws.config.AwsServiceConfig;
import org.opengroup.osdu.register.utils.AppServiceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
......@@ -32,14 +32,18 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.Map;
import java.util.Scanner;
//used by integration test to validate challenge response logic and confirm subscription
@RestController
......@@ -57,81 +61,88 @@ public class AwsSubscriberTestListenerApi {
@Inject
private javax.inject.Provider<DpsHeaders> headersProvider;
private final SnsMessageManager messageParser = new SnsMessageManager();
@Autowired
private AwsServiceConfig awsConfig;
@GetMapping("/aws/challenge/{count}")
public ResponseEntity<?> testCrc(@RequestParam("crc") @NotBlank String crc, @RequestParam("hmac") @NotBlank String hmac) {
try {
signatureService.verifyHmacSignature(hmac, this.serviceConfig.getSubscriberSecret());
} catch (SignatureServiceException e) {
return new ResponseEntity<>("Authorization signature validation Failed", HttpStatus.BAD_REQUEST);
}
logger.info("Signature verified and sending response");
// Use the secret you send to the subscriber registration create request
return getResponse(crc, this.serviceConfig.getSubscriberSecret());
}
public AmazonSNS snsClient;
@PostMapping("/aws/challenge/{count}")
public void process(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
messageParser.handleMessage(httpRequest.getInputStream(), new DefaultSnsMessageHandler() {
@Override
public void handle(SnsNotification snsNotification) {
// If the subject is "unsubscribe" then unsubscribe from this topic
if (snsNotification.getSubject().equalsIgnoreCase("unsubscribe")) {
snsNotification.unsubscribeFromTopic();
} else {
// Otherwise process the message
System.out.printf("Received message %n"
+ "Subject=%s %n"
+ "Message = %s %n",
snsNotification.getSubject(), snsNotification.getMessage());
public ResponseEntity process(HttpServletRequest request, HttpServletResponse response) throws IOException {
String messagetype = request.getHeader("x-amz-sns-message-type");
if(messagetype!=null) {
AmazonSNSConfig snsConfig = new AmazonSNSConfig(awsConfig.amazonRegion);
snsClient = snsConfig.AmazonSNS();
Scanner scan = new Scanner(request.getInputStream());
StringBuilder builder = new StringBuilder();
while (scan.hasNextLine()) {
builder.append(scan.nextLine());
}
InputStream bytes = new ByteArrayInputStream(builder.toString().getBytes());
Map<String, String> messageMap = new ObjectMapper().readValue(bytes, Map.class);
logger.info("Type="+messageMap.get("Type"));
logger.info("Message="+messageMap.get("Message"));
logger.info("TopicArn="+messageMap.get("TopicArn"));
if (messagetype.equals("SubscriptionConfirmation")) {
logger.info("Subscription Confirmation received=" + messageMap.get("Type"));
String topicarn = messageMap.get("TopicArn");
String token = messageMap.get("Token");
ConfirmSubscriptionRequest confirmReq = new ConfirmSubscriptionRequest()
.withTopicArn(topicarn)
.withToken(token);
snsClient.confirmSubscription(confirmReq);
logger.info("Subscription confirmed");
return new ResponseEntity<>(HttpStatus.OK);
}
if (messagetype.equals("Notification")) {
logger.info("Message="+messageMap.get("Message"));
try {
String hmac= request.getParameter("hmac");
signatureService.verifyHmacSignature(hmac, this.serviceConfig.getSubscriberSecret());
} catch (SignatureServiceException e) {
return new ResponseEntity<>("Authorization signature validation Failed", HttpStatus.BAD_REQUEST);
}
logger.info("Sending acknowledgement from hmac endpoint");
return new ResponseEntity<>(HttpStatus.OK);
}
@Override
public void handle(SnsUnsubscribeConfirmation message) {
logger.info("Received unsubscribe confirmation.");
if (messagetype.equals("UnsubscribeConfirmation")) {
logger.info("Unsubscribe Confirmation received");
}
}else
{
logger.info("Subscription Notification Message received");
try {
Scanner scan = new Scanner(request.getInputStream());
StringBuilder builder = new StringBuilder();
while (scan.hasNextLine()) {
builder.append(scan.nextLine());
}
logger.info("Message Received is="+builder.toString());
@Override
public void handle(SnsSubscriptionConfirmation message) {
super.handle(message);
logger.info("Received subscription confirmation.");
String hmac= request.getParameter("hmac");
signatureService.verifyHmacSignature(hmac, this.serviceConfig.getSubscriberSecret());
} catch (SignatureServiceException e) {
return new ResponseEntity<>("Authorization signature validation Failed", HttpStatus.BAD_REQUEST);
}
});
}
logger.info("Sending acknowledgement from hmac endpoint");
return new ResponseEntity<>(HttpStatus.OK);
@PostMapping("challenge/{count}")
public ResponseEntity testPushHmac(@RequestBody Object o, @RequestParam("hmac") String hmac) {
try {
signatureService.verifyHmacSignature(hmac, this.serviceConfig.getSubscriberSecret());
} catch (SignatureServiceException e) {
return new ResponseEntity<>("Authorization signature validation Failed", HttpStatus.BAD_REQUEST);
}
logger.info("Sending acknowledgement from hmac endpoint");
return new ResponseEntity<>(HttpStatus.OK);
}
class ChallengeResponse {
public String responseHash = "";
}
private boolean verifyToken() {
DpsHeaders headers = headersProvider.get();
if (Strings.isNullOrEmpty(headers.getAuthorization()))
return true;
@GetMapping("/aws/challenge/{count}")
public ResponseEntity<?> testCrc(@RequestParam("crc") @NotBlank String crc, @RequestParam("hmac") @NotBlank String hmac) {
try {
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(this.serviceConfig.getIntegrationTestJwtAudiences()))
.build();
GoogleIdToken idToken = verifier.verify(headers.getAuthorization());
return idToken != null;
} catch (Exception ex) {
return false;
signatureService.verifyHmacSignature(hmac, this.serviceConfig.getSubscriberSecret());
} catch (SignatureServiceException e) {
return new ResponseEntity<>("Authorization signature validation Failed", HttpStatus.BAD_REQUEST);
}
logger.info("Signature verified and sending response");
// Use the secret you send to the subscriber registration create request
return getResponse(crc, this.serviceConfig.getSubscriberSecret());
}
private ResponseEntity<ChallengeResponse> getResponse(String crc, String secretString) {
......@@ -144,4 +155,11 @@ public class AwsSubscriberTestListenerApi {
cr.responseHash = response;
return new ResponseEntity<>(cr, HttpStatus.OK);
}
class ChallengeResponse {
public String responseHash = "";
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment