diff --git a/jans-linux-setup/jans_setup/templates/jans-lock/dynamic-conf.json b/jans-linux-setup/jans_setup/templates/jans-lock/dynamic-conf.json index 81f47b5119c..7ffead6c2d1 100644 --- a/jans-linux-setup/jans_setup/templates/jans-lock/dynamic-conf.json +++ b/jans-linux-setup/jans_setup/templates/jans-lock/dynamic-conf.json @@ -7,7 +7,6 @@ "clientId": "%(lock_client_id)s", "clientPassword": "%(lock_client_encoded_pw)s", "tokenUrl": "%(jans_auth_token_endpoint)s", - "groupScopeEnabled": true, "endpointGroups": { "audit": [ "telemetry", @@ -52,14 +51,11 @@ "metricReporterKeepDataDays": 15, "metricReporterEnabled": true, "statEnabled": true, - "errorReasonEnabled": false, - "opaConfiguration": { - "baseUrl": "http://%(jans_opa_host)s:%(jans_opa_port)s/v1/", - "accessToken": "" - }, "policiesJsonUris": [], "policiesJsonUrisAuthorizationToken": "", "policiesZipUris": [], "policiesZipUrisAuthorizationToken": "", - "pdpType": "OPA" + "messageConsumerType" : "DISABLED", + "policyConsumerType" : "DISABLED", + "errorReasonEnabled": false } diff --git a/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/AppConfiguration.java b/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/AppConfiguration.java index 042ee8849b1..73aa99495ef 100644 --- a/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/AppConfiguration.java +++ b/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/AppConfiguration.java @@ -16,7 +16,6 @@ package io.jans.lock.model.config; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -70,10 +69,6 @@ public class AppConfiguration implements Configuration { @DocProperty(description = "Jans URL of the OpenID Connect Provider's OAuth 2.0 Token Endpoint") @Schema(description = "Jans URL of the OpenID Connect Provider's OAuth 2.0 Token Endpoint") private String tokenUrl; - - @DocProperty(description = "Group scope enabled") - @Schema(description = "Group scope enabled") - private boolean groupScopeEnabled; @DocProperty(description = "Endpoint groups") @Schema(description = "Endpoint groups") @@ -99,10 +94,6 @@ public class AppConfiguration implements Configuration { @Schema(description = "The path to the external log4j2 logging configuration") private String externalLoggerConfiguration; - @DocProperty(description = "Channel for metric reports", defaultValue = "jans_pdp_metric") - @Schema(description = "Channel for metric reports") - private String metricChannel; - @DocProperty(description = "The interval for metric reporter in seconds") @Schema(description = "The interval for metric reporter in seconds") private int metricReporterInterval; @@ -120,13 +111,6 @@ public class AppConfiguration implements Configuration { @Schema(description = "Time interval for the Clean Service in seconds") private int cleanServiceInterval; - @Schema(description = "Opa Configuration") - private OpaConfiguration opaConfiguration; - - @DocProperty(description = "PDP type") - @Schema(description = "PDP type") - private String pdpType; - @DocProperty(description = "Authorization token to access Json Uris") @Schema(description = "Authorization token to access Json Uris") private String policiesJsonUrisAuthorizationToken; @@ -143,6 +127,14 @@ public class AppConfiguration implements Configuration { @Schema(description = "List of Zip Uris with policies") private List policiesZipUris; + @DocProperty(description = "PubSub consumer service") + @Schema(description = "PubSub consumer service") + private String messageConsumerType; + + @DocProperty(description = "Policy consumer service") + @Schema(description = "Policy consumer service") + private String policyConsumerType; + @DocProperty(description = "Boolean value specifying whether to return detailed reason of the error from AS. Default value is false", defaultValue = "false") private Boolean errorReasonEnabled = false; @@ -217,14 +209,6 @@ public String getTokenUrl() { public void setTokenUrl(String tokenUrl) { this.tokenUrl = tokenUrl; } - - public boolean isGroupScopeEnabled() { - return groupScopeEnabled; - } - - public void setGroupScopeEnabled(boolean groupScopeEnabled) { - this.groupScopeEnabled = groupScopeEnabled; - } public Map> getEndpointGroups() { return endpointGroups; @@ -274,14 +258,6 @@ public void setExternalLoggerConfiguration(String externalLoggerConfiguration) { this.externalLoggerConfiguration = externalLoggerConfiguration; } - public String getMetricChannel() { - return metricChannel; - } - - public void setMetricChannel(String metricChannel) { - this.metricChannel = metricChannel; - } - public int getMetricReporterInterval() { return metricReporterInterval; } @@ -314,22 +290,6 @@ public void setCleanServiceInterval(int cleanServiceInterval) { this.cleanServiceInterval = cleanServiceInterval; } - public OpaConfiguration getOpaConfiguration() { - return opaConfiguration; - } - - public void setOpaConfiguration(OpaConfiguration opaConfiguration) { - this.opaConfiguration = opaConfiguration; - } - - public String getPdpType() { - return pdpType; - } - - public void setPdpType(String pdpType) { - this.pdpType = pdpType; - } - public String getPoliciesJsonUrisAuthorizationToken() { return policiesJsonUrisAuthorizationToken; } @@ -362,7 +322,25 @@ public void setPoliciesZipUris(List policiesZipUris) { this.policiesZipUris = policiesZipUris; } - public Boolean getErrorReasonEnabled() { + public String getMessageConsumerType() { + if (messageConsumerType == null) messageConsumerType = "DISABLED"; + return messageConsumerType; + } + + public void setMessageConsumerType(String messageConsumerType) { + this.messageConsumerType = messageConsumerType; + } + + public String getPolicyConsumerType() { + if (policyConsumerType == null) policyConsumerType = "DISABLED"; + return policyConsumerType; + } + + public void setPolicyConsumerType(String policyConsumerType) { + this.policyConsumerType = policyConsumerType; + } + + public Boolean getErrorReasonEnabled() { if (errorReasonEnabled == null) errorReasonEnabled = false; return errorReasonEnabled; } @@ -376,17 +354,16 @@ public String toString() { return "AppConfiguration [baseDN=" + baseDN + ", baseEndpoint=" + baseEndpoint + ", openIdIssuer=" + openIdIssuer + ", statEnabled=" + statEnabled + ", statTimerIntervalInSeconds=" + statTimerIntervalInSeconds + ", tokenChannels=" + tokenChannels + ", clientId=" + clientId - + ", clientPassword=" + clientPassword + ", tokenUrl=" + tokenUrl + ", groupScopeEnabled=" - + groupScopeEnabled + ", endpointGroups=" + endpointGroups + ", endpointDetails=" + endpointDetails - + ", disableJdkLogger=" + disableJdkLogger + ", loggingLevel=" + loggingLevel + ", loggingLayout=" - + loggingLayout + ", externalLoggerConfiguration=" + externalLoggerConfiguration + ", metricChannel=" - + metricChannel + ", metricReporterInterval=" + metricReporterInterval + ", metricReporterKeepDataDays=" - + metricReporterKeepDataDays + ", metricReporterEnabled=" + metricReporterEnabled - + ", cleanServiceInterval=" + cleanServiceInterval + ", opaConfiguration=" + opaConfiguration - + ", pdpType=" + pdpType + ", policiesJsonUrisAuthorizationToken=" + policiesJsonUrisAuthorizationToken - + ", policiesJsonUris=" + policiesJsonUris + ", policiesZipUrisAuthorizationToken=" - + policiesZipUrisAuthorizationToken + ", policiesZipUris=" + policiesZipUris + ", errorReasonEnabled=" - + errorReasonEnabled + "]"; + + ", clientPassword=" + clientPassword + ", tokenUrl=" + tokenUrl + ", endpointGroups=" + endpointGroups + + ", endpointDetails=" + endpointDetails + ", disableJdkLogger=" + disableJdkLogger + ", loggingLevel=" + + loggingLevel + ", loggingLayout=" + loggingLayout + ", externalLoggerConfiguration=" + + externalLoggerConfiguration + ", metricReporterInterval=" + metricReporterInterval + + ", metricReporterKeepDataDays=" + metricReporterKeepDataDays + ", metricReporterEnabled=" + + metricReporterEnabled + ", cleanServiceInterval=" + cleanServiceInterval + + ", policiesJsonUrisAuthorizationToken=" + policiesJsonUrisAuthorizationToken + ", policiesJsonUris=" + + policiesJsonUris + ", policiesZipUrisAuthorizationToken=" + policiesZipUrisAuthorizationToken + + ", policiesZipUris=" + policiesZipUris + ", messageConsumerType=" + messageConsumerType + + ", policyConsumerType=" + policyConsumerType + ", errorReasonEnabled=" + errorReasonEnabled + "]"; } } diff --git a/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/OpaConfiguration.java b/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/OpaConfiguration.java deleted file mode 100644 index a2ec77dc44d..00000000000 --- a/jans-lock/lock-server/model/src/main/java/io/jans/lock/model/config/OpaConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.model.config; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.jans.doc.annotation.DocProperty; -import jakarta.enterprise.inject.Vetoed; - -import io.swagger.v3.oas.annotations.media.Schema; - -/** - * - * @author Yuriy Movchan Date: 12/12/2023 - */ -@Vetoed -@JsonIgnoreProperties(ignoreUnknown = true) -public class OpaConfiguration implements Configuration { - - @Schema(description = "Base OPA URL") - @DocProperty(description = "Base OPA URL") - private String baseUrl; - - @Schema(description = "OPA access token") - @DocProperty(description = "OPA access token") - private String accessToken; - - public String getBaseUrl() { - return baseUrl; - } - - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/TokenEndpointService.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/TokenEndpointService.java index 0505a5e5add..28048212503 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/TokenEndpointService.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/TokenEndpointService.java @@ -1,6 +1,5 @@ package io.jans.lock.service; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -9,7 +8,6 @@ import java.util.Set; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateUtils; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; @@ -263,15 +261,12 @@ private String getEndpointUrl(String endpoint) { } private String getScopeForToken(String endpoint, boolean allGroupScopes) { - log.info("Request for token for endpoint:{}, allGroupScopes:{}, appConfiguration.isGroupScopeEnabled():{}", - endpoint, allGroupScopes, appConfiguration.isGroupScopeEnabled()); + log.info("Request for token for endpoint:{}, allGroupScopes:{}", endpoint, allGroupScopes); StringBuilder sb = new StringBuilder(); sb.append(ScopeType.OPENID.getValue()); List scopeList = null; - boolean groupScopeEnabled = this.appConfiguration.isGroupScopeEnabled(); - - if (allGroupScopes && groupScopeEnabled) { + if (allGroupScopes) { scopeList = this.getAllGroupScope(endpoint); } else { scopeList = this.getScopes(endpoint); @@ -389,19 +384,4 @@ private Response post(String url, String authType, String token, Map tokenDetails = new HashMap<>(); + private ExpiringMap issuedTokens; + + @PostConstruct + public void init() { + this.issuedTokens = ExpiringMap.builder().expirationPolicy(ExpirationPolicy.CREATED).variableExpiration().build(); + } public Response post(String endpoint, String postData, ContentType contentType) { log.info("postData - endpoint:{}, postData:{}, contentType:{}", endpoint, postData, contentType); + + Token token = issuedTokens.get(endpoint); - Date tokenExpiryDate = this.getTokenExpiryDate(); - log.debug("postData - tokenExpiryDate:{}", tokenExpiryDate); - boolean isTokenValid = this.tokenEndpointService.isTokenValid(tokenExpiryDate); - log.debug(" postData - tokenDetails:{}, tokenExpiryDate:{}, isTokenValid:{}", tokenDetails, tokenExpiryDate, - isTokenValid); - String accessToken = null; - if (tokenDetails != null && !tokenDetails.isEmpty() && isTokenValid) { - log.info("Reusing token as still valid!"); - accessToken = this.getToken(); - } else { - log.info("Generating new token !"); + String accessToken; + if (token == null) { + log.info("Generating new token for endpoint '{}'", endpoint); accessToken = this.getAccessTokenForAudit(endpoint); - } - return this.tokenEndpointService.post(endpoint, postData, contentType, accessToken); - } - - public JsonNode getJsonNode(HttpServletRequest request) { - JsonNode jsonBody = null; - if (request == null) { - return jsonBody; - } - - try { - jsonBody = dataMapperService.readTree(request.getInputStream()); - log.debug(" jsonBody:{}", jsonBody); - } catch (Exception ex) { - ex.printStackTrace(); - log.error("Exception while retriving json from request is - ", ex); + } else { + accessToken = token.getAccessToken(); + log.debug("Reusing token for endpoint '{}' : {}", endpoint, accessToken); } - return jsonBody; + return this.tokenEndpointService.post(endpoint, postData, contentType, accessToken); } private String getAccessTokenForAudit(String endpoint) { @@ -85,41 +63,13 @@ private String getAccessTokenForAudit(String endpoint) { log.debug("Get Access Token For Audit endpoint:{}, token:{}", endpoint, token); if (token != null) { + issuedTokens.put(endpoint, token, ExpirationPolicy.CREATED, token.getExpiresIn(), TimeUnit.SECONDS); + accessToken = token.getAccessToken(); - Integer expiresIn = token.getExpiresIn(); log.debug("Get Access Token For Audit endpoint:{}, accessToken:{}, expiresIn", endpoint, accessToken); - - tokenDetails.put(accessToken, this.tokenEndpointService.computeTokenExpiryTime(expiresIn)); - } - return accessToken; - } - - private Date getTokenExpiryDate() { - Date tokenExpiryDate = null; - if (tokenDetails != null && !tokenDetails.isEmpty() && tokenDetails.values() != null - && !tokenDetails.values().isEmpty()) { - Optional expiryDate = tokenDetails.values().stream().findFirst(); - - if (expiryDate.isPresent()) { - tokenExpiryDate = expiryDate.get(); - } - log.debug("tokenExpiryDate:{}", tokenExpiryDate); } - return tokenExpiryDate; - } - private String getToken() { - log.debug("tokenDetails:{}", tokenDetails); - String accessToken = null; - if (tokenDetails != null && !tokenDetails.isEmpty() && tokenDetails.keySet() != null - && !tokenDetails.keySet().isEmpty()) { - Optional token = tokenDetails.keySet().stream().findFirst(); - - if (token.isPresent() && StringUtils.isNotBlank(token.get())) { - accessToken = token.get(); - } - } - log.debug("accessToken:{}", accessToken); return accessToken; } + } diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/MessageConsumerFactory.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/MessageConsumerFactory.java index 58ba73a3605..9d98bfa15c6 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/MessageConsumerFactory.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/MessageConsumerFactory.java @@ -90,7 +90,7 @@ private void recreateMessageConsumer() { @Produces @ApplicationScoped public MessageConsumer produceMessageConsumer() { - String messageConsumerType = appConfiguration.getPdpType(); + String messageConsumerType = appConfiguration.getMessageConsumerType(); MessageConsumer messageConsumer = getMessageConsumer(messageConsumerType); return messageConsumer; diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/generic/NullMessageConsumer.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/generic/NullMessageConsumer.java index d66b2568531..f37d26fe22c 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/generic/NullMessageConsumer.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/generic/NullMessageConsumer.java @@ -40,6 +40,9 @@ public class NullMessageConsumer extends MessageConsumer { @Inject private Logger log; + /* + * Message: {"tknTyp" : "access_token", "tknId": "UUID"} + */ @Override @Asynchronous public void onMessage(String channel, String message) { diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/opa/OpaMessageConsumer.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/opa/OpaMessageConsumer.java deleted file mode 100644 index 71d1e84affa..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/message/opa/OpaMessageConsumer.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.consumer.message.opa; - -import static java.time.format.DateTimeFormatter.ISO_INSTANT; - -import java.io.IOException; -import java.time.Duration; -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.slf4j.Logger; - -import com.fasterxml.jackson.core.JacksonException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import io.jans.lock.model.config.AppConfiguration; -import io.jans.lock.model.config.OpaConfiguration; -import io.jans.lock.service.TokenService; -import io.jans.lock.service.external.ExternalLockService; -import io.jans.lock.service.external.context.ExternalLockContext; -import io.jans.model.token.TokenEntity; -import io.jans.service.EncryptionService; -import io.jans.service.cdi.async.Asynchronous; -import io.jans.service.cdi.qualifier.Implementation; -import io.jans.service.message.consumer.MessageConsumer; -import io.jans.service.net.BaseHttpService; -import io.jans.util.StringHelper; -import jakarta.annotation.PostConstruct; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; -import net.jodah.expiringmap.ExpirationListener; -import net.jodah.expiringmap.ExpirationPolicy; -import net.jodah.expiringmap.ExpiringMap; - -/** - * OPA message consumer - * - * @author Yuriy Movchan Date: 12/25/2023 - */ -@Implementation -@ApplicationScoped -public class OpaMessageConsumer extends MessageConsumer { - - public static String MESSAGE_CONSUMER_TYPE = "OPA"; - - @Inject - private Logger log; - - @Inject - private AppConfiguration appConfiguration; - - @Inject - private ExternalLockService externalLockService; - - @Inject - private BaseHttpService httpService; - - @Inject - private TokenService tokenService; - - @Inject - private EncryptionService encryptionService; - - private ObjectMapper objectMapper; - - private ExpiringMap loadedTokens; - private OpaExpirationListener expirationListener; - - @PostConstruct - public void init() { - this.objectMapper = new ObjectMapper(); - this.expirationListener = new OpaExpirationListener(); - this.loadedTokens = ExpiringMap.builder().expirationPolicy(ExpirationPolicy.CREATED).variableExpiration().expirationListener(expirationListener).build(); - } - - /* - * Message: {"tknTyp" : "access_token", "tknId": "UUID"} - */ - @Override - @Asynchronous - public void onMessage(String channel, String message) { - log.info("onMessage {} : {}", channel, message); - - try { - JsonNode messageNode = objectMapper.readTree(message); - - if (!(messageNode.hasNonNull("tknTyp") && messageNode.hasNonNull("tknId") && messageNode.hasNonNull("tknOp"))) { - log.error("Message has missing tknOp or tknTyp, or tknTyp: '{}'", message); - return; - } - - String tknOp = messageNode.get("tknOp").asText(); - if (StringHelper.equalsIgnoreCase(tknOp, "add")) { - putData(message, messageNode); - } else if (StringHelper.equalsIgnoreCase(tknOp, "del")) { - removeData(messageNode); - } else { - log.error("Message has unsupported operation: '{}'", message); - } - } catch (JacksonException ex) { - log.error("Failed to parse messge: '{}'", message, ex); - } - } - - @Override - public void onSubscribe(String channel, int subscribedChannels) { - log.debug("onSubscribe {} : {}", channel, subscribedChannels); - } - - @Override - public void onUnsubscribe(String channel, int subscribedChannels) { - log.debug("onUnsubscribe {} : {}", channel, subscribedChannels); - } - - @Override - public String getMessageConsumerType() { - return MESSAGE_CONSUMER_TYPE; - } - - @Override - public boolean putData(String message, JsonNode messageNode) { - ExternalLockContext lockContext = new ExternalLockContext(); - - String tknTyp = messageNode.get("tknTyp").asText(); - String tknId = messageNode.get("tknId").asText(); - - TokenEntity tokenEntity = tokenService.findToken(tknId); - log.debug("Token {} loaded successfully", tokenEntity); - lockContext.setTokenEntity(tokenEntity); - - ObjectNode dataNode = objectMapper.createObjectNode(); - buildBaseTokenObject(tokenEntity, dataNode); - - externalLockService.beforeDataPut(messageNode, dataNode, lockContext); - - if (lockContext.isCancelPdpOperation()) { - log.debug("DataPut was canceled by script"); - return true; - } - - // Send rest request to OPA - OpaConfiguration opaConfiguration = appConfiguration.getOpaConfiguration(); - String baseUrl = opaConfiguration.getBaseUrl(); - - HttpPut request = new HttpPut(String.format("%s/data/%s/%s", baseUrl, tknTyp, tknId)); - addAccessTokenHeader(request, opaConfiguration); - - request.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); - request.addHeader("If-None-Match", "*"); - - StringEntity stringEntity = new StringEntity(dataNode.toString(), ContentType.APPLICATION_JSON); - request.setEntity(stringEntity); - - boolean result = false; - try { - CloseableHttpClient httpClient = httpService.getHttpsClient(); - HttpResponse httpResponse = httpClient.execute(request); - - int statusCode = httpResponse.getStatusLine().getStatusCode(); - log.debug("Get OPA add data for token '{}' response with status code '{}'", tknId, statusCode); - - result = (statusCode == HttpStatus.SC_NO_CONTENT) || (statusCode == HttpStatus.SC_NOT_MODIFIED); - } catch (IOException ex) { - log.error("Failed to execute put data request", ex); - } - - if (result) { - loadedTokens.put(tknId, message, ExpirationPolicy.CREATED, getExpirationInSeconds(tokenEntity), TimeUnit.SECONDS); - } - - return result; - } - - public void buildBaseTokenObject(TokenEntity tokenEntity, ObjectNode dataNode) { - dataNode.put("scope", tokenEntity.getScope()); - dataNode.put("creationDate", ISO_INSTANT.format(tokenEntity.getCreationDate().toInstant())); - dataNode.put("expirationDate", ISO_INSTANT.format(tokenEntity.getExpirationDate().toInstant())); - dataNode.put("userId", tokenEntity.getUserId()); - dataNode.put("clientId", tokenEntity.getClientId()); - } - - protected boolean removeData(JsonNode messageNode) { - ExternalLockContext lockContext = new ExternalLockContext(); - - externalLockService.beforeDataRemoval(messageNode, lockContext); - - if (lockContext.isCancelPdpOperation()) { - log.debug("DataRemoval was canceled by script"); - return true; - } - - // Send rest request to OPA - String tknTyp = messageNode.get("tknTyp").asText(); - String tknId = messageNode.get("tknId").asText(); - - OpaConfiguration opaConfiguration = appConfiguration.getOpaConfiguration(); - String baseUrl = opaConfiguration.getBaseUrl(); - - HttpDelete request = new HttpDelete(String.format("%s/data/%s/%s", baseUrl, tknTyp, tknId)); - addAccessTokenHeader(request, opaConfiguration); - - boolean result = false; - try { - CloseableHttpClient httpClient = httpService.getHttpsClient(); - HttpResponse httpResponse = httpClient.execute(request); - - int statusCode = httpResponse.getStatusLine().getStatusCode(); - log.debug("Get OPA remove data for token '{}' response with status code '{}'", tknId, statusCode); - - result = statusCode == HttpStatus.SC_NO_CONTENT; - } catch (IOException ex) { - log.error("Failed to execute delete data request", ex); - } - - return result; - } - - protected long getExpirationInSeconds(TokenEntity tokenEntity) { - final Long duration = Duration.between(new Date().toInstant(), tokenEntity.getExpirationDate().toInstant()).getSeconds(); - - return duration; - } - - private void addAccessTokenHeader(HttpRequestBase request, OpaConfiguration opaConfiguration) { - String accessToken = encryptionService.decrypt(opaConfiguration.getAccessToken(), true); - if (StringHelper.isNotEmpty(accessToken)) { - request.setHeader("Authorization", "Bearer " + accessToken); - } - } - - protected class OpaExpirationListener implements ExpirationListener { - - public void expired(String key, String message) { - log.debug("Deleting expired token {}", key); - JsonNode messageNode; - try { - messageNode = objectMapper.readTree(message); - removeData(messageNode); - } catch (JacksonException ex) { - log.error("Failed to parse messge: '{}'", message, ex); - } - } - } - - @Override - public void destroy() { - log.debug("Destroy Messages"); - } - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/PolicyConsumerFactory.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/PolicyConsumerFactory.java index e175fc65d39..a48fd5cfe25 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/PolicyConsumerFactory.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/PolicyConsumerFactory.java @@ -78,7 +78,7 @@ private void recreatePolicyConsumer() { @Produces @ApplicationScoped public PolicyConsumer producePolicyConsumer() { - String policyConsumerType = appConfiguration.getPdpType(); + String policyConsumerType = appConfiguration.getPolicyConsumerType(); PolicyConsumer policyConsumer = buildPolicyConsumer(policyConsumerType); return policyConsumer; diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/opa/OpaPolicyConsumer.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/opa/OpaPolicyConsumer.java deleted file mode 100644 index 4559204853b..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/consumer/policy/opa/OpaPolicyConsumer.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.consumer.policy.opa; - -import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.slf4j.Logger; - -import com.unboundid.util.Base64; - -import io.jans.lock.model.config.AppConfiguration; -import io.jans.lock.model.config.OpaConfiguration; -import io.jans.lock.service.consumer.policy.PolicyConsumer; -import io.jans.lock.service.external.ExternalLockService; -import io.jans.lock.service.external.context.ExternalLockContext; -import io.jans.service.EncryptionService; -import io.jans.service.cdi.qualifier.Implementation; -import io.jans.service.net.BaseHttpService; -import io.jans.util.StringHelper; -import jakarta.annotation.PostConstruct; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.inject.Instance; -import jakarta.inject.Inject; - -/** - * OPA policy consumer - * - * @author Yuriy Movchan Date: 12/25/2023 - */ -@Implementation -@ApplicationScoped -public class OpaPolicyConsumer extends PolicyConsumer { - - public static String POLICY_CONSUMER_TYPE = "OPA"; - - @Inject - private AppConfiguration appConfiguration; - - @Inject - private ExternalLockService externalLockService; - - @Inject - private BaseHttpService httpService; - - @Inject - private Logger log; - - @Inject - @Implementation - private Instance policyConsumerProviderInstance; - - @Inject - private EncryptionService encryptionService; - - private MessageDigest sha256Digest; - - private Map> loadedPolicies; - - @PostConstruct - public void init() { - this.loadedPolicies = new ConcurrentHashMap>(); - try { - this.sha256Digest = MessageDigest.getInstance("SHA-256", "BC"); - } catch (NoSuchAlgorithmException ex) { - } catch (NoSuchProviderException ex) { - log.error("Failed to prepare SHA256 digister", ex); - } - } - - @Override - public boolean putPolicies(String sourceUri, List policies) { - log.debug("PutPolicies from {}, count {}", sourceUri, policies.size()); - - ExternalLockContext lockContext = new ExternalLockContext(); - externalLockService.beforePolicyPut(sourceUri, policies, lockContext); - - if (lockContext.isCancelPdpOperation()) { - log.debug("PutPolicies was canceled by script"); - return true; - } - - // Send rest request to OPA - String baseId = Base64.urlEncode(sourceUri, false); - - if (!loadedPolicies.containsKey(baseId)) { - loadedPolicies.put(baseId, new ArrayList<>(policies.size())); - } - - List policyIds = loadedPolicies.get(baseId); - - boolean result = true; - List cleanPolicyIds = new ArrayList<>(policyIds); - for (String policy : policies) { - byte[] digest = sha256Digest.digest(policy.getBytes(StandardCharsets.UTF_8)); - String policyId = new BigInteger(1, digest).toString(); - - if (policyIds.contains(policyId)) { - cleanPolicyIds.remove(policyId); - log.debug("Policy with digiest '{}' is already downloaded", policyId); - continue; - } - - OpaConfiguration opaConfiguration = appConfiguration.getOpaConfiguration(); - String baseUrl = opaConfiguration.getBaseUrl(); - - HttpPut request = new HttpPut(String.format("%s/policies/%s", baseUrl, policyId)); - addAccessTokenHeader(request, opaConfiguration); - - StringEntity stringEntity = new StringEntity(policy, ContentType.TEXT_PLAIN); - request.setEntity(stringEntity); - - try { - CloseableHttpClient httpClient = httpService.getHttpsClient(); - HttpResponse httpResponse = httpClient.execute(request); - - int statusCode = httpResponse.getStatusLine().getStatusCode(); - log.debug("Get OPA add policy for policyId '{}' response with status code '{}'", policyId, statusCode); - - result &= statusCode == HttpStatus.SC_OK; - } catch (IOException ex) { - log.error("Failed to add policy to OPA", ex); - } - - policyIds.add(policyId); - } - - // Remove old policies after processing currentPoliciesDigests - for (String policyId : cleanPolicyIds) { - result &= sendRemovePolicyRequest(sourceUri, policyId); - policyIds.remove(policyId); - } - - return result; - } - - @Override - public boolean removePolicies(String sourceUri) { - log.debug("RemovePolicies from {}", sourceUri); - - // Sent rest request to OPA - String baseId = Base64.urlEncode(sourceUri, false); - List policyIds = loadedPolicies.get(baseId); - - if (policyIds == null) { - log.warn("There is no loadeed policies from sourceUri: '{}'", sourceUri); - return true; - } - - boolean result = true; - for (String policyId : policyIds) { - result &= sendRemovePolicyRequest(sourceUri, policyId); - } - - return result; - } - - @Override - public void destroy() { - Map> clonedLoadedPolicies = new HashMap<>(loadedPolicies); - loadedPolicies.clear(); - - log.debug("Destroy Policies"); - for (String sourceUri : clonedLoadedPolicies.keySet()) { - removePolicies(sourceUri); - } - } - - public boolean sendRemovePolicyRequest(String sourceUri, String policyId) { - log.debug("Remove policy '{}'", policyId); - - ExternalLockContext lockContext = new ExternalLockContext(); - externalLockService.beforePolicyRemoval(sourceUri, lockContext); - - if (lockContext.isCancelPdpOperation()) { - log.debug("RemovePolicies was canceled by script"); - return true; - } - - OpaConfiguration opaConfiguration = appConfiguration.getOpaConfiguration(); - String baseUrl = opaConfiguration.getBaseUrl(); - - HttpDelete request = new HttpDelete(String.format("%s/policies/%s", baseUrl, policyId)); - addAccessTokenHeader(request, opaConfiguration); - - boolean result = true; - try { - CloseableHttpClient httpClient = httpService.getHttpsClient(); - HttpResponse httpResponse = httpClient.execute(request); - - int statusCode = httpResponse.getStatusLine().getStatusCode(); - log.debug("Get OPA remove policy for policyId '{}' response with status code '{}'", policyId, statusCode); - - result &= statusCode == HttpStatus.SC_OK; - } catch (IOException ex) { - log.error("Failed to remove policy from OPA", ex); - } - - return result; - } - - private void addAccessTokenHeader(HttpRequestBase request, OpaConfiguration opaConfiguration) { - String accessToken = encryptionService.decrypt(opaConfiguration.getAccessToken(), true); - if (StringHelper.isNotEmpty(accessToken)) { - request.setHeader("Authorization", "Bearer " + accessToken); - } - } - - @Override - public String getPolicyConsumerType() { - return POLICY_CONSUMER_TYPE; - } - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProducerFactory.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProducerFactory.java deleted file mode 100644 index a8751747fa9..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProducerFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.provider.metric; - -import org.slf4j.Logger; - -import io.jans.lock.model.config.AppConfiguration; -import io.jans.service.cdi.async.Asynchronous; -import io.jans.service.cdi.event.ApplicationInitialized; -import io.jans.service.cdi.event.ConfigurationUpdate; -import io.jans.service.cdi.qualifier.Implementation; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.event.Observes; -import jakarta.enterprise.inject.Instance; -import jakarta.enterprise.inject.Produces; -import jakarta.inject.Inject; - -/** - * Metric producer factory - * - * @author Yuriy Movchan Date: 05/03/2024 - */ -@ApplicationScoped -public class MetricProducerFactory { - - @Inject - private Logger log; - - @Inject - private AppConfiguration appConfiguration; - - @Inject - @Implementation - private Instance metricProviderInstances; - - private boolean appStarted = false; - - public void init(@Observes @ApplicationInitialized(ApplicationScoped.class) Object init) { - this.appStarted = true; - } - - @Asynchronous - public void configurationUpdateEvent(@Observes @ConfigurationUpdate AppConfiguration appConfiguration) { - if (!appStarted) { - return; - } - } - - @Produces - @ApplicationScoped - public MetricProvider produceMetricProvider() { - return new NullMetricProvider(); - } - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProvider.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProvider.java deleted file mode 100644 index a817d99ca7f..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProvider.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.provider.metric; - -/** - * Base message consumer - * - * @author Yuriy Movchan Date: 12/20/2023 - */ -public abstract class MetricProvider implements MetricProviderInterface { - - public abstract void destroy(); - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProviderInterface.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProviderInterface.java deleted file mode 100644 index 086e22d47ce..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/MetricProviderInterface.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.provider.metric; - -/** - * Interface for each policy consumer - * - * @author Yuriy Movchan Date: 12/20/2023 - */ -public interface MetricProviderInterface { - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/NullMetricProvider.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/NullMetricProvider.java deleted file mode 100644 index 20ca5b26b69..00000000000 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/provider/metric/NullMetricProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright [2024] [Janssen Project] - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.jans.lock.service.provider.metric; - -import org.slf4j.Logger; - -import io.jans.service.cdi.qualifier.Implementation; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; - -/** - * Null metric provider - * - * @author Yuriy Movchan Date: 05/23/2024 - */ -@Implementation -@ApplicationScoped -public class NullMetricProvider extends MetricProvider { - - public static String METRIC_PROVIDER_TYPE = "DISABLED"; - - @Inject - private Logger log; - - @Override - public void destroy() { - log.debug("Destroy metric provider"); - } - -} diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/ws/rs/audit/AuditRestWebServiceImpl.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/ws/rs/audit/AuditRestWebServiceImpl.java index a3fdfc3e4ba..0e439442c5b 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/ws/rs/audit/AuditRestWebServiceImpl.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/service/ws/rs/audit/AuditRestWebServiceImpl.java @@ -16,13 +16,20 @@ package io.jans.lock.service.ws.rs.audit; +import static io.jans.lock.service.audit.AuditService.AUDIT_HEALTH; +import static io.jans.lock.service.audit.AuditService.AUDIT_HEALTH_BULK; +import static io.jans.lock.service.audit.AuditService.AUDIT_LOG; +import static io.jans.lock.service.audit.AuditService.AUDIT_LOG_BULK; +import static io.jans.lock.service.audit.AuditService.AUDIT_TELEMETRY; +import static io.jans.lock.service.audit.AuditService.AUDIT_TELEMETRY_BULK; + import org.apache.http.entity.ContentType; import org.slf4j.Logger; import com.fasterxml.jackson.databind.JsonNode; +import io.jans.lock.service.DataMapperService; import io.jans.lock.service.audit.AuditService; -import io.jans.lock.service.stat.StatResponseService; import io.jans.lock.service.stat.StatService; import io.jans.lock.util.ServerUtil; import jakarta.enterprise.context.Dependent; @@ -34,8 +41,6 @@ import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.SecurityContext; -import static io.jans.lock.service.audit.AuditService.*; - /** * Provides interface for audit REST web services * @@ -55,6 +60,9 @@ public class AuditRestWebServiceImpl implements AuditRestWebService { @Inject private Logger log; + + @Inject + private DataMapperService dataMapperService; @Inject private AuditService auditService; @@ -112,7 +120,7 @@ private Response processAuditRequest(HttpServletRequest request, String requestT builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate()); builder.header(ServerUtil.PRAGMA, ServerUtil.NO_CACHE); - JsonNode json = this.auditService.getJsonNode(request); + JsonNode json = getJsonNode(request); if (reportStat) { if (bulkData) { @@ -145,6 +153,23 @@ private Response processAuditRequest(HttpServletRequest request, String requestT return builder.build(); } + public JsonNode getJsonNode(HttpServletRequest request) { + JsonNode jsonBody = null; + if (request == null) { + return jsonBody; + } + + try { + jsonBody = dataMapperService.readTree(request.getInputStream()); + log.debug(" jsonBody:{}", jsonBody); + } catch (Exception ex) { + ex.printStackTrace(); + log.error("Exception while retriving json from request is - ", ex); + } + + return jsonBody; + } + private void reportStat(JsonNode json) { boolean hasClientId = json.hasNonNull(LOG_CLIENT_ID); if (hasClientId) { diff --git a/jans-lock/lock-server/service/src/main/java/io/jans/lock/util/Constants.java b/jans-lock/lock-server/service/src/main/java/io/jans/lock/util/Constants.java index d4eac1f29cc..f8d88d43e20 100644 --- a/jans-lock/lock-server/service/src/main/java/io/jans/lock/util/Constants.java +++ b/jans-lock/lock-server/service/src/main/java/io/jans/lock/util/Constants.java @@ -12,9 +12,7 @@ */ public class Constants { - private Constants() { - } - + private Constants() {} public static final String MONTH = "month"; }