Search in sources :

Example 76 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class LoadAuthMechsFromK8s method createAuthMech.

private MechanismType createAuthMech(JSONObject item, String name) throws Exception {
    MechanismType mechType = new MechanismType();
    JSONObject spec = (JSONObject) item.get("spec");
    mechType.setName(name);
    mechType.setClassName((String) spec.get("className"));
    mechType.setUri((String) spec.get("uri"));
    mechType.setInit(new ConfigType());
    mechType.setParams(new ParamListType());
    JSONObject params = (JSONObject) spec.get("init");
    for (Object o : params.keySet()) {
        String keyName = (String) o;
        Object v = params.get(keyName);
        if (v instanceof String) {
            String val = (String) v;
            ParamType pt = new ParamType();
            pt.setName(keyName);
            pt.setValue(val);
            mechType.getInit().getParam().add(pt);
        } else if (v instanceof JSONArray) {
            for (Object ov : ((JSONArray) v)) {
                ParamType pt = new ParamType();
                pt.setName(keyName);
                pt.setValue((String) ov);
                mechType.getInit().getParam().add(pt);
            }
        }
    }
    JSONArray secretParams = (JSONArray) spec.get("secretParams");
    if (secretParams != null) {
        HttpCon nonwatchHttp = this.k8sWatch.getK8s().createClient();
        String token = this.k8sWatch.getK8s().getAuthToken();
        try {
            for (Object o : secretParams) {
                JSONObject secretParam = (JSONObject) o;
                String paramName = (String) secretParam.get("name");
                String secretName = (String) secretParam.get("secretName");
                String secretKey = (String) secretParam.get("secretKey");
                String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
                ParamType pt = new ParamType();
                pt.setName(paramName);
                pt.setValue(secretValue);
                mechType.getInit().getParam().add(pt);
            }
        } finally {
            nonwatchHttp.getHttp().close();
            nonwatchHttp.getBcm().close();
        }
    }
    return mechType;
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ParamListType(com.tremolosecurity.config.xml.ParamListType) JSONArray(org.json.simple.JSONArray) MechanismType(com.tremolosecurity.config.xml.MechanismType) JSONObject(org.json.simple.JSONObject) ConfigType(com.tremolosecurity.config.xml.ConfigType) ParamType(com.tremolosecurity.config.xml.ParamType)

Example 77 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class CheckForGit method findNamespaceGitUrl.

private void findNamespaceGitUrl(User user, Map<String, Object> request, String localNamespace, OpenShiftTarget target) throws ProvisioningException {
    if (user.getAttribs().get("gitUrl") != null) {
        // this is an add, get urls from the user
        request.put("namespaceGitUrl", user.getAttribs().get("gitUrl").getValues().get(0));
        request.put("gitUrlAnnotation", "tremolo.io/giturl: " + user.getAttribs().get("gitUrl").getValues().get(0));
        try {
            String privateKey = user.getAttribs().get("gitSshKey").getValues().get(0).trim() + "\n";
            String b64Key = java.util.Base64.getEncoder().encodeToString(privateKey.getBytes("UTF-8"));
            request.put("b64sshkey", b64Key);
        } catch (UnsupportedEncodingException e) {
            throw new ProvisioningException("Could not generate base64 key", e);
        }
    } else {
        // this is not an add, get the git URL from the namespace
        String namespaceUri = "/api/v1/namespaces/" + localNamespace;
        HttpCon http = null;
        try {
            http = target.createClient();
            String json = target.callWS(target.getAuthToken(), http, namespaceUri);
            JSONObject root = (JSONObject) new JSONParser().parse(json);
            if (root.get("kind") != null && !root.get("kind").equals("Namespace")) {
                logger.error("Not a namespace : '" + json + "'");
                throw new ProvisioningException("Could not lookup '" + localNamespace + "'");
            }
            JSONObject annotations = (JSONObject) ((JSONObject) root.get("metadata")).get("annotations");
            if (annotations == null) {
                logger.error("No annotations : '" + json + "'");
                throw new ProvisioningException("Could not lookup '" + localNamespace + "'");
            }
            String gitUrl = (String) annotations.get("tremolo.io/giturl");
            if (gitUrl == null) {
                logger.error("No tremolo.io/giturl annotation : '" + json + "'");
                throw new ProvisioningException("Could not lookup '" + localNamespace + "'");
            }
            request.put("namespaceGitUrl", gitUrl);
        } catch (Exception e) {
            throw new ProvisioningException("Could not retrieve namespace information", e);
        } finally {
            if (http != null) {
                try {
                    http.getHttp().close();
                } catch (IOException e) {
                }
                http.getBcm().close();
            }
        }
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 78 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class DeleteK8sObject 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");
    String localURL = task.renderTemplate(this.url, request);
    HttpCon con = null;
    String localTarget = task.renderTemplate(this.targetName, request);
    OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(localTarget).getProvider();
    try {
        String token = os.getAuthToken();
        con = os.createClient();
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            String localPath = task.renderTemplate(this.path, request);
            String dirName;
            String fileName;
            int lastSlash = localPath.lastIndexOf('/');
            if (lastSlash == -1) {
                dirName = "";
                fileName = localPath;
            } else {
                dirName = localPath.substring(0, lastSlash);
                fileName = localPath.substring(lastSlash + 1);
            }
            JSONObject fileInfo = new JSONObject();
            fileInfo.put("fileName", fileName);
            fileInfo.put("dirName", dirName);
            fileInfo.put("delete", true);
            GitFile gitFile = new GitFile(fileName, dirName, true, kind.equalsIgnoreCase("Namespace"));
            List<GitFile> gitFiles = (List<GitFile>) request.get(this.requestAttribute);
            if (gitFiles == null) {
                gitFiles = new ArrayList<GitFile>();
                request.put(this.requestAttribute, gitFiles);
            }
            gitFiles.add(gitFile);
        } else {
            String respJSON = os.callWSDelete(token, con, localURL);
            if (logger.isDebugEnabled()) {
                logger.debug("Response for deleting object : '" + 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 (logger.isDebugEnabled()) {
                logger.debug("kind : '" + kind + "' / '" + this.kind + "'");
            }
            if (kind.equalsIgnoreCase(this.kind)) {
                this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ProvisioningUtil.ActionType.Delete, approvalID, this.task.getWorkflow(), label, projectName);
            } else if (resp.get("status") != null) {
                String status = (String) resp.get("status");
                logger.info("status : '" + status + "'");
                if (status != null && status.equalsIgnoreCase("success")) {
                    this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ProvisioningUtil.ActionType.Delete, approvalID, this.task.getWorkflow(), label, projectName);
                } else {
                    throw new ProvisioningException("Could not delete " + kind + " with url '" + localURL + "' - '" + respJSON + "'");
                }
            } else {
                throw new ProvisioningException("Could not delete " + kind + " with url '" + localURL + "' - '" + respJSON + "'");
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not delete " + kind + " - " + localURL, e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
    return true;
}
Also used : GitFile(com.tremolosecurity.provisioning.tasks.dataobj.GitFile) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ArrayList(java.util.ArrayList) List(java.util.List) JSONParser(org.json.simple.parser.JSONParser)

Example 79 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class PatchK8sObject method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    String localTemplate = task.renderTemplate(template, request);
    if (logger.isDebugEnabled()) {
        logger.debug("localTemplate : '" + localTemplate + "'");
    }
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    String localURL = task.renderTemplate(this.url, request);
    HttpCon con = null;
    String localTarget = task.renderTemplate(this.targetName, request);
    OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(localTarget).getProvider();
    try {
        String token = os.getAuthToken();
        con = os.createClient();
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            String localPath = task.renderTemplate(this.path, request);
            String dirName;
            String fileName;
            int lastSlash = localPath.lastIndexOf('/');
            if (lastSlash == -1) {
                dirName = "";
                fileName = localPath;
            } else {
                dirName = localPath.substring(0, lastSlash);
                fileName = localPath.substring(lastSlash + 1);
            }
            GitFile gitFile = new GitFile(fileName, dirName, false, false);
            gitFile.setData(localTemplate);
            gitFile.setPatch(true);
            gitFile.setPatchType(this.patchType);
            List<GitFile> gitFiles = (List<GitFile>) request.get(this.requestAttribute);
            if (gitFiles == null) {
                gitFiles = new ArrayList<GitFile>();
                request.put(this.requestAttribute, gitFiles);
            }
            gitFiles.add(gitFile);
        } else {
            if (this.isObjectExists(os, token, con, localURL, localTemplate)) {
                String respJSON = os.callWSPatchJson(token, con, localURL, localTemplate, this.patchContentType);
                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(this.kind)) {
                    throw new ProvisioningException("Could not create " + kind + " with json '" + localTemplate + "' - '" + respJSON + "'");
                } else {
                    this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ActionType.Replace, approvalID, this.task.getWorkflow(), label, projectName);
                }
            } else {
                throw new ProvisioningException("Object '" + localURL + "' does not exist");
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not create " + kind, e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
    return true;
}
Also used : GitFile(com.tremolosecurity.provisioning.tasks.dataobj.GitFile) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ArrayList(java.util.ArrayList) List(java.util.List) JSONParser(org.json.simple.parser.JSONParser)

Example 80 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class PushToApiServer method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    String localTarget = task.renderTemplate(this.target, request);
    OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(localTarget).getProvider();
    HttpCon con = null;
    try {
        con = target.createClient();
        StringBuilder sb = new StringBuilder();
        List<GitFile> files = (List<GitFile>) request.get(requestObject);
        if (files == null) {
            throw new Exception("No gitfiles stored in '" + requestObject + "'");
        }
        for (GitFile f : files) {
            Yaml yaml = new Yaml();
            Map<String, Object> map = (Map<String, Object>) yaml.load(new ByteArrayInputStream(f.getData().getBytes("UTF-8")));
            JSONObject jsonObject = new JSONObject(map);
            String localTemplateJSON = jsonObject.toJSONString();
            if (!target.isObjectExistsByName(target.getAuthToken(), con, f.getDirName(), f.getFileName())) {
                logger.info(new StringBuilder().append("Writing ").append(f.getDirName()).append('/').append(f.getFileName()).toString());
                target.callWSPost(target.getAuthToken(), con, f.getDirName(), localTemplateJSON);
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not push to git", e);
    } finally {
        if (con != null) {
            try {
                con.getHttp().close();
            } catch (IOException e) {
            }
            con.getBcm().close();
        }
    }
    return true;
}
Also used : GitFile(com.tremolosecurity.provisioning.tasks.dataobj.GitFile) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) IOException(java.io.IOException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) List(java.util.List) JSONObject(org.json.simple.JSONObject) Map(java.util.Map)

Aggregations

HttpCon (com.tremolosecurity.provisioning.util.HttpCon)104 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)82 IOException (java.io.IOException)70 ClientProtocolException (org.apache.http.client.ClientProtocolException)49 JSONObject (org.json.simple.JSONObject)43 ParseException (org.json.simple.parser.ParseException)33 Workflow (com.tremolosecurity.provisioning.core.Workflow)32 ArrayList (java.util.ArrayList)32 UnsupportedEncodingException (java.io.UnsupportedEncodingException)31 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)27 JSONParser (org.json.simple.parser.JSONParser)25 HashMap (java.util.HashMap)24 JSONArray (org.json.simple.JSONArray)22 User (com.tremolosecurity.provisioning.core.User)18 Attribute (com.tremolosecurity.saml.Attribute)17 Gson (com.google.gson.Gson)16 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashSet (java.util.HashSet)13 List (java.util.List)13 KSToken (com.tremolosecurity.unison.openstack.util.KSToken)12