Search in sources :

Example 1 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class Helper method queryForGroups.

Set<AccountGroup.UUID> queryForGroups(final DirContext ctx, final String username, LdapQuery.Result account) throws NamingException {
    final LdapSchema schema = getSchema(ctx);
    final Set<String> groupDNs = new HashSet<>();
    if (!schema.groupMemberQueryList.isEmpty()) {
        final HashMap<String, String> params = new HashMap<>();
        if (account == null) {
            try {
                account = findAccount(schema, ctx, username, false);
            } catch (AccountException e) {
                return Collections.emptySet();
            }
        }
        for (String name : schema.groupMemberQueryList.get(0).getParameters()) {
            params.put(name, account.get(name));
        }
        params.put(LdapRealm.USERNAME, username);
        for (LdapQuery groupMemberQuery : schema.groupMemberQueryList) {
            for (LdapQuery.Result r : groupMemberQuery.query(ctx, params)) {
                recursivelyExpandGroups(groupDNs, schema, ctx, r.getDN());
            }
        }
    }
    if (schema.accountMemberField != null) {
        if (account == null || account.getAll(schema.accountMemberField) == null) {
            try {
                account = findAccount(schema, ctx, username, true);
            } catch (AccountException e) {
                return Collections.emptySet();
            }
        }
        final Attribute groupAtt = account.getAll(schema.accountMemberField);
        if (groupAtt != null) {
            final NamingEnumeration<?> groups = groupAtt.getAll();
            try {
                while (groups.hasMore()) {
                    final String nextDN = (String) groups.next();
                    recursivelyExpandGroups(groupDNs, schema, ctx, nextDN);
                }
            } catch (PartialResultException e) {
            // Ignored
            }
        }
    }
    final Set<AccountGroup.UUID> actual = new HashSet<>();
    for (String dn : groupDNs) {
        actual.add(new AccountGroup.UUID(LDAP_UUID + dn));
    }
    if (actual.isEmpty()) {
        return Collections.emptySet();
    }
    return ImmutableSet.copyOf(actual);
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) PartialResultException(javax.naming.PartialResultException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) AccountException(com.google.gerrit.server.account.AccountException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) HashSet(java.util.HashSet)

Example 2 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class AddMembers method createAccountByLdap.

private Account createAccountByLdap(String user) throws IOException {
    if (!user.matches(Account.USER_NAME_PATTERN)) {
        return null;
    }
    try {
        AuthRequest req = AuthRequest.forUser(user);
        req.setSkipAuthentication(true);
        return accountCache.get(accountManager.authenticate(req).getAccountId()).getAccount();
    } catch (AccountException e) {
        return null;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException)

Example 3 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class Helper method findAccount.

LdapQuery.Result findAccount(Helper.LdapSchema schema, DirContext ctx, String username, boolean fetchMemberOf) throws NamingException, AccountException {
    final HashMap<String, String> params = new HashMap<>();
    params.put(LdapRealm.USERNAME, username);
    List<LdapQuery> accountQueryList;
    if (fetchMemberOf && schema.type.accountMemberField() != null) {
        accountQueryList = schema.accountWithMemberOfQueryList;
    } else {
        accountQueryList = schema.accountQueryList;
    }
    for (LdapQuery accountQuery : accountQueryList) {
        List<LdapQuery.Result> res = accountQuery.query(ctx, params, userSearchLatencyTimer);
        if (res.size() == 1) {
            return res.get(0);
        } else if (res.size() > 1) {
            throw new AccountException("Duplicate users: " + username);
        }
    }
    throw new NoSuchUserException(username);
}
Also used : AccountException(com.google.gerrit.server.account.AccountException) HashMap(java.util.HashMap) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString)

Example 4 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class LdapRealm method authenticate.

@Override
public AuthRequest authenticate(AuthRequest who) throws AccountException {
    if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
        who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
    }
    final String username = who.getLocalUser();
    try {
        final DirContext ctx;
        if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
            ctx = helper.authenticate(username, who.getPassword());
        } else {
            ctx = helper.open();
        }
        try {
            final Helper.LdapSchema schema = helper.getSchema(ctx);
            LdapQuery.Result m;
            who.setAuthProvidesAccountActiveStatus(true);
            m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
            who.setActive(true);
            if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
                // We found the user account, but we need to verify
                // the password matches it before we can continue.
                // 
                helper.close(helper.authenticate(m.getDN(), who.getPassword()));
            }
            who.setDisplayName(apply(schema.accountFullName, m));
            who.setUserName(apply(schema.accountSshUserName, m));
            if (schema.accountEmailAddress != null) {
                who.setEmailAddress(apply(schema.accountEmailAddress, m));
            } else if (emailExpander.canExpand(username)) {
                // If LDAP cannot give us a valid email address for this user
                // try expanding it through the older email expander code which
                // assumes a user name within a domain.
                // 
                who.setEmailAddress(emailExpander.expand(username));
            }
            // 
            if (fetchMemberOfEagerly || mandatoryGroup != null) {
                Set<AccountGroup.UUID> groups = helper.queryForGroups(ctx, username, m);
                if (mandatoryGroup != null) {
                    GroupReference mandatoryGroupRef = GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
                    if (mandatoryGroupRef == null) {
                        throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
                    }
                    if (!groups.contains(mandatoryGroupRef.getUUID())) {
                        throw new AccountException("Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
                    }
                }
                // Regardless if we enabled fetchMemberOfEagerly, we already have the
                // groups and it would be a waste not to cache them.
                membershipCache.put(username, groups);
            }
            return who;
        } finally {
            helper.close(ctx);
        }
    } catch (IOException | NamingException e) {
        logger.atSevere().withCause(e).log("Cannot query LDAP to authenticate user");
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    } catch (LoginException e) {
        logger.atSevere().withCause(e).log("Cannot authenticate server via JAAS");
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    }
}
Also used : AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) DirContext(javax.naming.directory.DirContext) IOException(java.io.IOException) AccountException(com.google.gerrit.server.account.AccountException) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) GroupReference(com.google.gerrit.entities.GroupReference)

Example 5 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class HttpsClientSslCertAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
    X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null || certs.length == 0) {
        throw new ServletException("Couldn't get the attribute javax.servlet.request.X509Certificate from the request");
    }
    String name = certs[0].getSubjectDN().getName();
    Matcher m = REGEX_USERID.matcher(name);
    String userName;
    if (m.find()) {
        userName = m.group(1);
    } else {
        throw new ServletException("Couldn't extract username from your certificate");
    }
    final AuthRequest areq = authRequestFactory.createForUser(userName);
    final AuthResult arsp;
    try {
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        throw new ServletException("Unable to authenticate user \"" + userName + "\"", e);
    }
    webSession.get().login(arsp, true);
    chain.doFilter(req, rsp);
}
Also used : ServletException(javax.servlet.ServletException) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) Matcher(java.util.regex.Matcher) AuthResult(com.google.gerrit.server.account.AuthResult) X509Certificate(java.security.cert.X509Certificate)

Aggregations

AccountException (com.google.gerrit.server.account.AccountException)36 AuthRequest (com.google.gerrit.server.account.AuthRequest)19 Account (com.google.gerrit.entities.Account)12 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)11 Test (org.junit.Test)10 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)9 AuthResult (com.google.gerrit.server.account.AuthResult)7 ParameterizedString (com.google.gerrit.common.data.ParameterizedString)6 AccountState (com.google.gerrit.server.account.AccountState)5 IOException (java.io.IOException)5 AuthException (com.google.gerrit.extensions.restapi.AuthException)4 AuthenticationUnavailableException (com.google.gerrit.server.auth.AuthenticationUnavailableException)4 HashMap (java.util.HashMap)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 CurrentUser (com.google.gerrit.server.CurrentUser)3 NamingException (javax.naming.NamingException)3 DirContext (javax.naming.directory.DirContext)3 LoginException (javax.security.auth.login.LoginException)3 OAuthLoginProvider (com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider)2