Clean up registrar console login flow

Replaced the plethora of inter winding access functions and inputs in SessionUtils with just 2 functions, that both accept the same type for the user (AuthResult):

guessRegistrarForUser: given an AuthResult, finds a registrar that they have access to. If none is found - a ForbiddenException is thrown.

getRegistrarForUser[Cached]: (maybe should be called getRegistrarOnBehalfOfUser?) given an AuthResult and a clientId, loads and returns the registrar ONLY IF the user has access to it. Otherwise throws a ForbiddenException.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=214630657
This commit is contained in:
guyben 2018-09-26 10:53:14 -07:00 committed by jianglai
parent 6bddd5a8cb
commit 84a0ace2ea
16 changed files with 431 additions and 523 deletions

View file

@ -58,7 +58,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
@ -81,17 +80,23 @@ public class RdapDomainActionTest {
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private RdapDomainAction action;
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
@ -262,7 +267,6 @@ public class RdapDomainActionTest {
action = new RdapDomainAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.response = response;
@ -272,19 +276,17 @@ public class RdapDomainActionTest {
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.authResult = AUTH_RESULT;
action.rdapMetrics = rdapMetrics;
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn(clientId);
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT_ADMIN)).thenReturn("irrelevant");
action.authResult = AUTH_RESULT_ADMIN;
}
private Object generateActualJson(String domainName) {

View file

@ -71,7 +71,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@ -91,14 +90,21 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
@Rule public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapDomainSearchAction action = new RdapDomainSearchAction();
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
private FakeResponse response = new FakeResponse();
private Registrar registrar;
@ -388,7 +394,6 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
clock.nowUtc()));
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.requestUrl = "https://example.com/rdap/domains";
@ -401,22 +406,20 @@ public class RdapDomainSearchActionTest extends RdapSearchActionTestCase {
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.authResult = AUTH_RESULT;
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
action.rdapResultSetMaxSize = 4;
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn(clientId);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn("irrelevant");
action.authResult = AUTH_RESULT_ADMIN;
metricRole = ADMINISTRATOR;
}

View file

@ -53,7 +53,6 @@ import google.registry.ui.server.registrar.SessionUtils;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
@ -74,13 +73,9 @@ public class RdapEntityActionTest {
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private RdapEntityAction action;
@ -92,6 +87,16 @@ public class RdapEntityActionTest {
private ContactResource disconnectedContact;
private ContactResource deletedContact;
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
@ -163,7 +168,6 @@ public class RdapEntityActionTest {
clock.nowUtc().minusMonths(6));
action = new RdapEntityAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.response = response;
@ -173,19 +177,17 @@ public class RdapEntityActionTest {
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
action.rdapWhoisServer = null;
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.authResult = AUTH_RESULT;
action.rdapMetrics = rdapMetrics;
}
private void login(String registrar) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(registrar);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn(registrar);
}
private void loginAsAdmin() {
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AUTH_RESULT_ADMIN;
when(sessionUtils.guessClientIdForUser(AUTH_RESULT_ADMIN)).thenReturn("irrelevant");
}
private Object generateActualJson(String name) {

View file

@ -59,7 +59,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@ -82,12 +81,8 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
HANDLE
}
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapEntitySearchAction action = new RdapEntitySearchAction();
private FakeResponse response = new FakeResponse();
@ -132,6 +127,16 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
return JSONValue.parse(response.getPayload());
}
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
@ -182,7 +187,6 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
clock.nowUtc().minusMonths(6));
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.com/rdap";
action.requestUrl = "https://example.com/rdap/entities";
@ -199,21 +203,19 @@ public class RdapEntitySearchActionTest extends RdapSearchActionTestCase {
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.sessionUtils = sessionUtils;
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.authResult = AUTH_RESULT;
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
}
private void login(String registrar) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(registrar);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn(registrar);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("noregistrar");
action.authResult = AUTH_RESULT_ADMIN;
when(sessionUtils.guessClientIdForUser(AUTH_RESULT_ADMIN)).thenReturn("irrelevant");
metricRole = ADMINISTRATOR;
}

View file

@ -35,6 +35,7 @@ import google.registry.rdap.RdapMetrics.SearchType;
import google.registry.rdap.RdapMetrics.WildcardType;
import google.registry.rdap.RdapSearchResults.IncompletenessWarningType;
import google.registry.request.Action;
import google.registry.request.HttpException.ForbiddenException;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
@ -46,7 +47,6 @@ import google.registry.ui.server.registrar.SessionUtils;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONValue;
import org.junit.Before;
@ -67,15 +67,21 @@ public class RdapNameserverActionTest {
@Rule
public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapMetrics rdapMetrics = mock(RdapMetrics.class);
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
@ -106,8 +112,7 @@ public class RdapNameserverActionTest {
private RdapNameserverAction newRdapNameserverAction(
String input, Optional<String> desiredRegistrar, Optional<Boolean> includeDeleted) {
return newRdapNameserverAction(
input, desiredRegistrar, includeDeleted, AuthResult.create(AuthLevel.USER, userAuthInfo));
return newRdapNameserverAction(input, desiredRegistrar, includeDeleted, AUTH_RESULT);
}
private RdapNameserverAction newRdapNameserverAction(
@ -117,7 +122,6 @@ public class RdapNameserverActionTest {
AuthResult authResult) {
RdapNameserverAction action = new RdapNameserverAction();
action.clock = clock;
action.request = request;
action.requestMethod = Action.Method.GET;
action.fullServletPath = "https://example.tld/rdap";
action.response = response;
@ -358,23 +362,21 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_notFound_notLoggedIn() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(false);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenThrow(new ForbiddenException("blah"));
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true));
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedNameserver_notFound_loggedInAsDifferentRegistrar() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("otherregistrar");
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn("otherregistrar");
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true));
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void testDeletedNameserver_found_loggedInAsCorrectRegistrar() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn("TheRegistrar");
assertThat(
generateActualJson("nsdeleted.cat.lol", Optional.empty(), Optional.of(true)))
.isEqualTo(
@ -391,13 +393,12 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_found_loggedInAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
when(sessionUtils.guessClientIdForUser(AUTH_RESULT_ADMIN)).thenReturn("irrelevant");
newRdapNameserverAction(
"nsdeleted.cat.lol",
Optional.empty(),
Optional.of(true),
AuthResult.create(AuthLevel.USER, adminUserAuthInfo))
AUTH_RESULT_ADMIN)
.run();
assertThat(JSONValue.parse(response.getPayload()))
.isEqualTo(
@ -414,8 +415,7 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_found_sameRegistrarRequested() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn("TheRegistrar");
assertThat(
generateActualJson("nsdeleted.cat.lol", Optional.of("TheRegistrar"), Optional.of(true)))
.isEqualTo(
@ -432,8 +432,7 @@ public class RdapNameserverActionTest {
@Test
public void testDeletedNameserver_notFound_differentRegistrarRequested() {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn("TheRegistrar");
generateActualJson("ns1.cat.lol", Optional.of("otherregistrar"), Optional.of(false));
assertThat(response.getStatus()).isEqualTo(404);
}

View file

@ -58,7 +58,6 @@ import google.registry.ui.server.registrar.SessionUtils;
import java.net.URLDecoder;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@ -77,15 +76,22 @@ public class RdapNameserverSearchActionTest extends RdapSearchActionTestCase {
@Rule public final InjectRule inject = new InjectRule();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private FakeResponse response = new FakeResponse();
private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01T00:00:00Z"));
private final SessionUtils sessionUtils = mock(SessionUtils.class);
private final User user = new User("rdap.user@example.com", "gmail.com", "12345");
private final UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
private final UserAuthInfo adminUserAuthInfo = UserAuthInfo.create(user, true);
private final RdapNameserverSearchAction action = new RdapNameserverSearchAction();
private static final AuthResult AUTH_RESULT =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@user.com", "gmail.com", "12345"), false));
private static final AuthResult AUTH_RESULT_ADMIN =
AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(new User("rdap.user@google.com", "gmail.com", "12345"), true));
private DomainResource domainCatLol;
private HostResource hostNs1CatLol;
private HostResource hostNs2CatLol;
@ -183,7 +189,6 @@ public class RdapNameserverSearchActionTest extends RdapSearchActionTestCase {
action.requestUrl = "https://example.tld/rdap/nameservers";
action.requestPath = RdapNameserverSearchAction.PATH;
action.parameterMap = ImmutableListMultimap.of();
action.request = request;
action.requestMethod = Action.Method.GET;
action.response = response;
action.rdapJsonFormatter = RdapTestHelper.getTestRdapJsonFormatter();
@ -194,22 +199,19 @@ public class RdapNameserverSearchActionTest extends RdapSearchActionTestCase {
action.registrarParam = Optional.empty();
action.includeDeletedParam = Optional.empty();
action.formatOutputParam = Optional.empty();
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
action.authResult = AUTH_RESULT;
action.sessionUtils = sessionUtils;
action.rdapMetrics = rdapMetrics;
action.cursorTokenParam = Optional.empty();
}
private void login(String clientId) {
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn(clientId);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT)).thenReturn(clientId);
metricRole = REGISTRAR;
}
private void loginAsAdmin() {
when(sessionUtils.checkRegistrarConsoleLogin(request, adminUserAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("irrelevant");
action.authResult = AuthResult.create(AuthLevel.USER, adminUserAuthInfo);
when(sessionUtils.guessClientIdForUser(AUTH_RESULT_ADMIN)).thenReturn("irrelevant");
action.authResult = AUTH_RESULT_ADMIN;
metricRole = ADMINISTRATOR;
}

View file

@ -16,6 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.net.HttpHeaders.LOCATION;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
@ -24,6 +25,7 @@ import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.net.MediaType;
import google.registry.request.HttpException.ForbiddenException;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
@ -70,10 +72,11 @@ public class ConsoleUiActionTest {
action.sessionUtils = sessionUtils;
action.userService = UserServiceFactory.getUserService();
action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
UserAuthInfo userAuthInfo = UserAuthInfo.create(user, false);
action.authResult = AuthResult.create(AuthLevel.USER, userAuthInfo);
when(sessionUtils.checkRegistrarConsoleLogin(request, userAuthInfo)).thenReturn(true);
when(sessionUtils.getRegistrarClientId(request)).thenReturn("TheRegistrar");
AuthResult authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.authResult = authResult;
when(sessionUtils.guessClientIdForUser(authResult)).thenReturn("TheRegistrar");
when(sessionUtils.getRegistrarForUser("TheRegistrar", authResult))
.thenReturn(loadRegistrar("TheRegistrar"));
}
@Test
@ -110,9 +113,8 @@ public class ConsoleUiActionTest {
@Test
public void testUserDoesntHaveAccessToAnyRegistrar_showsWhoAreYouPage() {
when(sessionUtils.checkRegistrarConsoleLogin(
any(HttpServletRequest.class), any(UserAuthInfo.class)))
.thenReturn(false);
when(sessionUtils.guessClientIdForUser(any(AuthResult.class)))
.thenThrow(new ForbiddenException("forbidden"));
action.run();
assertThat(response.getPayload()).contains("<h1>You need permission</h1>");
}

View file

@ -22,19 +22,15 @@ import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static google.registry.testing.TestDataHelper.loadFile;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.export.sheet.SyncRegistrarsSheetAction;
import google.registry.model.registrar.Registrar;
import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.ForbiddenException;
import google.registry.request.auth.AuthResult;
import google.registry.testing.CertificateSamples;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CidrAddressBlock;
@ -42,7 +38,6 @@ import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.junit.Test;
@ -82,39 +77,27 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
assertNoTasksEnqueued("sheet");
}
/**
* Make sure that if someone spoofs a different registrar (they don't have access to), we fail.
* Also relevant if the person's privilege were revoked after the page load.
*/
@Test
public void testRead_notAuthorized_failure() {
when(sessionUtils.getRegistrarForAuthResult(
any(HttpServletRequest.class), any(AuthResult.class)))
.thenThrow(new ForbiddenException("Not authorized to access Registrar Console"));
assertThrows(ForbiddenException.class, () -> action.handleJsonRequest(ImmutableMap.of()));
public void testFailure_readRegistrarInfo_notAuthorized() {
action.authResult = USER_UNAUTHORIZED;
assertThrows(
ForbiddenException.class, () -> action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID)));
assertNoTasksEnqueued("sheet");
}
/**
* This is the default read test for the registrar settings actions.
*/
/** This is the default read test for the registrar settings actions. */
@Test
public void testSuccess_readRegistrarInfo_authorized() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of("id", CLIENT_ID));
assertThat(response).containsExactly(
"status", "SUCCESS",
"message", "Success",
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
}
/**
* We got a different CLIENT_ID from the JS than the one we find ourself.
*
* <p>This might happen if the user's "guessed" registrar changes after the initial page load. For
* example, if the user was added as contact to a different registrar, or removed as contact from
* the current registrar (but is still a contact of a different one, so the "guessing" works).
*/
@Test
public void testFailure_readRegistrarInfo_differentClientId() {
assertThrows(
BadRequestException.class,
() -> action.handleJsonRequest(ImmutableMap.of("id", "different")));
assertThat(response)
.containsExactly(
"status", "SUCCESS",
"message", "Success",
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
}
@Test
@ -159,6 +142,19 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
}
@Test
public void testFailute_updateRegistrarInfo_notAuthorized() {
action.authResult = USER_UNAUTHORIZED;
assertThrows(
ForbiddenException.class,
() ->
action.handleJsonRequest(
ImmutableMap.of(
"op", "update",
"id", CLIENT_ID,
"args", ImmutableMap.of("lastUpdateTime", getLastUpdateTime()))));
}
@Test
public void testUpdate_badEmail_errorEmailField() {
Map<String, Object> response = action.handleJsonRequest(ImmutableMap.of(

View file

@ -24,6 +24,7 @@ import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.model.ofy.Ofy;
import google.registry.request.HttpException.ForbiddenException;
import google.registry.request.JsonActionRunner;
import google.registry.request.JsonResponse;
import google.registry.request.ResponseImpl;
@ -57,6 +58,13 @@ public class RegistrarSettingsActionTestCase {
static final String CLIENT_ID = "TheRegistrar";
static final AuthResult USER_AUTHORIZED =
AuthResult.create(AuthLevel.USER, UserAuthInfo.create(new User("user", "gmail.com"), false));
static final AuthResult USER_UNAUTHORIZED =
AuthResult.create(
AuthLevel.USER, UserAuthInfo.create(new User("unauthorized", "gmail.com"), false));
@Rule
public final AppEngineRule appEngine =
AppEngineRule.builder().withDatastore().withTaskQueue().build();
@ -79,11 +87,10 @@ public class RegistrarSettingsActionTestCase {
@Before
public void setUp() throws Exception {
action.request = req;
action.sessionUtils = sessionUtils;
action.appEngineServiceUtils = appEngineServiceUtils;
when(appEngineServiceUtils.getCurrentVersionHostname("backend")).thenReturn("backend.hostname");
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.authResult = USER_AUTHORIZED;
action.jsonActionRunner = new JsonActionRunner(
ImmutableMap.of(), new JsonResponse(new ResponseImpl(rsp)));
action.registrarChangesNotificationEmailAddresses = ImmutableList.of(
@ -102,7 +109,9 @@ public class RegistrarSettingsActionTestCase {
// the result is out of date after mutations.
// (for example, if someone wants to change the registrar to prepare for a test, the function
// would still return the old value)
when(sessionUtils.getRegistrarForAuthResult(req, action.authResult))
when(sessionUtils.getRegistrarForUser(CLIENT_ID, USER_AUTHORIZED))
.thenAnswer(x -> loadRegistrar(CLIENT_ID));
when(sessionUtils.getRegistrarForUser(CLIENT_ID, USER_UNAUTHORIZED))
.thenThrow(new ForbiddenException("forbidden"));
}
}

View file

@ -24,7 +24,6 @@ import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar;
@ -112,8 +111,6 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
.setClientCertificate(SAMPLE_CERT, START_OF_TIME)
.setFailoverClientCertificate(SAMPLE_CERT2, START_OF_TIME)
.build());
when(sessionUtils.getRegistrarForAuthResult(req, action.authResult))
.thenReturn(initialRegistrar);
Map<String, Object> jsonMap = initialRegistrar.toJsonMap();
jsonMap.put("clientCertificate", null);
jsonMap.put("failoverClientCertificate", "");

View file

@ -16,29 +16,25 @@ package google.registry.ui.server.registrar;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.AppEngineRule.THE_REGISTRAR_GAE_USER_ID;
import static google.registry.testing.DatastoreHelper.deleteResource;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.LogsSubject.assertAboutLogs;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.common.flogger.LoggerConfig;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.TestLogHandler;
import google.registry.model.registrar.RegistrarContact;
import google.registry.request.HttpException.ForbiddenException;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.UserAuthInfo;
import google.registry.testing.AppEngineRule;
import google.registry.testing.InjectRule;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@ -55,25 +51,27 @@ public class SessionUtilsTest {
private final HttpServletRequest req = mock(HttpServletRequest.class);
private final HttpServletResponse rsp = mock(HttpServletResponse.class);
private final HttpSession session = mock(HttpSession.class);
private final TestLogHandler testLogHandler = new TestLogHandler();
private SessionUtils sessionUtils;
private static final UserAuthInfo AUTHORIZED_USER = createAuthInfo(true, false);
private static final UserAuthInfo UNAUTHORIZED_USER = createAuthInfo(false, false);
private static final UserAuthInfo AUTHORIZED_ADMIN = createAuthInfo(true, true);
private static final UserAuthInfo UNAUTHORIZED_ADMIN = createAuthInfo(false, true);
private static final AuthResult AUTHORIZED_USER = createAuthResult(true, false);
private static final AuthResult UNAUTHORIZED_USER = createAuthResult(false, false);
private static final AuthResult AUTHORIZED_ADMIN = createAuthResult(true, true);
private static final AuthResult UNAUTHORIZED_ADMIN = createAuthResult(false, true);
private static final AuthResult NO_USER = AuthResult.create(AuthLevel.NONE);
private static final String DEFAULT_CLIENT_ID = "TheRegistrar";
private static final String ADMIN_CLIENT_ID = "NewRegistrar";
private static UserAuthInfo createAuthInfo(boolean isAuthorized, boolean isAdmin) {
return UserAuthInfo.create(
new User(
"user1@google.com",
"google.com",
isAuthorized ? THE_REGISTRAR_GAE_USER_ID : "badGaeUserId"),
isAdmin);
private static AuthResult createAuthResult(boolean isAuthorized, boolean isAdmin) {
return AuthResult.create(
AuthLevel.USER,
UserAuthInfo.create(
new User(
"user1@google.com",
"google.com",
isAuthorized ? THE_REGISTRAR_GAE_USER_ID : "badGaeUserId"),
isAdmin));
}
@Before
@ -82,7 +80,6 @@ public class SessionUtilsTest {
sessionUtils = new SessionUtils();
sessionUtils.registryAdminClientId = ADMIN_CLIENT_ID;
persistResource(loadRegistrar(ADMIN_CLIENT_ID));
when(req.getSession()).thenReturn(session);
}
@After
@ -90,240 +87,161 @@ public class SessionUtilsTest {
LoggerConfig.getConfig(SessionUtils.class).removeHandler(testLogHandler);
}
/** User needs to be logged in before calling checkRegistrarConsoleLogin */
@Test
public void testCheckRegistrarConsoleLogin_notLoggedIn_throwsIllegalStateException() {
assertThrows(
IllegalStateException.class,
() -> {
@SuppressWarnings("unused")
boolean unused = sessionUtils.checkRegistrarConsoleLogin(req, null);
});
private String formatMessage(String message, AuthResult authResult, String clientId) {
return message
.replace("{user}", authResult.userIdForLogging())
.replace("{clientId}", String.valueOf(clientId));
}
/**
* If clientId exists in the session and the user does not have access to that registrar, then no
* access should be granted.
*/
/** Fail loading registrar if user doesn't have access to it. */
@Test
public void testCheckRegistrarConsoleLogin_hasSession_noAccess_isNotAdmin() {
when(session.getAttribute("clientId")).thenReturn(DEFAULT_CLIENT_ID);
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_USER)).isFalse();
verify(session).invalidate();
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(Level.INFO, "Registrar Console access revoked");
public void testGetRegistrarForUser_noAccess_isNotAdmin() {
expectGetRegistrarFailure(
DEFAULT_CLIENT_ID,
UNAUTHORIZED_USER,
"User {user} doesn't have access to registrar {clientId}");
}
/**
* If clientId exists in the session and the user does not have access to that registrar, then
* access should be revoked. The admin flag should be ignored.
*/
/** Fail loading registrar if there's no user associated with the request. */
@Test
public void testCheckRegistrarConsoleLogin_hasSession_noAccess_isAdmin() {
when(session.getAttribute("clientId")).thenReturn(DEFAULT_CLIENT_ID);
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_ADMIN)).isFalse();
verify(session).invalidate();
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(Level.INFO, "Registrar Console access revoked");
public void testGetRegistrarForUser_noUser() {
expectGetRegistrarFailure(DEFAULT_CLIENT_ID, NO_USER, "Not logged in");
}
/**
* If clientId exists in the session and the user does have access to that registrar, then access
* should be allowed.
*/
/** Succeed loading registrar if user has access to it. */
@Test
public void testCheckRegistrarConsoleLogin_hasSession_hasAccess_isNotAdmin() {
when(session.getAttribute("clientId")).thenReturn(DEFAULT_CLIENT_ID);
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, AUTHORIZED_USER)).isTrue();
verify(session).getAttribute("clientId");
verifyNoMoreInteractions(session);
public void testGetRegistrarForUser_hasAccess_isNotAdmin() {
expectGetRegistrarSuccess(AUTHORIZED_USER, "User {user} has access to registrar {clientId}");
}
/** Succeed loading registrar if admin. */
@Test
public void testGetRegistrarForUser_hasAccess_isAdmin() {
expectGetRegistrarSuccess(AUTHORIZED_ADMIN, "User {user} has access to registrar {clientId}");
}
/** Fail loading registrar if admin isn't on the approved contacts list. */
@Test
public void testGetRegistrarForUser_noAccess_isAdmin() {
expectGetRegistrarFailure(
DEFAULT_CLIENT_ID,
UNAUTHORIZED_ADMIN,
"User {user} doesn't have access to registrar {clientId}");
}
/** Succeed loading registrarAdmin even if unauthorized admin. */
@Test
public void testGetRegistrarForUser_registrarAdminClientId() {
sessionUtils.registryAdminClientId = DEFAULT_CLIENT_ID;
expectGetRegistrarSuccess(
UNAUTHORIZED_ADMIN, "Allowing admin {user} access to registrar {clientId}.");
}
/** Fail loading registrar even if admin, if registrar doesn't exist. */
@Test
public void testGetRegistrarForUser_doesntExist_isAdmin() {
expectGetRegistrarFailure("BadClientId", UNAUTHORIZED_ADMIN, "Registrar {clientId} not found");
}
private void expectGetRegistrarSuccess(AuthResult authResult, String message) {
assertThat(sessionUtils.getRegistrarForUser(DEFAULT_CLIENT_ID, authResult)).isNotNull();
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Associating user %s with given registrar %s.",
AUTHORIZED_USER.user().getUserId(), DEFAULT_CLIENT_ID));
Level.INFO, formatMessage(message, authResult, DEFAULT_CLIENT_ID));
}
private void expectGetRegistrarFailure(String clientId, AuthResult authResult, String message) {
ForbiddenException exception =
assertThrows(
ForbiddenException.class, () -> sessionUtils.getRegistrarForUser(clientId, authResult));
assertThat(exception).hasMessageThat().contains(formatMessage(message, authResult, clientId));
assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.INFO);
}
/** If a user has access to a registrar, we should guess that registrar. */
@Test
public void testGuessClientIdForUser_hasAccess_isNotAdmin() {
expectGuessRegistrarSuccess(
AUTHORIZED_USER,
DEFAULT_CLIENT_ID,
"Associating user {user} with found registrar {clientId}.");
}
/** If a user doesn't have access to any registrars, guess returns nothing. */
@Test
public void testGuessClientIdForUser_noAccess_isNotAdmin() {
expectGuessRegistrarFailure(
UNAUTHORIZED_USER, "User {user} isn't associated with any registrar");
}
/**
* If clientId exists in the session and the user does have access to that registrar, then access
* should be allowed. The admin flag should be ignored.
* If an admin has access to a registrar, we should guess that registrar (rather than the
* ADMIN_CLIENT_ID).
*/
@Test
public void testCheckRegistrarConsoleLogin_hasSession_hasAccess_isAdmin() {
when(session.getAttribute("clientId")).thenReturn(DEFAULT_CLIENT_ID);
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, AUTHORIZED_ADMIN)).isTrue();
verify(session).getAttribute("clientId");
verifyNoMoreInteractions(session);
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Associating user %s with given registrar %s.",
AUTHORIZED_ADMIN.user().getUserId(), DEFAULT_CLIENT_ID));
public void testGuessClientIdForUser_hasAccess_isAdmin() {
expectGuessRegistrarSuccess(
AUTHORIZED_ADMIN,
DEFAULT_CLIENT_ID,
"Associating user {user} with found registrar {clientId}.");
}
/** If an admin doesn't have access to a registrar, we should guess the ADMIN_CLIENT_ID. */
@Test
public void testGuessClientIdForUser_noAccess_isAdmin() {
expectGuessRegistrarSuccess(
UNAUTHORIZED_ADMIN,
ADMIN_CLIENT_ID,
"User {user} is an admin with no associated registrar."
+ " Automatically associating the user with configured client Id {clientId}.");
}
/**
* If clientId does not exist in the session and the user has access to a registrar, then access
* should be granted to that registrar.
* If an admin is not associated with a registrar and there is no configured adminClientId, we
* can't guess the clientId.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_hasAccess_isNotAdmin() {
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, AUTHORIZED_USER)).isTrue();
verify(session).setAttribute(eq("clientId"), eq(DEFAULT_CLIENT_ID));
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Associating user %s with found registrar %s.",
AUTHORIZED_USER.user().getUserId(), DEFAULT_CLIENT_ID));
}
/**
* If clientId does not exist in the session and the user has access to a registrar, then access
* should be granted to that registrar. The admin flag should be ignored.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_hasAccess_isAdmin() {
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, AUTHORIZED_ADMIN)).isTrue();
verify(session).setAttribute(eq("clientId"), eq(DEFAULT_CLIENT_ID));
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Associating user %s with found registrar %s.",
AUTHORIZED_ADMIN.user().getUserId(), DEFAULT_CLIENT_ID));
}
/**
* If clientId does not exist in the session, the user is not associated with a registrar and the
* user is an admin, then access could be granted to the configured adminClientId. But if the
* configured adminClientId is empty or null, no access is granted.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_noAccess_isAdmin_adminClientIdEmpty() {
public void testGuessClientIdForUser_noAccess_isAdmin_adminClientIdEmpty() {
sessionUtils.registryAdminClientId = "";
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_ADMIN)).isFalse();
expectGuessRegistrarFailure(
UNAUTHORIZED_ADMIN, "User {user} isn't associated with any registrar");
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Cannot associate admin user %s with configured client Id."
+ " ClientId is null or empty.",
UNAUTHORIZED_ADMIN.user().getUserId()));
"Cannot associate admin user badGaeUserId with configured client Id."
+ " ClientId is null or empty.");
}
/**
* If clientId does not exist in the session, the user is not associated with a registrar and the
* user is an admin, then access could be granted to the configured adminClientId. But if the
* configured adminClientId does not reference a registry, then no access is granted.
* If an admin is not associated with a registrar and the configured adminClientId points to a
* non-existent registrar, we still guess it (we will later failing loading the registrar).
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_noAccess_isAdmin_adminClientIdInvalid() {
sessionUtils.registryAdminClientId = "NonexistentRegistry";
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_ADMIN)).isFalse();
public void testGuessClientIdForUser_noAccess_isAdmin_adminClientIdInvalid() {
sessionUtils.registryAdminClientId = "NonexistentRegistrar";
expectGuessRegistrarSuccess(
UNAUTHORIZED_ADMIN,
"NonexistentRegistrar",
"User {user} is an admin with no associated registrar."
+ " Automatically associating the user with configured client Id {clientId}.");
}
private void expectGuessRegistrarSuccess(AuthResult authResult, String clientId, String message) {
assertThat(sessionUtils.guessClientIdForUser(authResult)).isEqualTo(clientId);
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Cannot associate admin user %s with configured client Id %s."
+ " Registrar does not exist.",
UNAUTHORIZED_ADMIN.user().getUserId(), "NonexistentRegistry"));
.hasLogAtLevelWithMessage(Level.INFO, formatMessage(message, authResult, clientId));
}
/**
* If clientId does not exist in the session, the user does not have access to a registrar and the
* user is an admin, then grant the user access to the validated configured adminClientId.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_noAccess_isAdmin() {
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_ADMIN)).isTrue();
verify(session).setAttribute(eq("clientId"), eq(ADMIN_CLIENT_ID));
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"User %s is an admin with no associated registrar."
+ " Automatically associating the user with configured client Id %s.",
UNAUTHORIZED_ADMIN.user().getUserId(), ADMIN_CLIENT_ID));
}
/**
* If session clientId points to the adminClientId, and the user is an admin that doesn't have
* access to this registrar - it means this is the second (or later) visit of this admin and they
* were granted access to the default registrar because they aren't associated with any other
* registrar.
*
* We continue to grant the admin access.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_noAccess_isAdmin_secondRequest() {
when(session.getAttribute("clientId")).thenReturn(ADMIN_CLIENT_ID);
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_ADMIN)).isTrue();
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"Associating user %s with given registrar %s.",
UNAUTHORIZED_ADMIN.user().getUserId(), ADMIN_CLIENT_ID));
}
/**
* If clientId does not exist in the session and the user is not associated with a registrar, then
* access should not be granted.
*/
@Test
public void testCheckRegistrarConsoleLogin_noSession_noAccess_isNotAdmin() {
assertThat(sessionUtils.checkRegistrarConsoleLogin(req, UNAUTHORIZED_USER)).isFalse();
assertAboutLogs()
.that(testLogHandler)
.hasLogAtLevelWithMessage(
Level.INFO,
String.format(
"User not associated with any Registrar: %s",
UNAUTHORIZED_USER.user().getUserId()));
}
@Test
public void testHasAccessToRegistrar_orphanedContact_returnsFalse() {
deleteResource(loadRegistrar(DEFAULT_CLIENT_ID));
assertThat(
sessionUtils.hasAccessToRegistrar(DEFAULT_CLIENT_ID, THE_REGISTRAR_GAE_USER_ID, false))
.isFalse();
}
@Test
public void testHasAccessToRegistrar_accessRevoked_returnsFalse() {
RegistrarContact.updateContacts(loadRegistrar(DEFAULT_CLIENT_ID), new java.util.HashSet<>());
assertThat(
sessionUtils.hasAccessToRegistrar(DEFAULT_CLIENT_ID, THE_REGISTRAR_GAE_USER_ID, false))
.isFalse();
}
@Test
public void testHasAccessToRegistrar_orphanedAdmin_notAdminRegistrar_returnsFalse() {
RegistrarContact.updateContacts(loadRegistrar(DEFAULT_CLIENT_ID), new java.util.HashSet<>());
assertThat(
sessionUtils.hasAccessToRegistrar(DEFAULT_CLIENT_ID, THE_REGISTRAR_GAE_USER_ID, true))
.isFalse();
}
@Test
public void testHasAccessToRegistrar_orphanedAdmin_onAdminRegistrar_returnsTrue() {
RegistrarContact.updateContacts(loadRegistrar(ADMIN_CLIENT_ID), new java.util.HashSet<>());
assertThat(
sessionUtils.hasAccessToRegistrar(ADMIN_CLIENT_ID, THE_REGISTRAR_GAE_USER_ID, true))
.isTrue();
private void expectGuessRegistrarFailure(AuthResult authResult, String message) {
ForbiddenException exception =
assertThrows(ForbiddenException.class, () -> sessionUtils.guessClientIdForUser(authResult));
assertThat(exception)
.hasMessageThat()
.contains(formatMessage(message, UNAUTHORIZED_USER, null));
}
@Test