use of com.tremolosecurity.provisioning.core.ProvisioningException in project OpenUnison by TremoloSecurity.
the class OpenShiftTarget method findUser.
@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
try {
User user = null;
String token = this.getAuthToken();
// users aren't bound to groups and there's no way to directly lookup what groups a user has
// so we need to read all groups and see if the user exists
ArrayList<String> groupsForUser = new ArrayList<String>();
HttpCon con = this.createClient();
StringBuffer b = new StringBuffer();
com.tremolosecurity.unison.openshiftv3.model.List<GroupItem> groupList = null;
try {
String json = callWS(token, con, "/apis/user.openshift.io/v1/groups");
Gson gson = new Gson();
TypeToken<com.tremolosecurity.unison.openshiftv3.model.List<GroupItem>> tokenType = new TypeToken<com.tremolosecurity.unison.openshiftv3.model.List<GroupItem>>() {
};
groupList = gson.fromJson(json, tokenType.getType());
b.append("/apis/user.openshift.io/v1/users/").append(userID);
json = callWS(token, con, b.toString());
com.tremolosecurity.unison.openshiftv3.model.users.User osUser = gson.fromJson(json, com.tremolosecurity.unison.openshiftv3.model.users.User.class);
if (osUser.getKind().equalsIgnoreCase("User")) {
user = new User(userID);
for (String attrName : osUser.getMetadata().keySet()) {
if (!attrName.equalsIgnoreCase("fullName") && attributes.contains(attrName)) {
user.getAttribs().put(attrName, new Attribute(attrName, (String) osUser.getMetadata().get(attrName)));
}
}
if (attributes.contains("fullName") && osUser.getFullName() != null) {
user.getAttribs().put("fullName", new Attribute("fullName", osUser.getFullName()));
}
}
} finally {
if (con != null) {
con.getBcm().shutdown();
}
}
for (GroupItem group : groupList.getItems()) {
if (group.getUsers() != null && group.getUsers().contains(userID)) {
groupsForUser.add((String) group.getMetadata().get("name"));
}
}
if (groupsForUser.isEmpty()) {
return user;
} else {
if (user == null) {
// user = new User(userID);
return null;
}
user.getGroups().addAll(groupsForUser);
return user;
}
} catch (Exception e) {
throw new ProvisioningException("Could not load " + userID, e);
}
}
use of com.tremolosecurity.provisioning.core.ProvisioningException in project OpenUnison by TremoloSecurity.
the class OpenShiftTarget method getAuthToken.
public String getAuthToken() throws Exception {
HttpCon con = this.createClient();
try {
if (!this.useToken) {
StringBuffer b = new StringBuffer();
b.append(this.getUrl()).append("/oauth/authorize?response_type=token&client_id=openshift-challenging-client");
HttpGet get = new HttpGet(b.toString());
b.setLength(0);
b.append(this.userName).append(':').append(this.password);
String b64 = Base64.encodeBase64String(b.toString().getBytes("UTF-8"));
b.setLength(0);
b.append("Basic ").append(b64.substring(0, b64.length() - 2));
get.addHeader(new BasicHeader("Authorization", b.toString()));
HttpResponse resp = con.getHttp().execute(get);
String token = "";
if (resp.getStatusLine().getStatusCode() == 302) {
String url = resp.getFirstHeader("Location").getValue();
int start = url.indexOf("access_token") + "access_token=".length();
int end = url.indexOf("&", start + 1);
token = url.substring(start, end);
} else {
throw new Exception("Unable to obtain token : " + resp.getStatusLine().toString());
}
return token;
} else {
switch(this.tokenType) {
case NONE:
return null;
case TOKENAPI:
this.checkProjectedToken();
case LEGACY:
case STATIC:
return this.osToken;
case OIDC:
return this.generateOidcToken();
default:
throw new ProvisioningException("Unknown tokenType");
}
}
} finally {
if (con != null) {
con.getBcm().shutdown();
}
}
}
use of com.tremolosecurity.provisioning.core.ProvisioningException in project OpenUnison by TremoloSecurity.
the class LoadApplicationsFromK8s method addObject.
@Override
public void addObject(TremoloType cfg, JSONObject item) throws ProvisioningException {
String rawJson = item.toJSONString();
StringBuffer b = new StringBuffer();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, rawJson);
try {
JSONObject newRoot = (JSONObject) new JSONParser().parse(b.toString());
JSONObject metadata = (JSONObject) newRoot.get("metadata");
if (metadata == null) {
throw new ProvisioningException("No metadata");
}
String name = (String) metadata.get("name");
logger.info("Adding application " + name);
try {
synchronized (GlobalEntries.getGlobalEntries().getConfigManager()) {
ApplicationType app = this.createApplication(item, name);
GlobalEntries.getGlobalEntries().getConfigManager().initializeUrls(GlobalEntries.getGlobalEntries().getConfigManager().addApplication(app));
}
} catch (Exception e) {
logger.warn("Could not initialize application " + name, e);
}
} catch (ParseException e) {
throw new ProvisioningException("Could not parse application", e);
}
}
use of com.tremolosecurity.provisioning.core.ProvisioningException in project OpenUnison by TremoloSecurity.
the class OpenShiftTarget method init.
@Override
public void init(Map<String, Attribute> cfg, ConfigManager cfgMgr, String name) throws ProvisioningException {
this.url = this.loadOption("url", cfg, false);
this.useDefaultCaPath = false;
String tmpUseToken = this.loadOptionalAttributeValue("useToken", "Use Token", cfg, null);
this.useToken = tmpUseToken != null && tmpUseToken.equalsIgnoreCase("true");
if (!useToken) {
this.userName = this.loadOption("userName", cfg, false);
this.password = this.loadOption("password", cfg, true);
} else {
String localTokenType = this.loadOptionalAttributeValue("tokenType", "tokenType", cfg, null);
if (localTokenType == null || localTokenType.trim().isEmpty()) {
localTokenType = "LEGACY";
}
this.tokenType = TokenType.valueOf(localTokenType.toUpperCase());
switch(tokenType) {
case STATIC:
this.osToken = this.loadOptionalAttributeValue("token", "Token", cfg, "***************************");
break;
case LEGACY:
try {
this.osToken = new String(Files.readAllBytes(Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/token")), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new ProvisioningException("Could not load token", e);
}
// check if token is projected, starting in 1.21 this is the default
int firstPeriod = this.osToken.indexOf('.');
int lastPeriod = this.osToken.lastIndexOf('.');
String json = new String(Base64.decodeBase64(this.osToken.substring(firstPeriod + 1, lastPeriod)));
try {
JSONObject claims = (JSONObject) new JSONParser().parse(json);
if (claims.containsKey("exp")) {
logger.info("Default token is projected, switching to TokenAPI");
this.tokenType = TokenType.TOKENAPI;
this.tokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token";
this.useDefaultCaPath = true;
this.checkProjectedToken();
}
} catch (ParseException e1) {
throw new ProvisioningException("Could not load token", e1);
}
break;
case TOKENAPI:
this.tokenPath = this.loadOption("tokenPath", cfg, false);
this.checkProjectedToken();
break;
case NONE:
break;
case OIDC:
this.initRemoteOidc(cfg, cfgMgr, localTokenType);
break;
}
if (this.url.isEmpty()) {
this.localToken = true;
String certAlias = this.loadOptionalAttributeValue("caCertAlias", "caCertAlias", cfg, null);
if (certAlias == null) {
certAlias = "k8s-master";
}
try {
logger.info("Cert Alias Storing - '" + certAlias + "'");
X509Certificate cert = null;
if (tokenType == TokenType.LEGACY || this.useDefaultCaPath) {
cert = CertUtil.readCertificate("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
} else if (tokenType == TokenType.TOKENAPI) {
// -\("/)/-
cert = CertUtil.readCertificate(this.loadOption("certPath", cfg, false));
}
logger.info("Certificate - " + cert);
cfgMgr.getKeyStore().setCertificateEntry(certAlias, cert);
} catch (KeyStoreException | EncodingException | StreamException e) {
throw new ProvisioningException("Could not load ca cert", e);
}
}
}
this.cfgMgr = cfgMgr;
this.name = name;
if (cfg.get("certificate") != null) {
String certificate = cfg.get("certificate").getValues().get(0);
try {
X509Certificate cert = this.pem2cert(certificate);
cfgMgr.getKeyStore().setCertificateEntry("k8s-certificate-" + this.name, cert);
} catch (Exception e) {
throw new ProvisioningException("Could not load certificate", e);
}
}
try {
cfgMgr.buildHttpConfig();
} catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
throw new ProvisioningException("Could not rebuild http configuration", e);
}
this.label = this.loadOptionalAttributeValue("label", "label", cfg, null);
if (this.label == null) {
this.label = this.name;
}
this.gitUrl = this.loadOptionalAttributeValue("gitUrl", "gitUrl", cfg, null);
}
use of com.tremolosecurity.provisioning.core.ProvisioningException in project OpenUnison by TremoloSecurity.
the class OpenShiftTarget method addGroup.
@Override
public void addGroup(String name, Map<String, String> additionalAttributes, User user, Map<String, Object> request) throws ProvisioningException {
HttpCon con = null;
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
try {
String token = this.getAuthToken();
con = this.createClient();
Gson gson = new Gson();
// first lets see if the group exists
StringBuilder sb = new StringBuilder();
sb.append("/apis/user.openshift.io/v1/groups/").append(name);
com.tremolosecurity.unison.openshiftv3.model.groups.Group group = new com.tremolosecurity.unison.openshiftv3.model.groups.Group();
group.setKind("Group");
group.setApiVersion("user.openshift.io/v1");
group.setMetadata(new HashMap<String, Object>());
group.getMetadata().put("name", name);
group.getMetadata().put("creationTimestamp", null);
group.setUsers(null);
String jsonInput = gson.toJson(group);
if (!this.isObjectExists(token, con, "/apis/user.openshift.io/v1/groups", jsonInput)) {
String json = this.callWSPost(token, con, "/apis/user.openshift.io/v1/groups", jsonInput);
Response resp = gson.fromJson(json, Response.class);
if (resp.getKind().equalsIgnoreCase("Group")) {
this.cfgMgr.getProvisioningEngine().logAction(name, true, ActionType.Add, approvalID, workflow, "group-object", name);
} else {
throw new ProvisioningException("Unknown response : '" + json + "'");
}
}
} catch (Exception e) {
throw new ProvisioningException("Could not load group", e);
} finally {
if (con != null) {
con.getBcm().close();
}
}
}
Aggregations