Search in sources :

Example 11 with HttpCon

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

the class LoadTargetsFromK8s method createTarget.

private TargetType createTarget(JSONObject item, String name) throws ProvisioningException {
    TargetType target = new TargetType();
    target.setName(name);
    target.setParams(new TargetConfigType());
    HttpCon nonwatchHttp = null;
    JSONObject spec = (JSONObject) item.get("spec");
    try {
        nonwatchHttp = this.k8sWatch.getK8s().createClient();
        String token = this.k8sWatch.getK8s().getAuthToken();
        StringBuffer b = new StringBuffer();
        b.setLength(0);
        OpenUnisonConfigLoader.integrateIncludes(b, (String) spec.get("className"));
        target.setClassName(b.toString());
        JSONArray params = (JSONArray) spec.get("params");
        for (Object o : params) {
            JSONObject param = (JSONObject) o;
            ParamType pt = new ParamType();
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("name"));
            pt.setName(b.toString());
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("value"));
            pt.setValue(b.toString());
            target.getParams().getParam().add(pt);
        }
        JSONArray secretParams = (JSONArray) spec.get("secretParams");
        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);
            target.getParams().getParam().add(pt);
        }
        JSONArray attrs = (JSONArray) spec.get("targetAttributes");
        for (Object o : attrs) {
            JSONObject attr = (JSONObject) o;
            TargetAttributeType ta = new TargetAttributeType();
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, (String) attr.get("name"));
            ta.setName(b.toString());
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, (String) attr.get("source"));
            ta.setSource(b.toString());
            ta.setSourceType((String) attr.get("sourceType"));
            ta.setTargetType((String) attr.get("targetType"));
            target.getTargetAttribute().add(ta);
        }
        synchronized (this.tremolo.getProvisioning().getTargets().getTarget()) {
            int found = -1;
            int ii = 0;
            for (TargetType tt : this.tremolo.getProvisioning().getTargets().getTarget()) {
                if (tt.getName().equals(target.getName())) {
                    found = ii;
                    break;
                }
                ii++;
            }
            if (found >= 0) {
                this.tremolo.getProvisioning().getTargets().getTarget().remove(found);
            }
            this.tremolo.getProvisioning().getTargets().getTarget().add(target);
        }
        return target;
    } catch (Exception e) {
        throw new ProvisioningException("Could not add target '" + name + "'", e);
    } finally {
        if (nonwatchHttp != null) {
            try {
                nonwatchHttp.getHttp().close();
            } catch (IOException e) {
            }
            nonwatchHttp.getBcm().close();
        }
    }
}
Also used : JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException) ParamType(com.tremolosecurity.config.xml.ParamType) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) TargetAttributeType(com.tremolosecurity.config.xml.TargetAttributeType) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) TargetType(com.tremolosecurity.config.xml.TargetType) TargetConfigType(com.tremolosecurity.config.xml.TargetConfigType) JSONObject(org.json.simple.JSONObject)

Example 12 with HttpCon

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

the class CreateK8sObject 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);
    String localTemplateJSON = "";
    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();
        if (this.yaml) {
            Yaml yaml = new Yaml();
            Map<String, Object> map = (Map<String, Object>) yaml.load(new ByteArrayInputStream(localTemplate.getBytes("UTF-8")));
            JSONObject jsonObject = new JSONObject(map);
            localTemplateJSON = jsonObject.toJSONString();
        } else {
            localTemplateJSON = localTemplate;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Write To Request  : '" + this.writeToRequestConfig + "'");
        }
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            if (!os.isObjectExists(token, con, localURL, localTemplateJSON)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Url '" + localURL + "' doesn't exist");
                }
                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("data", Base64.getEncoder().encodeToString(localTemplate.getBytes("UTF-8")));
                GitFile gitFile = new GitFile(fileName, dirName, localTemplate);
                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 {
            writeToAPIServer(localTemplateJSON, approvalID, localURL, con, os, token, localTarget);
        }
    } 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) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) Yaml(org.yaml.snakeyaml.Yaml) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Example 13 with HttpCon

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

the class K8sProjectCheck method createTremoloUser.

@Override
public String createTremoloUser(NewUserRequest newUser, List<String> errors, AuthInfo userData) throws ProvisioningException {
    if (errors.size() == 0) {
        String targetName = newUser.getAttributes().get("cluster");
        if (targetName == null) {
            targetName = this.targetName;
        }
        OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(targetName).getProvider();
        HttpCon con = null;
        try {
            String token = target.getAuthToken();
            con = target.createClient();
            if (target.isObjectExistsByName(token, con, "/api/v1/namespaces", newUser.getAttributes().get(this.projectAttributeName))) {
                errors.add("Namespace name already exists");
                return "";
            }
        } catch (Exception e) {
            throw new ProvisioningException("Could not check if namespace exists", e);
        } finally {
            if (con != null) {
                try {
                    con.getHttp().close();
                } catch (IOException e) {
                // doesn't matter
                }
                con.getBcm().close();
            }
        }
        if (target.getGitUrl() != null && !target.getGitUrl().isEmpty()) {
            String gitUrlForNs = newUser.getAttributes().get("gitUrl");
            String sshPrivKey = newUser.getAttributes().get("gitSshKey");
            if (gitUrlForNs == null || gitUrlForNs.isEmpty()) {
                errors.add("Git URL is required for clusters configured to use git");
            }
            if (sshPrivKey == null || sshPrivKey.isEmpty()) {
                errors.add("Git SSH Private Key is required for clusters configured to use git");
            }
            if (errors.size() > 0) {
                return "";
            }
            GitUtils gitUtil = new GitUtils(gitUrlForNs, sshPrivKey);
            try {
                gitUtil.checkOut();
            } catch (Throwable t) {
                logger.warn("Could not checkout '" + gitUrlForNs + "'", t);
                errors.add(t.getMessage());
            } finally {
                gitUtil.cleanup();
            }
        }
        return this.workflowName;
    } else {
        return "";
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) GitUtils(com.tremolosecurity.git.GitUtils) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) IOException(java.io.IOException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException)

Example 14 with HttpCon

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

the class AttributeChange method createInternalUser.

private void createInternalUser(User user, Set<String> attributes, Map<String, Object> request, int approvalID, Workflow workflow) throws ProvisioningException {
    JSONObject root = new JSONObject();
    if (user.getAttribs().get("accountEnabled") != null) {
        root.put("accountEnabled", user.getAttribs().get("accountEnabled").getValues().get(0).equalsIgnoreCase("true"));
    }
    root.put("displayName", user.getAttribs().get("displayName").getValues().get(0));
    if (user.getAttribs().get("onPremisesImmutableId") != null) {
        root.put("onPremisesImmutableId", user.getAttribs().get("onPremisesImmutableId").getValues().get(0));
    }
    String mail;
    if (user.getAttribs().get("mail") != null) {
        mail = user.getAttribs().get("mail").getValues().get(0);
    } else {
        mail = user.getAttribs().get("userPrincipalName").getValues().get(0);
    }
    String mailNickName = mail.substring(0, mail.indexOf('@'));
    root.put("mailNickname", mailNickName);
    root.put("userPrincipalName", user.getAttribs().get("userPrincipalName").getValues().get(0));
    JSONObject passwordPolicy = new JSONObject();
    if (user.getPassword() != null && !user.getPassword().isEmpty()) {
        passwordPolicy.put("password", user.getPassword());
    } else {
        passwordPolicy.put("password", new GenPasswd(50, true, true, true, true).getPassword());
    }
    passwordPolicy.put("forceChangePasswordNextSignIn", request.get("tremolo.azuread.create.forceChangePasswordNextSignIn") != null && request.get("tremolo.azuread.create.forceChangePasswordNextSignIn").equals("true"));
    passwordPolicy.put("forceChangePasswordNextSignInWithMfa", request.get("tremolo.azuread.create.forceChangePasswordNextSignInWithMfa") != null && request.get("tremolo.azuread.create.forceChangePasswordNextSignInWithMfa").equals("true"));
    root.put("passwordProfile", passwordPolicy);
    HttpCon con = null;
    try {
        con = this.createClient();
        String json = this.callWSPostJsonReesponseExpected(con, "/users", root.toString());
        JSONObject resp = (JSONObject) new JSONParser().parse(json);
        user.getAttribs().put("id", new Attribute("id", (String) resp.get("id")));
        this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Add, approvalID, workflow, "userPrincipalName", user.getAttribs().get("userPrincipalName").getValues().get(0));
        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "userPrincipalName", user.getAttribs().get("userPrincipalName").getValues().get(0));
        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "password", "*********8");
        if (user.getAttribs().get("accountEnabled") != null) {
            this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "accountEnabled", user.getAttribs().get("accountEnabled").getValues().get(0));
        }
        if (user.getAttribs().get("onPremisesImmutableId") != null) {
            this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "onPremisesImmutableId", user.getAttribs().get("onPremisesImmutableId").getValues().get(0));
        }
        User fromAzure = new User(user.getUserID());
        fromAzure.getAttribs().put("id", new Attribute("id", user.getAttribs().get("id").getValues().get(0)));
        fromAzure.getAttribs().put("userPrincipalName", new Attribute("displayName", user.getAttribs().get("userPrincipalName").getValues().get(0)));
        this.synUser(user, true, attributes, fromAzure, approvalID, workflow);
    } catch (Exception e) {
        throw new ProvisioningException("Could not create user", e);
    } finally {
        try {
            con.getHttp().close();
        } catch (IOException e) {
        }
        con.getBcm().close();
    }
}
Also used : GenPasswd(com.tremolosecurity.provisioning.util.GenPasswd) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) User(com.tremolosecurity.provisioning.core.User) JSONObject(org.json.simple.JSONObject) Attribute(com.tremolosecurity.saml.Attribute) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 15 with HttpCon

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

the class AttributeChange method createClient.

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();
    defheaders.add(new BasicHeader("X-Csrf-Token", "1"));
    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(cfgMgr.getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders).setDefaultRequestConfig(rc).build();
    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);
    return con;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.http.message.BasicHeader) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

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