Make PermissionBackend#ForRef authoritative
This change fixes a misconception that leads to data being accessible through Gerrit APIs that should be locked down. Gerrit had two components for determining if a Git ref is visible to a user: (Default)RefFilter and PermissionBackend#ForRef (ex RefControl). The former was always capable of providing correct results for all refs. The latter only had logic to decide if a Git ref is visible according to the Gerrit READ permissions. This includes all refs under refs/heads as well as any other ref that isn't a database ref or a Git tag. This component was unware of Git tags and database references. Hence, when asked for a database reference such as refs/changes/xx/yyyyxx/meta the logic would allow access if the user has READ permissions on any of the ref prefixes, such as the default "read refs/* Anonymous Users". That is problematic, because it bypasses documented behavior [1] where a user should only have access to a change if they can see the destination ref. The same goes for other database references. This change fixes the problem. It is intentionally kept to a minimally invasive code change so that it's easier to backport it. Add tests to assert the correct behavior. These tests would fail before this fix. We have included them in this change to be able to backport just a single commit. [1] https://gerrit-review.googlesource.com/Documentation/access-control.html Change-Id: Ice3a756cf573dd9b38e3f198ccc44899ccf65f75
This commit is contained in:
committed by
Marco Miller
parent
e467e71055
commit
2000bacbb7
@@ -288,10 +288,16 @@ public class RefNames {
|
||||
* Whether the ref is managed by Gerrit. Covers all Gerrit-internal refs like refs/cache-automerge
|
||||
* and refs/meta as well as refs/changes. Does not cover user-created refs like branches or custom
|
||||
* ref namespaces like refs/my-company.
|
||||
*
|
||||
* <p>Any ref for which this method evaluates to true will be served to users who have the {@code
|
||||
* ACCESS_DATABASE} capability.
|
||||
*
|
||||
* <p><b>Caution</b>Any ref not in this list will be served if the user was granted a READ
|
||||
* permission on it using Gerrit's permission model.
|
||||
*/
|
||||
public static boolean isGerritRef(String ref) {
|
||||
return ref.startsWith(REFS_CHANGES)
|
||||
|| ref.startsWith(REFS_META)
|
||||
|| ref.startsWith(REFS_EXTERNAL_IDS)
|
||||
|| ref.startsWith(REFS_CACHE_AUTOMERGE)
|
||||
|| ref.startsWith(REFS_DRAFT_COMMENTS)
|
||||
|| ref.startsWith(REFS_DELETED_GROUPS)
|
||||
@@ -299,7 +305,8 @@ public class RefNames {
|
||||
|| ref.startsWith(REFS_GROUPS)
|
||||
|| ref.startsWith(REFS_GROUPNAMES)
|
||||
|| ref.startsWith(REFS_USERS)
|
||||
|| ref.startsWith(REFS_STARRED_CHANGES);
|
||||
|| ref.startsWith(REFS_STARRED_CHANGES)
|
||||
|| ref.startsWith(REFS_REJECT_COMMITS);
|
||||
}
|
||||
|
||||
static Integer parseShardedRefPart(String name) {
|
||||
|
||||
@@ -61,11 +61,12 @@ class ChangeControl {
|
||||
}
|
||||
|
||||
/** Can this user see this change? */
|
||||
private boolean isVisible(ChangeData cd) {
|
||||
if (getChange().isPrivate() && !isPrivateVisible(cd)) {
|
||||
boolean isVisible() {
|
||||
if (getChange().isPrivate() && !isPrivateVisible(changeData)) {
|
||||
return false;
|
||||
}
|
||||
return refControl.isVisible();
|
||||
// Does the user have READ permission on the destination?
|
||||
return refControl.asForRef().testOrFalse(RefPermission.READ);
|
||||
}
|
||||
|
||||
/** Can this user abandon this change? */
|
||||
@@ -201,17 +202,13 @@ class ChangeControl {
|
||||
|
||||
private ForChangeImpl() {}
|
||||
|
||||
private ChangeData changeData() {
|
||||
return changeData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String resourcePath() {
|
||||
if (resourcePath == null) {
|
||||
resourcePath =
|
||||
String.format(
|
||||
"/projects/%s/+changes/%s",
|
||||
getProjectControl().getProjectState().getName(), changeData().getId().get());
|
||||
getProjectControl().getProjectState().getName(), changeData.getId().get());
|
||||
}
|
||||
return resourcePath;
|
||||
}
|
||||
@@ -256,7 +253,7 @@ class ChangeControl {
|
||||
try {
|
||||
switch (perm) {
|
||||
case READ:
|
||||
return isVisible(changeData());
|
||||
return isVisible();
|
||||
case ABANDON:
|
||||
return canAbandon();
|
||||
case DELETE:
|
||||
|
||||
@@ -16,10 +16,7 @@ package com.google.gerrit.server.permissions;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.gerrit.entities.RefNames.REFS_CACHE_AUTOMERGE;
|
||||
import static com.google.gerrit.entities.RefNames.REFS_CONFIG;
|
||||
import static com.google.gerrit.entities.RefNames.REFS_USERS_SELF;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
|
||||
import com.google.auto.value.AutoValue;
|
||||
@@ -29,8 +26,6 @@ import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.flogger.FluentLogger;
|
||||
import com.google.gerrit.common.Nullable;
|
||||
import com.google.gerrit.entities.Account;
|
||||
import com.google.gerrit.entities.AccountGroup;
|
||||
import com.google.gerrit.entities.BranchNameKey;
|
||||
import com.google.gerrit.entities.Change;
|
||||
import com.google.gerrit.entities.Project;
|
||||
@@ -41,13 +36,10 @@ import com.google.gerrit.metrics.Counter0;
|
||||
import com.google.gerrit.metrics.Description;
|
||||
import com.google.gerrit.metrics.MetricMaker;
|
||||
import com.google.gerrit.server.CurrentUser;
|
||||
import com.google.gerrit.server.IdentifiedUser;
|
||||
import com.google.gerrit.server.account.GroupCache;
|
||||
import com.google.gerrit.server.config.GerritServerConfig;
|
||||
import com.google.gerrit.server.git.SearchingChangeCacheImpl;
|
||||
import com.google.gerrit.server.git.TagCache;
|
||||
import com.google.gerrit.server.git.TagMatcher;
|
||||
import com.google.gerrit.server.group.InternalGroup;
|
||||
import com.google.gerrit.server.logging.TraceContext;
|
||||
import com.google.gerrit.server.logging.TraceContext.TraceTimer;
|
||||
import com.google.gerrit.server.notedb.ChangeNotes;
|
||||
@@ -79,8 +71,8 @@ class DefaultRefFilter {
|
||||
private final TagCache tagCache;
|
||||
private final ChangeNotes.Factory changeNotesFactory;
|
||||
@Nullable private final SearchingChangeCacheImpl changeCache;
|
||||
private final GroupCache groupCache;
|
||||
private final PermissionBackend permissionBackend;
|
||||
private final RefVisibilityControl refVisibilityControl;
|
||||
private final ProjectControl projectControl;
|
||||
private final CurrentUser user;
|
||||
private final ProjectState projectState;
|
||||
@@ -96,16 +88,16 @@ class DefaultRefFilter {
|
||||
TagCache tagCache,
|
||||
ChangeNotes.Factory changeNotesFactory,
|
||||
@Nullable SearchingChangeCacheImpl changeCache,
|
||||
GroupCache groupCache,
|
||||
PermissionBackend permissionBackend,
|
||||
RefVisibilityControl refVisibilityControl,
|
||||
@GerritServerConfig Config config,
|
||||
MetricMaker metricMaker,
|
||||
@Assisted ProjectControl projectControl) {
|
||||
this.tagCache = tagCache;
|
||||
this.changeNotesFactory = changeNotesFactory;
|
||||
this.changeCache = changeCache;
|
||||
this.groupCache = groupCache;
|
||||
this.permissionBackend = permissionBackend;
|
||||
this.refVisibilityControl = refVisibilityControl;
|
||||
this.skipFullRefEvaluationIfAllRefsAreVisible =
|
||||
config.getBoolean("auth", "skipFullRefEvaluationIfAllRefsAreVisible", true);
|
||||
this.projectControl = projectControl;
|
||||
@@ -226,131 +218,56 @@ class DefaultRefFilter {
|
||||
logger.atFinest().log("Doing full ref filtering");
|
||||
fullFilterCount.increment();
|
||||
|
||||
boolean viewMetadata;
|
||||
boolean isAdmin;
|
||||
Account.Id userId;
|
||||
IdentifiedUser identifiedUser;
|
||||
PermissionBackend.WithUser withUser = permissionBackend.user(user);
|
||||
if (user.isIdentifiedUser()) {
|
||||
viewMetadata = withUser.testOrFalse(GlobalPermission.ACCESS_DATABASE);
|
||||
isAdmin = withUser.testOrFalse(GlobalPermission.ADMINISTRATE_SERVER);
|
||||
identifiedUser = user.asIdentifiedUser();
|
||||
userId = identifiedUser.getAccountId();
|
||||
logger.atFinest().log(
|
||||
"Account = %d; can view metadata = %s; is admin = %s",
|
||||
userId.get(), viewMetadata, isAdmin);
|
||||
} else {
|
||||
logger.atFinest().log("User is anonymous");
|
||||
viewMetadata = false;
|
||||
isAdmin = false;
|
||||
userId = null;
|
||||
identifiedUser = null;
|
||||
}
|
||||
|
||||
boolean hasAccessDatabase =
|
||||
permissionBackend
|
||||
.user(projectControl.getUser())
|
||||
.testOrFalse(GlobalPermission.ACCESS_DATABASE);
|
||||
List<Ref> resultRefs = new ArrayList<>(refs.size());
|
||||
List<Ref> deferredTags = new ArrayList<>();
|
||||
for (Ref ref : refs) {
|
||||
String name = ref.getName();
|
||||
String refName = ref.getName();
|
||||
Change.Id changeId;
|
||||
Account.Id accountId;
|
||||
AccountGroup.UUID accountGroupUuid;
|
||||
if (name.startsWith(REFS_CACHE_AUTOMERGE)) {
|
||||
continue;
|
||||
} else if (opts.filterMeta() && isMetadata(name)) {
|
||||
logger.atFinest().log("Filter out metadata ref %s", name);
|
||||
continue;
|
||||
} else if (RefNames.isRefsEdit(name)) {
|
||||
// Edits are visible only to the owning user, if change is visible.
|
||||
if (viewMetadata || visibleEdit(repo, name)) {
|
||||
logger.atFinest().log("Include edit ref %s", name);
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out edit ref %s", name);
|
||||
}
|
||||
} else if ((changeId = Change.Id.fromRef(name)) != null) {
|
||||
// Change ref is visible only if the change is visible.
|
||||
if (viewMetadata || visible(repo, changeId)) {
|
||||
logger.atFinest().log("Include change ref %s", name);
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out change ref %s", name);
|
||||
}
|
||||
} else if ((accountId = Account.Id.fromRef(name)) != null) {
|
||||
// Account ref is visible only to the corresponding account.
|
||||
if (viewMetadata || (accountId.equals(userId) && canReadRef(name))) {
|
||||
logger.atFinest().log("Include user ref %s", name);
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out user ref %s", name);
|
||||
}
|
||||
} else if ((accountGroupUuid = AccountGroup.UUID.fromRef(name)) != null) {
|
||||
// Group ref is visible only to the corresponding owner group.
|
||||
InternalGroup group = groupCache.get(accountGroupUuid).orElse(null);
|
||||
if (viewMetadata
|
||||
|| (group != null
|
||||
&& isGroupOwner(group, identifiedUser, isAdmin)
|
||||
&& canReadRef(name))) {
|
||||
logger.atFinest().log("Include group ref %s", name);
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out group ref %s", name);
|
||||
}
|
||||
if (opts.filterMeta() && isMetadata(refName)) {
|
||||
logger.atFinest().log("Filter out metadata ref %s", refName);
|
||||
} else if (isTag(ref)) {
|
||||
if (hasReadOnRefsStar) {
|
||||
// The user has READ on refs/*. This is the broadest permission one can assign. There is
|
||||
// no way to grant access to (specific) tags in Gerrit, so we have to assume that these
|
||||
// users can see all tags because there could be tags that aren't reachable by any visible
|
||||
// ref while the user can see all non-Gerrit refs. This matches Gerrit's historic
|
||||
// behavior.
|
||||
// The user has READ on refs/* with no effective block permission. This is the broadest
|
||||
// permission one can assign. There is no way to grant access to (specific) tags in
|
||||
// Gerrit,
|
||||
// so we have to assume that these users can see all tags because there could be tags that
|
||||
// aren't reachable by any visible ref while the user can see all non-Gerrit refs. This
|
||||
// matches Gerrit's historic behavior.
|
||||
// This makes it so that these users could see commits that they can't see otherwise
|
||||
// (e.g. a private change ref) if a tag was attached to it. Tags are meant to be used on
|
||||
// the regular Git tree that users interact with, not on any of the Gerrit trees, so this
|
||||
// is a negligible risk.
|
||||
logger.atFinest().log("Include tag ref %s because user has read on refs/*", name);
|
||||
logger.atFinest().log("Include tag ref %s because user has read on refs/*", refName);
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
// If its a tag, consider it later.
|
||||
if (ref.getObjectId() != null) {
|
||||
logger.atFinest().log("Defer tag ref %s", name);
|
||||
logger.atFinest().log("Defer tag ref %s", refName);
|
||||
deferredTags.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out tag ref %s that is not a tag", name);
|
||||
logger.atFinest().log("Filter out tag ref %s that is not a tag", refName);
|
||||
}
|
||||
}
|
||||
} else if (name.startsWith(RefNames.REFS_SEQUENCES)) {
|
||||
// Sequences are internal database implementation details.
|
||||
if (viewMetadata) {
|
||||
logger.atFinest().log("Include sequence ref %s", name);
|
||||
} else if ((changeId = Change.Id.fromRef(refName)) != null) {
|
||||
// This is a mere performance optimization. RefVisibilityControl could determine the
|
||||
// visibility of these refs just fine. But instead, we use highly-optimized logic that
|
||||
// looks only on the last 10k most recent changes using the change index and a cache.
|
||||
if (hasAccessDatabase) {
|
||||
resultRefs.add(ref);
|
||||
} else if (!visible(repo, changeId)) {
|
||||
logger.atFinest().log("Filter out invisible change ref %s", refName);
|
||||
} else if (RefNames.isRefsEdit(refName) && !visibleEdit(repo, refName)) {
|
||||
logger.atFinest().log("Filter out invisible change edit ref %s", refName);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out sequence ref %s", name);
|
||||
}
|
||||
} else if (projectState.isAllUsers()
|
||||
&& (name.equals(RefNames.REFS_EXTERNAL_IDS) || name.equals(RefNames.REFS_GROUPNAMES))) {
|
||||
// The notes branches with the external IDs / group names must not be exposed to normal
|
||||
// users.
|
||||
if (viewMetadata) {
|
||||
logger.atFinest().log("Include external IDs branch %s", name);
|
||||
// Change is visible
|
||||
resultRefs.add(ref);
|
||||
} else {
|
||||
logger.atFinest().log("Filter out external IDs branch %s", name);
|
||||
}
|
||||
} else if (canReadRef(ref.getLeaf().getName())) {
|
||||
// Use the leaf to lookup the control data. If the reference is
|
||||
// symbolic we want the control around the final target. If its
|
||||
// not symbolic then getLeaf() is a no-op returning ref itself.
|
||||
logger.atFinest().log(
|
||||
"Include ref %s because its leaf %s is readable", name, ref.getLeaf().getName());
|
||||
} else if (refVisibilityControl.isVisible(projectControl, ref.getLeaf().getName())) {
|
||||
resultRefs.add(ref);
|
||||
} else if (isRefsUsersSelf(ref)) {
|
||||
// viewMetadata allows to see all account refs, hence refs/users/self should be included as
|
||||
// well
|
||||
if (viewMetadata) {
|
||||
logger.atFinest().log("Include ref %s", REFS_USERS_SELF);
|
||||
resultRefs.add(ref);
|
||||
}
|
||||
} else {
|
||||
logger.atFinest().log("Filter out ref %s", name);
|
||||
}
|
||||
}
|
||||
Result result = new AutoValue_DefaultRefFilter_Result(resultRefs, deferredTags);
|
||||
@@ -373,7 +290,8 @@ class DefaultRefFilter {
|
||||
r ->
|
||||
!RefNames.isGerritRef(r.getName())
|
||||
&& !r.getName().startsWith(RefNames.REFS_TAGS)
|
||||
&& !r.isSymbolic())
|
||||
&& !r.isSymbolic()
|
||||
&& !r.getName().equals(RefNames.REFS_CONFIG))
|
||||
// Don't use the default Java Collections.toList() as that is not size-aware and would
|
||||
// expand an array list as new elements are added. Instead, provide a list that has the
|
||||
// right size. This spares incremental list expansion which is quadratic in complexity.
|
||||
@@ -519,10 +437,6 @@ class DefaultRefFilter {
|
||||
return ref.getLeaf().getName().startsWith(Constants.R_TAGS);
|
||||
}
|
||||
|
||||
private static boolean isRefsUsersSelf(Ref ref) {
|
||||
return ref.getName().startsWith(REFS_USERS_SELF);
|
||||
}
|
||||
|
||||
private boolean canReadRef(String ref) throws PermissionBackendException {
|
||||
try {
|
||||
permissionBackendForProject.ref(ref).check(RefPermission.READ);
|
||||
@@ -543,17 +457,6 @@ class DefaultRefFilter {
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isGroupOwner(
|
||||
InternalGroup group, @Nullable IdentifiedUser user, boolean isAdmin) {
|
||||
requireNonNull(group);
|
||||
|
||||
// Keep this logic in sync with GroupControl#isOwner().
|
||||
boolean isGroupOwner =
|
||||
isAdmin || (user != null && user.getEffectiveGroups().contains(group.getOwnerGroupUUID()));
|
||||
logger.atFinest().log("User is owner of group %s = %s", group.getGroupUUID(), isGroupOwner);
|
||||
return isGroupOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the user can see the provided change ref. Uses NoteDb for evaluation, hence
|
||||
* does not suffer from the limitations documented in {@link SearchingChangeCacheImpl}.
|
||||
|
||||
@@ -38,6 +38,7 @@ import com.google.gerrit.server.CurrentUser;
|
||||
import com.google.gerrit.server.account.GroupMembership;
|
||||
import com.google.gerrit.server.config.GitReceivePackGroups;
|
||||
import com.google.gerrit.server.config.GitUploadPackGroups;
|
||||
import com.google.gerrit.server.git.GitRepositoryManager;
|
||||
import com.google.gerrit.server.group.SystemGroupBackend;
|
||||
import com.google.gerrit.server.notedb.ChangeNotes;
|
||||
import com.google.gerrit.server.permissions.PermissionBackend.ForChange;
|
||||
@@ -68,6 +69,8 @@ class ProjectControl {
|
||||
private final Set<AccountGroup.UUID> uploadGroups;
|
||||
private final Set<AccountGroup.UUID> receiveGroups;
|
||||
private final PermissionBackend permissionBackend;
|
||||
private final RefVisibilityControl refVisibilityControl;
|
||||
private final GitRepositoryManager repositoryManager;
|
||||
private final CurrentUser user;
|
||||
private final ProjectState state;
|
||||
private final PermissionCollection.Factory permissionFilter;
|
||||
@@ -84,6 +87,8 @@ class ProjectControl {
|
||||
@GitReceivePackGroups Set<AccountGroup.UUID> receiveGroups,
|
||||
PermissionCollection.Factory permissionFilter,
|
||||
PermissionBackend permissionBackend,
|
||||
RefVisibilityControl refVisibilityControl,
|
||||
GitRepositoryManager repositoryManager,
|
||||
DefaultRefFilter.Factory refFilterFactory,
|
||||
ChangeData.Factory changeDataFactory,
|
||||
@Assisted CurrentUser who,
|
||||
@@ -92,6 +97,8 @@ class ProjectControl {
|
||||
this.receiveGroups = receiveGroups;
|
||||
this.permissionFilter = permissionFilter;
|
||||
this.permissionBackend = permissionBackend;
|
||||
this.refVisibilityControl = refVisibilityControl;
|
||||
this.repositoryManager = repositoryManager;
|
||||
this.refFilterFactory = refFilterFactory;
|
||||
this.changeDataFactory = changeDataFactory;
|
||||
user = who;
|
||||
@@ -117,7 +124,9 @@ class ProjectControl {
|
||||
RefControl ctl = refControls.get(refName);
|
||||
if (ctl == null) {
|
||||
PermissionCollection relevant = permissionFilter.filter(access(), refName, user);
|
||||
ctl = new RefControl(changeDataFactory, this, refName, relevant);
|
||||
ctl =
|
||||
new RefControl(
|
||||
changeDataFactory, refVisibilityControl, this, repositoryManager, refName, relevant);
|
||||
refControls.put(refName, ctl);
|
||||
}
|
||||
return ctl;
|
||||
@@ -442,7 +451,7 @@ class ProjectControl {
|
||||
return canPushToAtLeastOneRef();
|
||||
|
||||
case READ_CONFIG:
|
||||
return controlForRef(RefNames.REFS_CONFIG).isVisible();
|
||||
return controlForRef(RefNames.REFS_CONFIG).hasReadPermissionOnRef(false);
|
||||
|
||||
case BAN_COMMIT:
|
||||
case READ_REFLOG:
|
||||
|
||||
@@ -16,6 +16,7 @@ package com.google.gerrit.server.permissions;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.flogger.FluentLogger;
|
||||
import com.google.gerrit.entities.Change;
|
||||
import com.google.gerrit.entities.Permission;
|
||||
@@ -28,23 +29,31 @@ import com.google.gerrit.exceptions.StorageException;
|
||||
import com.google.gerrit.extensions.conditions.BooleanCondition;
|
||||
import com.google.gerrit.extensions.restapi.AuthException;
|
||||
import com.google.gerrit.server.CurrentUser;
|
||||
import com.google.gerrit.server.git.GitRepositoryManager;
|
||||
import com.google.gerrit.server.logging.CallerFinder;
|
||||
import com.google.gerrit.server.notedb.ChangeNotes;
|
||||
import com.google.gerrit.server.permissions.PermissionBackend.ForChange;
|
||||
import com.google.gerrit.server.permissions.PermissionBackend.ForRef;
|
||||
import com.google.gerrit.server.query.change.ChangeData;
|
||||
import com.google.gerrit.server.util.MagicBranch;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.eclipse.jgit.lib.Constants;
|
||||
import org.eclipse.jgit.lib.Ref;
|
||||
import org.eclipse.jgit.lib.Repository;
|
||||
|
||||
/** Manages access control for Git references (aka branches, tags). */
|
||||
class RefControl {
|
||||
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
|
||||
|
||||
private final ChangeData.Factory changeDataFactory;
|
||||
private final RefVisibilityControl refVisibilityControl;
|
||||
private final ProjectControl projectControl;
|
||||
private final GitRepositoryManager repositoryManager;
|
||||
private final String refName;
|
||||
|
||||
/** All permissions that apply to this reference. */
|
||||
@@ -57,15 +66,19 @@ class RefControl {
|
||||
private Boolean owner;
|
||||
private Boolean canForgeAuthor;
|
||||
private Boolean canForgeCommitter;
|
||||
private Boolean isVisible;
|
||||
private Boolean hasReadPermissionOnRef;
|
||||
|
||||
RefControl(
|
||||
ChangeData.Factory changeDataFactory,
|
||||
RefVisibilityControl refVisibilityControl,
|
||||
ProjectControl projectControl,
|
||||
GitRepositoryManager repositoryManager,
|
||||
String ref,
|
||||
PermissionCollection relevant) {
|
||||
this.changeDataFactory = changeDataFactory;
|
||||
this.refVisibilityControl = refVisibilityControl;
|
||||
this.projectControl = projectControl;
|
||||
this.repositoryManager = repositoryManager;
|
||||
this.refName = ref;
|
||||
this.relevant = relevant;
|
||||
this.callerFinder =
|
||||
@@ -98,12 +111,27 @@ class RefControl {
|
||||
return owner;
|
||||
}
|
||||
|
||||
/** Can this user see this reference exists? */
|
||||
boolean isVisible() {
|
||||
if (isVisible == null) {
|
||||
isVisible = getUser().isInternalUser() || canPerform(Permission.READ);
|
||||
/**
|
||||
* Returns {@code true} if the user has permission to read the ref. This method evaluates {@link
|
||||
* RefPermission#READ} only. Hence, it is not authoritative. For example, it does not tell if the
|
||||
* user can see NoteDb refs such as {@code refs/meta/external-ids} which requires {@link
|
||||
* GlobalPermission#ACCESS_DATABASE} and deny access in this case.
|
||||
*/
|
||||
boolean hasReadPermissionOnRef(boolean allowNoteDbRefs) {
|
||||
// Don't allow checking for NoteDb refs unless instructed otherwise.
|
||||
if (!allowNoteDbRefs
|
||||
&& (refName.startsWith(Constants.R_TAGS) || RefNames.isGerritRef(refName))) {
|
||||
logger.atWarning().atMostEvery(30, TimeUnit.SECONDS).log(
|
||||
"%s: Can't determine visibility of %s in RefControl. Denying access. "
|
||||
+ "This case should have been handled before.",
|
||||
projectControl.getProject().getName(), refName);
|
||||
return false;
|
||||
}
|
||||
return isVisible;
|
||||
|
||||
if (hasReadPermissionOnRef == null) {
|
||||
hasReadPermissionOnRef = getUser().isInternalUser() || canPerform(Permission.READ);
|
||||
}
|
||||
return hasReadPermissionOnRef;
|
||||
}
|
||||
|
||||
/** @return true if this user can add a new patch set to this ref */
|
||||
@@ -578,7 +606,10 @@ class RefControl {
|
||||
private boolean can(RefPermission perm) throws PermissionBackendException {
|
||||
switch (perm) {
|
||||
case READ:
|
||||
return isVisible();
|
||||
if (refName.startsWith(Constants.R_TAGS)) {
|
||||
return isTagVisible();
|
||||
}
|
||||
return refVisibilityControl.isVisible(projectControl, refName);
|
||||
case CREATE:
|
||||
// TODO This isn't an accurate test.
|
||||
return canPerform(refPermissionName(perm));
|
||||
@@ -628,6 +659,38 @@ class RefControl {
|
||||
}
|
||||
throw new PermissionBackendException(perm + " unsupported");
|
||||
}
|
||||
|
||||
private boolean isTagVisible() throws PermissionBackendException {
|
||||
if (projectControl.asForProject().test(ProjectPermission.READ)) {
|
||||
// The user has READ on refs/* with no effective block permission. This is the broadest
|
||||
// permission one can assign. There is no way to grant access to (specific) tags in Gerrit,
|
||||
// so we have to assume that these users can see all tags because there could be tags that
|
||||
// aren't reachable by any visible ref while the user can see all non-Gerrit refs. This
|
||||
// matches Gerrit's historic behavior.
|
||||
// This makes it so that these users could see commits that they can't see otherwise
|
||||
// (e.g. a private change ref) if a tag was attached to it. Tags are meant to be used on
|
||||
// the regular Git tree that users interact with, not on any of the Gerrit trees, so this
|
||||
// is a negligible risk.
|
||||
return true;
|
||||
}
|
||||
|
||||
try (Repository repo =
|
||||
repositoryManager.openRepository(projectControl.getProject().getNameKey())) {
|
||||
// Tag visibility requires going through RefFilter because it entails loading all taggable
|
||||
// refs and filtering them all by visibility.
|
||||
Ref resolvedRef = repo.getRefDatabase().exactRef(refName);
|
||||
if (resolvedRef == null) {
|
||||
return false;
|
||||
}
|
||||
return projectControl.asForProject()
|
||||
.filter(
|
||||
ImmutableList.of(resolvedRef), repo, PermissionBackend.RefFilterOptions.defaults())
|
||||
.stream()
|
||||
.anyMatch(r -> refName.equals(r.getName()));
|
||||
} catch (IOException e) {
|
||||
throw new PermissionBackendException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String refPermissionName(RefPermission refPermission) {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// Copyright (C) 2020 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.permissions;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static com.google.gerrit.entities.RefNames.REFS_CACHE_AUTOMERGE;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.flogger.FluentLogger;
|
||||
import com.google.gerrit.entities.Account;
|
||||
import com.google.gerrit.entities.AccountGroup;
|
||||
import com.google.gerrit.entities.Change;
|
||||
import com.google.gerrit.entities.RefNames;
|
||||
import com.google.gerrit.exceptions.NoSuchGroupException;
|
||||
import com.google.gerrit.exceptions.StorageException;
|
||||
import com.google.gerrit.extensions.restapi.AuthException;
|
||||
import com.google.gerrit.server.CurrentUser;
|
||||
import com.google.gerrit.server.account.GroupControl;
|
||||
import com.google.gerrit.server.project.NoSuchChangeException;
|
||||
import com.google.gerrit.server.query.change.ChangeData;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
import org.eclipse.jgit.lib.Constants;
|
||||
|
||||
/**
|
||||
* This class is a component that is internal to {@link DefaultPermissionBackend}. It can
|
||||
* authoritatively tell if a ref is accessible by a user.
|
||||
*/
|
||||
@Singleton
|
||||
class RefVisibilityControl {
|
||||
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
|
||||
|
||||
private final PermissionBackend permissionBackend;
|
||||
private final GroupControl.GenericFactory groupControlFactory;
|
||||
private final ChangeData.Factory changeDataFactory;
|
||||
|
||||
@Inject
|
||||
RefVisibilityControl(
|
||||
PermissionBackend permissionBackend,
|
||||
GroupControl.GenericFactory groupControlFactory,
|
||||
ChangeData.Factory changeDataFactory) {
|
||||
this.permissionBackend = permissionBackend;
|
||||
this.groupControlFactory = groupControlFactory;
|
||||
this.changeDataFactory = changeDataFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an authoritative answer if the ref is visible to the user. Does not have support for
|
||||
* tags and will throw a {@link PermissionBackendException} if asked for tags visibility.
|
||||
*/
|
||||
boolean isVisible(ProjectControl projectControl, String refName)
|
||||
throws PermissionBackendException {
|
||||
if (refName.startsWith(Constants.R_TAGS)) {
|
||||
throw new PermissionBackendException(
|
||||
"can't check tags through RefVisibilityControl. Use PermissionBackend#filter instead.");
|
||||
}
|
||||
if (!RefNames.isGerritRef(refName)) {
|
||||
// This is not a special Gerrit ref and not a NoteDb ref. Likely, it's just a ref under
|
||||
// refs/heads or another ref the user created. Apply the regular permissions with inheritance.
|
||||
return projectControl.controlForRef(refName).hasReadPermissionOnRef(false);
|
||||
}
|
||||
|
||||
if (refName.startsWith(REFS_CACHE_AUTOMERGE)) {
|
||||
// Internal cache state that is accessible to no one.
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean hasAccessDatabase =
|
||||
permissionBackend
|
||||
.user(projectControl.getUser())
|
||||
.testOrFalse(GlobalPermission.ACCESS_DATABASE);
|
||||
if (hasAccessDatabase) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Change and change edit visibility
|
||||
Change.Id changeId;
|
||||
if ((changeId = Change.Id.fromRef(refName)) != null) {
|
||||
// Change ref is visible only if the change is visible.
|
||||
ChangeData cd;
|
||||
try {
|
||||
cd = changeDataFactory.create(projectControl.getProject().getNameKey(), changeId);
|
||||
checkState(cd.change().getId().equals(changeId));
|
||||
} catch (StorageException e) {
|
||||
if (Throwables.getCausalChain(e).stream()
|
||||
.anyMatch(e2 -> e2 instanceof NoSuchChangeException)) {
|
||||
// The change was deleted or is otherwise not accessible anymore.
|
||||
// If the caller can see all refs and is allowed to see private changes on refs/, allow
|
||||
// access. This is an escape hatch for receivers of "ref deleted" events.
|
||||
PermissionBackend.ForProject forProject = projectControl.asForProject();
|
||||
return forProject.test(ProjectPermission.READ)
|
||||
&& forProject.ref("refs/").test(RefPermission.READ_PRIVATE_CHANGES);
|
||||
}
|
||||
throw new PermissionBackendException(e);
|
||||
}
|
||||
if (RefNames.isRefsEdit(refName)) {
|
||||
// Edits are visible only to the owning user, if change is visible.
|
||||
return visibleEdit(refName, projectControl, cd);
|
||||
}
|
||||
return projectControl.controlFor(cd).isVisible();
|
||||
}
|
||||
|
||||
// Account visibility
|
||||
CurrentUser user = projectControl.getUser();
|
||||
Account.Id currentUserAccountId = user.isIdentifiedUser() ? user.getAccountId() : null;
|
||||
Account.Id accountId;
|
||||
if ((accountId = Account.Id.fromRef(refName)) != null) {
|
||||
// Account ref is visible only to the corresponding account.
|
||||
if (accountId.equals(currentUserAccountId)
|
||||
&& projectControl.controlForRef(refName).hasReadPermissionOnRef(true)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Group visibility
|
||||
AccountGroup.UUID accountGroupUuid;
|
||||
if ((accountGroupUuid = AccountGroup.UUID.fromRef(refName)) != null) {
|
||||
// Group ref is visible only to the corresponding owner group.
|
||||
try {
|
||||
return projectControl.controlForRef(refName).hasReadPermissionOnRef(true)
|
||||
&& groupControlFactory.controlFor(user, accountGroupUuid).isOwner();
|
||||
} catch (NoSuchGroupException e) {
|
||||
// The group is broken, but the ref is still around. Pretend the ref is not visible.
|
||||
logger.atWarning().withCause(e).log("Found group ref %s but group isn't parsable", refName);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// We are done checking all cases where we would allow access to Gerrit-managed refs. Deny
|
||||
// access in case we got this far.
|
||||
logger.atFine().log(
|
||||
"Denying access to %s because user doesn't have access to this Gerrit ref", refName);
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean visibleEdit(String refName, ProjectControl projectControl, ChangeData cd)
|
||||
throws PermissionBackendException {
|
||||
Change.Id id = Change.Id.fromEditRefPart(refName);
|
||||
if (id == null) {
|
||||
throw new IllegalStateException("unable to parse change id from edit ref " + refName);
|
||||
}
|
||||
|
||||
if (!projectControl.controlFor(cd).isVisible()) {
|
||||
// The user can't see the change so they can't see any edits.
|
||||
return false;
|
||||
}
|
||||
|
||||
if (projectControl.getUser().isIdentifiedUser()
|
||||
&& refName.startsWith(
|
||||
RefNames.refsEditPrefix(projectControl.getUser().asIdentifiedUser().getAccountId()))) {
|
||||
logger.atFinest().log("Own change edit ref is visible: %s", refName);
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
// Default to READ_PRIVATE_CHANGES as there is no special permission for reading edits.
|
||||
projectControl
|
||||
.asForProject()
|
||||
.ref(cd.change().getDest().branch())
|
||||
.check(RefPermission.READ_PRIVATE_CHANGES);
|
||||
logger.atFinest().log("Foreign change edit ref is visible: %s", refName);
|
||||
return true;
|
||||
} catch (AuthException e) {
|
||||
logger.atFinest().log("Foreign change edit ref is not visible: %s", refName);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user