@Test public void testLoginWrongRealmForLoginModule() throws Exception { Principal principal = new BasicUserPrincipal("foo"); PasswordCredential cred = new PasswordCredential("foo", "bar".toCharArray(), "dummyJdbcRealm"); Subject subject = new Subject(true, new HashSet<>( Arrays.asList(principal)), new HashSet<>(), new HashSet<>( Arrays.asList(cred))); JDBCLoginModule module = new JDBCLoginModule(); module.initialize(subject, callbackHandler, new HashMap<>(), new HashMap<>()); expectedException.expect(LoginException.class); expectedException.expectMessage("JDBCLoginModule requires JDBCRealm"); module.login(); }
@Test public void testGetIdWithUserIdURI() throws RepositoryException { // test with an absolute user uri final String userUri = TEST_USER_AGENT_BASE_URI + FEDORA_USER; when(request.getRemoteUser()).thenReturn(userUri); when(request.getUserPrincipal()).thenReturn(new BasicUserPrincipal(userUri)); when(request.isUserInRole(eq("admin"))).thenReturn(true); ServletCredentials credentials = new ServletCredentials(request); FedoraSession session = repo.login(credentials); assertEquals("User agent URI invalid.", URI.create(userUri), session.getUserURI()); // test with an Opaque user uri final String opaqueUserUri = "user:info:" + FEDORA_USER; when(request.getRemoteUser()).thenReturn(opaqueUserUri); when(request.getUserPrincipal()).thenReturn(new BasicUserPrincipal(opaqueUserUri)); when(request.isUserInRole(eq("admin"))).thenReturn(true); credentials = new ServletCredentials(request); session = repo.login(credentials); assertEquals("User agent URI invalid.", URI.create(opaqueUserUri), session.getUserURI()); }
@Test public void testPermissiveFAD() throws RepositoryException { when(request.getRemoteUser()).thenReturn("fred"); when(request.getUserPrincipal()).thenReturn( new BasicUserPrincipal("fred")); when( request.isUserInRole(Mockito .eq(ServletContainerAuthenticationProvider.FEDORA_USER_ROLE))) .thenReturn(true); Mockito.reset(fad); when(fad.hasPermission(any(Session.class), any(Path.class), any(String[].class))).thenReturn(true); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); final Session jcrSession = getJcrSession(session); final Privilege[] rootPrivs = jcrSession.getAccessControlManager().getPrivileges("/"); for (final Privilege p : rootPrivs) { logger.debug("got priv: " + p.getName()); } final ContainerService os = new ContainerServiceImpl(); os.findOrCreate(session, "/myobject"); verify(fad, atLeastOnce()).hasPermission(any(Session.class), any(Path.class), any(String[].class)); }
@Test(expected = AccessDeniedException.class) public void testRestrictiveFAD() throws Throwable { when(request.getRemoteUser()).thenReturn("fred"); when(request.getUserPrincipal()).thenReturn( new BasicUserPrincipal("fred")); when( request.isUserInRole(Mockito .eq(ServletContainerAuthenticationProvider.FEDORA_USER_ROLE))) .thenReturn(true); // first permission check is for login Mockito.reset(fad); when(fad.hasPermission(any(Session.class), any(Path.class), any(String[].class))).thenReturn(true, false); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); final ContainerService os = new ContainerServiceImpl(); try { os.findOrCreate(session, "/myobject"); } catch (final RepositoryRuntimeException e) { throw e.getCause(); } verify(fad, times(5)).hasPermission(any(Session.class), any(Path.class), any(String[].class)); }
@Test public void testEmptyPrincipalProvider() throws RepositoryException { when(request.getRemoteUser()).thenReturn("fred"); when(request.getUserPrincipal()).thenReturn( new BasicUserPrincipal("fred")); when( request.isUserInRole(Mockito .eq(ServletContainerAuthenticationProvider.FEDORA_USER_ROLE))) .thenReturn(true); Mockito.reset(fad); when(fad.hasPermission(any(Session.class), any(Path.class), any(String[].class))).thenReturn(true); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); final Session jcrSession = getJcrSession(session); final Privilege[] rootPrivs = jcrSession.getAccessControlManager().getPrivileges("/"); for (final Privilege p : rootPrivs) { logger.debug("got priv: " + p.getName()); } final ContainerService os = new ContainerServiceImpl(); os.findOrCreate(session, "/myobject"); verify(fad, atLeastOnce()).hasPermission(any(Session.class), any(Path.class), any(String[].class)); }
/** * The constructor with the Diadoc API client ID and auth token arguments. * * @param apiClientId the Diadoc API client ID * @param authToken the Diadoc authorization token */ public DiadocCredentials(String apiClientId, String authToken) { super(); if (apiClientId == null) { throw new IllegalArgumentException("ApiClientId may not be null"); } this.principal = new BasicUserPrincipal(apiClientId); this.authToken = authToken; }
@Test public void returnsFailureIfCannotFindUser() throws Exception { User amy = user().withFirstName("Amy").build(); given(userRepository.findOne(amy.getId())).willReturn(amy); Principal p = new BasicUserPrincipal("name"); Try<User> userTry = underTest.extractUserFromPrincipal(p); assertThat(userTry, isFailure(instanceOf(UserSessionFailure.class))); }
@Before public void setup() { AddressSpace addressSpace = mock(AddressSpace.class); AddressSpaceApi addressSpaceApi = mock(AddressSpaceApi.class); addressApi = mock(AddressApi.class); securityContext = mock(SecurityContext.class); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("me")); when(securityContext.isUserInRole(any())).thenReturn(true); when(addressSpaceApi.getAddressSpaceWithName(eq("test"))).thenReturn(Optional.of(addressSpace)); when(addressSpaceApi.withAddressSpace(eq(addressSpace))).thenReturn(addressApi); helper = new AddressApiHelper(addressSpaceApi); }
@Before public void setup() { addressSpaceApi = new TestAddressSpaceApi(); addressSpaceService = new HttpAddressSpaceService(addressSpaceApi, "controller"); securityContext = mock(SecurityContext.class); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("me")); when(securityContext.isUserInRole(any())).thenReturn(true); when(securityContext.getAuthenticationScheme()).thenReturn("unknown"); a1 = new AddressSpace.Builder() .setName("a1") .setNamespace("myspace") .setType(new StandardAddressSpaceType()) .setEndpointList(Arrays.asList( new Endpoint.Builder() .setName("messaging") .setService("messaging") .setHost("messaging.example.com") .build(), new Endpoint.Builder() .setName("mqtt") .setService("mqtt") .setHost("mqtt.example.com") .build())) .build(); a2 = new AddressSpace.Builder() .setName("a2") .setType(new StandardAddressSpaceType()) .setNamespace("othernamespace") .build(); }
@Before public void setup() { addressSpaceApi = new TestAddressSpaceApi(); this.addressService = new HttpAddressService(addressSpaceApi); AddressSpace addressSpace = new AddressSpace.Builder() .setName("myspace") .setType(new StandardAddressSpaceType()) .build(); securityContext = mock(SecurityContext.class); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("me")); when(securityContext.isUserInRole(any())).thenReturn(true); addressSpaceApi.createAddressSpace(addressSpace); addressApi = (TestAddressApi) addressSpaceApi.withAddressSpace(addressSpace); q1 = new Address.Builder() .setName("q1") .setType(StandardType.QUEUE) .build(); a1 = new Address.Builder() .setName("a1") .setType(StandardType.ANYCAST) .build(); addressApi.createAddress(q1); addressApi.createAddress(a1); }
protected SecurityContext getSecurityContext() { SecurityContext securityContext = mock(SecurityContext.class); when(securityContext.isUserInRole(any())).thenReturn(true); when(securityContext.isSecure()).thenReturn(true); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("myuser")); return securityContext; }
@Override public Principal getUserPrincipal() { if (principal == null) { getCredentials(); if (principal == null) { return new BasicUserPrincipal(""); } } return principal; }
protected void getCredentials() { try { // Search within the registered servers by prefix final List<Server> servers = Activator.getDefault().getServerStore().readAllServers(); String storeKey = url; for (Server server : servers) { if (url.startsWith(server.getBaseURL())) { storeKey = server.getBaseURL(); break; } } CredentialsStore.Credentials creds = Activator.getDefault().getCredentialsStore().get(storeKey); if (creds == null && PlatformUI.isWorkbenchRunning()) { final Display display = PlatformUI.getWorkbench().getDisplay(); final CredentialsPrompter prompter = new CredentialsPrompter(display); display.syncExec(prompter); creds = prompter.getCredentials(); } if (creds != null) { principal = new BasicUserPrincipal(creds.getUsername()); password = creds.getPassword(); } } catch (Exception e) { Activator.getDefault().logError(e); } }
@Override public Optional<BasicUserPrincipal> authenticate(BasicCredentials credentials) throws AuthenticationException { String loginUserName = credentials.getUsername(); String loginPassword = credentials.getPassword(); String htUsersPass = readHtUsers().getPassword(loginUserName); if(negate(comparePasswords(loginPassword, htUsersPass))) { logger.info("Failed to login " + loginUserName); return Optional.empty(); } return Optional.of(new BasicUserPrincipal(loginUserName)); }
private void registerBasicAuth(Environment environment, String htusers) { if(isNotBlank(htusers)) { environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<BasicUserPrincipal>() .setAuthenticator(new HtUserAuthenticator(htusers)) .setRealm("All") .buildAuthFilter())); } }
public boolean doLogin(String principalName, String userName, String password) throws Exception { Principal principal = new BasicUserPrincipal(principalName); PasswordCredential cred = new PasswordCredential(userName, password.toCharArray(), "jdbcRealm"); Subject subject = new Subject(true, new HashSet<>( Arrays.asList(principal)), new HashSet<>(), new HashSet<>( Arrays.asList(cred))); JDBCLoginModule module = new JDBCLoginModule(); module.initialize(subject, callbackHandler, new HashMap<>(), new HashMap<>()); return module.login(); }
@Test public void testGetIdExceptionWithUserIdNonURI() throws RepositoryException { when(request.getRemoteUser()).thenReturn(FEDORA_USER); when(request.getUserPrincipal()).thenReturn(new BasicUserPrincipal(FEDORA_USER)); when(request.isUserInRole(eq("admin"))).thenReturn(true); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); // should be the default local user agent URI assertEquals("User agent URI invalid.", URI.create(FedoraSessionUserUtil.DEFAULT_USER_AGENT_BASE_URI + FEDORA_USER), session.getUserURI()); }
@Test public void testGetIdWithUserIdNonURI() throws RepositoryException { // Set basic URI for user agent with environment variable: fcrepo.auth.webac.userAgent.baseUri System.setProperty(FedoraSessionUserUtil.USER_AGENT_BASE_URI_PROPERTY, TEST_USER_AGENT_BASE_URI); when(request.getRemoteUser()).thenReturn(FEDORA_USER); when(request.getUserPrincipal()).thenReturn(new BasicUserPrincipal(FEDORA_USER)); when(request.isUserInRole(eq("admin"))).thenReturn(true); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); assertEquals("User agent URI invalid.", URI.create(TEST_USER_AGENT_BASE_URI + FEDORA_USER), session.getUserURI()); }
@Test public void testDelegatedUserAccess() throws RepositoryException { // mock request by an admin user, on behalf of a regular user when(request.getRemoteUser()).thenReturn("admin1"); when(request.getUserPrincipal()).thenReturn(new BasicUserPrincipal("admin1")); when(request.isUserInRole(eq(ServletContainerAuthenticationProvider.FEDORA_ADMIN_ROLE))).thenReturn(true); when(request.getHeader("On-Behalf-Of")).thenReturn("user1"); Mockito.reset(fad); // set up a restrictive mock FAD, which should deny non-admin users when(fad.hasPermission(any(Session.class), any(Path.class), any(String[].class))).thenReturn(false); final ServletCredentials credentials = new ServletCredentials(request); final FedoraSession session = repo.login(credentials); final Session jcrSession = getJcrSession(session); assertEquals("Session user principal is user1", "user1", ((Principal) jcrSession.getAttribute(FedoraAuthorizationDelegate.FEDORA_USER_PRINCIPAL)).getName()); // try to create an object, this should fail because it is being executed as a non-admin user final ContainerService os = new ContainerServiceImpl(); try { os.findOrCreate(session, "/myobject"); } catch (final RepositoryRuntimeException e) { final Throwable cause = e.getCause(); if (cause != null && cause instanceof AccessDeniedException) { logger.debug("caught expected access denied exception"); } else { throw e; } } verify(fad, atLeastOnce()).hasPermission(any(Session.class), any(Path.class), any(String[].class)); }
protected void addPrincipal(SOAPMessageContext context, String userKey) { Subject sub = (Subject) context.get("javax.security.auth.Subject"); sub.getPrincipals().add(new BasicUserPrincipal(userKey)); }
@Test public void testChooseClientAliasNotfound() throws Exception { final X509KeyManager m = new CertificateStoreX509KeyManager(new DisabledCertificateStore(), new Host(new TestProtocol())).init(); assertNull(m.chooseClientAlias(new String[]{"RSA", "DSA"}, new Principal[]{new BasicUserPrincipal("user")}, new Socket("test.cyberduck.ch", 443))); }
@Test public void testAuthToken() throws Exception { Response resp = adminExecutor.execute(Request.Get(rootUri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode()); Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString()); Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString()); Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString()); assertNotNull("check not null auth token header", _authToken); assertNotNull("check not null auth token valid header", _authTokenValid); assertNotNull("check not null auth token location header", _authTokenLocation); assertTrue("check not empty array auth token header array ", _authToken.length == 1); assertTrue("check not empty array auth token valid header array", _authTokenValid.length == 1); assertTrue("check not empty array auth token location header array", _authTokenLocation.length == 1); assertTrue("check not empty array auth token header value not null or empty", _authToken[0] != null && _authToken[0].getValue() != null && !_authToken[0].getValue().isEmpty()); assertTrue("check not empty array auth token valid value not null or empty", _authTokenValid[0] != null && _authTokenValid[0].getValue() != null && !_authTokenValid[0].getValue().isEmpty()); assertTrue("check not empty array auth token location not null or empty", _authTokenLocation[0] != null && _authTokenLocation[0].getValue() != null && !_authTokenLocation[0].getValue().isEmpty()); Response resp2 = unauthExecutor.auth(new Credentials() { @Override public Principal getUserPrincipal() { return new BasicUserPrincipal("admin"); } @Override public String getPassword() { return _authToken[0].getValue(); } }).execute(Request.Get(rootUri)); HttpResponse httpResp2 = resp2.returnResponse(); assertNotNull(httpResp2); StatusLine statusLine2 = httpResp2.getStatusLine(); assertNotNull(statusLine2); assertEquals("check authorized via auth token", HttpStatus.SC_OK, statusLine2.getStatusCode()); }
@Test public void testAuthTokenResourceLocation() throws Exception { Response resp = adminExecutor.execute(Request.Get(rootUri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode()); Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString()); Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString()); Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString()); assertNotNull("check not null auth token header", _authToken); assertNotNull("check not null auth token valid header", _authTokenValid); assertNotNull("check not null auth token location header", _authTokenLocation); assertTrue("check not empty array auth token header array ", _authToken.length == 1); assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1); assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1); String locationURI = _authTokenLocation[0].getValue(); URI authTokenResourceUri = rootUri.resolve(locationURI); final String host = MONGO_HOST; final int port = conf.getHttpPort(); Response resp2 = unauthExecutor.authPreemptive(new HttpHost(host, port, HTTP)).auth(new Credentials() { @Override public Principal getUserPrincipal() { return new BasicUserPrincipal("admin"); } @Override public String getPassword() { return _authToken[0].getValue(); } }).execute(Request.Get(authTokenResourceUri)); HttpResponse httpResp2 = resp2.returnResponse(); assertNotNull(httpResp2); StatusLine statusLine2 = httpResp2.getStatusLine(); assertNotNull(statusLine2); HttpEntity entity = httpResp2.getEntity(); assertNotNull(entity); Header[] _authTokenValid2 = httpResp2.getHeaders(AUTH_TOKEN_VALID_HEADER.toString()); assertEquals("check auth token resource URI", HttpStatus.SC_OK, statusLine2.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("check content of auth token resource", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("parsing received json"); } assertNotNull("check content - auth_token not null", json.get("auth_token")); assertNotNull("check content - auth_token_valid_until not null", json.get("auth_token_valid_until")); assertTrue("check content - auth_token not empty", !json.get("auth_token").asString().isEmpty()); assertTrue("check content - auth_token_valid_until not empty", !json.get("auth_token_valid_until").asString().isEmpty()); assertEquals(json.get("auth_token").asString(), _authToken[0].getValue()); assertEquals(json.get("auth_token_valid_until").asString(), _authTokenValid2[0].getValue()); }
@Test public void testAuthTokenInvalidation() throws Exception { Response resp = adminExecutor.execute(Request.Get(rootUri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode()); Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString()); Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString()); Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString()); assertNotNull("check not null auth token header", _authToken); assertNotNull("check not null auth token valid header", _authTokenValid); assertNotNull("check not null auth token location header", _authTokenLocation); assertTrue("check not empty array auth token header array ", _authToken.length == 1); assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1); assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1); String locationURI = _authTokenLocation[0].getValue(); URI authTokenResourceUri = rootUri.resolve(locationURI); Response resp2 = unauthExecutor.auth(new Credentials() { @Override public Principal getUserPrincipal() { return new BasicUserPrincipal("admin"); } @Override public String getPassword() { return _authToken[0].getValue(); } }).execute(Request.Delete(authTokenResourceUri)); HttpResponse httpResp2 = resp2.returnResponse(); assertNotNull(httpResp2); StatusLine statusLine2 = httpResp2.getStatusLine(); assertNotNull(statusLine2); assertEquals("check auth token resource URI", HttpStatus.SC_NO_CONTENT, statusLine2.getStatusCode()); Response resp3 = unauthExecutor.auth(new Credentials() { @Override public Principal getUserPrincipal() { return new BasicUserPrincipal("admin"); } @Override public String getPassword() { return _authToken[0].getValue(); } }).execute(Request.Get(rootUri)); HttpResponse httpResp3 = resp3.returnResponse(); assertNotNull(httpResp3); StatusLine statusLine3 = httpResp3.getStatusLine(); assertNotNull(statusLine3); assertEquals("check auth token resource URI", HttpStatus.SC_UNAUTHORIZED, statusLine3.getStatusCode()); }