PrincipalManagerImpl.java

/*
 * Copyright (c) 2007-2026 MetaSolutions AB
 *
 * 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 org.entrystore.impl;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.entrystore.AuthorizationException;
import org.entrystore.Entry;
import org.entrystore.EntryType;
import org.entrystore.GraphType;
import org.entrystore.Group;
import org.entrystore.PrincipalManager;
import org.entrystore.User;
import org.entrystore.repository.RepositoryEvent;
import org.entrystore.repository.RepositoryEventObject;
import org.entrystore.repository.config.Settings;
import org.entrystore.repository.security.Password;
import org.entrystore.repository.util.URISplit;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;


/**
 * Creates a
 * @author Olov Wikberg, IML Umeå University
 * @author matthias
 * @author Hannes Ebner
 *
 */
@Slf4j
public class PrincipalManagerImpl extends EntryNamesContext implements PrincipalManager {

	private static final ThreadLocal<URI> authenticatedUserURI = new ThreadLocal<>();
	@Getter
	public User adminUser = null;
	@Getter
	public Group adminGroup = null;
	@Getter
	public User guestUser = null;
	@Getter
	public Group userGroup = null;

	private static final String ENV_ADMIN_PASSWORD = "ENTRYSTORE_ADMIN_PASSWORD";

	/**
	 * A user's group set together with the invalidation epoch it was computed under.
	 * {@link #groupsIfCurrent(AtomicLong)} is the only way a reader should obtain the set: it hands the set out
	 * while the stamp is current and null once an invalidation has moved the epoch on, so correctness rests on the
	 * stamp, not on clearing the map.
	 */
	record CachedGroups(long epoch, Set<URI> groups) {

		CachedGroups {
			groups = Set.copyOf(groups);
		}

		/**
		 * Takes the counter rather than a sampled value, so the record is necessarily in hand before the epoch is
		 * read. Sampling first and passing the number would let a reader accept a set that a loader published,
		 * under the epoch the reader saw, after the invalidation that should have rejected it.
		 */
		Set<URI> groupsIfCurrent(AtomicLong currentEpoch) {
			return epoch == currentEpoch.get() ? groups : null;
		}
	}

	/** The result of one principals-context scan; only an authoritative scan may be cached. Package-private for tests. */
	record GroupScan(Set<URI> groups, boolean authoritative) {

		/** The only way to build a cache entry, so a scan taken over a short listing cannot be published by mistake. */
		CachedGroups toCacheEntry(long epoch) {
			if (!authoritative) {
				throw new IllegalStateException("only an authoritative scan may be cached");
			}
			return new CachedGroups(epoch, groups);
		}
	}

	/**
	 * User resource URI to that user's {@link CachedGroups}: the immutable set {@link #scanGroups(URI)} found,
	 * stamped with the epoch it was scanned under. An entry stamped with an older epoch is never served and is
	 * replaced by that user's next authoritative scan; the map is never cleared, so it holds at most one entry per
	 * principal that has made a group-consulting decision since startup, and a deleted user's entry is evicted.
	 */
	private final Map<URI, CachedGroups> userGroupsCache = new ConcurrentHashMap<>();

	/**
	 * Bumped by every group-sourced event the invalidator is registered for (see {@link #onRepositoryEvent}). A
	 * reader compares a cached stamp against it after reading
	 * the value, so a decision that starts after an invalidation can never accept a set computed before it, however
	 * the two interleave; a loader also publishes only while the epoch it read before scanning is still current.
	 */
	private final AtomicLong userGroupsCacheEpoch = new AtomicLong();

	/**
	 * Entry URIs {@link #scanGroups(URI)} has already reported as listed in the index but not loadable. The scan
	 * runs on the authorization decision path, so warning on every occurrence would put an unbounded log write
	 * there: each URI is warned about once per {@code PrincipalManagerImpl} instance and logged at debug
	 * afterwards.
	 * <p>
	 * It only grows, and is bounded by the number of distinct principal entries that have ever failed to load for
	 * this instance — not by the number dangling right now. Only a deletion can produce that condition, never a
	 * creation: {@code addToIndex} collects into the transaction's pending operations and applies them after the
	 * commit, so an entry is never listed before it is loadable, whereas {@code ContextImpl.remove} commits,
	 * applies the index operations and only then evicts the cache, leaving a scan whose listing predates the
	 * removal to resolve that URI to null.
	 */
	private final Set<URI> reportedUnloadableEntries = ConcurrentHashMap.newKeySet();

	/**
	 * Whether a scan taken over an incomplete principals index has already been reported. Such a scan decides the
	 * request from a possibly short listing and is never
	 * cached, so without this the only trace of a denial caused by a broken index is whatever
	 * {@code ContextImpl.loadIndexes} logged when the statement failed to index, possibly hours earlier. Reported
	 * once for the same reason the unloadable entries are: the scan is on the decision path. It deliberately does
	 * not cover an unresolvable principal, which is routine and client-triggerable — a request carrying a session
	 * for a deleted user reaches the scan — and would otherwise consume the report before the index condition it
	 * exists for ever occurred.
	 */
	private final java.util.concurrent.atomic.AtomicBoolean reportedNonAuthoritativeScan =
			new java.util.concurrent.atomic.AtomicBoolean();

	@Getter(AccessLevel.PACKAGE)
	private final boolean groupCacheEnabled;

	/**
	 * Creates a principal manager
	 * @param entry this principal managers entry
	 * @param uri this principal managers URI
	 * @param softCache
	 */
	public PrincipalManagerImpl(EntryImpl entry, String uri, SoftCache softCache) {
		super(entry, uri, softCache);
		this.groupCacheEnabled = entry.getRepositoryManager().getConfiguration()
				.getBoolean(Settings.AUTH_GROUP_CACHE, true);
	}


	public String getPrincipalName(URI principal) {
		Entry principalEntry = null;
		User u = getUser(principal);
		if (u != null) {
			principalEntry = u.getEntry();
		} else {
			Group g = getGroup(principal);
			if (g != null) {
				principalEntry = g.getEntry();
			}
		}

		if (principalEntry == null) {
			throw new org.entrystore.repository.RepositoryException("Unable to resolve URI into principal: " + principal);
		}

		checkAuthenticatedUserAuthorized(principalEntry, AccessProperty.ReadMetadata);
		return getName(principalEntry.getEntryURI());
	}

	public Entry getPrincipalEntry(String name) {
		Entry principalEntry = getEntryByName(name.toLowerCase());
		if (principalEntry == null) {
			return null;
		} else if (principalEntry.getGraphType() == GraphType.User ||
						principalEntry.getGraphType() == GraphType.Group) {
			return principalEntry;
		}
		throw new org.entrystore.repository.RepositoryException("""
				Found entry for the name is not a principal...
				this is either a programming error or someone have been tampering with the RDF directly.""");
	}

	public boolean setPrincipalName(URI principal, String newName) {
		if (principal == null || newName == null) {
			throw new IllegalArgumentException("Parameters must not be null");
		}
		String noZeroLengthSpaceName = newName.replaceAll("[\\p{Cf}]", "");
		String trimmedName = org.apache.commons.lang3.StringUtils.trimToNull(noZeroLengthSpaceName);
		if (trimmedName == null) {
			throw new IllegalArgumentException("Principal name must not be null");
		}
		String normalizedName = trimmedName.toLowerCase();
		URISplit us = new URISplit(principal, this.entry.getRepositoryManager().getRepositoryURL());
		Entry principalEntry = getByEntryURI(us.getMetaMetadataURI());
		if (principalEntry == null) {
			throw new org.entrystore.repository.RepositoryException("Cannot find an entry for the specified URI");
		} else if (principalEntry.getGraphType() == GraphType.User || principalEntry.getGraphType() == GraphType.Group) {
			return setEntryName(us.getMetaMetadataURI(), normalizedName);
		}
		throw new org.entrystore.repository.RepositoryException("Given URI does not refer to a Principal.");
	}

    public boolean isUserAdminOrAdminGroup(URI principal) {
		URI currentUserURI = getAuthenticatedUserURI();
		if (principal == null) {
			principal = currentUserURI;
		}
		URI adminUserURI = getAdminUser().getURI();

		try {
			setAuthenticatedUserURI(adminUserURI);
			User user = getUser(principal);
			if (adminUserURI.equals(principal) || getAdminGroup().isMember(user)) {
				return true;
			}
		} finally {
			setAuthenticatedUserURI(currentUserURI);
		}

		return false;
    }


    /**
	 * Returns this principal managers all user URIs
	 * @return all user URIs in this principal manager
	 */
	public List<URI> getUsersAsUris() {
		Iterator <URI> entryIterator = getEntries().iterator();
		List<URI> userUris = new ArrayList<>();

		//sort out the users
		while(entryIterator.hasNext()) {
			URI nextURI = entryIterator.next();

			Entry nextEntry = getByEntryURI(nextURI);
			if(nextEntry.getGraphType() == GraphType.User) {
				userUris.add(nextEntry.getResourceURI());
			}
		}

		return userUris;
	}

	/**
	 * Returns this principal managers all user URIs
	 * @return all user URIs in this principal manager
	 */
	public List<User> getUsers() {
		Iterator<URI> entryIterator = getEntries().iterator();
		List<User> userUris = new ArrayList<>();

		//sort out the users
		while(entryIterator.hasNext()) {
			URI nextURI = entryIterator.next();

			Entry nextEntry = getByEntryURI(nextURI);
			if(nextEntry.getGraphType() == GraphType.User) {
				userUris.add((User) nextEntry.getResource());
			}
		}

		return userUris;
	}


	/**
	 * Returns a User object representing a user.
	 * @param userUri The URI to the user.
	 * @return the User object
	 */
	public User getUser(URI userUri) {
		for(Entry user: getByResourceURI(userUri)) {
			if (user.getGraphType() == GraphType.User) {
				return (User) user.getResource();
			}
		}
		return null;
	}

	/**
	 * Returns a Group object representing a group of users.
	 * @param groupUri URI to the group.
	 * @return the Group object
	 */
	public Group getGroup(URI groupUri) {
		for(Entry user: getByResourceURI(groupUri)) {
			if (user.getGraphType() == GraphType.Group) {
				return (Group) user.getResource();
			}
		}
		return null;
	}

	public Set <URI> getGroupUris() {
		Iterator <URI> entryIterator = getEntries().iterator();
		Set <URI> groupUris = new HashSet<>();

		//sort out the groups
		while(entryIterator.hasNext()) {
			URI nextURI = entryIterator.next();

			Entry nextGroup = getByEntryURI(nextURI);
			if (GraphType.Group.equals(nextGroup.getGraphType())) {
				groupUris.add(nextGroup.getResourceURI());
			}
		}

		return groupUris;
	}

	/**
	 * Mutable snapshot of a fresh scan, regardless of whether it was authoritative. Production decisions go through
	 * {@link #getGroupUrisCached(URI)}; this is for the cache's disabled branch and for tests.
	 */
	Set<URI> getGroupUris(URI userUri) {
		return new HashSet<>(scanGroups(userUri).groups());
	}

	/**
	 * Scans the principals context for the groups {@code userUri} belongs to. The scan is authoritative only when
	 * the user resolved and {@link #isIndexComplete()} held both before the listing was taken and after it was
	 * consumed, so the two samples bracket the listing: a short listing (ENTRYSTORE-1095) or an unresolvable
	 * principal is a per-decision denial, and caching it would hold that denial until the next group write,
	 * because index repair fires no repository event of its own. A listed entry the store cannot produce is
	 * skipped without counting against the scan, so one stale index triple cannot disable the cache for the whole
	 * instance; the cost of that choice is that a dangling mapping naming a group the user belongs to yields a
	 * denial that holds until the next group write, which is why it is warned about. A group deleted while the
	 * scan runs fires EntryDeleted, which bumps the epoch and rejects the scan's publication. Package-private so
	 * a test can hold a scan back.
	 */
	GroupScan scanGroups(URI userUri) {
		Set<URI> groupUris = new HashSet<>();

		User user = getUser(userUri);
		if (user == null) {
			return new GroupScan(groupUris, false);
		}
		boolean indexCompleteBeforeListing = isIndexComplete();
		for (URI nextURI : getEntries()) {
			Entry nextEntry = getByEntryURI(nextURI);
			if (nextEntry == null) {
				if (reportedUnloadableEntries.add(nextURI)) {
					log.warn("Entry {} is listed in the principals index but could not be loaded (deleted "
							+ "concurrently, or a stale index mapping); it is skipped in the group scan, and "
							+ "further occurrences of this URI are logged at debug level", nextURI);
				} else {
					log.debug("Entry {} is listed in the principals index but could not be loaded; skipping it "
							+ "in the group scan", nextURI);
				}
				continue;
			}
			if (GraphType.Group.equals(nextEntry.getGraphType())
					&& nextEntry.getResource() instanceof Group nextGroup && nextGroup.isMember(user)) {
				groupUris.add(nextGroup.getURI());
			}
		}
		boolean authoritative = indexCompleteBeforeListing && isIndexComplete();
		if (!authoritative && reportedNonAuthoritativeScan.compareAndSet(false, true)) {
			log.warn("The principals index is incomplete, so group memberships are being read from a possibly "
					+ "short listing and no scan is cached until it is repaired. Further occurrences are logged "
					+ "at debug level.");
		} else if (!authoritative) {
			log.debug("Group scan over an incomplete principals index; the result is not cached");
		}
		return new GroupScan(groupUris, authoritative);
	}

	/**
	 * Cache-fronted {@link #scanGroups(URI)}. The returned set is immutable in both branches. A cached set is served
	 * only while its stamp equals the current epoch (value read first, epoch second); otherwise the principals
	 * context is scanned again, and the result is published only when the scan is authoritative and the epoch did
	 * not move while it ran, so a scan that overlaps a group write is either not published or stamped with an epoch
	 * the write's own event has already left behind. Concurrent misses for one user may scan in parallel, and a
	 * scan that was not authoritative is repeated on that user's next decision.
	 */
	Set<URI> getGroupUrisCached(URI userURI) {
		if (!groupCacheEnabled) {
			return Set.copyOf(scanGroups(userURI).groups());
		}
		CachedGroups cached = userGroupsCache.get(userURI);
		if (cached != null) {
			Set<URI> current = cached.groupsIfCurrent(userGroupsCacheEpoch);
			if (current != null) {
				return current;
			}
		}
		long epochBefore = userGroupsCacheEpoch.get();
		GroupScan scan = scanGroups(userURI);
		if (scan.authoritative() && userGroupsCacheEpoch.get() == epochBefore) {
			CachedGroups published = scan.toCacheEntry(epochBefore);
			userGroupsCache.put(userURI, published);
			return published.groups();
		}
		return Set.copyOf(scan.groups());
	}

	/** Read-only view for tests; keys are user resource URIs, a value may carry a stale epoch. */
	Map<URI, CachedGroups> cachedGroupsView() {
		return Collections.unmodifiableMap(userGroupsCache);
	}

	/** Read-only view for tests, so the warn-once suppression is observable rather than only visible in a log. */
	Set<URI> reportedUnloadableEntriesView() {
		return Collections.unmodifiableSet(reportedUnloadableEntries);
	}

	/**
	 * Keeps {@link #userGroupsCache} consistent with the repository. A {@link RepositoryEventObject} carries no
	 * previous state, so any event sourced from a Group entry invalidates every cached set by bumping the epoch
	 * (directory mutations are rare next to decisions), while a deleted User drops only its own key. Registered for
	 * EntryCreated, EntryUpdated, ResourceUpdated, RelationsUpdated and EntryDeleted: the post-commit events through
	 * which a group's member list can change, including the ResourceUpdated {@code ListImpl} fires from a failed
	 * member-list write. Metadata-only events cannot change membership and are not subscribed; ResourceDeleted
	 * fires inside the transaction and is followed by EntryDeleted. Runs synchronously under the repository's
	 * listener monitor, so it only touches the map and the counter and never reads the repository.
	 * <p>
	 * Never throws a RuntimeException: dispatch would only log it, and the change behind the event would then stay
	 * unseen by the cache, so a revoked membership could keep granting access. A failure clears the whole cache.
	 */
	void onRepositoryEvent(RepositoryEventObject eventObject) {
		if (!(eventObject.getSource() instanceof Entry source)) {
			return;
		}
		try {
			switch (source.getGraphType()) {
				case Group -> invalidateGroupCache();
				case User -> {
					if (eventObject.getEvent() == RepositoryEvent.EntryDeleted) {
						evictFromGroupCache(source.getResourceURI());
					}
				}
				default -> { }
			}
		} catch (RuntimeException e) {
			log.error("Failed to apply {} to the user-to-groups cache; clearing the whole cache",
					eventObject.getEvent(), e);
			invalidateGroupCache();
			userGroupsCache.clear();
		}
	}

	private void invalidateGroupCache() {
		userGroupsCacheEpoch.incrementAndGet();
	}

	/**
	 * A loader racing this removal may re-publish the deleted user's set; that entry is inert, because
	 * {@link #hasAccess} fails closed before consulting the cache once the principal no longer resolves.
	 */
	private void evictFromGroupCache(URI userURI) {
		userGroupsCache.remove(userURI);
	}

	public List<URI> getGroupEntryUris() {
		Iterator < URI > entryIterator = getEntries().iterator();
		List<URI> groupUris = new ArrayList<>();

		//sort out the groups
		while(entryIterator.hasNext()) {
			URI nextURI = entryIterator.next();
			Entry e = getByEntryURI(nextURI);
			if(e.getGraphType() == GraphType.Group) {
				groupUris.add(nextURI);
			}
		}

		return groupUris;
	}

	/**
	 * Sets which user that is authenticated in this specific thread.
	 * @param userUri The URI to the user that was authenticated.
	 */
	public void setAuthenticatedUserURI(URI userUri) {
		authenticatedUserURI.set(userUri);
	}

	public URI getAuthenticatedUserURI() {
		return authenticatedUserURI.get();
	}

	@Override
	public boolean currentUserIsGuest() {
		URI currentUserUri = authenticatedUserURI.get();
		return currentUserUri == null || getGuestUser().getURI().equals(currentUserUri);
	}

	@Override
	public boolean currentUserIsAdminOrAdminGroup() {
		URI currentUserUri = authenticatedUserURI.get();
		return isUserAdminOrAdminGroup(currentUserUri);
	}

	@Override
	public Set<URI> getAclPrincipalsOfAuthenticatedUser() {
		URI currentUserURI = getAuthenticatedUserURI();
		URI guestURI = getGuestUser().getURI();
		URI userURI = currentUserURI != null ? currentUserURI : guestURI;
		try {
			// as in checkAuthenticatedUserAuthorized: resolving principals must not be hindered by their own ACLs
			setAuthenticatedUserURI(getAdminUser().getURI());
			if (getUser(userURI) == null) {
				return Set.of();
			}
			Set<URI> principals = new HashSet<>(getGroupUrisCached(userURI));
			principals.add(userURI);
			principals.add(guestURI);
			if (!guestURI.equals(userURI)) {
				principals.add(getUserGroup().getURI());
			}
			return Set.copyOf(principals);
		} finally {
			setAuthenticatedUserURI(currentUserURI);
		}
	}

	/**
	 * Checks if the authenticated user it authorized to perform a specific task on a Entry. The task is defined by an access property.
	 * @param entry the entry on which to check the specified accessProperty.
	 * @param accessProperty the access property to check the entry for.
	 * @throws AuthorizationException if not allowed.
	 */
	public void checkAuthenticatedUserAuthorized(Entry entry, AccessProperty accessProperty) throws AuthorizationException {

		//is check authorization on?
		if(!entry.getRepositoryManager().isCheckForAuthorization()) {
			return;
		}

		URI currentUserURI = getAuthenticatedUserURI();

		//is anyone logged in on this thread?
		if (currentUserURI == null) {
			currentUserURI = getGuestUser().getURI();
			log.warn("Authenticated user not set, assuming guest user");
		}

		//is admin?
		if(currentUserURI.equals(getAdminUser().getURI())) {
			return;
		}

		if (currentUserURI.equals(entry.getResourceURI()) &&
				(accessProperty == AccessProperty.ReadMetadata || accessProperty == AccessProperty.ReadResource)) {
			return;
		}

		try {
			//Switch to admin so that the PrincipalManager can perform all
			//neccessary checks without being hindered by itself (results in loops).
			setAuthenticatedUserURI(getAdminUser().getURI());

			//Fetch the current user from thread local.
			User currentUser = getUser(currentUserURI);

			//Check if user is in admingroup.
			if (getAdminGroup().isMember(currentUser)) {
				return;
			}

			Entry contextEntry = entry.getContext().getEntry();
			//Check if user is owner of surrounding context
			if (hasAccess(currentUser, contextEntry, AccessProperty.Administer)) {
				return;
			} else {
				//If entry overrides Context ACL (only relevant if the user is not an owner of the context)
				if(entry.hasAllowedPrincipals()) {
					if (hasAccess(currentUser, entry, AccessProperty.Administer)
                    || hasAccess(currentUser, entry, accessProperty)) {
						return;
					} else if (accessProperty == AccessProperty.ReadMetadata
                            && hasAccess(currentUser, entry, AccessProperty.WriteMetadata)) {
                        return; //WriteMetadata implies ReadMetadata
                    } else if (accessProperty == AccessProperty.ReadResource
                        && hasAccess(currentUser, entry, AccessProperty.WriteResource)) {
                        return; //WriteResource implies ReadResource
                    }
				} else {
					//Check if user has access to the surrounding context of the entry.
					if (accessProperty == AccessProperty.ReadMetadata || accessProperty == AccessProperty.ReadResource) {
						if (hasAccess(currentUser, contextEntry, AccessProperty.ReadResource)
                                || hasAccess(currentUser, contextEntry, AccessProperty.WriteResource)) {
							return; //Both read and write on the context resource implies read on all entries for both the metadata and the resource.
						}
					} else {
						if (hasAccess(currentUser, contextEntry, AccessProperty.WriteResource)) {
							return;
						}
					}
				}
			}

			throw new AuthorizationException(currentUser, entry, accessProperty);
		} finally {
			//Switch back to the current user.
			setAuthenticatedUserURI(currentUserURI);
		}
	}

	protected boolean hasAccess(User currentUser, Entry entry, AccessProperty prop) {
		if (currentUser == null) {
			// Fail closed on a principal that could not be resolved. Without this, the "_users" check below
			// reads currentUser != getGuestUser() as true, so every entry granting the user group would be
			// granted to an unresolvable principal, and the check after it dereferences null. getUser
			// returns null whenever the principal's resHasEntry mapping is unreadable — for instance from a
			// context whose index is incomplete (ENTRYSTORE-1095) — and "I could not read the principal"
			// must not answer the same as "this principal is allowed".
			//
			// This deliberately returns before the guest check below, so an unresolvable principal is also
			// denied entries that are explicitly guest-readable: a session carrying the URI of a deleted
			// user entry loses access to public content it could read before. That is the conservative
			// direction — the alternative is to keep serving a session whose principal we demonstrably
			// cannot read, and public content is reachable by simply not authenticating.
			log.warn("Denying {} access: the authenticated principal could not be resolved to a user", prop);
			return false;
		}
		URI userURI = currentUser.getURI();
		Set<URI> principals = entry.getAllowedPrincipalsFor(prop);
		if (!principals.isEmpty()) {

			//Check if guest is in principals.
			if (principals.contains(getGuestUser().getURI())) {
				return true;
			}

			//Check if the special "user" group is in principals and user is not guest.
			if (currentUser != getGuestUser() && principals.contains(getUserGroup().getURI())) {
				return true;
			}

			if (matchesUserOrItsGroups(userURI, principals)) {
				return true;
			}
		}

		if (prop != AccessProperty.Administer) {
			principals = entry.getAllowedPrincipalsFor(AccessProperty.Administer);
			if (!principals.isEmpty()) {

				return matchesUserOrItsGroups(userURI, principals);
			}
		}
		return false;
	}

	/** The one rule both ACL branches of {@link #hasAccess} apply: the principals name the user or one of its groups. */
	private boolean matchesUserOrItsGroups(URI userURI, Set<URI> principals) {
		return principals.contains(userURI) || !Collections.disjoint(getGroupUrisCached(userURI), principals);
	}

	public Set<AccessProperty> getRights(Entry entry) {
		Set<AccessProperty> set = new HashSet<>();
		//is check authorization on?
		if(!entry.getRepositoryManager().isCheckForAuthorization()) {
			set.add(AccessProperty.Administer);
			return set;
		}

		URI currentUserURI = getAuthenticatedUserURI();

		//is anyone logged in on this thread?
		if (currentUserURI == null) {
			//TODO, should we perhaps assume guest if none set?
			log.error("Authenticated user not set, should at least be guest");
			throw new AuthorizationException(null, entry, null);
		}

		//is admin?
		if(currentUserURI.equals(getAdminUser().getURI())) {
			set.add(AccessProperty.Administer);
			return set;
		}

		try {
			//Switch to admin so that the PrincipalManager can perform all
			//neccessary checks without being hindered by itself (results in loops).
			setAuthenticatedUserURI(getAdminUser().getURI());

			//Fetch the current user from thread local.
			User currentUser = getUser(currentUserURI);

			//Check if user is in admingroup.
			if (getAdminGroup().isMember(currentUser)) {
				set.add(AccessProperty.Administer);
				return set;
			}

			Entry contextEntry = entry.getContext().getEntry();
			//Check if user is owner of surrounding context
			if (hasAccess(currentUser, contextEntry, AccessProperty.Administer)) {
				set.add(AccessProperty.Administer);
			} else {
				//If entry overrides Context ACL (only relevant if the user is not an owner of the context)
				if(entry.hasAllowedPrincipals()) {
					if (hasAccess(currentUser, entry, AccessProperty.Administer)) {
						set.add(AccessProperty.Administer);
						return set;
					} else {
						if (hasAccess(currentUser, entry, AccessProperty.WriteMetadata)) {
							set.add(AccessProperty.WriteMetadata);
						} else if (hasAccess(currentUser, entry, AccessProperty.ReadMetadata)) {
							set.add(AccessProperty.ReadMetadata);
						}
						if (hasAccess(currentUser, entry, AccessProperty.WriteResource)) {
							set.add(AccessProperty.WriteResource);
						} else if (hasAccess(currentUser, entry, AccessProperty.ReadResource)) {
							set.add(AccessProperty.ReadResource);
						}
					}
				} else {
					if (hasAccess(currentUser, contextEntry, AccessProperty.WriteResource)) {
						set.add(AccessProperty.Administer);
					} else if (hasAccess(currentUser, contextEntry, AccessProperty.ReadResource)) {
						set.add(AccessProperty.ReadMetadata);
						set.add(AccessProperty.ReadResource);
					}
				}
			}
		} finally {
			//Switch back to the current user.
			setAuthenticatedUserURI(currentUserURI);
		}
		return set;
	}


	/**
	 * Checks if a secret is valid.
	 * @param secret Secret to be checked.
	 * @return true If the secret fullfils minimum requirements, currently a minimum length of 8 characters.
	 */
	public boolean isValidSecret(String secret) {
		return Password.conformsToRules(secret);
	}

	@Override
	public void initResource(EntryImpl newEntry) throws RepositoryException {
		if (newEntry.getEntryType() != EntryType.Local) {
			return;
		}
		switch (newEntry.getGraphType()) {
		case User:
			newEntry.setResource(new UserImpl(newEntry, newEntry.getSesameResourceURI(), softCache));
			break;
		case Group:
			newEntry.setResource(new GroupImpl(newEntry, newEntry.getSesameResourceURI(), softCache));
			break;
		default:
			super.initResource(newEntry);
		}
	}

	public void initializeSystemEntries() {
		super.initializeSystemEntries();
		Entry adminUserEntry;
		Entry adminGroupEntry;
		Entry userGroupEntry;
		Entry guestUserEntry;

		guestUserEntry = get("_guest");
		if (guestUserEntry != null) {
			guestUser = (User) guestUserEntry.getResource();
		} else {
			guestUserEntry = this.createNewMinimalItem(null, null, EntryType.Local, GraphType.User, null, "_guest");
			setMetadata(guestUserEntry, "Guest user", "All non logged in users will automatically appear as this user.");
			guestUser = (User) guestUserEntry.getResource();
			guestUser.setName("guest");
			guestUserEntry.addAllowedPrincipalsFor(AccessProperty.ReadMetadata, guestUser.getURI());
			log.info("Successfully added the guest user");
		}
		addSystemEntryToSystemEntries(guestUserEntry.getEntryURI());


		adminUserEntry = get("_admin");
		if (adminUserEntry != null) {
			adminUser = (User) adminUserEntry.getResource();
		} else {
			adminUserEntry = this.createNewMinimalItem(null, null, EntryType.Local, GraphType.User, null, "_admin");
			setMetadata(adminUserEntry, "Admin user", "Default super user, has all rights.");
			adminUser = (User) adminUserEntry.getResource();
			adminUser.setName("admin");
			String adminSecret = System.getenv(ENV_ADMIN_PASSWORD);
			if (adminSecret != null) {
				log.info("Setting admin password based on environment variable {}", ENV_ADMIN_PASSWORD);
				if (!adminUser.setSecret(adminSecret)) {
					log.warn("Password in environment variable does not conform to configured rules, initializing admin user without password");
				}
			} else {
				log.warn("Environment variable {} not found, initializing admin user without password", ENV_ADMIN_PASSWORD);
			}
			adminUserEntry.addAllowedPrincipalsFor(AccessProperty.ReadMetadata, guestUser.getURI());
			log.info("Successfully added the admin user");
		}
		addSystemEntryToSystemEntries(adminUserEntry.getEntryURI());

		adminGroupEntry = get("_admins");
		if(adminGroupEntry != null) {
			adminGroup = (Group) adminGroupEntry.getResource();
		} else {
			adminGroupEntry = this.createNewMinimalItem(null, null, EntryType.Local, GraphType.Group, null, "_admins");
			setMetadata(adminGroupEntry, "Admin group", "All members of this group have super user rights.");
			adminGroup = (Group) adminGroupEntry.getResource();
			adminGroup.setName("admins");
			adminGroupEntry.addAllowedPrincipalsFor(AccessProperty.ReadMetadata, guestUser.getURI());
			log.info("Successfully added the admin group");
		}
		addSystemEntryToSystemEntries(adminGroupEntry.getEntryURI());

		userGroupEntry = get("_users");
		if(userGroupEntry == null) {
			userGroupEntry = this.createNewMinimalItem(null, null, EntryType.Local, GraphType.Group, null, "_users");
			setMetadata(userGroupEntry, "Users group", "All regular users are part of this group.");
			setPrincipalName(userGroupEntry.getResourceURI(), "users");
			userGroupEntry.addAllowedPrincipalsFor(AccessProperty.ReadMetadata, guestUser.getURI());
			log.info("Successfully added the user group");
		}
		EntryImpl e = (EntryImpl) userGroupEntry;
		e.setResource(new SystemGroup(e, e.getSesameResourceURI()) {
			@Override
			public boolean isMember(User user) {
				return (user != null &&
						PrincipalManagerImpl.this.guestUser != null &&
						!user.getURI().equals(PrincipalManagerImpl.this.guestUser.getURI()));
				// return true;
			}
			@Override
			public List<User> members() {
                this.entry.getRepositoryManager().getPrincipalManager().checkAuthenticatedUserAuthorized(this.entry, AccessProperty.ReadResource);
                return getUsers();
			}
			@Override
			public List<URI> memberUris() {
                this.entry.getRepositoryManager().getPrincipalManager().checkAuthenticatedUserAuthorized(this.entry, AccessProperty.ReadResource);
                return getUsersAsUris();
			}
		});

		userGroup = (Group) userGroupEntry.getResource();
		addSystemEntryToSystemEntries(userGroupEntry.getEntryURI());
	}

}