@Test public void renewCertificate_Non_Admin_Success() throws Exception { String certficateName = "testCert.t-mobile.com"; String certficateType = "internal"; String token = "FSR&&%S*"; String jsonStr = "{ \"username\": \"testusername1\", \"password\": \"testpassword1\"}"; String jsonStr2 = "{\"certificates\":[{\"sortedSubjectName\": \"CN=CertificateName.t-mobile.com, C=US, " + "ST=Washington, " + "L=Bellevue, O=T-Mobile USA, Inc\"," + "\"certificateId\":57258,\"certificateStatus\":\"Active\"," + "\"containerName\":\"cont_12345\",\"NotAfter\":\"2021-06-15T04:35:58-07:00\"}]}"; UserDetails userDetails = new UserDetails(); userDetails.setSelfSupportToken("tokentTest"); userDetails.setUsername("normaluser"); userDetails.setAdmin(false); userDetails.setClientToken(token); userDetails.setSelfSupportToken(token); Map<String, Object> requestMap = new HashMap<>(); requestMap.put("access_token", "12345"); requestMap.put("token_type", "type"); when(ControllerUtil.parseJson(jsonStr)).thenReturn(requestMap); CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setToken_type("token type"); certManagerLogin.setAccess_token("1234"); String metaDataJson = "{\"data\":{\"akmid\":\"102463\",\"applicationName\":\"tvs\",\"applicationOwnerEmailId\":\"SpectrumClearingTools@T-Mobile.com\",\"applicationTag\":\"TVS\",\"authority\":\"T-Mobile Issuing CA 01 - SHA2\",\"certCreatedBy\":\"nnazeer1\",\"certOwnerEmailId\":\"ltest@smail.com\",\"certType\":\"internal\",\"certificateId\":59880,\"certificateName\":\"certtest260630.t-mobile.com\",\"certificateStatus\":\"Revoked\",\"containerName\":\"VenafiBin_12345\",\"createDate\":\"2020-06-26T05:10:41-07:00\",\"expiryDate\":\"2021-06-26T05:10:41-07:00\",\"projectLeadEmailId\":\"Daniel.Urrutia@T-Mobile.Com\",\"users\":{\"normaluser\":\"write\",\"certuser\":\"read\",\"safeadmin\":\"deny\",\"testsafeuser\":\"write\",\"testuser1\":\"deny\",\"testuser2\":\"read\"}}}"; Response response = new Response(); response.setHttpstatus(HttpStatus.OK); response.setResponse(metaDataJson); response.setSuccess(true); when(reqProcessor.process(eq("/read"), anyObject(), anyString())).thenReturn(response); CertResponse certResponse = new CertResponse(); certResponse.setHttpstatus(HttpStatus.OK); certResponse.setResponse(jsonStr); certResponse.setSuccess(true); when(reqProcessor.processCert(eq("/auth/certmanager/login"), anyObject(), anyString(), anyString())).thenReturn(certResponse); CertResponse renewResponse = new CertResponse(); renewResponse.setHttpstatus(HttpStatus.OK); renewResponse.setResponse(null); renewResponse.setSuccess(true); when(reqProcessor.processCert(eq("/certificates/renew"), anyObject(), anyString(), anyString())).thenReturn(renewResponse); CertResponse findCertResponse = new CertResponse(); findCertResponse.setHttpstatus(HttpStatus.OK); findCertResponse.setResponse(jsonStr2); findCertResponse.setSuccess(true); when(reqProcessor.processCert(eq("/certmanager/findCertificate"), anyObject(), anyString(), anyString())).thenReturn(findCertResponse); when(ControllerUtil.updateMetaData(anyString(), anyMap(), anyString())).thenReturn(Boolean.TRUE); ResponseEntity<?> renewCertResponse = sSLCertificateService.renewCertificate(certficateType, certficateName, userDetails, token); assertNotNull(renewCertResponse); }
public ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token) { Map<String, String> metaDataParams = new HashMap<>(); Boolean isPermission = true; if (!isValidInputs(certificateName, certType)) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "renewCertificate") .put(LogMessage.MESSAGE, "Invalid user inputs") .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)).build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String endPoint = certificateName; String metaDataPath = (certType.equalsIgnoreCase("internal"))? SSLCertificateConstants.SSL_CERT_PATH + "/" + endPoint :SSLCertificateConstants.SSL_EXTERNAL_CERT_PATH + "/" + endPoint; Response response = new Response(); if (!userDetails.isAdmin()) { isPermission = validateCertOwnerPermissionForNonAdmin(userDetails, certificateName,certType); if (!isPermission) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body("{\"errors\":[\"" + "Access denied: No permission to renew certificate" + "\"]}"); } } try { if (userDetails.isAdmin()) { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", token); } else { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", userDetails.getSelfSupportToken()); } } catch (Exception e) { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), response.getResponse())) .build())); return ResponseEntity.status(response.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate unavailable" + "\"]}"); } if (!HttpStatus.OK.equals(response.getHttpstatus())) { return ResponseEntity.status(response.getHttpstatus()) .body("{\"errors\":[\"" + "Certificate unavailable" + "\"]}"); } JsonParser jsonParser = new JsonParser(); JsonObject object = ((JsonObject) jsonParser.parse(response.getResponse())).getAsJsonObject("data"); metaDataParams = new Gson().fromJson(object.toString(), Map.class); String certID = object.get("certificateId").getAsString(); int containerId = object.get("containerId").getAsInt(); float value = Float.valueOf(certID); int certificateId = (int) value; CertResponse renewResponse = new CertResponse(); try { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, String.format("Trying to renew certificate for [%s] renewed by [%s] on [%s]", certificateName,userDetails.getUsername(),LocalDateTime.now())) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); String nclmAccessToken = isMockingEnabled(certType) ? TVaultConstants.NCLM_MOCK_VALUE : getNclmToken(); if(!StringUtils.isEmpty(nclmAccessToken)) { CertificateData cerificatetData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId): nclmMockUtil.getRenewCertificateMockData(); if((!ObjectUtils.isEmpty(cerificatetData)&& cerificatetData.getCertificateId()!=0)) { if(cerificatetData.getCertificateStatus().equalsIgnoreCase("Revoked")) { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .body("{\"errors\":[\"" + "Certificate in Revoked status cannot be renewed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .build())); return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{\"errors\":[\"" + "Certificate " + "unavailable in System." + "\"]}"); } if(!isMockingEnabled(certType) ) { String nclmApiRenewEndpoint = renewCertificateEndpoint.replace("certID", String.valueOf(certificateId)); renewResponse = reqProcessor.processCert("/certificates/renew", "", nclmAccessToken, getCertmanagerEndPoint(nclmApiRenewEndpoint)); } else { renewResponse = nclmMockUtil.getRenewMockResponse(); } Thread.sleep(renewDelayTime); log.debug( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, "Renew certificate for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); if (renewResponse!=null && (HttpStatus.OK.equals(renewResponse.getHttpstatus()) || HttpStatus.ACCEPTED.equals(renewResponse.getHttpstatus())) ) { CertificateData certData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId):nclmMockUtil.getRenewCertificateMockData(); boolean sslMetaDataUpdationStatus=true; boolean isApprovalReq=false; if(!ObjectUtils.isEmpty(certData)) { int actionId=0; if(certType.equalsIgnoreCase("external")) { CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setAccess_token(nclmAccessToken); Map<String, Object> responseMap = ControllerUtil.parseJson(renewResponse.getResponse()); if (!MapUtils.isEmpty(responseMap) && responseMap.get("actionId") != null) { actionId = (Integer) responseMap.get("actionId"); if (actionId != 0) { renewResponse = approvalRequest(certManagerLogin, actionId); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, String.format("approvalRequest Completed Successfully [%s]" + " = certificate name = [%s]", renewResponse.getResponse(), certificateName)). build())); metaDataParams.put("requestStatus", SSLCertificateConstants.RENEW_PENDING); metaDataParams.put("actionId", String.valueOf(actionId)); isApprovalReq = true; } else { metaDataParams.put("certificateId", ((Integer) certData.getCertificateId()).toString() != null ? ((Integer) certData.getCertificateId()).toString() : String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate() != null ? certData.getCreateDate() : object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate() != null ? certData.getExpiryDate() : object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus() != null ? certData.getCertificateStatus() : object.get("certificateStatus").getAsString()); } } }else { metaDataParams.put("certificateId",((Integer)certData.getCertificateId()).toString()!=null? ((Integer)certData.getCertificateId()).toString():String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate()!=null?certData.getCreateDate():object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate()!=null?certData.getExpiryDate():object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus()!=null?certData.getCertificateStatus(): object.get("certificateStatus").getAsString()); } if (userDetails.isAdmin()) { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, token); } else { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, userDetails.getSelfSupportToken()); } } if (sslMetaDataUpdationStatus) { String certOwnerEmailId = metaDataParams.get("certOwnerEmailId"); String certOwnerNtId = metaDataParams.get("certOwnerNtid"); sendRenewEmail(certType, certificateName, certOwnerEmailId,certOwnerNtId, token,isApprovalReq); return ResponseEntity.status(renewResponse.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate renewed successfully" + "\"]}"); } else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Metadata updation failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Metadata updation Failed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Certificate Renewal Failed" + "\"]}"); } }else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "renew certificate"). put(LogMessage.MESSAGE, "NCLM services are down. Please try after some time."). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + nclmErrorMessage + "\"]}"); } } catch (TVaultValidationException error) { log.error( JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside TVaultValidationException = [%s] = Message [%s]", Arrays.toString(error.getStackTrace()), error.getMessage())) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"" + error.getMessage() + "\"]}"); } catch (Exception e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), e.getMessage())) .build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + e.getMessage() + "\"]}"); } }
SSLCertificateService { public ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token) { Map<String, String> metaDataParams = new HashMap<>(); Boolean isPermission = true; if (!isValidInputs(certificateName, certType)) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "renewCertificate") .put(LogMessage.MESSAGE, "Invalid user inputs") .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)).build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String endPoint = certificateName; String metaDataPath = (certType.equalsIgnoreCase("internal"))? SSLCertificateConstants.SSL_CERT_PATH + "/" + endPoint :SSLCertificateConstants.SSL_EXTERNAL_CERT_PATH + "/" + endPoint; Response response = new Response(); if (!userDetails.isAdmin()) { isPermission = validateCertOwnerPermissionForNonAdmin(userDetails, certificateName,certType); if (!isPermission) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body("{\"errors\":[\"" + "Access denied: No permission to renew certificate" + "\"]}"); } } try { if (userDetails.isAdmin()) { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", token); } else { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", userDetails.getSelfSupportToken()); } } catch (Exception e) { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), response.getResponse())) .build())); return ResponseEntity.status(response.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate unavailable" + "\"]}"); } if (!HttpStatus.OK.equals(response.getHttpstatus())) { return ResponseEntity.status(response.getHttpstatus()) .body("{\"errors\":[\"" + "Certificate unavailable" + "\"]}"); } JsonParser jsonParser = new JsonParser(); JsonObject object = ((JsonObject) jsonParser.parse(response.getResponse())).getAsJsonObject("data"); metaDataParams = new Gson().fromJson(object.toString(), Map.class); String certID = object.get("certificateId").getAsString(); int containerId = object.get("containerId").getAsInt(); float value = Float.valueOf(certID); int certificateId = (int) value; CertResponse renewResponse = new CertResponse(); try { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, String.format("Trying to renew certificate for [%s] renewed by [%s] on [%s]", certificateName,userDetails.getUsername(),LocalDateTime.now())) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); String nclmAccessToken = isMockingEnabled(certType) ? TVaultConstants.NCLM_MOCK_VALUE : getNclmToken(); if(!StringUtils.isEmpty(nclmAccessToken)) { CertificateData cerificatetData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId): nclmMockUtil.getRenewCertificateMockData(); if((!ObjectUtils.isEmpty(cerificatetData)&& cerificatetData.getCertificateId()!=0)) { if(cerificatetData.getCertificateStatus().equalsIgnoreCase("Revoked")) { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .body("{\"errors\":[\"" + "Certificate in Revoked status cannot be renewed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .build())); return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{\"errors\":[\"" + "Certificate " + "unavailable in System." + "\"]}"); } if(!isMockingEnabled(certType) ) { String nclmApiRenewEndpoint = renewCertificateEndpoint.replace("certID", String.valueOf(certificateId)); renewResponse = reqProcessor.processCert("/certificates/renew", "", nclmAccessToken, getCertmanagerEndPoint(nclmApiRenewEndpoint)); } else { renewResponse = nclmMockUtil.getRenewMockResponse(); } Thread.sleep(renewDelayTime); log.debug( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, "Renew certificate for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); if (renewResponse!=null && (HttpStatus.OK.equals(renewResponse.getHttpstatus()) || HttpStatus.ACCEPTED.equals(renewResponse.getHttpstatus())) ) { CertificateData certData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId):nclmMockUtil.getRenewCertificateMockData(); boolean sslMetaDataUpdationStatus=true; boolean isApprovalReq=false; if(!ObjectUtils.isEmpty(certData)) { int actionId=0; if(certType.equalsIgnoreCase("external")) { CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setAccess_token(nclmAccessToken); Map<String, Object> responseMap = ControllerUtil.parseJson(renewResponse.getResponse()); if (!MapUtils.isEmpty(responseMap) && responseMap.get("actionId") != null) { actionId = (Integer) responseMap.get("actionId"); if (actionId != 0) { renewResponse = approvalRequest(certManagerLogin, actionId); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, String.format("approvalRequest Completed Successfully [%s]" + " = certificate name = [%s]", renewResponse.getResponse(), certificateName)). build())); metaDataParams.put("requestStatus", SSLCertificateConstants.RENEW_PENDING); metaDataParams.put("actionId", String.valueOf(actionId)); isApprovalReq = true; } else { metaDataParams.put("certificateId", ((Integer) certData.getCertificateId()).toString() != null ? ((Integer) certData.getCertificateId()).toString() : String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate() != null ? certData.getCreateDate() : object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate() != null ? certData.getExpiryDate() : object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus() != null ? certData.getCertificateStatus() : object.get("certificateStatus").getAsString()); } } }else { metaDataParams.put("certificateId",((Integer)certData.getCertificateId()).toString()!=null? ((Integer)certData.getCertificateId()).toString():String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate()!=null?certData.getCreateDate():object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate()!=null?certData.getExpiryDate():object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus()!=null?certData.getCertificateStatus(): object.get("certificateStatus").getAsString()); } if (userDetails.isAdmin()) { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, token); } else { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, userDetails.getSelfSupportToken()); } } if (sslMetaDataUpdationStatus) { String certOwnerEmailId = metaDataParams.get("certOwnerEmailId"); String certOwnerNtId = metaDataParams.get("certOwnerNtid"); sendRenewEmail(certType, certificateName, certOwnerEmailId,certOwnerNtId, token,isApprovalReq); return ResponseEntity.status(renewResponse.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate renewed successfully" + "\"]}"); } else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Metadata updation failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Metadata updation Failed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Certificate Renewal Failed" + "\"]}"); } }else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "renew certificate"). put(LogMessage.MESSAGE, "NCLM services are down. Please try after some time."). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + nclmErrorMessage + "\"]}"); } } catch (TVaultValidationException error) { log.error( JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside TVaultValidationException = [%s] = Message [%s]", Arrays.toString(error.getStackTrace()), error.getMessage())) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"" + error.getMessage() + "\"]}"); } catch (Exception e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), e.getMessage())) .build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + e.getMessage() + "\"]}"); } } }
SSLCertificateService { public ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token) { Map<String, String> metaDataParams = new HashMap<>(); Boolean isPermission = true; if (!isValidInputs(certificateName, certType)) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "renewCertificate") .put(LogMessage.MESSAGE, "Invalid user inputs") .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)).build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String endPoint = certificateName; String metaDataPath = (certType.equalsIgnoreCase("internal"))? SSLCertificateConstants.SSL_CERT_PATH + "/" + endPoint :SSLCertificateConstants.SSL_EXTERNAL_CERT_PATH + "/" + endPoint; Response response = new Response(); if (!userDetails.isAdmin()) { isPermission = validateCertOwnerPermissionForNonAdmin(userDetails, certificateName,certType); if (!isPermission) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body("{\"errors\":[\"" + "Access denied: No permission to renew certificate" + "\"]}"); } } try { if (userDetails.isAdmin()) { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", token); } else { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", userDetails.getSelfSupportToken()); } } catch (Exception e) { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), response.getResponse())) .build())); return ResponseEntity.status(response.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate unavailable" + "\"]}"); } if (!HttpStatus.OK.equals(response.getHttpstatus())) { return ResponseEntity.status(response.getHttpstatus()) .body("{\"errors\":[\"" + "Certificate unavailable" + "\"]}"); } JsonParser jsonParser = new JsonParser(); JsonObject object = ((JsonObject) jsonParser.parse(response.getResponse())).getAsJsonObject("data"); metaDataParams = new Gson().fromJson(object.toString(), Map.class); String certID = object.get("certificateId").getAsString(); int containerId = object.get("containerId").getAsInt(); float value = Float.valueOf(certID); int certificateId = (int) value; CertResponse renewResponse = new CertResponse(); try { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, String.format("Trying to renew certificate for [%s] renewed by [%s] on [%s]", certificateName,userDetails.getUsername(),LocalDateTime.now())) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); String nclmAccessToken = isMockingEnabled(certType) ? TVaultConstants.NCLM_MOCK_VALUE : getNclmToken(); if(!StringUtils.isEmpty(nclmAccessToken)) { CertificateData cerificatetData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId): nclmMockUtil.getRenewCertificateMockData(); if((!ObjectUtils.isEmpty(cerificatetData)&& cerificatetData.getCertificateId()!=0)) { if(cerificatetData.getCertificateStatus().equalsIgnoreCase("Revoked")) { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .body("{\"errors\":[\"" + "Certificate in Revoked status cannot be renewed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .build())); return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{\"errors\":[\"" + "Certificate " + "unavailable in System." + "\"]}"); } if(!isMockingEnabled(certType) ) { String nclmApiRenewEndpoint = renewCertificateEndpoint.replace("certID", String.valueOf(certificateId)); renewResponse = reqProcessor.processCert("/certificates/renew", "", nclmAccessToken, getCertmanagerEndPoint(nclmApiRenewEndpoint)); } else { renewResponse = nclmMockUtil.getRenewMockResponse(); } Thread.sleep(renewDelayTime); log.debug( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, "Renew certificate for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); if (renewResponse!=null && (HttpStatus.OK.equals(renewResponse.getHttpstatus()) || HttpStatus.ACCEPTED.equals(renewResponse.getHttpstatus())) ) { CertificateData certData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId):nclmMockUtil.getRenewCertificateMockData(); boolean sslMetaDataUpdationStatus=true; boolean isApprovalReq=false; if(!ObjectUtils.isEmpty(certData)) { int actionId=0; if(certType.equalsIgnoreCase("external")) { CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setAccess_token(nclmAccessToken); Map<String, Object> responseMap = ControllerUtil.parseJson(renewResponse.getResponse()); if (!MapUtils.isEmpty(responseMap) && responseMap.get("actionId") != null) { actionId = (Integer) responseMap.get("actionId"); if (actionId != 0) { renewResponse = approvalRequest(certManagerLogin, actionId); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, String.format("approvalRequest Completed Successfully [%s]" + " = certificate name = [%s]", renewResponse.getResponse(), certificateName)). build())); metaDataParams.put("requestStatus", SSLCertificateConstants.RENEW_PENDING); metaDataParams.put("actionId", String.valueOf(actionId)); isApprovalReq = true; } else { metaDataParams.put("certificateId", ((Integer) certData.getCertificateId()).toString() != null ? ((Integer) certData.getCertificateId()).toString() : String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate() != null ? certData.getCreateDate() : object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate() != null ? certData.getExpiryDate() : object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus() != null ? certData.getCertificateStatus() : object.get("certificateStatus").getAsString()); } } }else { metaDataParams.put("certificateId",((Integer)certData.getCertificateId()).toString()!=null? ((Integer)certData.getCertificateId()).toString():String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate()!=null?certData.getCreateDate():object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate()!=null?certData.getExpiryDate():object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus()!=null?certData.getCertificateStatus(): object.get("certificateStatus").getAsString()); } if (userDetails.isAdmin()) { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, token); } else { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, userDetails.getSelfSupportToken()); } } if (sslMetaDataUpdationStatus) { String certOwnerEmailId = metaDataParams.get("certOwnerEmailId"); String certOwnerNtId = metaDataParams.get("certOwnerNtid"); sendRenewEmail(certType, certificateName, certOwnerEmailId,certOwnerNtId, token,isApprovalReq); return ResponseEntity.status(renewResponse.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate renewed successfully" + "\"]}"); } else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Metadata updation failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Metadata updation Failed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Certificate Renewal Failed" + "\"]}"); } }else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "renew certificate"). put(LogMessage.MESSAGE, "NCLM services are down. Please try after some time."). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + nclmErrorMessage + "\"]}"); } } catch (TVaultValidationException error) { log.error( JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside TVaultValidationException = [%s] = Message [%s]", Arrays.toString(error.getStackTrace()), error.getMessage())) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"" + error.getMessage() + "\"]}"); } catch (Exception e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), e.getMessage())) .build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + e.getMessage() + "\"]}"); } }  }
SSLCertificateService { public ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token) { Map<String, String> metaDataParams = new HashMap<>(); Boolean isPermission = true; if (!isValidInputs(certificateName, certType)) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "renewCertificate") .put(LogMessage.MESSAGE, "Invalid user inputs") .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)).build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String endPoint = certificateName; String metaDataPath = (certType.equalsIgnoreCase("internal"))? SSLCertificateConstants.SSL_CERT_PATH + "/" + endPoint :SSLCertificateConstants.SSL_EXTERNAL_CERT_PATH + "/" + endPoint; Response response = new Response(); if (!userDetails.isAdmin()) { isPermission = validateCertOwnerPermissionForNonAdmin(userDetails, certificateName,certType); if (!isPermission) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body("{\"errors\":[\"" + "Access denied: No permission to renew certificate" + "\"]}"); } } try { if (userDetails.isAdmin()) { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", token); } else { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", userDetails.getSelfSupportToken()); } } catch (Exception e) { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), response.getResponse())) .build())); return ResponseEntity.status(response.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate unavailable" + "\"]}"); } if (!HttpStatus.OK.equals(response.getHttpstatus())) { return ResponseEntity.status(response.getHttpstatus()) .body("{\"errors\":[\"" + "Certificate unavailable" + "\"]}"); } JsonParser jsonParser = new JsonParser(); JsonObject object = ((JsonObject) jsonParser.parse(response.getResponse())).getAsJsonObject("data"); metaDataParams = new Gson().fromJson(object.toString(), Map.class); String certID = object.get("certificateId").getAsString(); int containerId = object.get("containerId").getAsInt(); float value = Float.valueOf(certID); int certificateId = (int) value; CertResponse renewResponse = new CertResponse(); try { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, String.format("Trying to renew certificate for [%s] renewed by [%s] on [%s]", certificateName,userDetails.getUsername(),LocalDateTime.now())) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); String nclmAccessToken = isMockingEnabled(certType) ? TVaultConstants.NCLM_MOCK_VALUE : getNclmToken(); if(!StringUtils.isEmpty(nclmAccessToken)) { CertificateData cerificatetData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId): nclmMockUtil.getRenewCertificateMockData(); if((!ObjectUtils.isEmpty(cerificatetData)&& cerificatetData.getCertificateId()!=0)) { if(cerificatetData.getCertificateStatus().equalsIgnoreCase("Revoked")) { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .body("{\"errors\":[\"" + "Certificate in Revoked status cannot be renewed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .build())); return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{\"errors\":[\"" + "Certificate " + "unavailable in System." + "\"]}"); } if(!isMockingEnabled(certType) ) { String nclmApiRenewEndpoint = renewCertificateEndpoint.replace("certID", String.valueOf(certificateId)); renewResponse = reqProcessor.processCert("/certificates/renew", "", nclmAccessToken, getCertmanagerEndPoint(nclmApiRenewEndpoint)); } else { renewResponse = nclmMockUtil.getRenewMockResponse(); } Thread.sleep(renewDelayTime); log.debug( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, "Renew certificate for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); if (renewResponse!=null && (HttpStatus.OK.equals(renewResponse.getHttpstatus()) || HttpStatus.ACCEPTED.equals(renewResponse.getHttpstatus())) ) { CertificateData certData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId):nclmMockUtil.getRenewCertificateMockData(); boolean sslMetaDataUpdationStatus=true; boolean isApprovalReq=false; if(!ObjectUtils.isEmpty(certData)) { int actionId=0; if(certType.equalsIgnoreCase("external")) { CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setAccess_token(nclmAccessToken); Map<String, Object> responseMap = ControllerUtil.parseJson(renewResponse.getResponse()); if (!MapUtils.isEmpty(responseMap) && responseMap.get("actionId") != null) { actionId = (Integer) responseMap.get("actionId"); if (actionId != 0) { renewResponse = approvalRequest(certManagerLogin, actionId); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, String.format("approvalRequest Completed Successfully [%s]" + " = certificate name = [%s]", renewResponse.getResponse(), certificateName)). build())); metaDataParams.put("requestStatus", SSLCertificateConstants.RENEW_PENDING); metaDataParams.put("actionId", String.valueOf(actionId)); isApprovalReq = true; } else { metaDataParams.put("certificateId", ((Integer) certData.getCertificateId()).toString() != null ? ((Integer) certData.getCertificateId()).toString() : String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate() != null ? certData.getCreateDate() : object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate() != null ? certData.getExpiryDate() : object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus() != null ? certData.getCertificateStatus() : object.get("certificateStatus").getAsString()); } } }else { metaDataParams.put("certificateId",((Integer)certData.getCertificateId()).toString()!=null? ((Integer)certData.getCertificateId()).toString():String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate()!=null?certData.getCreateDate():object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate()!=null?certData.getExpiryDate():object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus()!=null?certData.getCertificateStatus(): object.get("certificateStatus").getAsString()); } if (userDetails.isAdmin()) { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, token); } else { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, userDetails.getSelfSupportToken()); } } if (sslMetaDataUpdationStatus) { String certOwnerEmailId = metaDataParams.get("certOwnerEmailId"); String certOwnerNtId = metaDataParams.get("certOwnerNtid"); sendRenewEmail(certType, certificateName, certOwnerEmailId,certOwnerNtId, token,isApprovalReq); return ResponseEntity.status(renewResponse.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate renewed successfully" + "\"]}"); } else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Metadata updation failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Metadata updation Failed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Certificate Renewal Failed" + "\"]}"); } }else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "renew certificate"). put(LogMessage.MESSAGE, "NCLM services are down. Please try after some time."). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + nclmErrorMessage + "\"]}"); } } catch (TVaultValidationException error) { log.error( JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside TVaultValidationException = [%s] = Message [%s]", Arrays.toString(error.getStackTrace()), error.getMessage())) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"" + error.getMessage() + "\"]}"); } catch (Exception e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), e.getMessage())) .build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + e.getMessage() + "\"]}"); } }  ResponseEntity<String> authenticate(CertManagerLoginRequest certManagerLoginRequest); CertManagerLogin login(CertManagerLoginRequest certManagerLoginRequest); ResponseEntity<String> generateSSLCertificate(SSLCertificateRequest sslCertificateRequest,
                                                               UserDetails userDetails ,String token); ResponseEntity<String> getServiceCertificates(String token, UserDetails userDetails, String certName, Integer limit, Integer offset, String certType); String getNclmToken(); ResponseEntity<String> getTargetSystemList(String token, UserDetails userDetails,String certType); ResponseEntity<String> getTargetSystemServiceList(String token, UserDetails userDetails, String targetSystemId); ResponseEntity<String> getRevocationReasons(Integer certificateId, String token); ResponseEntity<String> issueRevocationRequest(String certType, String certificateName, UserDetails userDetails, String token,
			RevocationRequest revocationRequest); String getCurrentLocalDateTimeStamp(); Boolean validateOwnerPermissionForNonAdmin(UserDetails userDetails, String certificateName); ResponseEntity<String> addUserToCertificate(CertificateUser certificateUser, UserDetails userDetails, boolean addSudoPermission); ResponseEntity<String> addGroupToCertificate(UserDetails userDetails, String userToken, CertificateGroup certificateGroup); boolean isAuthorized(UserDetails userDetails, String certificatename, String certType); ResponseEntity<String> addingGroupToCertificate(String token, CertificateGroup certificateGroup, UserDetails userDetails); ResponseEntity<String> associateApproletoCertificate(CertificateApprole certificateApprole, UserDetails userDetails); boolean hasDownloadPermission(String certificateName, UserDetails userDetails, String certType); SSLCertificateMetadataDetails getCertificateMetadata(String token, String certificateName); ResponseEntity<InputStreamResource> downloadCertificateWithPrivateKey(String token, CertificateDownloadRequest certificateDownloadRequest, UserDetails userDetails); ResponseEntity<InputStreamResource> downloadCertificateWithPrivateKey(CertificateDownloadRequest certificateDownloadRequest, SSLCertificateMetadataDetails sslCertificateMetadataDetails); ResponseEntity<InputStreamResource> downloadCertificate(String token, UserDetails userDetails,
                                                                   String certificateName, String certificateType,
                                                                   String sslCertType); ResponseEntity<String> getCertificateDetails(String token, String certificateName, String certificateType); ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token); ResponseEntity<String> removeUserFromCertificate(CertificateUser certificateUser, UserDetails userDetails); ResponseEntity<String> removeGroupFromCertificate(CertificateGroup certificateGroup, UserDetails userDetails); ResponseEntity<String> getListOfCertificates(String token, String certificateType); ResponseEntity<String> updateCertOwner(String token, String certType,String certName,String certOwnerEmailId,  UserDetails userDetails); ResponseEntity<String> validateApprovalStatusAndGetCertificateDetails(String certName, String certType,
			UserDetails userDetails); ResponseEntity<String> deleteCertificate( String token, String certType, String certificateName, UserDetails userDetails); Boolean validateCertOwnerPermissionForNonAdmin(UserDetails userDetails, String certificateName, String certType); ResponseEntity<String> getAllCertificates(String token, String certName, Integer limit, Integer offset); ResponseEntity<String> getAllCertificatesOnCertType(UserDetails userDetails, String certificateType); ResponseEntity<String> checkCertificateStatus(String certName, String certType,	
			UserDetails userDetails); ResponseEntity<String> getAllSelfServiceGroups(UserDetails userDetails); ResponseEntity<String> removeGroupFromCertificateForDelete(CertificateGroup certificateGroup, UserDetails userDetails); }
SSLCertificateService { public ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token) { Map<String, String> metaDataParams = new HashMap<>(); Boolean isPermission = true; if (!isValidInputs(certificateName, certType)) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "renewCertificate") .put(LogMessage.MESSAGE, "Invalid user inputs") .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)).build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String endPoint = certificateName; String metaDataPath = (certType.equalsIgnoreCase("internal"))? SSLCertificateConstants.SSL_CERT_PATH + "/" + endPoint :SSLCertificateConstants.SSL_EXTERNAL_CERT_PATH + "/" + endPoint; Response response = new Response(); if (!userDetails.isAdmin()) { isPermission = validateCertOwnerPermissionForNonAdmin(userDetails, certificateName,certType); if (!isPermission) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body("{\"errors\":[\"" + "Access denied: No permission to renew certificate" + "\"]}"); } } try { if (userDetails.isAdmin()) { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", token); } else { response = reqProcessor.process("/read", "{\"path\":\"" + metaDataPath + "\"}", userDetails.getSelfSupportToken()); } } catch (Exception e) { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), response.getResponse())) .build())); return ResponseEntity.status(response.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate unavailable" + "\"]}"); } if (!HttpStatus.OK.equals(response.getHttpstatus())) { return ResponseEntity.status(response.getHttpstatus()) .body("{\"errors\":[\"" + "Certificate unavailable" + "\"]}"); } JsonParser jsonParser = new JsonParser(); JsonObject object = ((JsonObject) jsonParser.parse(response.getResponse())).getAsJsonObject("data"); metaDataParams = new Gson().fromJson(object.toString(), Map.class); String certID = object.get("certificateId").getAsString(); int containerId = object.get("containerId").getAsInt(); float value = Float.valueOf(certID); int certificateId = (int) value; CertResponse renewResponse = new CertResponse(); try { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, String.format("Trying to renew certificate for [%s] renewed by [%s] on [%s]", certificateName,userDetails.getUsername(),LocalDateTime.now())) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); String nclmAccessToken = isMockingEnabled(certType) ? TVaultConstants.NCLM_MOCK_VALUE : getNclmToken(); if(!StringUtils.isEmpty(nclmAccessToken)) { CertificateData cerificatetData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId): nclmMockUtil.getRenewCertificateMockData(); if((!ObjectUtils.isEmpty(cerificatetData)&& cerificatetData.getCertificateId()!=0)) { if(cerificatetData.getCertificateStatus().equalsIgnoreCase("Revoked")) { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .body("{\"errors\":[\"" + "Certificate in Revoked status cannot be renewed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .build())); return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{\"errors\":[\"" + "Certificate " + "unavailable in System." + "\"]}"); } if(!isMockingEnabled(certType) ) { String nclmApiRenewEndpoint = renewCertificateEndpoint.replace("certID", String.valueOf(certificateId)); renewResponse = reqProcessor.processCert("/certificates/renew", "", nclmAccessToken, getCertmanagerEndPoint(nclmApiRenewEndpoint)); } else { renewResponse = nclmMockUtil.getRenewMockResponse(); } Thread.sleep(renewDelayTime); log.debug( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate") .put(LogMessage.MESSAGE, "Renew certificate for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); if (renewResponse!=null && (HttpStatus.OK.equals(renewResponse.getHttpstatus()) || HttpStatus.ACCEPTED.equals(renewResponse.getHttpstatus())) ) { CertificateData certData = (!isMockingEnabled(certType)) ? getLatestCertificate(certificateName,nclmAccessToken, containerId):nclmMockUtil.getRenewCertificateMockData(); boolean sslMetaDataUpdationStatus=true; boolean isApprovalReq=false; if(!ObjectUtils.isEmpty(certData)) { int actionId=0; if(certType.equalsIgnoreCase("external")) { CertManagerLogin certManagerLogin = new CertManagerLogin(); certManagerLogin.setAccess_token(nclmAccessToken); Map<String, Object> responseMap = ControllerUtil.parseJson(renewResponse.getResponse()); if (!MapUtils.isEmpty(responseMap) && responseMap.get("actionId") != null) { actionId = (Integer) responseMap.get("actionId"); if (actionId != 0) { renewResponse = approvalRequest(certManagerLogin, actionId); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, String.format("approvalRequest Completed Successfully [%s]" + " = certificate name = [%s]", renewResponse.getResponse(), certificateName)). build())); metaDataParams.put("requestStatus", SSLCertificateConstants.RENEW_PENDING); metaDataParams.put("actionId", String.valueOf(actionId)); isApprovalReq = true; } else { metaDataParams.put("certificateId", ((Integer) certData.getCertificateId()).toString() != null ? ((Integer) certData.getCertificateId()).toString() : String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate() != null ? certData.getCreateDate() : object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate() != null ? certData.getExpiryDate() : object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus() != null ? certData.getCertificateStatus() : object.get("certificateStatus").getAsString()); } } }else { metaDataParams.put("certificateId",((Integer)certData.getCertificateId()).toString()!=null? ((Integer)certData.getCertificateId()).toString():String.valueOf(certificateId)); metaDataParams.put("createDate", certData.getCreateDate()!=null?certData.getCreateDate():object.get("createDate").getAsString()); metaDataParams.put("expiryDate", certData.getExpiryDate()!=null?certData.getExpiryDate():object.get("expiryDate").getAsString()); metaDataParams.put("certificateStatus", certData.getCertificateStatus()!=null?certData.getCertificateStatus(): object.get("certificateStatus").getAsString()); } if (userDetails.isAdmin()) { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, token); } else { sslMetaDataUpdationStatus = ControllerUtil.updateMetaData(metaDataPath, metaDataParams, userDetails.getSelfSupportToken()); } } if (sslMetaDataUpdationStatus) { String certOwnerEmailId = metaDataParams.get("certOwnerEmailId"); String certOwnerNtId = metaDataParams.get("certOwnerNtid"); sendRenewEmail(certType, certificateName, certOwnerEmailId,certOwnerNtId, token,isApprovalReq); return ResponseEntity.status(renewResponse.getHttpstatus()) .body("{\"messages\":[\"" + "Certificate renewed successfully" + "\"]}"); } else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Metadata updation failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Metadata updation Failed." + "\"]}"); } }else { log.error( JSONUtil.getJSON( ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, "Renew certificate Failed") .put(LogMessage.MESSAGE, "Renew Request failed for CertificateID") .put(LogMessage.STATUS, renewResponse.getHttpstatus().toString()) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("{\"errors\":[\"" + "Certificate Renewal Failed" + "\"]}"); } }else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "renew certificate"). put(LogMessage.MESSAGE, "NCLM services are down. Please try after some time."). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + nclmErrorMessage + "\"]}"); } } catch (TVaultValidationException error) { log.error( JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside TVaultValidationException = [%s] = Message [%s]", Arrays.toString(error.getStackTrace()), error.getMessage())) .build())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"" + error.getMessage() + "\"]}"); } catch (Exception e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()) .put(LogMessage.ACTION, String.format("Inside Exception = [%s] = Message [%s]", Arrays.toString(e.getStackTrace()), e.getMessage())) .build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("{\"errors\":[\"" + e.getMessage() + "\"]}"); } }  ResponseEntity<String> authenticate(CertManagerLoginRequest certManagerLoginRequest); CertManagerLogin login(CertManagerLoginRequest certManagerLoginRequest); ResponseEntity<String> generateSSLCertificate(SSLCertificateRequest sslCertificateRequest,
                                                               UserDetails userDetails ,String token); ResponseEntity<String> getServiceCertificates(String token, UserDetails userDetails, String certName, Integer limit, Integer offset, String certType); String getNclmToken(); ResponseEntity<String> getTargetSystemList(String token, UserDetails userDetails,String certType); ResponseEntity<String> getTargetSystemServiceList(String token, UserDetails userDetails, String targetSystemId); ResponseEntity<String> getRevocationReasons(Integer certificateId, String token); ResponseEntity<String> issueRevocationRequest(String certType, String certificateName, UserDetails userDetails, String token,
			RevocationRequest revocationRequest); String getCurrentLocalDateTimeStamp(); Boolean validateOwnerPermissionForNonAdmin(UserDetails userDetails, String certificateName); ResponseEntity<String> addUserToCertificate(CertificateUser certificateUser, UserDetails userDetails, boolean addSudoPermission); ResponseEntity<String> addGroupToCertificate(UserDetails userDetails, String userToken, CertificateGroup certificateGroup); boolean isAuthorized(UserDetails userDetails, String certificatename, String certType); ResponseEntity<String> addingGroupToCertificate(String token, CertificateGroup certificateGroup, UserDetails userDetails); ResponseEntity<String> associateApproletoCertificate(CertificateApprole certificateApprole, UserDetails userDetails); boolean hasDownloadPermission(String certificateName, UserDetails userDetails, String certType); SSLCertificateMetadataDetails getCertificateMetadata(String token, String certificateName); ResponseEntity<InputStreamResource> downloadCertificateWithPrivateKey(String token, CertificateDownloadRequest certificateDownloadRequest, UserDetails userDetails); ResponseEntity<InputStreamResource> downloadCertificateWithPrivateKey(CertificateDownloadRequest certificateDownloadRequest, SSLCertificateMetadataDetails sslCertificateMetadataDetails); ResponseEntity<InputStreamResource> downloadCertificate(String token, UserDetails userDetails,
                                                                   String certificateName, String certificateType,
                                                                   String sslCertType); ResponseEntity<String> getCertificateDetails(String token, String certificateName, String certificateType); ResponseEntity<String> renewCertificate(String certType, String certificateName, UserDetails userDetails, String token); ResponseEntity<String> removeUserFromCertificate(CertificateUser certificateUser, UserDetails userDetails); ResponseEntity<String> removeGroupFromCertificate(CertificateGroup certificateGroup, UserDetails userDetails); ResponseEntity<String> getListOfCertificates(String token, String certificateType); ResponseEntity<String> updateCertOwner(String token, String certType,String certName,String certOwnerEmailId,  UserDetails userDetails); ResponseEntity<String> validateApprovalStatusAndGetCertificateDetails(String certName, String certType,
			UserDetails userDetails); ResponseEntity<String> deleteCertificate( String token, String certType, String certificateName, UserDetails userDetails); Boolean validateCertOwnerPermissionForNonAdmin(UserDetails userDetails, String certificateName, String certType); ResponseEntity<String> getAllCertificates(String token, String certName, Integer limit, Integer offset); ResponseEntity<String> getAllCertificatesOnCertType(UserDetails userDetails, String certificateType); ResponseEntity<String> checkCertificateStatus(String certName, String certType,	
			UserDetails userDetails); ResponseEntity<String> getAllSelfServiceGroups(UserDetails userDetails); ResponseEntity<String> removeGroupFromCertificateForDelete(CertificateGroup certificateGroup, UserDetails userDetails); @Value("${sslcertmanager.targetsystemgroup.public_single_san.ts_gp_id}")
    private int public_single_san_ts_gp_id; @Value("${sslcertmanager.targetsystemgroup.public_multi_san.ts_gp_id}")
    private int public_multi_san_ts_gp_id; }