Search in sources :

Example 6 with Response

use of com.tremolosecurity.unison.openshiftv3.model.Response in project OpenUnison by TremoloSecurity.

the class K8sSessionStore method deleteAllSessions.

@Override
public void deleteAllSessions(String sessionId) throws Exception {
    String sessionIdName = new StringBuilder().append("x").append(sessionId).append("x").toString();
    OpenShiftTarget k8s = null;
    try {
        k8s = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
    } catch (ProvisioningException e1) {
        logger.error("Could not retrieve kubernetes target", e1);
        throw new ProvisioningException("Could not connect to kubernetes", e1);
    }
    String url = new StringBuilder().append("/apis/openunison.tremolo.io/v1/namespaces/").append(this.nameSpace).append("/oidc-sessions/").append(sessionIdName).toString();
    try {
        HttpCon con = k8s.createClient();
        try {
            String jsonResp = k8s.callWS(k8s.getAuthToken(), con, url);
            JSONObject root = (JSONObject) new JSONParser().parse(jsonResp);
            if (root.containsKey("kind") && root.get("kind").equals("Status") && ((Long) root.get("code")) == 404) {
                logger.warn(new StringBuilder().append("Session ID ").append(sessionId).append(" does not exist"));
                return;
            }
            JSONObject metadata = (JSONObject) root.get("metadata");
            JSONObject labels = (JSONObject) metadata.get("labels");
            String dnHash = (String) labels.get("tremolo.io/user-dn");
            url = new StringBuilder().append("/apis/openunison.tremolo.io/v1/namespaces/").append(this.nameSpace).append("/oidc-sessions?labelSelector=tremolo.io%2Fuser-dn%3D").append(dnHash).toString();
            jsonResp = k8s.callWSDelete(k8s.getAuthToken(), con, url);
            if (logger.isDebugEnabled()) {
                logger.debug("json response from deleting object : " + jsonResp);
            }
        } finally {
            con.getHttp().close();
            con.getBcm().close();
        }
    } catch (Exception e) {
        logger.error("Could not search k8s", e);
        throw new Exception("Error searching kubernetes", e);
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) JSONParser(org.json.simple.parser.JSONParser) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 7 with Response

use of com.tremolosecurity.unison.openshiftv3.model.Response in project OpenUnison by TremoloSecurity.

the class K8sSessionStore method deleteSession.

@Override
public void deleteSession(String sessionId) throws Exception {
    String sessionIdName = new StringBuilder().append("x").append(sessionId).append("x").toString();
    OpenShiftTarget k8s = null;
    try {
        k8s = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
    } catch (ProvisioningException e1) {
        logger.error("Could not retrieve kubernetes target", e1);
        throw new ProvisioningException("Could not connect to kubernetes", e1);
    }
    String url = new StringBuilder().append("/apis/openunison.tremolo.io/v1/namespaces/").append(this.nameSpace).append("/oidc-sessions/").append(sessionIdName).toString();
    try {
        HttpCon con = k8s.createClient();
        try {
            String jsonResp = k8s.callWSDelete(k8s.getAuthToken(), con, url);
            if (logger.isDebugEnabled()) {
                logger.debug("json response from deleting object : " + jsonResp);
            }
        } finally {
            con.getHttp().close();
            con.getBcm().close();
        }
    } catch (Exception e) {
        logger.error("Could not search k8s", e);
        throw new Exception("Error searching kubernetes", e);
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 8 with Response

use of com.tremolosecurity.unison.openshiftv3.model.Response in project OpenUnison by TremoloSecurity.

the class K8sSessionStore method resetSession.

@Override
public void resetSession(OidcSessionState session) throws Exception {
    String sessionIdName = new StringBuilder().append("x").append(session.getSessionID()).append("x").toString();
    OpenShiftTarget k8s = null;
    try {
        k8s = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
    } catch (ProvisioningException e1) {
        logger.error("Could not retrieve kubernetes target", e1);
        throw new ProvisioningException("Could not connect to kubernetes", e1);
    }
    String url = new StringBuilder().append("/apis/openunison.tremolo.io/v1/namespaces/").append(this.nameSpace).append("/oidc-sessions/").append(sessionIdName).toString();
    try {
        HttpCon con = k8s.createClient();
        try {
            String jsonResp = k8s.callWS(k8s.getAuthToken(), con, url);
            if (logger.isDebugEnabled()) {
                logger.debug("json response from deleting object : " + jsonResp);
            }
            Map ret = gson.fromJson(jsonResp, Map.class);
            Map obj = new HashMap();
            Map spec = (Map) ret.get("spec");
            obj.put("spec", spec);
            if (spec == null) {
                return;
            }
            spec.put("encrypted_id_token", session.getEncryptedIdToken());
            spec.put("encrypted_access_token", session.getEncryptedAccessToken());
            spec.put("refresh_token", session.getRefreshToken());
            spec.put("expires", ISODateTimeFormat.dateTime().print(session.getExpires()));
            jsonResp = k8s.callWSPatchJson(k8s.getAuthToken(), con, url, gson.toJson(obj));
            if (logger.isDebugEnabled()) {
                logger.debug("json response from patch : '" + jsonResp + "'");
            }
        } finally {
            con.getHttp().close();
            con.getBcm().close();
        }
    } catch (Exception e) {
        logger.error("Could not search k8s", e);
        throw new Exception("Error searching kubernetes", e);
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) HashMap(java.util.HashMap) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) HashMap(java.util.HashMap) Map(java.util.Map) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 9 with Response

use of com.tremolosecurity.unison.openshiftv3.model.Response in project OpenUnison by TremoloSecurity.

the class AddtoRBAC method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    HttpCon con = null;
    OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
    try {
        String token = os.getAuthToken();
        con = os.createClient();
        String rbacCfgMapJson = os.callWS(token, con, "/api/v1/namespaces/argocd/configmaps/argocd-rbac-cm");
        JSONObject rbacCfgMap = (JSONObject) new JSONParser().parse(rbacCfgMapJson);
        JSONObject data = (JSONObject) rbacCfgMap.get("data");
        StringBuilder newRbac = new StringBuilder();
        if (data != null) {
            newRbac.append(data.get("policy.csv")).append('\n');
        }
        String policiesToAdd = this.task.renderTemplate(this.toAdd, request);
        newRbac.append(policiesToAdd);
        JSONObject patch = new JSONObject();
        JSONObject pdata = new JSONObject();
        patch.put("data", pdata);
        pdata.put("policy.csv", newRbac.toString());
        String json = patch.toString();
        String respJSON = os.callWSPatchJson(token, con, "/api/v1/namespaces/argocd/configmaps/argocd-rbac-cm", json);
        if (logger.isDebugEnabled()) {
            logger.debug("Response for creating project : '" + respJSON + "'");
        }
        JSONParser parser = new JSONParser();
        JSONObject resp = (JSONObject) parser.parse(respJSON);
        String kind = (String) resp.get("kind");
        String projectName = (String) ((JSONObject) resp.get("metadata")).get("name");
        if (!kind.equalsIgnoreCase("ConfigMap")) {
            throw new ProvisioningException("Could not update the ArgoCD RBAC ConfigMap - '" + respJSON + "'");
        } else {
            this.task.getConfigManager().getProvisioningEngine().logAction(this.k8sTarget, true, ActionType.Replace, approvalID, this.task.getWorkflow(), "argocd-rbac-cm", projectName);
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not update argocd rbac", e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
    return true;
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) JSONParser(org.json.simple.parser.JSONParser) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 10 with Response

use of com.tremolosecurity.unison.openshiftv3.model.Response in project OpenUnison by TremoloSecurity.

the class K8sWatcher method initalRun.

public void initalRun() throws ProvisioningException {
    OpenShiftTarget k8s = (OpenShiftTarget) provisioningEngine.getTarget(k8sTarget).getProvider();
    if (k8s == null) {
        throw new ProvisioningException("Target " + k8sTarget + " does not exist");
    }
    HttpCon http;
    try {
        http = k8s.createClient();
    } catch (Exception e1) {
        throw new ProvisioningException("Could not create http connection", e1);
    }
    this.resourceVersions = new HashSet<String>();
    try {
        String token = k8s.getAuthToken();
        String json = null;
        try {
            json = k8s.callWS(token, http, uri);
        } catch (HttpResponseException e) {
            logger.warn("Could not retrieve urls, dynamic urls will not be supported", e);
            return;
        }
        JSONObject list = (JSONObject) new JSONParser().parse(json);
        JSONArray items = (JSONArray) list.get("items");
        if (items == null) {
            logger.error("Invalid JSON Response : '" + json + "'");
            return;
        }
        for (Object o : items) {
            JSONObject jsonObj = (JSONObject) o;
            String strjson = jsonObj.toString();
            if (logger.isDebugEnabled())
                logger.debug("json before includes : " + strjson);
            StringBuffer b = new StringBuffer();
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, strjson);
            if (logger.isDebugEnabled())
                logger.debug("json after includes : " + b.toString());
            jsonObj = (JSONObject) new JSONParser().parse(b.toString());
            JSONObject metadata = (JSONObject) jsonObj.get("metadata");
            String resourceVersion = (String) metadata.get("resourceVersion");
            if (this.resourceVersions.contains(resourceVersion)) {
                logger.info("Resource " + resourceVersion + " already processed, skipping");
            } else {
                this.resourceVersions.add(resourceVersion);
                this.watchee.addObject(cfgMgr.getCfg(), jsonObj);
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not get urls", e);
    } finally {
        try {
            http.getHttp().close();
        } catch (IOException e) {
            logger.warn(e);
        }
        http.getBcm().close();
    }
    this.keepRunning = true;
    logger.info("Adding stoppable thread");
    GlobalEntries.getGlobalEntries().getConfigManager().addThread(this);
    logger.info("Starting watch");
    new Thread(this).start();
}
Also used : JSONArray(org.json.simple.JSONArray) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) StopableThread(com.tremolosecurity.server.StopableThread) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Aggregations

ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)17 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)14 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)14 JSONObject (org.json.simple.JSONObject)12 JSONParser (org.json.simple.parser.JSONParser)9 IOException (java.io.IOException)8 ParseException (org.json.simple.parser.ParseException)8 Gson (com.google.gson.Gson)7 Workflow (com.tremolosecurity.provisioning.core.Workflow)7 Response (com.tremolosecurity.unison.openshiftv3.model.Response)7 ClientProtocolException (org.apache.http.client.ClientProtocolException)7 JoseException (org.jose4j.lang.JoseException)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 KeyManagementException (java.security.KeyManagementException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 UnrecoverableKeyException (java.security.UnrecoverableKeyException)5 HashMap (java.util.HashMap)5 HttpResponse (org.apache.http.HttpResponse)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5