Search in sources :

Example 1 with AccountState

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

the class ElasticTestUtils method createAllIndexes.

static void createAllIndexes(ElasticNodeInfo nodeInfo) {
    Schema<ChangeData> changeSchema = ChangeSchemaDefinitions.INSTANCE.getLatest();
    ChangeMapping openChangesMapping = new ChangeMapping(changeSchema);
    ChangeMapping closedChangesMapping = new ChangeMapping(changeSchema);
    openChangesMapping.closedChanges = null;
    closedChangesMapping.openChanges = null;
    nodeInfo.node.client().admin().indices().prepareCreate(String.format("%s%04d", CHANGES_PREFIX, changeSchema.getVersion())).addMapping(OPEN_CHANGES, gson.toJson(openChangesMapping)).addMapping(CLOSED_CHANGES, gson.toJson(closedChangesMapping)).execute().actionGet();
    Schema<AccountState> accountSchema = AccountSchemaDefinitions.INSTANCE.getLatest();
    AccountMapping accountMapping = new AccountMapping(accountSchema);
    nodeInfo.node.client().admin().indices().prepareCreate(String.format("%s%04d", ACCOUNTS_PREFIX, accountSchema.getVersion())).addMapping(ElasticAccountIndex.ACCOUNTS, gson.toJson(accountMapping)).execute().actionGet();
    Schema<AccountGroup> groupSchema = GroupSchemaDefinitions.INSTANCE.getLatest();
    GroupMapping groupMapping = new GroupMapping(groupSchema);
    nodeInfo.node.client().admin().indices().prepareCreate(String.format("%s%04d", GROUPS_PREFIX, groupSchema.getVersion())).addMapping(ElasticGroupIndex.GROUPS, gson.toJson(groupMapping)).execute().actionGet();
}
Also used : AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) AccountState(com.google.gerrit.server.account.AccountState) AccountMapping(com.google.gerrit.elasticsearch.ElasticAccountIndex.AccountMapping) GroupMapping(com.google.gerrit.elasticsearch.ElasticGroupIndex.GroupMapping) ChangeData(com.google.gerrit.server.query.change.ChangeData) ChangeMapping(com.google.gerrit.elasticsearch.ElasticChangeIndex.ChangeMapping)

Example 2 with AccountState

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

the class FakeAccountCache method put.

public synchronized void put(Account account) {
    AccountState state = newState(account);
    byId.put(account.getId(), state);
    if (account.getUserName() != null) {
        byUsername.put(account.getUserName(), state);
    }
}
Also used : AccountState(com.google.gerrit.server.account.AccountState)

Example 3 with AccountState

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

the class CreateChange method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    if (Strings.isNullOrEmpty(input.project)) {
        throw new BadRequestException("project must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.branch)) {
        throw new BadRequestException("branch must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.subject)) {
        throw new BadRequestException("commit message must be non-empty");
    }
    if (input.status != null) {
        if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
            throw new BadRequestException("unsupported change status");
        }
        if (!allowDrafts && input.status == ChangeStatus.DRAFT) {
            throw new MethodNotAllowedException("draft workflow is disabled");
        }
    }
    String refName = RefNames.fullName(input.branch);
    ProjectResource rsrc = projectsCollection.parse(input.project);
    Capable r = rsrc.getControl().canPushToAtLeastOneRef();
    if (r != Capable.OK) {
        throw new AuthException(r.getMessage());
    }
    RefControl refControl = rsrc.getControl().controlForRef(refName);
    if (!refControl.canUpload() || !refControl.isVisible()) {
        throw new AuthException("cannot upload review");
    }
    Project.NameKey project = rsrc.getNameKey();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        ObjectId parentCommit;
        List<String> groups;
        if (input.baseChange != null) {
            List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
            if (ctls.size() != 1) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            ChangeControl ctl = Iterables.getOnlyElement(ctls);
            if (!ctl.isVisible(db.get())) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
            parentCommit = ObjectId.fromString(ps.getRevision().get());
            groups = ps.getGroups();
        } else {
            Ref destRef = git.getRefDatabase().exactRef(refName);
            if (destRef != null) {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    throw new ResourceConflictException(String.format("Branch %s already exists.", refName));
                }
                parentCommit = destRef.getObjectId();
            } else {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    parentCommit = null;
                } else {
                    throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName));
                }
            }
            groups = Collections.emptyList();
        }
        RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        AccountState account = accountCache.get(me.getAccountId());
        GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
        ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
        ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
        String commitMessage = ChangeIdUtil.insertId(input.subject, id);
        if (Boolean.TRUE.equals(info.signedOffBy)) {
            commitMessage += String.format("%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
        }
        RevCommit c;
        if (input.merge != null) {
            // create a merge commit
            if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
                throw new BadRequestException("Submit type: " + submitType + " is not supported");
            }
            c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
        } else {
            // create an empty commit
            c = newCommit(oi, rw, author, mergeTip, commitMessage);
        }
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
        ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
        String topic = input.topic;
        if (topic != null) {
            topic = Strings.emptyToNull(topic.trim());
        }
        ins.setTopic(topic);
        ins.setDraft(input.status == ChangeStatus.DRAFT);
        ins.setPrivate(input.isPrivate != null && input.isPrivate);
        ins.setWorkInProgress(input.workInProgress != null && input.workInProgress);
        ins.setGroups(groups);
        ins.setNotify(input.notify);
        ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.insertChange(ins);
            bu.execute();
        }
        ChangeJson json = jsonFactory.noOptions();
        return Response.created(json.format(ins.getChange()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Capable(com.google.gerrit.common.data.Capable) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) AccountState(com.google.gerrit.server.account.AccountState) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) ProjectResource(com.google.gerrit.server.project.ProjectResource) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 4 with AccountState

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

the class ContainerAuthFilter method verify.

private boolean verify(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    String username = RemoteUserUtil.getRemoteUser(req, loginHttpHeader);
    if (username == null) {
        rsp.sendError(SC_FORBIDDEN);
        return false;
    }
    if (config.getBoolean("auth", "userNameToLowerCase", false)) {
        username = username.toLowerCase(Locale.US);
    }
    final AccountState who = accountCache.getByUsername(username);
    if (who == null || !who.getAccount().isActive()) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    WebSession ws = session.get();
    ws.setUserAccountId(who.getAccount().getId());
    ws.setAccessPathOk(AccessPath.GIT, true);
    ws.setAccessPathOk(AccessPath.REST_API, true);
    return true;
}
Also used : AccountState(com.google.gerrit.server.account.AccountState)

Example 5 with AccountState

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

the class ProjectBasicAuthFilter method verify.

private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
    final String hdr = req.getHeader(AUTHORIZATION);
    if (hdr == null || !hdr.startsWith(LIT_BASIC)) {
        // session cookie instead of basic authentication.
        return true;
    }
    final byte[] decoded = BaseEncoding.base64().decode(hdr.substring(LIT_BASIC.length()));
    String usernamePassword = new String(decoded, encoding(req));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    String username = usernamePassword.substring(0, splitPos);
    String password = usernamePassword.substring(splitPos + 1);
    if (Strings.isNullOrEmpty(password)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    if (authConfig.isUserNameToLowerCase()) {
        username = username.toLowerCase(Locale.US);
    }
    Optional<AccountState> accountState = accountCache.getByUsername(username).filter(a -> a.account().isActive());
    if (!accountState.isPresent()) {
        logger.atWarning().log("Authentication failed for %s: account inactive or not provisioned in Gerrit", username);
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    AccountState who = accountState.get();
    GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
        if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
            logger.atFine().log("HTTP:%s %s username/password authentication succeeded", req.getMethod(), req.getRequestURI());
            return succeedAuthentication(who, null);
        }
    }
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP) {
        return failAuthentication(rsp, username, req);
    }
    AuthRequest whoAuth = authRequestFactory.createForUser(username);
    whoAuth.setPassword(password);
    try {
        AuthResult whoAuthResult = accountManager.authenticate(whoAuth);
        setUserIdentified(whoAuthResult.getAccountId(), whoAuthResult);
        logger.atFine().log("HTTP:%s %s Realm authentication succeeded", req.getMethod(), req.getRequestURI());
        return true;
    } catch (NoSuchUserException e) {
        if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
            return succeedAuthentication(who, null);
        }
        logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AuthenticationFailedException e) {
        // This exception is thrown if the user provided wrong credentials, we don't need to log a
        // stacktrace for it.
        logger.atWarning().log(authenticationFailedMsg(username, req) + ": %s", e.getMessage());
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AuthenticationUnavailableException e) {
        logger.atSevere().withCause(e).log("could not reach authentication backend");
        rsp.sendError(SC_SERVICE_UNAVAILABLE);
        return false;
    } catch (AccountException e) {
        logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) GitBasicAuthPolicy(com.google.gerrit.extensions.client.GitBasicAuthPolicy) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Aggregations

AccountState (com.google.gerrit.server.account.AccountState)63 Account (com.google.gerrit.entities.Account)37 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)18 IOException (java.io.IOException)17 Test (org.junit.Test)16 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)15 Inject (com.google.inject.Inject)15 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ArrayList (java.util.ArrayList)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 HashSet (java.util.HashSet)11 List (java.util.List)11 ImmutableSet (com.google.common.collect.ImmutableSet)10 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)10 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)10 AccountsUpdate (com.google.gerrit.server.account.AccountsUpdate)10 TestAccount (com.google.gerrit.acceptance.TestAccount)9 Nullable (com.google.gerrit.common.Nullable)9 StorageException (com.google.gerrit.exceptions.StorageException)9