Commit 2ac3fc11 authored by Alok Joshi's avatar Alok Joshi
Browse files

remove Jwt implementation from other providers

parent f10c83a2
Pipeline #34204 failed with stage
in 28 seconds
// Copyright © 2020 Amazon Web Services
//
// 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 org.opengroup.osdu.search.provider.aws.util;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterResult;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.opengroup.osdu.core.aws.entitlements.ServicePrincipal;
import org.opengroup.osdu.core.aws.iam.IAMConfig;
import org.opengroup.osdu.core.aws.secrets.SecretsManager;
import com.amazonaws.auth.AWSCredentialsProvider;
import javax.annotation.PostConstruct;
@Component
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
@Value("${aws.region}")
@Getter()
@Setter(AccessLevel.PROTECTED)
public String amazonRegion;
@Value("${aws.ssm}")
@Getter()
@Setter(AccessLevel.PROTECTED)
public Boolean ssmEnabled;
@Value("${aws.environment}")
@Getter()
@Setter(AccessLevel.PROTECTED)
public String environment;
private String awsOauthCustomScope;
String client_credentials_secret;
String client_credentials_clientid;
ServicePrincipal sp;
private AWSCredentialsProvider amazonAWSCredentials;
private AWSSimpleSystemsManagement ssmManager;
@PostConstruct
public void init() {
if (ssmEnabled) {
SecretsManager sm = new SecretsManager();
String oauth_token_url = "/osdu/" + environment + "/oauth-token-uri";
String oauth_custom_scope = "/osdu/" + environment + "/oauth-custom-scope";
String client_credentials_client_id = "/osdu/" + environment + "/client-credentials-client-id";
String client_secret_key = "client_credentials_client_secret";
String client_secret_secretName = "/osdu/" + environment + "/client_credentials_secret";
amazonAWSCredentials = IAMConfig.amazonAWSCredentials();
ssmManager = AWSSimpleSystemsManagementClientBuilder.standard()
.withCredentials(amazonAWSCredentials)
.withRegion(amazonRegion)
.build();
client_credentials_clientid = getSsmParameter(client_credentials_client_id);
client_credentials_secret = sm.getSecret(client_secret_secretName,amazonRegion,client_secret_key);
String tokenUrl = getSsmParameter(oauth_token_url);
awsOauthCustomScope = getSsmParameter(oauth_custom_scope);
sp = new ServicePrincipal(amazonRegion,environment,tokenUrl,awsOauthCustomScope);
}
}
@Override
public String getIdToken(String tenantName) {
String token= sp.getServicePrincipalAccessToken(client_credentials_clientid,client_credentials_secret);
return token;
}
private String getSsmParameter(String parameterKey) {
GetParameterRequest paramRequest = (new GetParameterRequest()).withName(parameterKey).withWithDecryption(true);
GetParameterResult paramResult = ssmManager.getParameter(paramRequest);
return paramResult.getParameter().getValue();
}
}
......@@ -28,7 +28,7 @@ aws.elasticache.cluster.index.endpoint=${CACHE_CLUSTER_ENDPOINT}
aws.elasticache.cluster.index.port=${CACHE_CLUSTER_PORT}
aws.elasticache.cluster.index.expiration=60
## Default Elasticsearch Settings
## Default Elasticsearch Settings
ELASTIC_HOST=""
ELASTIC_PORT=0
aws.es.host=${ELASTIC_HOST}
......@@ -50,10 +50,6 @@ AGGREGATION_SIZE=1000
awsParameterStorePropertySource.enabled=true
## AWS ElastiCache configuration
aws.elasticache.cluster.endpoint=${CACHE_CLUSTER_ENDPOINT}
aws.elasticache.cluster.port=${CACHE_CLUSTER_PORT}
aws.ssm=${SSM_ENABLED}
aws.ssm.prefix=/osdu/${ENVIRONMENT}
......@@ -65,11 +61,4 @@ server.ssl.key-store-type=PKCS12
server.ssl.key-store=${SSL_KEY_STORE_PATH:/certs/osduonaws.p12}
server.ssl.key-alias=${SSL_KEY_ALIAS:osduonaws}
server.ssl.key-password=${SSL_KEY_PASSWORD:}
server.ssl.key-store-password=${SSL_KEY_STORE_PASSWORD:}
# Policy service properties
service.policy.enabled=false
POLICY_API=${ENTITLEMENTS_BASE_URL}/api/policy/v1
POLICY_ID=search
PARTITION_API=${ENTITLEMENTS_BASE_URL}/api/partition/v1
aws.environment=${ENVIRONMENT}
\ No newline at end of file
server.ssl.key-store-password=${SSL_KEY_STORE_PASSWORD:}
\ No newline at end of file
// Copyright © Microsoft Corporation
//
// 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 org.opengroup.osdu.search.provider.byoc.utils;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
@Override
public String getIdToken(String tenantName){
return "dont-have-one";
}
}
/*
Copyright 2020 Google LLC
Copyright 2020 EPAM Systems, Inc
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 org.opengroup.osdu.search.provider.gcp.utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.SignJwtRequest;
import com.google.api.services.iam.v1.model.SignJwtResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.opengroup.osdu.core.common.provider.interfaces.ITenantFactory;
import org.opengroup.osdu.core.common.model.tenant.TenantInfo;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
private static final String JWT_AUDIENCE = "https://www.googleapis.com/oauth2/v4/token";
private static final String SERVICE_ACCOUNT_NAME_FORMAT = "projects/%s/serviceAccounts/%s";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private Iam iam;
@Autowired
private ITenantFactory tenantStorageFactory;
@Autowired
private JaxRsDpsLog logger;
@Value("${STORAGE_HOSTNAME}")
public String storageHostname;
@Value("${GOOGLE_AUDIENCES}")
public String googleAudiences;
@Override
public String getIdToken(String tenantName) {
this.logger.info("Tenant name received for auth token is: " + tenantName);
TenantInfo tenantInfo = this.tenantStorageFactory.getTenantInfo(tenantName);
if (tenantInfo == null) {
this.logger.error("Invalid tenant name receiving from pubsub");
throw new AppException(HttpStatus.SC_BAD_REQUEST, "Invalid tenant Name", "Invalid tenant Name from pubsub");
}
try {
// 1. get signed JWT
Map<String, Object> signJwtPayload = getJwtCreationPayload(tenantInfo);
SignJwtRequest signJwtRequest = new SignJwtRequest();
signJwtRequest.setPayload(JSON_FACTORY.toString(signJwtPayload));
String serviceAccountName = String.format(SERVICE_ACCOUNT_NAME_FORMAT, tenantInfo.getProjectId(),
tenantInfo.getServiceAccount());
Iam.Projects.ServiceAccounts.SignJwt signJwt = getIam().projects().serviceAccounts()
.signJwt(serviceAccountName, signJwtRequest);
SignJwtResponse signJwtResponse = signJwt.execute();
String signedJwt = signJwtResponse.getSignedJwt();
// 2. get id token
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
postParameters.add(new BasicNameValuePair("assertion", signedJwt));
HttpPost post = new HttpPost(JWT_AUDIENCE);
post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
post.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
CloseableHttpResponse httpResponse = httpClient.execute(post);
JsonObject jsonContent = new JsonParser().parse(EntityUtils.toString(httpResponse.getEntity()))
.getAsJsonObject();
if (!jsonContent.has("id_token")) {
this.logger.error(String.format("Google IAM response: %s", jsonContent.toString()));
throw new AppException(HttpStatus.SC_FORBIDDEN, "Access denied",
"User is not authorized to perform this operation.");
}
String token = jsonContent.get("id_token").getAsString();
return "Bearer " + token;
}
} catch (AppException e) {
throw e;
} catch (Exception e) {
throw new AppException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Persistence error", "Error generating token",
e);
}
}
Iam getIam() throws GeneralSecurityException, IOException {
if (this.iam == null) {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
scopes.add(IamScopes.CLOUD_PLATFORM);
credential = credential.createScoped(scopes);
}
this.iam = new Iam.Builder(httpTransport, JSON_FACTORY, new HttpCredentialsAdapter(credential))
.setApplicationName(storageHostname).build();
}
return this.iam;
}
private Map<String, Object> getJwtCreationPayload(TenantInfo tenantInfo) {
String googleAudience = googleAudiences;
if (googleAudience.contains(",")) {
googleAudience = googleAudience.split(",")[0];
}
Map<String, Object> payload = new HashMap<>();
payload.put("target_audience", googleAudience);
payload.put("aud", JWT_AUDIENCE);
payload.put("exp", System.currentTimeMillis() / 1000 + 3600);
payload.put("iat", System.currentTimeMillis() / 1000);
payload.put("iss", tenantInfo.getServiceAccount());
return payload;
}
}
......@@ -5,6 +5,4 @@ entitlements-host=https://entitlements-dot-opendes.appspot.com/entitlements/v1
indexer-host=https://os-indexer-dot-opendes.appspot.com/api/indexer/v2/
google-cloud-project=opendes
AUTHORIZE_API=https://entitlements-dot-opendes.appspot.com/entitlements/v1
REDIS_GROUP_HOST=10.0.16.28
\ No newline at end of file
AUTHORIZE_API=https://entitlements-dot-opendes.appspot.com/entitlements/v1
\ No newline at end of file
......@@ -9,6 +9,4 @@ AUTHORIZE_API=http://os-entitlement-service/entitlements/v1
google-cloud-project=${GOOGLE_CLOUD_PROJECT}
environment=${ENVIRONMENT_SEARCH}
disable.appengine.log.factory=true
REDIS_GROUP_HOST=${REDIS_GROUP_HOST}
\ No newline at end of file
disable.appengine.log.factory=true
\ No newline at end of file
......@@ -5,6 +5,4 @@ entitlements-host=https://entitlements-dot-opendes.appspot.com/entitlements/v1
indexer-host=https://os-indexer-dot-opendes.appspot.com/api/indexer/v2/
google-cloud-project=opendes
AUTHORIZE_API=https://entitlements-dot-opendes.appspot.com/entitlements/v1
REDIS_GROUP_HOST=127.0.0.1
\ No newline at end of file
AUTHORIZE_API=https://entitlements-dot-opendes.appspot.com/entitlements/v1
\ No newline at end of file
......@@ -5,6 +5,4 @@ entitlements-host=https://entitlements-dot-opendes-evt.appspot.com/entitlements/
indexer-host=https://os-indexer-dot-opendes-evt.appspot.com/api/indexer/v2/
google-cloud-project=opendes-evt
AUTHORIZE_API=https://entitlements-dot-opendes-evt.appspot.com/entitlements/v1
REDIS_GROUP_HOST=10.253.209.196
AUTHORIZE_API=https://entitlements-dot-opendes-evt.appspot.com/entitlements/v1
\ No newline at end of file
......@@ -28,6 +28,4 @@ query-default-limit=10
query-limit-maximum=1000
aggregation-size=1000
security.https.certificate.trust=false
REDIS_GROUP_PORT=6379
\ No newline at end of file
security.https.certificate.trust=false
\ No newline at end of file
/* Licensed Materials - Property of IBM */
/* (c) Copyright IBM Corp. 2020. All Rights Reserved.*/
package org.opengroup.osdu.search.provider.ibm.util;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
@Override
public String getIdToken(String tenantName){
return "dont-have-one";
}
}
/*
* Copyright 2021 Google LLC
* Copyright 2021 EPAM Systems, Inc
*
* 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
*
* https://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 org.opengroup.osdu.search.provider.reference.utils;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class ServiceAccountJwtClientImpl implements IServiceAccountJwtClient {
@Override
public String getIdToken(String tenantName) {
return "dont-have-one";
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment