Search in sources :

Example 36 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class Drupal8Target method syncUser.

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    if (user.getUserID().isEmpty()) {
        this.createUser(user, attributes, request);
        return;
    }
    int userID = 0;
    int approvalID = 0;
    int workflowID = 0;
    if (request.containsKey("TREMOLO_USER_ID")) {
        userID = (Integer) request.get("TREMOLO_USER_ID");
    }
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    if (request.containsKey("WORKFLOW_ID")) {
        workflowID = (Integer) request.get("WORKFLOW_ID");
    }
    User fromDrupal = this.findUser(user.getUserID(), attributes, request);
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    StringBuilder sb = new StringBuilder();
    JSONObject root = new JSONObject();
    HashMap<String, String> attrsForAudit = new HashMap<String, String>();
    if (syncAttribute("name", user, fromDrupal, attributes)) {
        this.setJsonValue("name", user.getAttribs().get("name").getValues().get(0), root);
        attrsForAudit.put("name", user.getAttribs().get("name").getValues().get(0));
    }
    if (syncAttribute("langcode", user, fromDrupal, attributes)) {
        this.setJsonValue("langcode", user.getAttribs().get("langcode").getValues().get(0), root);
        attrsForAudit.put("langcode", user.getAttribs().get("langcode").getValues().get(0));
    }
    if (syncAttribute("preferred_langcode", user, fromDrupal, attributes)) {
        this.setJsonValue("preferred_langcode", user.getAttribs().get("preferred_langcode").getValues().get(0), root);
        attrsForAudit.put("preferred_langcode", user.getAttribs().get("preferred_langcode").getValues().get(0));
    }
    if (syncAttribute("preferred_admin_langcode", user, fromDrupal, attributes)) {
        this.setJsonValue("preferred_admin_langcode", user.getAttribs().get("preferred_admin_langcode").getValues().get(0), root);
        attrsForAudit.put("preferred_admin_langcode", user.getAttribs().get("preferred_admin_langcode").getValues().get(0));
    }
    if (syncAttribute("mail", user, fromDrupal, attributes)) {
        this.setJsonValue("mail", user.getAttribs().get("mail").getValues().get(0), root);
        attrsForAudit.put("mail", user.getAttribs().get("mail").getValues().get(0));
    }
    if (syncAttribute("status", user, fromDrupal, attributes)) {
        this.setJsonValueBoolean("status", user.getAttribs().get("status").getValues().get(0), root);
        attrsForAudit.put("status", user.getAttribs().get("status").getValues().get(0));
    }
    for (String userAttributeName : user.getAttribs().keySet()) {
        if (!defaultAttributes.contains(userAttributeName) && this.syncAttribute(userAttributeName, user, fromDrupal, attributes)) {
            this.setJsonValue("field_" + userAttributeName, user.getAttribs().get(userAttributeName).getValues().get(0), root);
            attrsForAudit.put("field_" + userAttributeName, user.getAttribs().get(userAttributeName).getValues().get(0));
        }
    }
    JSONArray roles = new JSONArray();
    List<String> addedRoles = new ArrayList<String>();
    List<String> removedRoles = new ArrayList<String>();
    for (String groupName : user.getGroups()) {
        if (!fromDrupal.getGroups().contains(groupName)) {
            addedRoles.add(groupName);
        }
        JSONObject group = new JSONObject();
        group.put("target_id", groupName);
        roles.add(group);
    }
    for (String groupName : fromDrupal.getGroups()) {
        if (!user.getGroups().contains(groupName)) {
            if (addOnly) {
                JSONObject group = new JSONObject();
                group.put("target_id", groupName);
                roles.add(group);
            } else {
                removedRoles.add(groupName);
            }
        }
    }
    root.put("roles", roles);
    HttpPatch post = new HttpPatch(this.url + "/user/" + user.getUserID() + "?_format=json");
    post.setHeader(new BasicHeader("X-CSRF-Token", UUID.randomUUID().toString()));
    post.addHeader("Content-Type", "application/json");
    try {
        post.setEntity(new StringEntity(root.toJSONString()));
    } catch (UnsupportedEncodingException e) {
        throw new ProvisioningException("Couldn't create user", e);
    }
    sb.setLength(0);
    sb.append(this.user).append(":").append(this.password);
    String azHeader = java.util.Base64.getEncoder().encodeToString(sb.toString().getBytes());
    sb.setLength(0);
    post.setHeader("Authorization", sb.append("Basic ").append(azHeader).toString());
    HttpCon con = null;
    try {
        con = this.createClient();
    } catch (Exception e) {
        throw new ProvisioningException("Couldn't create user", e);
    }
    try {
        CloseableHttpResponse resp = con.getHttp().execute(post);
        if (resp.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(resp.getEntity());
            JSONParser parser = new JSONParser();
            root = (JSONObject) parser.parse(json);
            String uid = getJsonValue("uid", root);
            for (String attr : attrsForAudit.keySet()) {
                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow, attr, attrsForAudit.get(attr));
            }
            for (String groupName : addedRoles) {
                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "role", groupName);
            }
            for (String groupName : removedRoles) {
                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete, approvalID, workflow, "role", groupName);
            }
            user.setUserID(uid);
        } else {
            throw new ProvisioningException("Could not create user with code " + resp.getStatusLine().getStatusCode());
        }
    } catch (IOException | ParseException e) {
        throw new ProvisioningException("Couldn't create user", e);
    }
}
Also used : User(com.tremolosecurity.provisioning.core.User) HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) ArrayList(java.util.ArrayList) Workflow(com.tremolosecurity.provisioning.core.Workflow) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpPatch(org.apache.http.client.methods.HttpPatch) PropertyVetoException(java.beans.PropertyVetoException) SQLException(java.sql.SQLException) ParseException(org.json.simple.parser.ParseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StringEntity(org.apache.http.entity.StringEntity) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) BasicHeader(org.apache.http.message.BasicHeader)

Example 37 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class GitlabUserProvider method syncUser.

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    List<GitlabFedIdentity> ids = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    User fromGitlab = this.findUser(user.getUserID(), attributes, request);
    if (fromGitlab == null) {
        this.createUser(user, attributes, request);
        return;
    }
    List<GitlabFedIdentity> idsFromGitlab = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
    HashMap<String, String> toSet = new HashMap<String, String>();
    HashSet<String> toDelete = new HashSet<String>();
    for (String attrName : attributes) {
        Attribute attrFromGitlab = fromGitlab.getAttribs().get(attrName);
        Attribute attrIn = user.getAttribs().get(attrName);
        if ((attrIn != null && attrFromGitlab == null) || (attrIn != null && attrFromGitlab != null && !attrIn.getValues().get(0).equals(attrFromGitlab.getValues().get(0)))) {
            toSet.put(attrName, attrIn.getValues().get(0));
        } else if (!addOnly) {
            if (attrIn == null && attrFromGitlab != null) {
                toDelete.add(attrName);
            }
        }
    }
    org.gitlab4j.api.models.User toSave = this.findUserByName(user.getUserID());
    for (String attrName : toSet.keySet()) {
        try {
            this.beanUtils.setProperty(toSave, attrName, toSet.get(attrName));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ProvisioningException("Could not update user " + user.getUserID(), e);
        }
    }
    for (String attrName : toDelete) {
        try {
            this.beanUtils.setProperty(toSave, attrName, "");
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ProvisioningException("Could not update user " + user.getUserID(), e);
        }
    }
    if (ids != null) {
        ArrayList<Header> defheaders = new ArrayList<Header>();
        defheaders.add(new BasicHeader("Private-Token", this.token));
        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();
        try {
            for (GitlabFedIdentity id : ids) {
                boolean found = false;
                for (GitlabFedIdentity idfromgl : idsFromGitlab) {
                    if (id.getExternalUid().equals(idfromgl.getExternalUid()) && id.getProvider().equals(idfromgl.getProvider())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    HttpPut getmembers = new HttpPut(new StringBuilder().append(this.url).append("/api/v4/users/").append(toSave.getId()).append("?provider=").append(id.getProvider()).append("&extern_uid=").append(URLEncoder.encode(user.getUserID(), "UTF-8")).toString());
                    CloseableHttpResponse resp = http.execute(getmembers);
                    if (resp.getStatusLine().getStatusCode() != 200) {
                        throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
                    }
                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "identity-provider", id.getProvider());
                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "identity-externid", id.getExternalUid());
                }
            }
        } catch (IOException e) {
            throw new ProvisioningException("Could not set identity", e);
        } finally {
            try {
                http.close();
            } catch (IOException e) {
            }
            bhcm.close();
        }
    }
    try {
        this.userApi.updateUser(toSave, null);
    } catch (GitLabApiException e) {
        throw new ProvisioningException("Could not save user " + user.getUserID(), e);
    }
    for (String attrName : toSet.keySet()) {
        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow, attrName, toSet.get(attrName));
    }
    for (String attrName : toDelete) {
        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow, attrName, "");
    }
    HashMap<String, Integer> groupmap = (HashMap<String, Integer>) request.get(GitlabUserProvider.GITLAB_GROUP_ENTITLEMENTS);
    if (groupmap == null) {
        groupmap = new HashMap<String, Integer>();
    }
    for (String inGroup : user.getGroups()) {
        if (!fromGitlab.getGroups().contains(inGroup)) {
            try {
                Group groupObj = this.findGroupByName(inGroup);
                if (groupObj == null) {
                    logger.warn("Group " + inGroup + " does not exist");
                } else {
                    int accessLevel = AccessLevel.DEVELOPER.ordinal();
                    if (groupmap.containsKey(inGroup)) {
                        accessLevel = groupmap.get(inGroup);
                    }
                    this.groupApi.addMember(groupObj.getId(), toSave.getId(), accessLevel);
                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "group", inGroup);
                }
            } catch (GitLabApiException e) {
                if (e.getMessage().equalsIgnoreCase("Member already exists")) {
                    continue;
                } else {
                    throw new ProvisioningException("Could not find group " + inGroup, e);
                }
            }
        }
    }
    if (!addOnly) {
        for (String groupFromGitlab : fromGitlab.getGroups()) {
            if (!user.getGroups().contains(groupFromGitlab)) {
                try {
                    Group groupObj = this.findGroupByName(groupFromGitlab);
                    if (groupObj == null) {
                        logger.warn("Group " + groupFromGitlab + " does not exist");
                    } else {
                        this.groupApi.removeMember(groupObj.getId(), toSave.getId());
                        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete, approvalID, workflow, "group", groupFromGitlab);
                    }
                } catch (GitLabApiException e) {
                    throw new ProvisioningException("Could not find group " + groupFromGitlab);
                }
            }
        }
    }
}
Also used : Group(org.gitlab4j.api.models.Group) UserStoreProviderWithAddGroup(com.tremolosecurity.provisioning.core.UserStoreProviderWithAddGroup) User(com.tremolosecurity.provisioning.core.User) HashMap(java.util.HashMap) Attribute(com.tremolosecurity.saml.Attribute) ArrayList(java.util.ArrayList) HttpPut(org.apache.http.client.methods.HttpPut) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ArrayList(java.util.ArrayList) List(java.util.List) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HashSet(java.util.HashSet) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Workflow(com.tremolosecurity.provisioning.core.Workflow) GitLabApiException(org.gitlab4j.api.GitLabApiException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) BasicHeader(org.apache.http.message.BasicHeader)

Example 38 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class GitlabUserProvider method deleteUser.

@Override
public void deleteUser(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");
    org.gitlab4j.api.models.User fromGitlab = this.findUserByName(user.getUserID());
    if (fromGitlab == null) {
        return;
    }
    try {
        this.userApi.deleteUser(fromGitlab.getId(), false);
    } catch (GitLabApiException e) {
        throw new ProvisioningException("Could not delete " + user.getUserID(), e);
    }
    this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Delete, approvalID, workflow, "id", fromGitlab.getId().toString());
}
Also used : ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Workflow(com.tremolosecurity.provisioning.core.Workflow) GitLabApiException(org.gitlab4j.api.GitLabApiException)

Example 39 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class AddGroupToProject method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    if (request.get("newProjectJSON") == null) {
        logger.warn("Project not created, skipping");
        return true;
    }
    String localGroupName = task.renderTemplate(this.groupName, request);
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    GitlabUserProvider gitlab = (GitlabUserProvider) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    GitLabApi api = gitlab.getApi();
    ObjectMapper mapper = new ObjectMapper();
    Project newProject = null;
    if (this.projectName == null) {
        try {
            newProject = (Project) mapper.readValue((String) request.get("newProjectJSON"), Project.class);
        } catch (JsonProcessingException e) {
            throw new ProvisioningException("Could not parse", e);
        }
    } else {
        String localProjectName = task.renderTemplate(this.projectName, request);
        String localNamespace = task.renderTemplate(this.namespace, request);
        try {
            newProject = api.getProjectApi().getProject(localNamespace, localProjectName);
        } catch (GitLabApiException e) {
            throw new ProvisioningException("Could not find " + localNamespace + "/" + localProjectName, e);
        }
    }
    Group groupToAdd;
    try {
        groupToAdd = gitlab.findGroupByName(localGroupName);
        if (groupToAdd == null) {
            throw new ProvisioningException("Group " + localGroupName + " does not exist");
        }
        api.getProjectApi().shareProject(newProject, groupToAdd.getId(), AccessLevel.valueOf(accessLevel), null);
    } catch (GitLabApiException e) {
        throw new ProvisioningException("Could not add group " + localGroupName + " to project " + newProject.getNameWithNamespace(), e);
    }
    GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-project-" + newProject.getNameWithNamespace() + "-group", localGroupName);
    return true;
}
Also used : GitlabUserProvider(com.tremolosecurity.unison.gitlab.provisioning.targets.GitlabUserProvider) Project(org.gitlab4j.api.models.Project) Group(org.gitlab4j.api.models.Group) GitLabApi(org.gitlab4j.api.GitLabApi) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Workflow(com.tremolosecurity.provisioning.core.Workflow) GitLabApiException(org.gitlab4j.api.GitLabApiException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 40 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class CreateDeploymentKey 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");
    GitlabUserProvider gitlab = (GitlabUserProvider) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    GitLabApi api = gitlab.getApi();
    String localNamespace = task.renderTemplate(this.namespace, request);
    String localProjectName = task.renderTemplate(this.project, request);
    String localLabel = task.renderTemplate(this.keyLabel, request);
    try {
        Project project = api.getProjectApi().getProject(localNamespace, localProjectName);
        // generate deployment key
        KeyPairGenerator generator;
        generator = KeyPairGenerator.getInstance("RSA");
        // or: generator = KeyPairGenerator.getInstance("DSA");
        generator.initialize(2048);
        KeyPair keyPair = generator.genKeyPair();
        String sshPubKey = "ssh-rsa " + Base64.encodeBase64String(encodePublicKey((RSAPublicKey) keyPair.getPublic())) + " " + localLabel;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.bouncycastle.openssl.PEMWriter genPrivKey = new org.bouncycastle.openssl.PEMWriter(new OutputStreamWriter(baos));
        genPrivKey.writeObject(keyPair.getPrivate());
        genPrivKey.close();
        String pem = new String(baos.toByteArray());
        api.getDeployKeysApi().addDeployKey(project, localLabel, sshPubKey, this.makeWriteable);
        GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-project-" + project.getNameWithNamespace() + "-deploykey", localLabel);
        try {
            String base64PrivKey = java.util.Base64.getEncoder().encodeToString(pem.getBytes("UTF-8"));
            request.put(privateKeyRequestName, base64PrivKey);
            request.put(this.privateKeyRequestNamePT, pem);
        } catch (UnsupportedEncodingException e) {
            throw new ProvisioningException("Could get key", e);
        }
    } catch (GitLabApiException | NoSuchAlgorithmException | IOException e) {
        throw new ProvisioningException("Error creating key for " + localNamespace + "/" + localProjectName, e);
    }
    return true;
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) KeyPair(java.security.KeyPair) Workflow(com.tremolosecurity.provisioning.core.Workflow) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GitLabApiException(org.gitlab4j.api.GitLabApiException) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) GitlabUserProvider(com.tremolosecurity.unison.gitlab.provisioning.targets.GitlabUserProvider) Project(org.gitlab4j.api.models.Project) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OutputStreamWriter(java.io.OutputStreamWriter)

Aggregations

Workflow (com.tremolosecurity.provisioning.core.Workflow)78 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)68 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)32 IOException (java.io.IOException)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)22 ClientProtocolException (org.apache.http.client.ClientProtocolException)21 Attribute (com.tremolosecurity.saml.Attribute)19 ArrayList (java.util.ArrayList)18 LDAPException (com.novell.ldap.LDAPException)17 HashMap (java.util.HashMap)17 User (com.tremolosecurity.provisioning.core.User)16 HashSet (java.util.HashSet)15 ParseException (org.json.simple.parser.ParseException)14 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)12 JSONObject (org.json.simple.JSONObject)12 Gson (com.google.gson.Gson)11 LDAPEntry (com.novell.ldap.LDAPEntry)11 LDAPAttribute (com.novell.ldap.LDAPAttribute)10 GitLabApiException (org.gitlab4j.api.GitLabApiException)10 SQLException (java.sql.SQLException)9