src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
DefaultClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } Object message = input.getMessage(); if (!(message instanceof AuthenticationRequest)) { return null; } return ((AuthenticationRequest) message).getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }
@SuppressWarnings("unchecked") @Test public void testNullInput() { Assert.assertNull(lookup.apply(null)); ctx.setMessage(null); Assert.assertNull(lookup.apply(null)); } @Test public void testSuccess() { Assert.assertEquals(new ClientID("000123"), lookup.apply(ctx)); }
UserInfoRequestClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } if (!(input.getParent() instanceof ProfileRequestContext)) { return null; } MessageContext msgCtx = ((ProfileRequestContext) input.getParent()).getOutboundMessageContext(); if (msgCtx == null) { return null; } OIDCAuthenticationResponseContext ctx = msgCtx.getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null || ctx.getTokenClaimsSet() == null) { return null; } return ctx.getTokenClaimsSet().getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testNullInput() { lookup = new UserInfoRequestClientIDLookupFunction(); Assert.assertNull(lookup.apply(null)); oidcCtx.setTokenClaimsSet(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); oidcCtx.setTokenClaimsSet(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); prc.setInboundMessageContext(new MessageContext()); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); } @Test public void testSuccess() { lookup = new UserInfoRequestClientIDLookupFunction(); Assert.assertEquals(cliendID, lookup.apply(prc.getOutboundMessageContext())); }
DefaultValidRedirectUrisLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, Set<URI>> { @Override @Nullable public Set<URI> apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } OIDCMetadataContext ctx = input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); if (ctx == null || ctx.getClientInformation() == null || ctx.getClientInformation().getMetadata() == null) { return null; } return ctx.getClientInformation().getMetadata().getRedirectionURIs(); } @Override @Nullable Set<URI> apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); ctx.setClientInformation(null); Assert.assertNull(lookup.apply(prc)); prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
OIDCAuthenticationResponseContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCAuthenticationResponseContext> { @Override @Nullable public OIDCAuthenticationResponseContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } return input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); } @Override @Nullable OIDCAuthenticationResponseContext apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
FilesystemMetadataValueResolver extends AbstractFileOIDCEntityResolver<Identifier, Object> implements RefreshableMetadataValueResolver { @Override public Object resolveSingle(ProfileRequestContext profileRequestContext) throws ResolverException { return resolve(profileRequestContext).iterator().next(); } FilesystemMetadataValueResolver(@Nonnull final Resource metadata); FilesystemMetadataValueResolver(@Nullable final Timer backgroundTaskTimer, @Nonnull final Resource metadata); @Override Iterable<Object> resolve(ProfileRequestContext profileRequestContext); @Override Object resolveSingle(ProfileRequestContext profileRequestContext); }
@Test public void testString() throws Exception { final FilesystemMetadataValueResolver resolver = initTests("/org/geant/idpextension/oidc/metadata/impl/dyn-value1.json"); final Object value = resolver.resolveSingle(null); Assert.assertNotNull(value); Assert.assertTrue(value instanceof String); Assert.assertEquals(value, "mockValue"); } @Test public void testJson() throws Exception { final FilesystemMetadataValueResolver resolver = initTests("/org/geant/idpextension/oidc/metadata/impl/dyn-value2.json"); final Object value = resolver.resolveSingle(null); Assert.assertNotNull(value); Assert.assertTrue(value instanceof JSONObject); final JSONObject jsonValue = (JSONObject) value; Assert.assertEquals(jsonValue.size(), 1); Assert.assertEquals(jsonValue.get("mockKey"), "mockValue"); }
DefaultResponseClaimsSetLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, ClaimsSet> { @Override @Nullable public ClaimsSet apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getIDToken(); } @Override @Nullable ClaimsSet apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() { Assert.assertEquals("sub", (String) lookup.apply(prc).getClaim("sub")); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setIDToken(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
TokenRequestClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } Object message = input.getMessage(); if (!(message instanceof AbstractOptionallyAuthenticatedRequest)) { return null; } AbstractOptionallyAuthenticatedRequest req = (AbstractOptionallyAuthenticatedRequest) message; if (req.getClientAuthentication() != null && req.getClientAuthentication().getClientID() != null) { return req.getClientAuthentication().getClientID(); } if (!(message instanceof AbstractOptionallyIdentifiedRequest)) { return null; } return ((AbstractOptionallyIdentifiedRequest) req).getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }
@SuppressWarnings("unchecked") @Test public void testNullInput() { Assert.assertNull(lookup.apply(null)); ctx.setMessage(new String("totallynotmessage")); Assert.assertNull(lookup.apply(null)); ctx.setMessage(null); Assert.assertNull(lookup.apply(null)); } @Test public void testSuccess() { Assert.assertEquals(new ClientID("clientId"), lookup.apply(ctx)); }
ValidatedRedirectURILookupFunction implements ContextDataLookupFunction<ProfileRequestContext, URI> { @Override @Nullable public URI apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getRedirectURI(); } @Override @Nullable URI apply(@Nullable final ProfileRequestContext input); }
@SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setRedirectURI(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } @Test public void testSuccess() throws URISyntaxException { Assert.assertEquals(new URI("http: }
DefaultAuthTimeLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, Long> { @Override @Nullable public Long apply(@Nullable final ProfileRequestContext input) { if (input == null) { return null; } AuthenticationContext authCtx = input.getSubcontext(AuthenticationContext.class, false); if (authCtx == null) { return null; } AuthenticationResult authResult = authCtx.getAuthenticationResult(); if (authResult == null) { return null; } return authResult.getAuthenticationInstant(); } @Override @Nullable Long apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() { Assert.assertEquals(instant.getTime(), (long) lookup.apply(prc)); } @Test public void testNoCtxts() { Assert.assertNull(lookup.apply(null)); authCtx.setAuthenticationResult(null); Assert.assertNull(lookup.apply(prc)); prc.removeSubcontext(AuthenticationContext.class); Assert.assertNull(lookup.apply(prc)); }
ProfileResponderIdLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { @Override @Nullable public String apply(@Nullable final ProfileRequestContext input) { if (profileResponders.containsKey(input.getProfileId())) { return profileResponders.get(input.getProfileId()); } return defaultResponder; } void setDefaultResponder(@Nonnull String resp); void setProfileResponders(@Nullable Map<ProfileConfiguration, String> resp); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() throws ComponentInitializationException { prc.setProfileId("unknown"); Assert.assertEquals(lookup.apply(prc), "defaultvalue"); prc.setProfileId("id1"); Assert.assertEquals(lookup.apply(prc), "value1"); prc.setProfileId("id2"); Assert.assertEquals(lookup.apply(prc), "value2"); }
AbstractTokenClaimsLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext oidcResponseContext = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (oidcResponseContext == null) { return null; } TokenClaimsSet tokenClaims = oidcResponseContext.getTokenClaimsSet(); if (tokenClaims == null) { return null; } return doLookup(tokenClaims); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); }
@Test public void testSubjectSuccess() { Assert.assertEquals("subject", mock.apply(prc)); } @Test public void testNoCtxts() { Assert.assertNull(mock.apply(null)); prc.setOutboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setOutboundMessageContext(new MessageContext()); Assert.assertNull(mock.apply(prc)); prc.getOutboundMessageContext().addSubcontext(new OIDCAuthenticationResponseContext()); Assert.assertNull(mock.apply(prc)); }
DefaultOIDCMetadataContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCMetadataContext> { @Override @Nullable public OIDCMetadataContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } return input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); } @Override @Nullable OIDCMetadataContext apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() { OIDCMetadataContext ctx = lookup.apply(prc); Assert.assertNotNull(ctx); } @Test public void testNoMetadataCtx() { prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoMessageCtx() { prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } @Test public void testNoPrc() { Assert.assertNull(lookup.apply(null)); }
RevocationCache extends AbstractIdentifiableInitializableComponent { public void setStorage(@Nonnull final StorageService storageService) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); storage = Constraint.isNotNull(storageService, "StorageService cannot be null"); final StorageCapabilities caps = storage.getCapabilities(); if (caps instanceof StorageCapabilitiesEx) { Constraint.isTrue(((StorageCapabilitiesEx) caps).isServerSide(), "StorageService cannot be client-side"); } } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }
@Test public void testInit() { revocationCache = new RevocationCache(); try { revocationCache.setStorage(null); Assert.fail("Null StorageService should have caused constraint violation"); } catch (Exception e) { } try { revocationCache.setStorage(new ClientStorageService()); Assert.fail("ClientStorageService should have caused constraint violation"); } catch (Exception e) { } }
RevocationCache extends AbstractIdentifiableInitializableComponent { @Duration public void setEntryExpiration(@Positive @Duration final long entryExpiration) { expires = Constraint.isGreaterThan(0, entryExpiration, "revocation cache entry expiration must be greater than 0"); } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }
@Test (expectedExceptions = ConstraintViolationException.class) public void testExpirationSetter() throws ComponentInitializationException { revocationCache.setEntryExpiration(0); }
RevocationCache extends AbstractIdentifiableInitializableComponent { @NonnullAfterInit public StorageService getStorage() { return storage; } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }
@Test public void testStorageGetter() throws ComponentInitializationException { Assert.assertEquals(storageService, revocationCache.getStorage()); }
JSONSuccessResponse implements SuccessResponse { @Override public HTTPResponse toHTTPResponse() { HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK); httpResponse.setContentType(CommonContentTypes.APPLICATION_JSON); if (cacheControl != null) { httpResponse.setCacheControl(cacheControl); } if (pragma != null) { httpResponse.setPragma(pragma); } httpResponse.setContent(content.toJSONString()); return httpResponse; } JSONSuccessResponse(@Nonnull JSONObject contentObject); JSONSuccessResponse(@Nonnull JSONObject contentObject, String cacheControlValue, String pragmaValue); @Override boolean indicatesSuccess(); @Override HTTPResponse toHTTPResponse(); }
@Test public void testSuccess() throws ParseException { response = new JSONSuccessResponse(content, "no-store", "no-cache"); HTTPResponse httpResponse = response.toHTTPResponse(); Assert.assertEquals(HTTPResponse.SC_OK, httpResponse.getStatusCode()); Assert.assertEquals("application/json; charset=UTF-8", httpResponse.getContentType().toString()); Assert.assertEquals("no-store", httpResponse.getCacheControl()); Assert.assertEquals("no-cache", httpResponse.getPragma()); JSONObject parsedContent = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(httpResponse.getContent()); Assert.assertEquals(content.get("field1"), parsedContent.get("field1")); Assert.assertEquals(content.get("field2"), parsedContent.get("field2")); } @Test public void testSuccess2() throws ParseException { response = new JSONSuccessResponse(content); HTTPResponse httpResponse = response.toHTTPResponse(); Assert.assertEquals(HTTPResponse.SC_OK, httpResponse.getStatusCode()); Assert.assertEquals("application/json; charset=UTF-8", httpResponse.getContentType().toString()); Assert.assertNull(httpResponse.getCacheControl()); Assert.assertNull(httpResponse.getPragma()); JSONObject parsedContent = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(httpResponse.getContent()); Assert.assertEquals(content.get("field1"), parsedContent.get("field1")); Assert.assertEquals(content.get("field2"), parsedContent.get("field2")); }
StorageServiceClientInformationManager extends BaseStorageServiceClientInformationComponent implements ClientInformationManager { @Override public void storeClientInformation(final OIDCClientInformation clientInformation, final Long expiration) throws ClientInformationManagerException { log.debug("Attempting to store client information"); final String clientId = clientInformation.getID().getValue(); final String serialized = clientInformation.toJSONObject().toJSONString(); try { getStorageService().create(CONTEXT_NAME, clientId, serialized, expiration); } catch (IOException e) { log.error("Could not store the client information", e); throw new ClientInformationManagerException("Could not store the client information", e); } log.info("Successfully stored the client information for id {}", clientId); } StorageServiceClientInformationManager(); @Override void storeClientInformation(final OIDCClientInformation clientInformation, final Long expiration); @Override void destroyClientInformation(ClientID clientId); }
@Test public void testStore() throws Exception { final OIDCClientInformation clientInformation = initializeInformation(); manager.storeClientInformation(clientInformation, null); final CriteriaSet criteria = initializeCriteria(); final OIDCClientInformation result = resolver.resolveSingle(criteria); Assert.assertNotNull(result); Assert.assertEquals(result.getID().getValue(), clientIdValue); } @Test public void testExpiration() throws Exception { final OIDCClientInformation clientInformation = initializeInformation(); manager.storeClientInformation(clientInformation, System.currentTimeMillis() + new Long(2000)); final CriteriaSet criteria = initializeCriteria(); final OIDCClientInformation result = resolver.resolveSingle(criteria); Assert.assertNotNull(result); Assert.assertEquals(result.getID().getValue(), clientIdValue); Thread.sleep(2100); final OIDCClientInformation delayedResult = resolver.resolveSingle(criteria); Assert.assertNull(delayedResult); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setResolveAttributes(final boolean resolve) { resolveAttributes = resolve; } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetResolveAttributes() { Assert.assertTrue(config.isResolveAttributes()); config.setResolveAttributes(false); Assert.assertFalse(config.isResolveAttributes()); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts) { Constraint.isNotNull(contexts, "List of contexts cannot be null"); defaultAuthenticationContexts = new ArrayList<>(Collections2.filter(contexts, Predicates.notNull())); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetDefaultAuthenticationMethods() { Assert.assertTrue(config.getDefaultAuthenticationMethods().isEmpty()); List<Principal> principals = new ArrayList<Principal>(); principals.add(new AuthenticationMethodPrincipal("value")); config.setDefaultAuthenticationMethods(principals); Assert.assertTrue( config.getDefaultAuthenticationMethods().contains(new AuthenticationMethodPrincipal("value"))); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { @Duration public void setRefreshTokenLifetime(@Positive @Duration final long lifetime) { refreshTokenLifetime = Constraint.isGreaterThan(0, lifetime, "refresh token lifetime must be greater than 0"); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetRefreshTokenLifetime() { config.setRefreshTokenLifetimeLookupStrategy(null); config.setRefreshTokenLifetime(100); Assert.assertEquals(config.getRefreshTokenLifetime(), 100); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { @Duration public void setAccessTokenLifetime(@Positive @Duration final long lifetime) { accessTokenLifetime = Constraint.isGreaterThan(0, lifetime, "access token lifetime must be greater than 0"); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetAccessTokenLifetime() { config.setAccessTokenLifetime(100); Assert.assertEquals(config.getAccessTokenLifetime(), 100); }
AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public AuthenticationContextClassReferencePrincipal clone() throws CloneNotSupportedException { final AuthenticationContextClassReferencePrincipal copy = (AuthenticationContextClassReferencePrincipal) super.clone(); copy.authnContextClassReference = authnContextClassReference; return copy; } AuthenticationContextClassReferencePrincipal( @Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; }
@Test public void testClone() throws CloneNotSupportedException { Assert.assertEquals(principal, principal.clone()); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { @Duration public void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime) { authorizeCodeLifetime = Constraint.isGreaterThan(0, lifetime, "authorize code lifetime must be greater than 0"); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetAuthorizeCodeLifetime() { config.setAuthorizeCodeLifetime(100); Assert.assertEquals(config.getAuthorizeCodeLifetime(), 100); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { @Duration public void setIDTokenLifetime(@Positive @Duration final long lifetime) { idTokenLifetime = Constraint.isGreaterThan(0, lifetime, "id token lifetime must be greater than 0"); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetIDTokenLifetime() { config.setIDTokenLifetime(100); Assert.assertEquals(config.getIDTokenLifetime(), 100); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setAcrRequestAlwaysEssential(boolean isAlways) { acrRequestAlwaysEssential = isAlways; } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetAcrRequestAlwaysEssential() { Assert.assertFalse(config.getAcrRequestAlwaysEssential()); config.setAcrRequestAlwaysEssential(true); Assert.assertTrue(config.getAcrRequestAlwaysEssential()); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences) { Constraint.isNotNull(audiences, "Collection of additional audiences cannot be null"); additionalAudiences = new HashSet<>(StringSupport.normalizeStringCollection(audiences)); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetAdditionalAudiencesForIdToken() { Assert.assertTrue(config.getAdditionalAudiencesForIdToken().isEmpty()); Collection<String> audiences = new ArrayList<String>(); audiences.add("value"); config.setAdditionalAudiencesForIdToken(audiences); Assert.assertTrue(config.getAdditionalAudiencesForIdToken().contains("value")); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows) { Constraint.isNotNull(flows, "Collection of flows cannot be null"); authenticationFlows = new HashSet<>(StringSupport.normalizeStringCollection(flows)); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetAuthenticationFlows() { Assert.assertTrue(config.getAuthenticationFlows().isEmpty()); Collection<String> flows = new ArrayList<String>(); flows.add("value"); config.setAuthenticationFlows(flows); Assert.assertTrue(config.getAuthenticationFlows().contains("value")); }
OIDCCoreProtocolConfiguration extends AbstractOIDCFlowAwareProfileConfiguration implements InitializableComponent, AuthenticationProfileConfiguration { public void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows) { Constraint.isNotNull(flows, "Collection of flows cannot be null"); postAuthenticationFlows = new ArrayList<>(StringSupport.normalizeStringCollection(flows)); } OIDCCoreProtocolConfiguration(); OIDCCoreProtocolConfiguration(@Nonnull @NotEmpty final String profileId); boolean isResolveAttributes(); void setResolveAttributes(final boolean resolve); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAuthenticationFlows(); void setAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getPostAuthenticationFlows(); void setPostAuthenticationFlows(@Nonnull @NonnullElements final Collection<String> flows); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<Principal> getDefaultAuthenticationMethods(); void setDefaultAuthenticationMethods(@Nonnull @NonnullElements final List<Principal> contexts); @Override @Nonnull @NonnullElements @NotLive @Unmodifiable List<String> getNameIDFormatPrecedence(); void setNameIDFormatPrecedence(@Nonnull @NonnullElements final List<String> formats); void setIDTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAuthorizeCodeLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setAccessTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); void setRefreshTokenLifetimeLookupStrategy( @SuppressWarnings("rawtypes") @Nullable final Function<ProfileRequestContext, Long> strategy); @Positive @Duration long getIDTokenLifetime(); @Duration void setIDTokenLifetime(@Positive @Duration final long lifetime); @Duration void setAccessTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAccessTokenLifetime(); @Duration void setAuthorizeCodeLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getAuthorizeCodeLifetime(); @Duration void setRefreshTokenLifetime(@Positive @Duration final long lifetime); @Positive @Duration long getRefreshTokenLifetime(); void setAdditionalAudiencesForIdToken( @Nonnull @NonnullElements @NotLive @Unmodifiable Collection<String> audiences); @Nonnull @NonnullElements @NotLive @Unmodifiable Set<String> getAdditionalAudiencesForIdToken(); boolean getAcrRequestAlwaysEssential(); void setAcrRequestAlwaysEssential(boolean isAlways); void setForcePKCE(boolean forced); boolean getForcePKCE(); void setAllowPKCEPlain(boolean allowPlain); boolean getAllowPKCEPlain(); static final String PROTOCOL_URI; static final String PROFILE_ID; }
@Test void testsetPostAuthenticationFlows() { Assert.assertTrue(config.getPostAuthenticationFlows().isEmpty()); Collection<String> flows = new ArrayList<String>(); flows.add("value"); config.setPostAuthenticationFlows(flows); Assert.assertTrue(config.getPostAuthenticationFlows().contains("value")); }
SubjectActivationCondition implements Predicate<ProfileRequestContext> { @Override public boolean apply(ProfileRequestContext input) { final MessageContext outboundMessageCtx = input.getOutboundMessageContext(); if (outboundMessageCtx == null) { return true; } OIDCAuthenticationResponseContext oidcResponseContext = outboundMessageCtx.getSubcontext(OIDCAuthenticationResponseContext.class, false); if (oidcResponseContext == null) { return true; } return oidcResponseContext.getSubject() == null; } @Override boolean apply(ProfileRequestContext input); }
@Test public void testSubjectExists() { Assert.assertFalse(lookup.apply(prc)); } @Test public void testNoSubject() { respCtx.setSubject(null); Assert.assertTrue(lookup.apply(prc)); } @Test public void testNoOIDCResponseCtx() { prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertTrue(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoOutboundCtx() { prc.setOutboundMessageContext(null); Assert.assertTrue(lookup.apply(prc)); }
AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public String toString() { return MoreObjects.toStringHelper(this).add("authnContextClassReference", authnContextClassReference) .toString(); } AuthenticationContextClassReferencePrincipal( @Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; }
@Test public void testToString() { Assert.assertEquals(principal.toString(), "AuthenticationContextClassReferencePrincipal{authnContextClassReference=" + principal.getName() + "}"); }
AttributeResolutionSubjectLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { @Override @Nullable public String apply(@Nullable final ProfileRequestContext input) { AttributeContext attributeCtx = attributeContextLookupStrategy.apply(input); if (attributeCtx == null) { log.debug("No AttributeSubcontext available, nothing to do"); return null; } for (IdPAttribute attribute : attributeCtx.getIdPAttributes().values()) { final Set<AttributeEncoder<?>> encoders = attribute.getEncoders(); if (encoders.isEmpty()) { log.debug("Attribute {} does not have any encoders, nothing to do", attribute.getId()); continue; } for (final AttributeEncoder<?> encoder : encoders) { try { if (encoder instanceof AbstractOIDCAttributeEncoder && subClaimName.equals(((AbstractOIDCAttributeEncoder) encoder).getName())) { if (encoder.getActivationCondition() != null && !encoder.getActivationCondition().apply(input)) { log.debug("Encoder not active"); continue; } return (String) ((JSONObject) encoder.encode(attribute)).get(subClaimName); } } catch (AttributeEncodingException e) { log.warn("{} Unable to encode attribute {} as OIDC attribute", attribute.getId(), e); } } } return null; } AttributeResolutionSubjectLookupFunction(); void setAttributeContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, AttributeContext> strategy); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); }
@Test public void testSuccess() throws ComponentInitializationException { Assert.assertEquals(lookup.apply(prc), "joe"); } @Test public void testNoAttributeCtx() throws ComponentInitializationException { prc.getSubcontext(RelyingPartyContext.class).removeSubcontext(AttributeContext.class); Assert.assertNull(lookup.apply(prc)); } @Test public void testNoAttributes() throws ComponentInitializationException { prc.getSubcontext(RelyingPartyContext.class, true).getSubcontext(AttributeContext.class).setIdPAttributes(null); Assert.assertNull(lookup.apply(prc)); } @SuppressWarnings("rawtypes") @Test public void testOnlyActive() throws ComponentInitializationException { prc.getSubcontext(RelyingPartyContext.class).removeSubcontext(AttributeContext.class); Collection<AttributeEncoder<?>> newEncoders1 = new ArrayList<AttributeEncoder<?>>(); OIDCStringAttributeEncoder encoder1 = new OIDCStringAttributeEncoder(); Predicate<ProfileRequestContext> predicate = Predicates.alwaysFalse(); encoder1.setActivationCondition(predicate); encoder1.setName("sub"); newEncoders1.add(encoder1); IdPAttribute attribute1 = new IdPAttribute("test1"); List<StringAttributeValue> stringAttributeValues1 = new ArrayList<StringAttributeValue>(); stringAttributeValues1.add(new StringAttributeValue("passiveJoe")); attribute1.setValues(stringAttributeValues1); attribute1.setEncoders(newEncoders1); Collection<AttributeEncoder<?>> newEncoders2 = new ArrayList<AttributeEncoder<?>>(); SAML2StringAttributeEncoder encoder2 = new SAML2StringAttributeEncoder(); encoder2.setName("sub"); newEncoders2.add(encoder2); IdPAttribute attribute2 = new IdPAttribute("test2"); List<StringAttributeValue> stringAttributeValues2 = new ArrayList<StringAttributeValue>(); stringAttributeValues2.add(new StringAttributeValue("saml2Joe")); attribute2.setValues(stringAttributeValues2); attribute2.setEncoders(newEncoders2); IdPAttribute attribute3 = new IdPAttribute("test2"); List<StringAttributeValue> stringAttributeValues3 = new ArrayList<StringAttributeValue>(); stringAttributeValues3.add(new StringAttributeValue("noencodersJoe")); AttributeContext attributeCtx = new AttributeContext(); Collection<IdPAttribute> attributes = new ArrayList<IdPAttribute>(); attributes.add(attribute1); attributes.add(attribute2); attributes.add(attribute3); attributeCtx.setIdPAttributes(attributes); prc.getSubcontext(RelyingPartyContext.class).addSubcontext(attributeCtx); Assert.assertNull(lookup.apply(prc)); }
AttributeResolutionSubjectLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { public void setAttributeContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, AttributeContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); attributeContextLookupStrategy = Constraint.isNotNull(strategy, "AttributeContext lookup strategy cannot be null"); } AttributeResolutionSubjectLookupFunction(); void setAttributeContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, AttributeContext> strategy); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailNullStrategy() throws ComponentInitializationException { lookup = new AttributeResolutionSubjectLookupFunction(); lookup.setAttributeContextLookupStrategy(null); }
EncodeMessage extends AbstractProfileAction { public void setMessageEncoderFactory(@Nonnull final MessageEncoderFactory factory) { encoderFactory = Constraint.isNotNull(factory, "MessageEncoderFactory cannot be null"); } void setMessageEncoderFactory(@Nonnull final MessageEncoderFactory factory); void setMessageEncoder(@Nonnull final MessageEncoder enc); void setMessageHandler(@Nullable final MessageHandler handler); }
@SuppressWarnings("unchecked") @Test public void testDecodeMessage() throws Exception { EncodeMessage action = new EncodeMessage(); action.setMessageEncoderFactory(new MockEncoderFactory()); action.initialize(); action.execute(profileCtx); ActionTestingSupport.assertProceedEvent(profileCtx); Assert.assertEquals(encoder.getEncodedMessage(), expectedMessage); } @SuppressWarnings("unchecked") @Test public void testThrowException() throws Exception { encoder.setThrowException(true); EncodeMessage action = new EncodeMessage(); action.setMessageEncoderFactory(new MockEncoderFactory()); action.initialize(); action.execute(profileCtx); ActionTestingSupport.assertEvent(profileCtx, EventIds.UNABLE_TO_ENCODE); }
SetSectorIdentifierForAttributeResolution extends AbstractOIDCAuthenticationRequestAction { public void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); sectorIdentifierLookupStrategy = Constraint.isNotNull(strategy, "SectorIdentifierLookupStrategy lookup strategy cannot be null"); } SetSectorIdentifierForAttributeResolution(); void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategySectorIdentifier() { action = new SetSectorIdentifierForAttributeResolution(); action.setSectorIdentifierLookupStrategy(null); }
SetSectorIdentifierForAttributeResolution extends AbstractOIDCAuthenticationRequestAction { public void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); subjectTypeLookupStrategy = Constraint.isNotNull(strategy, "SubjectTypeLookupStrategy lookup strategy cannot be null"); } SetSectorIdentifierForAttributeResolution(); void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategySubjectType() { action = new SetSectorIdentifierForAttributeResolution(); action.setSubjectTypeLookupStrategy(null); }
RevokeConsent extends AbstractOIDCResponseAction { public void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); promptLookupStrategy = Constraint.isNotNull(strategy, "PromptLookupStrategy lookup strategy cannot be null"); } RevokeConsent(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategy() throws NoSuchAlgorithmException, ComponentInitializationException { action = new RevokeConsent(); action.setPromptLookupStrategy(null); }
OIDCClientInformationEncryptionParametersResolver extends BasicEncryptionParametersResolver { @Override @Nullable public EncryptionParameters resolveSingle(@Nonnull final CriteriaSet criteria) throws ResolverException { Constraint.isNotNull(criteria, "CriteriaSet was null"); Constraint.isNotNull(criteria.get(EncryptionConfigurationCriterion.class), "Resolver requires an instance of EncryptionConfigurationCriterion"); final Predicate<String> whitelistBlacklistPredicate = getWhitelistBlacklistPredicate(criteria); final EncryptionParameters params = (target == ParameterType.REQUEST_OBJECT_DECRYPTION) ? new OIDCDecryptionParameters() : new EncryptionParameters(); resolveAndPopulateCredentialsAndAlgorithms(params, criteria, whitelistBlacklistPredicate); boolean encryptionOptional = false; final EncryptionOptionalCriterion encryptionOptionalCrit = criteria.get(EncryptionOptionalCriterion.class); if (encryptionOptionalCrit != null) { encryptionOptional = encryptionOptionalCrit.isEncryptionOptional(); } if (validate(params, encryptionOptional)) { logResult(params); return params; } else { return null; } } void setParameterType(ParameterType value); @Override @Nullable EncryptionParameters resolveSingle(@Nonnull final CriteriaSet criteria); }
@Test public void testIdTokenParameters() throws ResolverException { EncryptionParameters params = resolver.resolveSingle(criteria); Assert.assertEquals("RSA-OAEP-256", params.getKeyTransportEncryptionAlgorithm()); Assert.assertEquals("A192CBC-HS384", params.getDataEncryptionAlgorithm()); Assert.assertNotNull(params.getKeyTransportEncryptionCredential().getPublicKey()); } @Test public void testIdTokenParametersDefaultEnc() throws ResolverException { metaData.setIDTokenJWEEnc(null); EncryptionParameters params = resolver.resolveSingle(criteria); Assert.assertEquals("RSA-OAEP-256", params.getKeyTransportEncryptionAlgorithm()); Assert.assertEquals("A128CBC-HS256", params.getDataEncryptionAlgorithm()); Assert.assertNotNull(params.getKeyTransportEncryptionCredential().getPublicKey()); }
InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); loginHintLookupStrategy = Constraint.isNotNull(strategy, "LoginHintLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullLoginHintLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setLoginHintLookupStrategy(null); }
InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); promptLookupStrategy = Constraint.isNotNull(strategy, "PromptLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullPromptLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setPromptLookupStrategy(null); }
InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); maxAgeLookupStrategy = Constraint.isNotNull(strategy, "MaxAgeLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullMaxAgeLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setMaxAgeLookupStrategy(null); }
EncryptProcessedToken extends AbstractOIDCResponseAction { public void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encryptionContextLookupStrategy = Constraint.isNotNull(strategy, "EncryptionContext lookup strategy cannot be null"); } EncryptProcessedToken(); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); }
@SuppressWarnings("rawtypes") @Test(expectedExceptions = UnmodifiableComponentException.class) public void testInitializationFail() { action.setEncryptionContextLookupStrategy( Functions.compose(new ChildContextLookup<>(EncryptionContext.class, false), new ChildContextLookup<ProfileRequestContext, RelyingPartyContext>(RelyingPartyContext.class))); } @Test(expectedExceptions = ConstraintViolationException.class) public void testInitializationFail2() { action = new EncryptProcessedToken(); action.setEncryptionContextLookupStrategy(null); }
SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); deliveryClaimsLookupStrategy = Constraint.isNotNull(strategy, "DeliveryClaimsLookupStrategy lookup strategy cannot be null"); } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategyDClaims() { action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setDeliveryClaimsLookupStrategy(null); }
SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); idTokenDeliveryClaimsLookupStrategy = strategy; } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }
@Test public void testNullStrategyIDTokenDClaims() throws ComponentInitializationException, URISyntaxException { init(); action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setIDTokenDeliveryClaimsLookupStrategy(null); action.initialize(); final Event event = action.execute(requestCtx); ActionTestingSupport.assertProceedEvent(event); OIDCAuthenticationResponseTokenClaimsContext respTokenClaims = respCtx.getSubcontext(OIDCAuthenticationResponseTokenClaimsContext.class); Assert.assertNotNull(respTokenClaims); Assert.assertEquals(respTokenClaims.getUserinfoClaims().getClaim("deliveryClaimUI"), "deliveryClaimUIValue"); Assert.assertNull(respTokenClaims.getIdtokenClaims().getClaim("deliveryClaimID")); Assert.assertEquals(respTokenClaims.getClaims().getClaim("deliveryClaim"), "deliveryClaimValue"); }
SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); userinfoDeliveryClaimsLookupStrategy = strategy; } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }
@Test public void testNullStrategyUIDClaims() throws ComponentInitializationException, URISyntaxException { init(); action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setUserinfoDeliveryClaimsLookupStrategy(null); action.initialize(); final Event event = action.execute(requestCtx); ActionTestingSupport.assertProceedEvent(event); OIDCAuthenticationResponseTokenClaimsContext respTokenClaims = respCtx.getSubcontext(OIDCAuthenticationResponseTokenClaimsContext.class); Assert.assertNotNull(respTokenClaims); Assert.assertNull(respTokenClaims.getUserinfoClaims().getClaim("deliveryClaimUI")); Assert.assertEquals(respTokenClaims.getIdtokenClaims().getClaim("deliveryClaimID"), "deliveryClaimIDValue"); Assert.assertEquals(respTokenClaims.getClaims().getClaim("deliveryClaim"), "deliveryClaimValue"); }
InitializeUnverifiedRelyingPartyContext extends AbstractProfileAction { public void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextCreationStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext creation strategy cannot be null"); } InitializeUnverifiedRelyingPartyContext(); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullRelyingPartyContextCreationStrategy() { action = new InitializeUnverifiedRelyingPartyContext(); action.setRelyingPartyContextCreationStrategy(null); }
PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); configurationLookupStrategy = Constraint.isNotNull(strategy, "EncryptionConfiguration lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyConf() { action = new PopulateOIDCEncryptionParameters(); action.setConfigurationLookupStrategy(null); }
PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encryptionContextLookupStrategy = Constraint.isNotNull(strategy, "EncryptionContext lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyEncrContext() { action = new PopulateOIDCEncryptionParameters(); action.setEncryptionContextLookupStrategy(null); }
PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); oidcMetadataContextLookupStrategy = Constraint.isNotNull(strategy, " OIDCMetadataContext lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyMetadataContext() { action = new PopulateOIDCEncryptionParameters(); action.setOIDCMetadataContextContextLookupStrategy(null); }
PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encParamsresolver = Constraint.isNotNull(newResolver, "EncryptionParametersResolver cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyEncrParamas() { action = new PopulateOIDCEncryptionParameters(); action.setEncryptionParametersResolver(null); }
InitializeRelyingPartyContext extends AbstractProfileAction { public void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); oidcMetadataContextLookupStrategy = Constraint.isNotNull(strategy, "OIDCMetadataContext lookup strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullOidcMetadataContextLookupStrategy() { action = new InitializeRelyingPartyContext(); action.setOidcMetadataContextLookupStrategy(null); }
InitializeRelyingPartyContext extends AbstractProfileAction { public void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); clientIDLookupStrategy = Constraint.isNotNull(strategy, "ClientIDLookupStrategy lookup strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullClientIDLookupStrategy() { action = new InitializeRelyingPartyContext(); action.setClientIDLookupStrategy(null); }
InitializeRelyingPartyContext extends AbstractProfileAction { public void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextCreationStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext creation strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullRelyingPartyContextCreationStrategy() { action = new InitializeRelyingPartyContext(); action.setRelyingPartyContextCreationStrategy(null); }
FormOutboundDiscoveryResponse extends AbstractProfileAction { public void setMetadataResolver(final ProviderMetadataResolver resolver) { metadataResolver = Constraint.isNotNull(resolver, "The metadata resolver cannot be null!"); } FormOutboundDiscoveryResponse(); void setMetadataResolver(final ProviderMetadataResolver resolver); }
@Test public void testStatic() throws Exception { action.setMetadataResolver(initMetadataResolver()); action.initialize(); ActionTestingSupport.assertProceedEvent(action.execute(requestCtx)); Assert.assertTrue(profileRequestCtx.getOutboundMessageContext().getMessage() instanceof JSONSuccessResponse); final JSONSuccessResponse resp = (JSONSuccessResponse) profileRequestCtx.getOutboundMessageContext().getMessage(); Assert.assertTrue(resp.indicatesSuccess()); final JSONObject jsonObject = resp.toHTTPResponse().getContentAsJSONObject(); Assert.assertEquals(jsonObject.size(), 17); Assert.assertNull(jsonObject.get(dynamicClaim)); } @Test public void testDynamic() throws Exception { final Map<String, MetadataValueResolver> map = new HashMap<>(); map.put(dynamicClaim, initMockResolver(dynamicClaimValue)); action.setMetadataResolver(initMetadataResolver(map)); action.initialize(); ActionTestingSupport.assertProceedEvent(action.execute(requestCtx)); final JSONSuccessResponse resp = (JSONSuccessResponse) profileRequestCtx.getOutboundMessageContext().getMessage(); Assert.assertTrue(resp.indicatesSuccess()); final JSONObject jsonObject = resp.toHTTPResponse().getContentAsJSONObject(); Assert.assertEquals(jsonObject.size(), 18); Assert.assertNotNull(jsonObject.get(dynamicClaim)); Assert.assertEquals(jsonObject.get(dynamicClaim), dynamicClaimValue); }
CheckRedirectURIs extends AbstractProfileAction { protected boolean checkForbiddenHostname(final Set<URI> redirectURIs, final String hostname) { for (final URI redirectUri : redirectURIs) { if (hostname.equalsIgnoreCase(redirectUri.getHost())) { log.trace("{} Found forbidden {} as the hostname in the redirect URIs", getLogPrefix(), hostname); return true; } } return false; } CheckRedirectURIs(); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); void doInitialize(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testCheckForbiddenHostname() throws Exception { Assert.assertFalse(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("custom.test:/testing"))), "testing")); Assert.assertTrue(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("custom.test: "testing")); Assert.assertTrue(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("http: "localhost")); }
ValidateAccessToken extends AbstractOIDCUserInfoValidationResponseAction { public void setRevocationCache(@Nonnull final RevocationCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); revocationCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateAccessToken(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRevocationCache(@Nonnull final RevocationCache cache); }
@Test public void testFailsRevoked() throws NoSuchAlgorithmException, ComponentInitializationException, URISyntaxException, DataSealerException { action = new ValidateAccessToken(getDataSealer()); action.setRevocationCache(new MockRevocationCache(true, true)); action.initialize(); TokenClaimsSet claims = new AccessTokenClaimsSet.Builder(idGenerator, new ClientID(), "issuer", "userPrin", "subject", new Date(), new Date(System.currentTimeMillis() + 1000), new Date(), new URI("http: BearerAccessToken token = new BearerAccessToken(claims.serialize(getDataSealer())); UserInfoRequest req = new UserInfoRequest(new URI("http: setUserInfoRequest(req); final Event event = action.execute(requestCtx); ActionTestingSupport.assertEvent(event, OidcEventIds.INVALID_GRANT); }
OIDCClientInformationSignatureSigningParametersResolver extends BasicSignatureSigningParametersResolver { @Nullable public SignatureSigningParameters resolveSingle(@Nonnull final CriteriaSet criteria) throws ResolverException { Constraint.isNotNull(criteria, "CriteriaSet was null"); Constraint.isNotNull(criteria.get(SignatureSigningConfigurationCriterion.class), "Resolver requires an instance of SignatureSigningConfigurationCriterion"); final Predicate<String> whitelistBlacklistPredicate = getWhitelistBlacklistPredicate(criteria); final SignatureSigningParameters params = new SignatureSigningParameters(); resolveAndPopulateCredentialAndSignatureAlgorithm(params, criteria, whitelistBlacklistPredicate); if (validate(params)) { logResult(params); return params; } else { return null; } } void setParameterType(ParameterType value); @Nullable SignatureSigningParameters resolveSingle(@Nonnull final CriteriaSet criteria); }
@Test public void testIdTokenParameters() throws ResolverException { SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "RS256"); Assert.assertTrue(params.getSigningCredential().getPrivateKey() instanceof RSAPrivateKey); } @Test public void testDefaultIdTokenParameters() throws ResolverException { metaData.setIDTokenJWSAlg(null); SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "RS256"); Assert.assertTrue(params.getSigningCredential().getPrivateKey() instanceof RSAPrivateKey); } @Test public void testIdTokenParametersHS() throws ResolverException { metaData.setIDTokenJWSAlg(JWSAlgorithm.HS256); SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "HS256"); Assert.assertNotNull(params.getSigningCredential().getSecretKey()); }
AddScopeToClientMetadata extends AbstractOIDCClientMetadataPopulationAction { public void setDefaultScope(final Scope scope) { defaultScope = Constraint.isNotNull(scope, "The default scope cannot be null"); } AddScopeToClientMetadata(); void setDefaultScope(final Scope scope); Scope getDefaultScope(); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullDefault() { action = new AddScopeToClientMetadata(); action.setDefaultScope(null); } @Test public void testNullScopeCustomDefault() throws ComponentInitializationException { action = new AddScopeToClientMetadata(); Scope defaultScope = new Scope(OIDCScopeValue.OPENID, OIDCScopeValue.ADDRESS); action.setDefaultScope(defaultScope); action.initialize(); OIDCClientMetadata input = new OIDCClientMetadata(); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), defaultScope); }
AddScopeToClientMetadata extends AbstractOIDCClientMetadataPopulationAction { public Scope getDefaultScope() { return defaultScope; } AddScopeToClientMetadata(); void setDefaultScope(final Scope scope); Scope getDefaultScope(); }
@Test public void testNullScope() throws ComponentInitializationException { OIDCClientMetadata input = new OIDCClientMetadata(); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), action.getDefaultScope()); } @Test public void testEmptyScope() throws ComponentInitializationException { OIDCClientMetadata input = new OIDCClientMetadata(); input.setScope(new Scope()); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), action.getDefaultScope()); }
AddUserInfoShell extends AbstractOIDCResponseAction { public void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); issuerLookupStrategy = Constraint.isNotNull(strategy, "IssuerLookupStrategy lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullIssuerLookupStrategy() { action = new AddUserInfoShell(); action.setIssuerLookupStrategy(null); }
AddUserInfoShell extends AbstractOIDCResponseAction { public void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextLookupStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNullRelyingPartyContextLookupStrategy() { action = new AddUserInfoShell(); action.setRelyingPartyContextLookupStrategy(null); }
AddUserInfoShell extends AbstractOIDCResponseAction { public void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); userInfoSigAlgStrategy = Constraint.isNotNull(strategy, "User Info Signing Algorithm lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNulltUserInfoSigningAlgLookupStrategy() { action = new AddUserInfoShell(); action.setUserInfoSigningAlgLookupStrategy(null); }
ValidateGrant extends AbstractOIDCTokenResponseAction { public void setReplayCache(@Nonnull final ReplayCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); replayCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateGrant(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setReplayCache(@Nonnull final ReplayCache cache); void setRevocationCache(@Nonnull final RevocationCache cache); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNoRevocationCache() throws NoSuchAlgorithmException, ComponentInitializationException { action = new ValidateGrant(getDataSealer()); ReplayCache replayCache = new ReplayCache(); MemoryStorageService storageService = new MemoryStorageService(); storageService.setId("mockId"); storageService.initialize(); replayCache.setStorage(storageService); action.setReplayCache(replayCache); action.initialize(); }
ValidateGrant extends AbstractOIDCTokenResponseAction { public void setRevocationCache(@Nonnull final RevocationCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); revocationCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateGrant(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setReplayCache(@Nonnull final ReplayCache cache); void setRevocationCache(@Nonnull final RevocationCache cache); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNoReplayCache() throws NoSuchAlgorithmException, ComponentInitializationException { action = new ValidateGrant(getDataSealer()); action.setRevocationCache(new MockRevocationCache(false, true)); action.initialize(); }
SetSubjectToResponseContext extends AbstractOIDCResponseAction { public void setSubjectLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); subjectLookupStrategy = Constraint.isNotNull(strategy, "SubjectLookupStrategy lookup strategy cannot be null"); } SetSubjectToResponseContext(); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); void setSubjectLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }
@Test(expectedExceptions = ConstraintViolationException.class) public void testNoStrategy() throws NoSuchAlgorithmException, ComponentInitializationException { action = new SetSubjectToResponseContext(); action.setSubjectLookupStrategy(null); } @Test(expectedExceptions = UnmodifiableComponentException.class) public void testInitialized() throws NoSuchAlgorithmException, ComponentInitializationException { init(); action.setSubjectLookupStrategy(new TokenRequestSubjectLookupFunction()); }
OIDCByteAttributeEncoder extends AbstractOIDCAttributeEncoder { @SuppressWarnings("rawtypes") @Override public JSONObject encode(IdPAttribute idpAttribute) throws AttributeEncodingException { Constraint.isNotNull(idpAttribute, "Attribute to encode cannot be null"); String attributeString = ""; JSONObject obj = new JSONObject(); JSONArray array = new JSONArray(); for (IdPAttributeValue value : idpAttribute.getValues()) { if (value instanceof ByteAttributeValue && value.getValue() != null) { if (getAsInt()) { JSONArray innerArray = new JSONArray(); for (byte byteValue : ((ByteAttributeValue) value).getValue()) { innerArray.add((int) byteValue); } array.add(innerArray); } else { if (attributeString.length() > 0 && getStringDelimiter() != null) { attributeString += getStringDelimiter(); } attributeString += Base64Support.encode(((ByteAttributeValue) value).getValue(), Base64Support.UNCHUNKED); if (getAsArray()) { array.add(attributeString.toString()); attributeString = ""; } } } } if (getAsArray() || getAsInt()) { obj.put(getName(), array.size() == 0 ? null : array); } else { obj.put(getName(), attributeString.toString().isEmpty() ? null : attributeString.toString()); } return obj; } @SuppressWarnings("rawtypes") @Override JSONObject encode(IdPAttribute idpAttribute); }
@Test public void testEncodingNull() throws ComponentInitializationException, AttributeEncodingException { init(); boolean exceptionOccurred = false; try { encoder.encode(null); } catch (ConstraintViolationException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); } @Test public void testEncoding() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<ByteAttributeValue> byteAttributeValues = new ArrayList<ByteAttributeValue>(); byte[] bytes = new byte[1]; bytes[0] = 0; byteAttributeValues.add(new ByteAttributeValue(bytes)); attribute.setValues(byteAttributeValues); JSONObject object = encoder.encode(attribute); String base64Coded = (String) object.get("attributeName"); Assert.assertEquals(bytes, Base64.decode(base64Coded)); } @Test public void testEncoding2() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<ByteAttributeValue> byteAttributeValues = new ArrayList<ByteAttributeValue>(); byte[] bytes = new byte[2]; bytes[0] = 0; bytes[1] = 1; byteAttributeValues.add(new ByteAttributeValue(bytes)); attribute.setValues(byteAttributeValues); encoder.setAsInt(true); JSONObject object = encoder.encode(attribute); JSONArray array = (JSONArray)object.get("attributeName"); JSONArray arrayInts = (JSONArray)array.get(0); Assert.assertEquals(arrayInts.get(0),0); Assert.assertEquals(arrayInts.get(1),1); } @Test public void testEncodingWrongType() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("value1")); attribute.setValues(stringAttributeValues); attribute.setValues(stringAttributeValues); JSONObject object = encoder.encode(attribute); Assert.assertNull(object.get("attributeName")); }
OIDCStringAttributeEncoder extends AbstractOIDCAttributeEncoder { @Override public JSONObject encode(IdPAttribute idpAttribute) throws AttributeEncodingException { Constraint.isNotNull(idpAttribute, "Attribute to encode cannot be null"); log.debug("Encoding attribute {}", idpAttribute.getId()); JSONObject obj = new JSONObject(); obj.put(getName(), encodeValues(getValues(idpAttribute.getValues()))); return obj; } @Override JSONObject encode(IdPAttribute idpAttribute); }
@Test public void testEncodingNull() throws ComponentInitializationException, AttributeEncodingException { init(); boolean exceptionOccurred = false; try { encoder.encode(null); } catch (ConstraintViolationException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); } @Test public void testEncodingString() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("value1")); stringAttributeValues.add(new StringAttributeValue("value2")); attribute.setValues(stringAttributeValues); encoder.setStringDelimiter(";"); JSONObject object = encoder.encode(attribute); Assert.assertTrue(((String) object.get("attributeName")).split(";")[0].equals("value1")); Assert.assertTrue(((String) object.get("attributeName")).split(";")[1].equals("value2")); Assert.assertTrue(((String) object.get("attributeName")).split(";").length == 2); } @Test public void testEncodingStringArray() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("value1")); stringAttributeValues.add(new StringAttributeValue("value2")); attribute.setValues(stringAttributeValues); encoder.setAsArray(true); JSONObject object = encoder.encode(attribute); JSONArray array = (JSONArray)object.get("attributeName"); Assert.assertEquals("value1",array.get(0)); Assert.assertEquals("value2",array.get(1)); Assert.assertTrue(array.size() == 2); } @Test public void testEncodingInteger() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("value1")); stringAttributeValues.add(new StringAttributeValue("2")); attribute.setValues(stringAttributeValues); encoder.setAsInt(true); JSONObject object = encoder.encode(attribute); Assert.assertEquals(2,object.get("attributeName")); } @Test public void testEncodingBoolean() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("true")); stringAttributeValues.add(new StringAttributeValue("2")); attribute.setValues(stringAttributeValues); encoder.setAsBoolean(true); JSONObject object = encoder.encode(attribute); Assert.assertTrue((boolean)object.get("attributeName")); } @Test public void testEncodingJSONObject() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("{ \"name\":\"John\", \"age\":30, \"car\":null }")); attribute.setValues(stringAttributeValues); encoder.setAsObject(true); JSONObject object = encoder.encode(attribute); Assert.assertEquals("John", ((JSONObject) object.get("attributeName")).get("name")); Assert.assertEquals(30, ((JSONObject) object.get("attributeName")).get("age")); Assert.assertTrue(((JSONObject) object.get("attributeName")).containsKey("car")); } @Test public void testEncodingWrongType() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<ByteAttributeValue> byteAttributeValues = new ArrayList<ByteAttributeValue>(); byte[] bytes = new byte[1]; bytes[0] = 0; byteAttributeValues.add(new ByteAttributeValue(bytes)); attribute.setValues(byteAttributeValues); JSONObject object = encoder.encode(attribute); Assert.assertNull(object.get("attributeName")); }
OIDCScopedStringAttributeEncoder extends AbstractOIDCAttributeEncoder { @SuppressWarnings("rawtypes") @Override public JSONObject encode(IdPAttribute idpAttribute) throws AttributeEncodingException { Constraint.isNotNull(idpAttribute, "Attribute to encode cannot be null"); Constraint.isNotNull(scopeDelimiter, "Scope delimiter cannot be null"); JSONObject obj = new JSONObject(); List<String> values = new ArrayList<String>(); for (IdPAttributeValue value : idpAttribute.getValues()) { if (value instanceof ScopedStringAttributeValue && value.getValue() != null) { values.add(value.getValue() + scopeDelimiter + ((ScopedStringAttributeValue) value).getScope()); } } obj.put(getName(), values.isEmpty() ? null : encodeValues(values)); return obj; } OIDCScopedStringAttributeEncoder(); void setScopeDelimiter(@Nullable final String newScopeDelimiter); @SuppressWarnings("rawtypes") @Override JSONObject encode(IdPAttribute idpAttribute); }
@Test public void testEncodingNull() throws ComponentInitializationException, AttributeEncodingException { init(); boolean exceptionOccurred = false; try { encoder.encode(null); } catch (ConstraintViolationException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); } @Test public void testEncodingWrongType() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<ByteAttributeValue> byteAttributeValues = new ArrayList<ByteAttributeValue>(); byte[] bytes = new byte[1]; bytes[0] = 0; byteAttributeValues.add(new ByteAttributeValue(bytes)); attribute.setValues(byteAttributeValues); JSONObject object = encoder.encode(attribute); Assert.assertNull(object.get("attributeName")); }
AttributeInOIDCRequestedClaimsMatcher extends AbstractIdentifiableInitializableComponent implements Matcher { @SuppressWarnings("rawtypes") @Override public Set<IdPAttributeValue<?>> getMatchingValues(@Nonnull IdPAttribute attribute, @Nonnull AttributeFilterContext filtercontext) { ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this); List<String> names = resolveClaimNames(attribute.getEncoders()); if (names.isEmpty()) { log.debug("{} No oidc encoders attached to attribute", getLogPrefix()); return null; } ProfileRequestContext profileRequestContext = new RecursiveTypedParentContextLookup<AttributeFilterContext, ProfileRequestContext>( ProfileRequestContext.class).apply(filtercontext); if (profileRequestContext == null || profileRequestContext.getOutboundMessageContext() == null) { log.trace("{} No outbound message context", getLogPrefix()); return null; } OIDCAuthenticationResponseContext respCtx = profileRequestContext.getOutboundMessageContext() .getSubcontext(OIDCAuthenticationResponseContext.class, false); if (respCtx == null) { log.debug("{} No oidc response ctx for this comparison", getLogPrefix()); return null; } ClaimsRequest request = respCtx.getRequestedClaims(); if (request == null || (request.getIDTokenClaims() == null && request.getUserInfoClaims() == null)) { log.debug("{} No claims in request", getLogPrefix()); if (getMatchIRequestedClaimsSilent()) { log.debug("{} all values matched as in silent mode", getLogPrefix()); return ImmutableSet.copyOf(attribute.getValues()); } else { log.debug("{} none of the values matched as not silent mode", getLogPrefix()); return Collections.emptySet(); } } if (request.getIDTokenClaimNames(false) != null && !getMatchOnlyUserInfo()) { if (!Collections.disjoint(request.getIDTokenClaimNames(false), names)) { if (verifyEssentiality(request.getIDTokenClaims(), names)) { log.debug("{} all values matched as {} is requested id token claims", getLogPrefix(), attribute.getId()); return ImmutableSet.copyOf(attribute.getValues()); } } } if (request.getUserInfoClaimNames(false) != null && !getMatchOnlyIDToken()) { if (!Collections.disjoint(request.getUserInfoClaimNames(false), names)) { if (verifyEssentiality(request.getUserInfoClaims(), names)) { log.debug("{} all values matched as {} is requested user info claims", getLogPrefix(), attribute.getId()); return ImmutableSet.copyOf(attribute.getValues()); } } } log.debug("{} attribute {} was not a requested claim, none of the values matched", getLogPrefix(), attribute.getId()); return Collections.emptySet(); } boolean getOnlyIfEssential(); void setOnlyIfEssential(boolean flag); boolean getMatchOnlyIDToken(); void setMatchOnlyIDToken(boolean flag); boolean getMatchOnlyUserInfo(); void setMatchOnlyUserInfo(boolean flag); boolean getMatchIRequestedClaimsSilent(); void setMatchIfRequestedClaimsSilent(final boolean flag); @SuppressWarnings("rawtypes") @Override Set<IdPAttributeValue<?>> getMatchingValues(@Nonnull IdPAttribute attribute, @Nonnull AttributeFilterContext filtercontext); }
@Test public void testNoEncoders() throws Exception { setUp(false, false); matcher.initialize(); attribute.setEncoders(null); Assert.assertNull(matcher.getMatchingValues(attribute, filtercontext)); } @SuppressWarnings("unchecked") @Test public void testFailNoMsgCtx() throws Exception { setUp(false, false); matcher.initialize(); prc.setOutboundMessageContext(null); Assert.assertNull(matcher.getMatchingValues(attribute, filtercontext)); } @Test public void testFailNoOidcMsgCtx() throws Exception { setUp(false, false); matcher.initialize(); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(matcher.getMatchingValues(attribute, filtercontext)); } @Test public void testNoClaims() throws Exception { setUp(false, false); matcher.initialize(); Set<IdPAttributeValue<?>> result = matcher.getMatchingValues(attribute, filtercontext); Assert.assertNotNull(result); Assert.assertEquals(result.size(), 0); } @Test public void testAnyMatchIdToken() throws Exception { setUp(true, false); matcher.initialize(); Assert.assertNotNull(matcher.getMatchingValues(attribute, filtercontext)); } @Test public void testAnyMatchUserInfo() throws Exception { setUp(false, true); matcher.initialize(); Assert.assertNotNull(matcher.getMatchingValues(attribute, filtercontext)); }
CredentialMetadataValueResolver extends AbstractIdentifiableInitializableComponent implements MetadataValueResolver { @Override public Object resolveSingle(ProfileRequestContext profileRequestContext) throws ResolverException { Iterator<Object> iterator = resolve(profileRequestContext).iterator(); if (iterator.hasNext()) { return iterator.next(); } else { return null; } } CredentialMetadataValueResolver(); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); JWK parseJwkCredential(final Credential credential); @Override Iterable<Object> resolve(ProfileRequestContext profileRequestContext); @Override Object resolveSingle(ProfileRequestContext profileRequestContext); }
@Test public void testRsa() throws Exception { final CredentialMetadataValueResolver resolver = initResolver("src/test/resources/org/geant/idpextension/oidc/metadata/impl/idp-signing-rs256.jwk"); final Object result = resolver.resolveSingle(profileRequestCtx); Assert.assertNotNull(result); System.out.println(result); Assert.assertTrue(result instanceof JSONArray); final JSONObject json = (JSONObject)((JSONArray) result).get(0); Assert.assertEquals(json.keySet().size(), 6); Assert.assertEquals(json.get("kty"), "RSA"); Assert.assertEquals(json.get("n"), "pNf03ghVzMAw5sWrwDAMAZdSYNY2q7OVlxMInljMgz8XB5mf8XKH3EtP7AKrb8IAf7rGhfuH3T1N1C7F-jwIeYjXxMm2nIAZ0hXApgbccvBpf4n2H7IZflMjt4A3tt587QQSxQ069drCP4sYevxhTcLplJy6RWA0cLj-5CHyWy94zPeeA4GRd6xgHFLz0RNiSF0pF0kE4rmRgQVZ-b4_BmD9SsWnIpwhms5Ihciw36WyAGQUeZqULGsfwAMwlNLIaTCBLAoRgv370p-XsLrgz86pTkNBJqXP5GwI-ZfgiLmJuHjQ9l85KqHM87f-QdsqiV8KoRcslgXPqb6VOTJBVw"); Assert.assertEquals(json.get("e"), "AQAB"); Assert.assertEquals(json.get("alg"), "RS256"); Assert.assertEquals(json.get("use"), "sig"); Assert.assertEquals(json.get("kid"), "testkey"); }
AttributeOIDCScopePolicyRule extends AbstractStringPolicyRule { @SuppressWarnings("rawtypes") @Override public Tristate matches(@Nonnull final AttributeFilterContext filterContext) { ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this); ProfileRequestContext profileRequestContext = new RecursiveTypedParentContextLookup<AttributeFilterContext, ProfileRequestContext>( ProfileRequestContext.class).apply(filterContext); if (profileRequestContext == null || profileRequestContext.getOutboundMessageContext() == null) { log.trace("{} No outbound message context", getLogPrefix()); return Tristate.FALSE; } OIDCAuthenticationResponseContext ctx = profileRequestContext.getOutboundMessageContext() .getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null || ctx.getScope() == null) { log.trace("{} No verified requested scopes for oidc found", getLogPrefix()); return Tristate.FALSE; } List<String> scopes = ctx.getScope().toStringList(); if (scopes == null || scopes.isEmpty()) { log.warn("{} No scopes in oidc request, should not happen", getLogPrefix()); return Tristate.FAIL; } for (String scope : scopes) { log.debug("{} evaluating scope {}", getLogPrefix(), scope); if (stringCompare(scope) == Tristate.TRUE) { return Tristate.TRUE; } } return Tristate.FALSE; } @SuppressWarnings("rawtypes") @Override Tristate matches(@Nonnull final AttributeFilterContext filterContext); }
@Test public void testMatch() throws Exception { Assert.assertEquals(Tristate.TRUE, rule.matches(filtercontext)); } @Test public void testNoMatch() throws Exception { Scope scope = new Scope(); scope.add("openid"); scope.add("test_no_match"); authRespCtx.setScope(scope); Assert.assertEquals(Tristate.FALSE, rule.matches(filtercontext)); } @Test public void testNoOIDCRespCtx() throws Exception { msgCtx.removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertEquals(Tristate.FALSE, rule.matches(filtercontext)); } @Test public void testNoScope() throws Exception { Scope scope = new Scope(); authRespCtx.setScope(scope); Assert.assertEquals(Tristate.FAIL, rule.matches(filtercontext)); }
RefreshTokenClaimsSet extends TokenClaimsSet { public static RefreshTokenClaimsSet parse(String refreshTokenClaimsSet) throws ParseException { JWTClaimsSet atClaimsSet = JWTClaimsSet.parse(refreshTokenClaimsSet); verifyParsedClaims(VALUE_TYPE_RF, atClaimsSet); return new RefreshTokenClaimsSet(atClaimsSet); } RefreshTokenClaimsSet(@Nonnull TokenClaimsSet tokenClaimsSet, @Nonnull Date iat, @Nonnull Date exp); private RefreshTokenClaimsSet(JWTClaimsSet refreshTokenClaimsSet); static RefreshTokenClaimsSet parse(String refreshTokenClaimsSet); static RefreshTokenClaimsSet parse(@Nonnull String wrappedAccessToken, @Nonnull DataSealer dataSealer); }
@Test public void testSerialization() throws ParseException, DataSealerException { init(); RefreshTokenClaimsSet rfClaimsSet2 = RefreshTokenClaimsSet.parse(rfClaimsSet.serialize()); Assert.assertEquals(rfClaimsSet2.getACR(), acr.getValue()); RefreshTokenClaimsSet rfClaimsSet3 = RefreshTokenClaimsSet.parse(rfClaimsSet2.serialize(sealer), sealer); Assert.assertEquals(rfClaimsSet3.getACR(), acr.getValue()); } @Test(expectedExceptions = ParseException.class) public void testSerializationWrongType() throws ParseException { AuthorizeCodeClaimsSet accessnClaimsSet = new AuthorizeCodeClaimsSet.Builder(new SecureRandomIdentifierGenerationStrategy(), clientID, issuer, userPrincipal, subject, iat, exp, authTime, redirectURI, scope).build(); rfClaimsSet = RefreshTokenClaimsSet.parse(accessnClaimsSet.serialize()); }
AuthorizeCodeClaimsSet extends TokenClaimsSet { public static AuthorizeCodeClaimsSet parse(String authorizeCodeClaimsSet) throws ParseException { JWTClaimsSet acClaimsSet = JWTClaimsSet.parse(authorizeCodeClaimsSet); verifyParsedClaims(VALUE_TYPE_AC, acClaimsSet); return new AuthorizeCodeClaimsSet(acClaimsSet); } private AuthorizeCodeClaimsSet(@Nonnull IdentifierGenerationStrategy idGenerator, @Nonnull ClientID clientID, @Nonnull String issuer, @Nonnull String userPrincipal, @Nonnull String subject, @Nonnull ACR acr, @Nonnull Date iat, @Nonnull Date exp, @Nullable Nonce nonce, @Nonnull Date authTime, @Nonnull URI redirectURI, @Nonnull Scope scope, @Nullable ClaimsRequest claims, @Nullable ClaimsSet dlClaims, @Nullable ClaimsSet dlClaimsID, @Nullable ClaimsSet dlClaimsUI, @Nullable JSONArray consentableClaims, @Nullable JSONArray consentedClaims, @Nullable String codeChallenge); private AuthorizeCodeClaimsSet(JWTClaimsSet authzCodeClaimsSet); static AuthorizeCodeClaimsSet parse(String authorizeCodeClaimsSet); static AuthorizeCodeClaimsSet parse(@Nonnull String wrappedAuthCode, @Nonnull DataSealer dataSealer); static final String VALUE_TYPE_AC; }
@Test public void testSerialization() throws ParseException, DataSealerException { init(); AuthorizeCodeClaimsSet acClaimsSet2 = AuthorizeCodeClaimsSet.parse(acClaimsSet.serialize()); Assert.assertEquals(acClaimsSet2.getACR(), acr.getValue()); AuthorizeCodeClaimsSet acClaimsSet3 = AuthorizeCodeClaimsSet.parse(acClaimsSet2.serialize(sealer), sealer); Assert.assertEquals(acClaimsSet3.getACR(), acr.getValue()); } @Test(expectedExceptions = ParseException.class) public void testSerializationWrongType() throws ParseException { AccessTokenClaimsSet accessnClaimsSet = new AccessTokenClaimsSet.Builder(new SecureRandomIdentifierGenerationStrategy(), clientID, issuer, userPrincipal, subject, iat, exp, authTime, redirectURI, scope).build(); acClaimsSet = AuthorizeCodeClaimsSet.parse(accessnClaimsSet.serialize()); }
AccessTokenClaimsSet extends TokenClaimsSet { public static AccessTokenClaimsSet parse(String accessTokenClaimsSet) throws ParseException { JWTClaimsSet atClaimsSet = JWTClaimsSet.parse(accessTokenClaimsSet); verifyParsedClaims(VALUE_TYPE_AT, atClaimsSet); return new AccessTokenClaimsSet(atClaimsSet); } AccessTokenClaimsSet(@Nonnull TokenClaimsSet tokenClaimSet, @Nonnull Scope scope, @Nullable ClaimsSet dlClaims, @Nullable ClaimsSet dlClaimsUI, @Nonnull Date iat, @Nonnull Date exp); private AccessTokenClaimsSet(@Nonnull IdentifierGenerationStrategy idGenerator, @Nonnull ClientID clientID, @Nonnull String issuer, @Nonnull String userPrincipal, @Nonnull String subject, @Nullable ACR acr, @Nonnull Date iat, @Nonnull Date exp, @Nullable Nonce nonce, @Nonnull Date authTime, @Nonnull URI redirectURI, @Nonnull Scope scope, @Nullable ClaimsRequest claims, @Nullable ClaimsSet dlClaims, @Nullable ClaimsSet dlClaimsUI, @Nullable JSONArray consentableClaims, @Nullable JSONArray consentedClaims); private AccessTokenClaimsSet(JWTClaimsSet accessTokenClaimsSet); static AccessTokenClaimsSet parse(String accessTokenClaimsSet); static AccessTokenClaimsSet parse(@Nonnull String wrappedAccessToken, @Nonnull DataSealer dataSealer); }
@Test public void testSerialization() throws ParseException, DataSealerException { init(); AccessTokenClaimsSet acClaimsSet2 = AccessTokenClaimsSet.parse(atClaimsSet.serialize()); Assert.assertEquals(acClaimsSet2.getACR(), acr.getValue()); AccessTokenClaimsSet acClaimsSet3 = AccessTokenClaimsSet.parse(acClaimsSet2.serialize(sealer), sealer); Assert.assertEquals(acClaimsSet3.getACR(), acr.getValue()); } @Test(expectedExceptions = ParseException.class) public void testSerializationWrongType() throws ParseException { AuthorizeCodeClaimsSet accessnClaimsSet = new AuthorizeCodeClaimsSet.Builder(new SecureRandomIdentifierGenerationStrategy(), clientID, issuer, userPrincipal, subject, iat, exp, authTime, redirectURI, scope).setACR(acr).build(); atClaimsSet = AccessTokenClaimsSet.parse(accessnClaimsSet.serialize()); }
ChaosMonkeyScheduler { public void reloadConfig() { String cronExpression = config.getRuntimeAssaultCronExpression(); boolean active = !"OFF".equals(cronExpression); if (currentTask != null) { Logger.info("Cancelling previous task"); currentTask.cancel(); currentTask = null; } if (active) { CronTask task = new CronTask(runtimeScope::callChaosMonkey, cronExpression); currentTask = scheduler.scheduleCronTask(task); } } ChaosMonkeyScheduler( ScheduledTaskRegistrar scheduler, AssaultProperties config, ChaosMonkeyRuntimeScope runtimeScope); void reloadConfig(); }
@Test void shouldScheduleANewTaskAfterAnUpdate() { String schedule = "*/1 * * * * ?"; ScheduledTask oldTask = mock(ScheduledTask.class); ScheduledTask newTask = mock(ScheduledTask.class); when(config.getRuntimeAssaultCronExpression()).thenReturn(schedule); when(registrar.scheduleCronTask(any())).thenReturn(oldTask, newTask); ChaosMonkeyScheduler cms = new ChaosMonkeyScheduler(registrar, config, scope); cms.reloadConfig(); verify(registrar, times(2)).scheduleCronTask(argThat(hasScheduleLike(schedule))); verify(oldTask).cancel(); }
LatencyAssault implements ChaosMonkeyRequestAssault { @Override public void attack() { Logger.debug("Chaos Monkey - timeout"); atomicTimeoutGauge.set(determineLatency()); if (metricEventPublisher != null) { metricEventPublisher.publishMetricEvent(MetricType.LATENCY_ASSAULT); metricEventPublisher.publishMetricEvent(MetricType.LATENCY_ASSAULT, atomicTimeoutGauge); } assaultExecutor.execute(atomicTimeoutGauge.get()); } LatencyAssault( ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher, ChaosMonkeyLatencyAssaultExecutor executor); LatencyAssault(ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher); @Override boolean isActive(); @Override void attack(); }
@Test void threadSleepHasBeenCalled() { int latencyRangeStart = 100; int latencyRangeEnd = 200; TestLatencyAssaultExecutor executor = new TestLatencyAssaultExecutor(); when(assaultProperties.getLatencyRangeStart()).thenReturn(latencyRangeStart); when(assaultProperties.getLatencyRangeEnd()).thenReturn(latencyRangeEnd); when(chaosMonkeySettings.getAssaultProperties()).thenReturn(assaultProperties); LatencyAssault latencyAssault = new LatencyAssault(chaosMonkeySettings, null, executor); latencyAssault.attack(); assertTrue(executor.executed); String assertionMessage = "Latency not in range 100-200, actual latency: " + executor.duration; assertTrue(executor.duration >= latencyRangeStart, assertionMessage); assertTrue(executor.duration <= latencyRangeEnd, assertionMessage); }
KillAppAssault implements ChaosMonkeyRuntimeAssault, ApplicationContextAware { @Override public void attack() { try { Logger.info("Chaos Monkey - I am killing your Application!"); if (metricEventPublisher != null) { metricEventPublisher.publishMetricEvent(MetricType.KILLAPP_ASSAULT); } int exit = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0); Thread.sleep(5000); System.exit(exit); } catch (Exception e) { Logger.info("Chaos Monkey - Unable to kill the App, I am not the BOSS!"); } } KillAppAssault(ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher); @Override boolean isActive(); @Override void attack(); @Override void setApplicationContext(ApplicationContext applicationContext); }
@Test void killsSpringBootApplication() { KillAppAssault killAppAssault = new KillAppAssault(null, metricsMock); killAppAssault.attack(); verify(mockAppender, times(2)).doAppend(captorLoggingEvent.capture()); assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(0).getLevel()); assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(1).getLevel()); assertEquals( "Chaos Monkey - I am killing your Application!", captorLoggingEvent.getAllValues().get(0).getMessage()); assertEquals( "Chaos Monkey - Unable to kill the App, I am not the BOSS!", captorLoggingEvent.getAllValues().get(1).getMessage()); }
GreetingService { public String greet() { return "Greetings from the server side!"; } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }
@Test public void greet() { assertThat(greetingService.greet(), is("Greetings from the server side!")); }
GreetingService { public String greetFromRepo() { Hello databaseSide = helloRepo.save(new Hello(0, "Greetings from the database side")); return databaseSide.getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }
@Test public void greetFromRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoMock.save(any(Hello.class))).thenReturn(saveObject); assertThat(greetingService.greetFromRepo(), is(message)); verify(helloRepoMock, times(1)).save(any(Hello.class)); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
GreetingService { public String greetFromRepoPagingSorting() { Hello databaseSide = repoSearchAndSorting.save( new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = repoSearchAndSorting.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }
@Test public void testPagingAndSorting() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoSearchAndSortingMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoSearchAndSortingMock.findById(saveObject.getId())) .thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoPagingSorting(), is(message)); verify(helloRepoSearchAndSortingMock, times(1)).save(any(Hello.class)); verify(helloRepoSearchAndSortingMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
GreetingService { public String greetFromRepoJpa() { Hello databaseSide = helloRepoJpa.save(new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = helloRepoJpa.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }
@Test public void testJpaRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoJpaMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoJpaMock.findById(saveObject.getId())).thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoJpa(), is(message)); verify(helloRepoJpaMock, times(1)).save(any(Hello.class)); verify(helloRepoJpaMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
GreetingService { public String greetFromRepoAnnotation() { Hello databaseSide = helloRepoAnnotation.save( new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = helloRepoAnnotation.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }
@Test public void testAnnotationRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoAnnotationMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoAnnotationMock.findById(saveObject.getId())).thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoAnnotation(), is(message)); verify(helloRepoAnnotationMock, times(1)).save(any(Hello.class)); verify(helloRepoAnnotationMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
ExponentialMovingAverage { public static long predictNext(TreeMap<Integer, Long> laps) { float smoothing = (((float) 2) / (laps.size() + 1)); long previousEMA = laps.get(laps.firstKey()); Set<Integer> keys = laps.keySet(); for (Iterator<Integer> i = keys.iterator(); i.hasNext();) { Integer key = i.next(); previousEMA = (long) ((laps.get(key) - previousEMA) * smoothing + previousEMA); } return (long) ((previousEMA - previousEMA) * smoothing + previousEMA); } static long getAverage(TreeMap<Integer, Long> laps); static long predictNext(TreeMap<Integer, Long> laps); }
@Test public void test() { TreeMap<Integer, Long> laps = new TreeMap<Integer, Long>(); laps.put(1, (long) 2227); laps.put(2, (long) 2219); laps.put(3, (long) 2208); laps.put(4, (long) 2217); laps.put(5, (long) 2213); laps.put(6, (long) 2223); laps.put(7, (long) 2243); laps.put(8, (long) 2224); laps.put(9, (long) 2229); System.out.println(ExponentialMovingAverage.predictNext(laps)); }
MyService { @GET @Path("/helloworld") public String helloWorld() { return "Hello World!"; } @GET @Path("/helloworld") String helloWorld(); @GET @Path("/friends/{name}") Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db); @POST @Path("/permissions") Response permissions(String body, @Context GraphDatabaseService db); }
@Test public void shouldRespondToHelloWorld() { assertEquals("Hello World!", service.helloWorld()); }
MyService { @GET @Path("/friends/{name}") public Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db) throws IOException { ExecutionEngine executionEngine = new ExecutionEngine(db); ExecutionResult result = executionEngine.execute("START person=node:Users(unique_id={n}) MATCH person-[:KNOWS]-other RETURN other.unique_id", Collections.<String, Object>singletonMap("n", name)); List<String> friends = new ArrayList<String>(); for (Map<String, Object> item : result) { friends.add((String) item.get("other.unique_id")); } return Response.ok().entity(objectMapper.writeValueAsString(friends)).build(); } @GET @Path("/helloworld") String helloWorld(); @GET @Path("/friends/{name}") Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db); @POST @Path("/permissions") Response permissions(String body, @Context GraphDatabaseService db); }
@Test public void shouldQueryDbForFriends() throws IOException { Response response = service.getFriends("B", db); List list = objectMapper.readValue((String) response.getEntity(), List.class); assertEquals(new HashSet<String>(Arrays.asList("A", "C")), new HashSet<String>(list)); }
MyService { @POST @Path("/permissions") public Response permissions(String body, @Context GraphDatabaseService db) throws IOException { String[] splits = body.split(","); PermissionRequest ids = new PermissionRequest(splits[0], splits[1]); Set<String> documents = new HashSet<String>(); Set<Node> documentNodes = new HashSet<Node>(); List<Node> groupNodes = new ArrayList<Node>(); Set<Node> parentNodes = new HashSet<Node>(); HashMap<Node, ArrayList<Node>> foldersAndDocuments = new HashMap<Node, ArrayList<Node>>(); IndexHits<Node> uid = db.index().forNodes("Users").get("unique_id", ids.userAccountUid); IndexHits<Node> docids = db.index().forNodes("Documents").query("unique_id:(" + ids.documentUids + ")"); try { for ( Node node : docids ) { documentNodes.add(node); } } finally { docids.close(); } Node user = uid.getSingle(); if ( user != null && documentNodes.size() > 0) { for ( Relationship relationship : user.getRelationships( RelTypes.IS_MEMBER_OF, Direction.OUTGOING ) ) { groupNodes.add(relationship.getEndNode()); } Iterator listIterator ; do { listIterator = documentNodes.iterator(); Node document = (Node) listIterator.next(); listIterator.remove(); Node found = getAllowed(document, user); if (found != null) { if (foldersAndDocuments.get(found) != null) { for(Node docs : foldersAndDocuments.get(found)) { documents.add(docs.getProperty("unique_id").toString()); } } else { documents.add(found.getProperty("unique_id").toString()); } } for (Node group : groupNodes){ found = getAllowed(document, group); if (found != null) { if (foldersAndDocuments.get(found) != null) { for(Node docs : foldersAndDocuments.get(found)) { documents.add(docs.getProperty("unique_id").toString()); } } else { documents.add(found.getProperty("unique_id").toString()); } } } Relationship parentRelationship = document.getSingleRelationship(RelTypes.HAS_CHILD_CONTENT,Direction.INCOMING); if (parentRelationship != null){ Node parent = parentRelationship.getStartNode(); ArrayList<Node> myDocs = foldersAndDocuments.get(document); if(myDocs == null) myDocs = new ArrayList<Node>(); ArrayList<Node> existingDocs = foldersAndDocuments.get(parent); if(existingDocs == null) existingDocs = new ArrayList<Node>(); for (Node myDoc:myDocs) { existingDocs.add(myDoc); } if (myDocs.isEmpty()) existingDocs.add(document); foldersAndDocuments.put(parent, existingDocs); parentNodes.add(parent); } if(listIterator.hasNext() == false){ documentNodes.clear(); for( Node parentNode : parentNodes){ documentNodes.add(parentNode); } parentNodes.clear(); listIterator = documentNodes.iterator(); } } while (listIterator.hasNext()); } else {documents.add("Error: User or Documents not found");} uid.close(); return Response.ok().entity(objectMapper.writeValueAsString(documents)).build(); } @GET @Path("/helloworld") String helloWorld(); @GET @Path("/friends/{name}") Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db); @POST @Path("/permissions") Response permissions(String body, @Context GraphDatabaseService db); }
@Test public void shouldRespondToPermissions() throws BadInputException, IOException { String ids = "A,DOC1 DOC2 DOC3 DOC4 DOC5 DOC6 DOC7"; Response response = service.permissions(ids, db); List list = objectMapper.readValue((String) response.getEntity(), List.class); assertEquals(new HashSet<String>(Arrays.asList("DOC1", "DOC2", "DOC3", "DOC4", "DOC5", "DOC7")), new HashSet<String>(list)); } @Test public void shouldRespondToPermissions2() throws BadInputException, IOException { String ids = "B,DOC1 DOC2 DOC3 DOC4 DOC5 DOC6 DOC7"; Response response = service.permissions(ids, db); List list = objectMapper.readValue((String) response.getEntity(), List.class); assertEquals(new HashSet<String>(Arrays.asList("DOC4", "DOC6")), new HashSet<String>(list)); }
InstructionLoader { void loadInstruction() { bannerComponentTree.loadInstruction(textView); } InstructionLoader(TextView textView, @NonNull BannerText bannerText); InstructionLoader(TextView textView, BannerComponentTree bannerComponentTree); }
@Test public void loadInstruction() { TextView textView = mock(TextView.class); BannerComponentTree bannerComponentTree = mock(BannerComponentTree.class); InstructionLoader instructionLoader = new InstructionLoader(textView, bannerComponentTree); instructionLoader.loadInstruction(); verify(bannerComponentTree).loadInstruction(textView); }
MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { @Override public void onTransitionFinished(int trackingMode) { updateCameraTracking(trackingMode); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }
@Test public void onTransitionFinished_resetFpsWhenNotTracking() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.onTransitionFinished(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE); verify(mapView).setMaximumFps(eq(Integer.MAX_VALUE)); }
MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { @Override public void onTransitionCancelled(int trackingMode) { updateCameraTracking(trackingMode); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }
@Test public void onTransitionCancelled_resetFpsWhenNotTracking() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.onTransitionCancelled(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE); verify(mapView).setMaximumFps(eq(Integer.MAX_VALUE)); }
MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { void updateEnabled(boolean isEnabled) { this.isEnabled = isEnabled; resetMaxFps(!isEnabled); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }
@Test public void updateEnabledFalse_maxFpsReset() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.updateEnabled(false); mapView.setMaximumFps(eq(Integer.MAX_VALUE)); }
MapWayNameChangedListener implements OnWayNameChangedListener { @Override public void onWayNameChanged(@NonNull String wayName) { for (OnWayNameChangedListener listener : listeners) { listener.onWayNameChanged(wayName); } } MapWayNameChangedListener(List<OnWayNameChangedListener> listeners); @Override void onWayNameChanged(@NonNull String wayName); }
@Test public void onWayNameChanged_listenersAreUpdated() { List<OnWayNameChangedListener> listeners = new ArrayList<>(); OnWayNameChangedListener listener = mock(OnWayNameChangedListener.class); listeners.add(listener); MapWayNameChangedListener wayNameChangedListener = new MapWayNameChangedListener(listeners); String someWayName = "some way name"; wayNameChangedListener.onWayNameChanged(someWayName); verify(listener).onWayNameChanged(eq(someWayName)); }
MapPaddingAdjustor { void adjustLocationIconWith(@NonNull int[] customPadding) { this.customPadding = customPadding; updatePaddingWith(customPadding); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }
@Test public void adjustLocationIconWith_customPaddingIsSet() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; int[] customPadding = {0, 0, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.adjustLocationIconWith(customPadding); verify(mapboxMap).setPadding(0, 0, 0, 0); }
MapPaddingAdjustor { boolean isUsingDefault() { return customPadding == null; } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }
@Test public void isUsingDefault_trueWithoutCustomPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); assertTrue(paddingAdjustor.isUsingDefault()); }
MapPaddingAdjustor { void updatePaddingWith(int[] padding) { mapboxMap.setPadding(padding[0], padding[1], padding[2], padding[3]); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }
@Test public void updatePaddingWithZero_updatesMapToZeroPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.updatePaddingWith(new int[]{0, 0, 0, 0}); verify(mapboxMap).setPadding(0, 0, 0, 0); }
MapPaddingAdjustor { @NonNull int[] retrieveCurrentPadding() { return mapboxMap.getPadding(); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }
@Test public void retrieveCurrentPadding_returnsCurrentMapPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.retrieveCurrentPadding(); verify(mapboxMap).getPadding(); }
MapLayerInteractor { void updateLayerVisibility(boolean isVisible, String layerIdentifier) { List<Layer> layers = mapboxMap.getStyle().getLayers(); updateLayerWithVisibility(layerIdentifier, layers, isVisible); } MapLayerInteractor(MapboxMap mapboxMap); }
@Test public void updateLayerVisibility_visibilityIsSet() { LineLayer anySymbolOrLineLayer = mock(LineLayer.class); when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any"); List<Layer> layers = buildLayerListWith(anySymbolOrLineLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); layerInteractor.updateLayerVisibility(true, "any"); verify(anySymbolOrLineLayer).setProperties(any(PropertyValue.class)); } @Test public void updateLayerVisibility_visibilityIsNotSet() { SymbolLayer anySymbolOrLineLayer = mock(SymbolLayer.class); when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any"); List<Layer> layers = buildLayerListWith(anySymbolOrLineLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); layerInteractor.updateLayerVisibility(true, "random"); verify(anySymbolOrLineLayer, times(0)).setProperties(any(PropertyValue.class)); } @Test public void updateLayerVisibility_visibilityIsNotSetIfInvalidLayer() { CircleLayer invalidLayer = mock(CircleLayer.class); List<Layer> layers = buildLayerListWith(invalidLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); layerInteractor.updateLayerVisibility(true, "circle"); verify(invalidLayer, times(0)).setProperties(any(PropertyValue.class)); }
UrlDensityMap extends SparseArray<String> { @NonNull public String get(String url) { return url + super.get(displayDensity); } UrlDensityMap(int displayDensity, @NonNull SdkVersionChecker sdkVersionChecker); @NonNull String get(String url); }
@Test public void checksAndroidLollipopMr1AndTwoHundredAndEightyDensityReturnsTwoXPngUrl() { int twoHundredAndEightyDensityDpi = 280; SdkVersionChecker lollipopMr1Checker = new SdkVersionChecker(22); UrlDensityMap urlDensityMap = new UrlDensityMap(twoHundredAndEightyDensityDpi, lollipopMr1Checker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@2x.png", threeXPng); } @Test public void checksAndroidMAndThreeHundredAndSixtyDensityReturnsThreeXPngUrl() { int threeHundredAndSixtyDensityDpi = 360; SdkVersionChecker mChecker = new SdkVersionChecker(23); UrlDensityMap urlDensityMap = new UrlDensityMap(threeHundredAndSixtyDensityDpi, mChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidMAndFourHundredAndTwentyDensityReturnsThreeXPngUrl() { int fourHundredAndTwentyDensityDpi = 420; SdkVersionChecker mChecker = new SdkVersionChecker(23); UrlDensityMap urlDensityMap = new UrlDensityMap(fourHundredAndTwentyDensityDpi, mChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidNMr1AndTwoHundredAndSixtyDensityReturnsTwoXPngUrl() { int twoHundredAndSixtyDensityDpi = 260; SdkVersionChecker nMr1Checker = new SdkVersionChecker(25); UrlDensityMap urlDensityMap = new UrlDensityMap(twoHundredAndSixtyDensityDpi, nMr1Checker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@2x.png", threeXPng); } @Test public void checksAndroidNMr1AndThreeHundredDensityReturnsTwoXPngUrl() { int threeHundredDensityDpi = 300; SdkVersionChecker nMr1Checker = new SdkVersionChecker(25); UrlDensityMap urlDensityMap = new UrlDensityMap(threeHundredDensityDpi, nMr1Checker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@2x.png", threeXPng); } @Test public void checksAndroidNMr1AndThreeHundredAndFortyDensityReturnsThreeXPngUrl() { int threeHundredAndFortyDensityDpi = 340; SdkVersionChecker nMr1Checker = new SdkVersionChecker(25); UrlDensityMap urlDensityMap = new UrlDensityMap(threeHundredAndFortyDensityDpi, nMr1Checker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidPAndFourHundredAndFortyDensityReturnsThreeXPngUrl() { int fourHundredAndFortyDensityDpi = 440; SdkVersionChecker androidPChecker = new SdkVersionChecker(28); UrlDensityMap urlDensityMap = new UrlDensityMap(fourHundredAndFortyDensityDpi, androidPChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksDensityLowReturnsOneXPngUrl() { int lowDensityDpi = 120; SdkVersionChecker anySdkVersionChecker = new SdkVersionChecker(18); UrlDensityMap urlDensityMap = new UrlDensityMap(lowDensityDpi, anySdkVersionChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@1x.png", threeXPng); } @Test public void checksDensityMediumReturnsOneXPngUrl() { int mediumDensityDpi = 160; SdkVersionChecker anySdkVersionChecker = new SdkVersionChecker(14); UrlDensityMap urlDensityMap = new UrlDensityMap(mediumDensityDpi, anySdkVersionChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@1x.png", threeXPng); } @Test public void checksDensityHighReturnsTwoXPngUrl() { int highDensityDpi = 240; SdkVersionChecker anySdkVersionChecker = new SdkVersionChecker(15); UrlDensityMap urlDensityMap = new UrlDensityMap(highDensityDpi, anySdkVersionChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@2x.png", threeXPng); } @Test public void checksDensityXHighReturnsThreeXPngUrl() { int xhighDensityDpi = 320; SdkVersionChecker anySdkVersionChecker = new SdkVersionChecker(21); UrlDensityMap urlDensityMap = new UrlDensityMap(xhighDensityDpi, anySdkVersionChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidJellyBeanAndDensityXxhighReturnsThreeXPngUrl() { int xxhighDensityDpi = 480; SdkVersionChecker jellyBeanChecker = new SdkVersionChecker(16); UrlDensityMap urlDensityMap = new UrlDensityMap(xxhighDensityDpi, jellyBeanChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidJellyBeanMr2AndDensityXxxhighReturnsFourXPngUrl() { int xxxhighDensityDpi = 640; SdkVersionChecker jellyBeanMr2Checker = new SdkVersionChecker(18); UrlDensityMap urlDensityMap = new UrlDensityMap(xxxhighDensityDpi, jellyBeanMr2Checker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@4x.png", threeXPng); } @Test public void checksAndroidKitkatAndFourHundredDensityReturnsThreeXPngUrl() { int fourHundredDensityDpi = 400; SdkVersionChecker kitkatChecker = new SdkVersionChecker(19); UrlDensityMap urlDensityMap = new UrlDensityMap(fourHundredDensityDpi, kitkatChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@3x.png", threeXPng); } @Test public void checksAndroidLollipopAndFiveHundredAndSixtyDensityReturnsFourXPngUrl() { int fiveHundredAndSixtyDensityDpi = 560; SdkVersionChecker lollipopChecker = new SdkVersionChecker(21); UrlDensityMap urlDensityMap = new UrlDensityMap(fiveHundredAndSixtyDensityDpi, lollipopChecker); String anyUrl = "any.url"; String threeXPng = urlDensityMap.get(anyUrl); assertEquals(anyUrl + "@4x.png", threeXPng); }
MapLayerInteractor { boolean isLayerVisible(String layerIdentifier) { List<Layer> layers = mapboxMap.getStyle().getLayers(); return findLayerVisibility(layerIdentifier, layers); } MapLayerInteractor(MapboxMap mapboxMap); }
@Test public void isLayerVisible_visibleReturnsTrue() { SymbolLayer anySymbolOrLineLayer = mock(SymbolLayer.class); when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any"); when(anySymbolOrLineLayer.getVisibility()).thenReturn(visibility(Property.VISIBLE)); List<Layer> layers = buildLayerListWith(anySymbolOrLineLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); boolean isVisible = layerInteractor.isLayerVisible("any"); assertTrue(isVisible); } @Test public void isLayerVisible_visibleReturnsFalse() { LineLayer anySymbolOrLineLayer = mock(LineLayer.class); when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any"); when(anySymbolOrLineLayer.getVisibility()).thenReturn(visibility(Property.NONE)); List<Layer> layers = buildLayerListWith(anySymbolOrLineLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); boolean isVisible = layerInteractor.isLayerVisible("any"); assertFalse(isVisible); } @Test public void isLayerVisible_visibleReturnsFalseIfInvalidLayer() { HeatmapLayer invalidLayer = mock(HeatmapLayer.class); List<Layer> layers = buildLayerListWith(invalidLayer); MapboxMap map = mock(MapboxMap.class); when(map.getStyle()).thenReturn(mock(Style.class)); when(map.getStyle().getLayers()).thenReturn(layers); MapLayerInteractor layerInteractor = new MapLayerInteractor(map); boolean isVisible = layerInteractor.isLayerVisible("heatmap"); assertFalse(isVisible); }
WaynameFeatureFinder { @NonNull List<Feature> queryRenderedFeatures(@NonNull PointF point, String[] layerIds) { return mapboxMap.queryRenderedFeatures(point, layerIds); } WaynameFeatureFinder(MapboxMap mapboxMap); }
@Test public void queryRenderedFeatures_mapboxMapIsCalled() { MapboxMap mapboxMap = mock(MapboxMap.class); WaynameFeatureFinder featureFinder = new WaynameFeatureFinder(mapboxMap); PointF point = mock(PointF.class); String[] layerIds = {"id", "id"}; featureFinder.queryRenderedFeatures(point, layerIds); verify(mapboxMap).queryRenderedFeatures(point, layerIds); }
NavigationSymbolManager { void addDestinationMarkerFor(@NonNull Point position) { if (destinationSymbol != null) { symbolManager.delete(destinationSymbol); markersSymbols.remove(destinationSymbol.getId()); } SymbolOptions options = createSymbolOptionsFor(position); destinationSymbol = createSymbolFrom(options); } NavigationSymbolManager(@NonNull SymbolManager symbolManager); }
@Test public void addDestinationMarkerFor_symbolManagerAddsOptions() { SymbolManager symbolManager = mock(SymbolManager.class); Symbol symbol = buildSymbolWith(DEFAULT_SYMBOL_ID, DEFAULT_SYMBOL_ICON_IMAGE); when(symbolManager.create(any(SymbolOptions.class))).thenReturn(symbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); Point position = Point.fromLngLat(1.2345, 1.3456); navigationSymbolManager.addDestinationMarkerFor(position); verify(symbolManager).create(any(SymbolOptions.class)); } @Test public void addDestinationMarkerFor_destinationSymbolRemovedIfPreviouslyAdded() { SymbolManager symbolManager = mock(SymbolManager.class); Symbol oldDestinationSymbol = mock(Symbol.class); Symbol currentDestinationSymbol = mock(Symbol.class); when(symbolManager.create(any(SymbolOptions.class))).thenReturn(oldDestinationSymbol, currentDestinationSymbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); Point position = Point.fromLngLat(1.2345, 1.3456); navigationSymbolManager.addDestinationMarkerFor(position); navigationSymbolManager.addDestinationMarkerFor(position); verify(symbolManager, times(2)).create(any(SymbolOptions.class)); verify(symbolManager, times(1)).delete(eq(oldDestinationSymbol)); }
NavigationSymbolManager { Symbol addCustomSymbolFor(@NonNull SymbolOptions options) { return createSymbolFrom(options); } NavigationSymbolManager(@NonNull SymbolManager symbolManager); }
@Test public void addCustomSymbolFor_symbolManagerCreatesSymbol() { Symbol symbol = buildSymbolWith(DEFAULT_SYMBOL_ID, DEFAULT_SYMBOL_ICON_IMAGE); SymbolOptions symbolOptions = mock(SymbolOptions.class); SymbolManager symbolManager = buildSymbolManager(symbolOptions, symbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); navigationSymbolManager.addCustomSymbolFor(symbolOptions); verify(symbolManager).create(symbolOptions); }