summaryrefslogtreecommitdiffstats
path: root/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
blob: acae533b7e85f59e3beb7445f403d78a5bc2b8ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git.validators;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.events.RefReceivedEvent;
import com.google.gerrit.server.permissions.GlobalPermission;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.plugincontext.PluginSetContext;
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.transport.ReceiveCommand;

public class RefOperationValidators {
  private static final FluentLogger logger = FluentLogger.forEnclosingClass();

  private static final GetErrorMessages GET_ERRORS = new GetErrorMessages();

  public interface Factory {
    RefOperationValidators create(Project project, IdentifiedUser user, ReceiveCommand cmd);
  }

  public static ReceiveCommand getCommand(RefUpdate update, ReceiveCommand.Type type) {
    return new ReceiveCommand(
        update.getExpectedOldObjectId(), update.getNewObjectId(), update.getName(), type);
  }

  private final PermissionBackend.WithUser perm;
  private final AllUsersName allUsersName;
  private final PluginSetContext<RefOperationValidationListener> refOperationValidationListeners;
  private final RefReceivedEvent event;

  @Inject
  RefOperationValidators(
      PermissionBackend permissionBackend,
      AllUsersName allUsersName,
      PluginSetContext<RefOperationValidationListener> refOperationValidationListeners,
      @Assisted Project project,
      @Assisted IdentifiedUser user,
      @Assisted ReceiveCommand cmd) {
    this.perm = permissionBackend.user(user);
    this.allUsersName = allUsersName;
    this.refOperationValidationListeners = refOperationValidationListeners;
    event = new RefReceivedEvent();
    event.command = cmd;
    event.project = project;
    event.user = user;
  }

  public List<ValidationMessage> validateForRefOperation() throws RefOperationValidationException {
    List<ValidationMessage> messages = new ArrayList<>();
    boolean withException = false;
    try {
      messages.addAll(
          new DisallowCreationAndDeletionOfUserBranches(perm, allUsersName).onRefOperation(event));
      refOperationValidationListeners.runEach(
          l -> l.onRefOperation(event), ValidationException.class);
    } catch (ValidationException e) {
      messages.add(new ValidationMessage(e.getMessage(), true));
      withException = true;
    }

    if (withException) {
      throwException(messages, event);
    }

    return messages;
  }

  private void throwException(Iterable<ValidationMessage> messages, RefReceivedEvent event)
      throws RefOperationValidationException {
    Iterable<ValidationMessage> errors = Iterables.filter(messages, GET_ERRORS);
    String header =
        String.format(
            "Ref \"%s\" %S in project %s validation failed",
            event.command.getRefName(), event.command.getType(), event.project.getName());
    logger.atSevere().log(header);
    throw new RefOperationValidationException(header, errors);
  }

  private static class GetErrorMessages implements Predicate<ValidationMessage> {
    @Override
    public boolean apply(ValidationMessage input) {
      return input.isError();
    }
  }

  private static class DisallowCreationAndDeletionOfUserBranches
      implements RefOperationValidationListener {
    private final PermissionBackend.WithUser perm;
    private final AllUsersName allUsersName;

    DisallowCreationAndDeletionOfUserBranches(
        PermissionBackend.WithUser perm, AllUsersName allUsersName) {
      this.perm = perm;
      this.allUsersName = allUsersName;
    }

    @Override
    public List<ValidationMessage> onRefOperation(RefReceivedEvent refEvent)
        throws ValidationException {
      if (refEvent.project.getNameKey().equals(allUsersName)) {
        if (refEvent.command.getRefName().startsWith(RefNames.REFS_USERS)
            && !refEvent.command.getRefName().equals(RefNames.REFS_USERS_DEFAULT)) {
          if (refEvent.command.getType().equals(ReceiveCommand.Type.CREATE)) {
            try {
              perm.check(GlobalPermission.ACCESS_DATABASE);
            } catch (AuthException | PermissionBackendException e) {
              throw new ValidationException("Not allowed to create user branch.");
            }
            if (Account.Id.fromRef(refEvent.command.getRefName()) == null) {
              throw new ValidationException(
                  String.format(
                      "Not allowed to create non-user branch under %s.", RefNames.REFS_USERS));
            }
          } else if (refEvent.command.getType().equals(ReceiveCommand.Type.DELETE)) {
            try {
              perm.check(GlobalPermission.ACCESS_DATABASE);
            } catch (AuthException | PermissionBackendException e) {
              throw new ValidationException("Not allowed to delete user branch.");
            }
          }
        }

        if (RefNames.isGroupRef(refEvent.command.getRefName())) {
          if (refEvent.command.getType().equals(ReceiveCommand.Type.CREATE)) {
            throw new ValidationException("Not allowed to create group branch.");
          } else if (refEvent.command.getType().equals(ReceiveCommand.Type.DELETE)) {
            throw new ValidationException("Not allowed to delete group branch.");
          }
        }
      }
      return ImmutableList.of();
    }
  }
}