Search in sources :

Example 31 with NonNull

use of lombok.NonNull in project cas by apereo.

the class SamlProfileSamlSubjectBuilder method buildSubject.

private Subject buildSubject(final HttpServletRequest request, final HttpServletResponse response, final RequestAbstractType authnRequest, final Object casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    final Assertion assertion = Assertion.class.cast(casAssertion);
    final ZonedDateTime validFromDate = ZonedDateTime.ofInstant(assertion.getValidFromDate().toInstant(), ZoneOffset.UTC);
    LOGGER.debug("Locating the assertion consumer service url for binding [{}]", binding);
    @NonNull final AssertionConsumerService acs = adaptor.getAssertionConsumerService(binding);
    final String location = StringUtils.isBlank(acs.getResponseLocation()) ? acs.getLocation() : acs.getResponseLocation();
    if (StringUtils.isBlank(location)) {
        LOGGER.warn("Subject recipient is not defined from either authentication request or metadata for [{}]", adaptor.getEntityId());
    }
    final NameID nameId = getNameIdForService(request, response, authnRequest, service, adaptor, binding, assertion);
    final Subject subject = newSubject(nameId, service.isSkipGeneratingSubjectConfirmationRecipient() ? null : location, service.isSkipGeneratingSubjectConfirmationNotOnOrAfter() ? null : validFromDate.plusSeconds(this.skewAllowance), service.isSkipGeneratingSubjectConfirmationInResponseTo() ? null : authnRequest.getID(), service.isSkipGeneratingSubjectConfirmationNotBefore() ? null : ZonedDateTime.now());
    LOGGER.debug("Created SAML subject [{}]", subject);
    return subject;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) NameID(org.opensaml.saml.saml2.core.NameID) NonNull(lombok.NonNull) Assertion(org.jasig.cas.client.validation.Assertion) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) Subject(org.opensaml.saml.saml2.core.Subject)

Example 32 with NonNull

use of lombok.NonNull in project cas by apereo.

the class GoogleAuthenticatorAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final GoogleAuthenticatorTokenCredential tokenCredential = (GoogleAuthenticatorTokenCredential) credential;
    if (!StringUtils.isNumeric(tokenCredential.getToken())) {
        throw new PreventedException("Invalid non-numeric OTP format specified.", new IllegalArgumentException("Invalid token " + tokenCredential.getToken()));
    }
    final int otp = Integer.parseInt(tokenCredential.getToken());
    LOGGER.debug("Received OTP [{}]", otp);
    @NonNull final Authentication authentication = WebUtils.getInProgressAuthentication();
    final String uid = authentication.getPrincipal().getId();
    LOGGER.debug("Received principal id [{}]", uid);
    final OneTimeTokenAccount acct = this.credentialRepository.get(uid);
    if (acct == null || StringUtils.isBlank(acct.getSecretKey())) {
        throw new AccountNotFoundException(uid + " cannot be found in the registry");
    }
    if (this.tokenRepository.exists(uid, otp)) {
        throw new AccountExpiredException(uid + " cannot reuse OTP " + otp + " as it may be expired/invalid");
    }
    boolean isCodeValid = this.googleAuthenticatorInstance.authorize(acct.getSecretKey(), otp);
    if (!isCodeValid && acct.getScratchCodes().contains(otp)) {
        LOGGER.warn("Using scratch code [{}] to authenticate user [{}]. Scratch code will be removed", otp, uid);
        acct.getScratchCodes().removeIf(token -> token == otp);
        this.credentialRepository.update(acct);
        isCodeValid = true;
    }
    if (isCodeValid) {
        this.tokenRepository.store(new GoogleAuthenticatorToken(otp, uid));
        return createHandlerResult(tokenCredential, this.principalFactory.createPrincipal(uid));
    }
    throw new FailedLoginException("Failed to authenticate code " + otp);
}
Also used : OneTimeTokenAccount(org.apereo.cas.otp.repository.credentials.OneTimeTokenAccount) FailedLoginException(javax.security.auth.login.FailedLoginException) Authentication(org.apereo.cas.authentication.Authentication) AccountExpiredException(javax.security.auth.login.AccountExpiredException) NonNull(lombok.NonNull) GoogleAuthenticatorToken(org.apereo.cas.adaptors.gauth.token.GoogleAuthenticatorToken) PreventedException(org.apereo.cas.authentication.PreventedException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException)

Example 33 with NonNull

use of lombok.NonNull in project cas by apereo.

the class SSOSamlProfileCallbackHandlerController method determineProfileBinding.

/**
 * Determine profile binding.
 *
 * @param authenticationContext the authentication context
 * @param assertion             the assertion
 * @return the string
 */
protected String determineProfileBinding(final Pair<AuthnRequest, MessageContext> authenticationContext, final Assertion assertion) {
    final AuthnRequest authnRequest = authenticationContext.getKey();
    final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> pair = getRegisteredServiceAndFacade(authnRequest);
    final SamlRegisteredServiceServiceProviderMetadataFacade facade = pair.getValue();
    final String binding = StringUtils.defaultIfBlank(authnRequest.getProtocolBinding(), SAMLConstants.SAML2_POST_BINDING_URI);
    LOGGER.debug("Determined authentication request binding is [{}], issued by [{}]", binding, authnRequest.getIssuer().getValue());
    LOGGER.debug("Checking metadata for [{}] to see if binding [{}] is supported", facade.getEntityId(), binding);
    @NonNull final AssertionConsumerService svc = facade.getAssertionConsumerService(binding);
    LOGGER.debug("Binding [{}] is supported by [{}]", svc.getBinding(), facade.getEntityId());
    return binding;
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) NonNull(lombok.NonNull) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService)

Example 34 with NonNull

use of lombok.NonNull in project SONG by overture-stack.

the class AnalysisService method publish.

public ResponseEntity<String> publish(@NonNull String accessToken, @NonNull String id) {
    val files = readFiles(id);
    val missingFileIds = files.stream().filter(f -> !confirmUploaded(accessToken, f.getObjectId())).collect(toImmutableList());
    val isMissingFiles = missingFileIds.size() > 0;
    checkServer(!isMissingFiles, getClass(), UNPUBLISHED_FILE_IDS, "The following file ids must be published before analysisId %s can be published: %s", id, COMMA.join(missingFileIds));
    checkedUpdateState(id, PUBLISHED);
    sender.send(String.format("{\"analysis_id\": %s, \"state\": \"PUBLISHED\"}", id));
    return ok("AnalysisId %s successfully published", id);
}
Also used : lombok.val(lombok.val) ANALYSIS_ID_NOT_FOUND(org.icgc.dcc.song.core.exceptions.ServerErrors.ANALYSIS_ID_NOT_FOUND) File(org.icgc.dcc.song.server.model.entity.File) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Autowired(org.springframework.beans.factory.annotation.Autowired) SequencingReadAnalysis(org.icgc.dcc.song.server.model.analysis.SequencingReadAnalysis) DUPLICATE_ANALYSIS_ATTEMPT(org.icgc.dcc.song.core.exceptions.ServerErrors.DUPLICATE_ANALYSIS_ATTEMPT) COMMA(org.icgc.dcc.common.core.util.Joiners.COMMA) Analysis(org.icgc.dcc.song.server.model.analysis.Analysis) SequencingRead(org.icgc.dcc.song.server.model.experiment.SequencingRead) InfoSearchResponse(org.icgc.dcc.song.server.repository.search.InfoSearchResponse) SearchRepository(org.icgc.dcc.song.server.repository.search.SearchRepository) VARIANT_CALL_REPOSITORY_CREATE_RECORD(org.icgc.dcc.song.core.exceptions.ServerErrors.VARIANT_CALL_REPOSITORY_CREATE_RECORD) Service(org.springframework.stereotype.Service) VariantCallAnalysis(org.icgc.dcc.song.server.model.analysis.VariantCallAnalysis) ANALYSIS_STATE_UPDATE_FAILED(org.icgc.dcc.song.core.exceptions.ServerErrors.ANALYSIS_STATE_UPDATE_FAILED) PUBLISHED(org.icgc.dcc.song.server.model.enums.AnalysisStates.PUBLISHED) Objects.isNull(java.util.Objects.isNull) ServerException.checkServer(org.icgc.dcc.song.core.exceptions.ServerException.checkServer) Sender(org.icgc.dcc.song.server.kafka.Sender) UNPUBLISHED_FILE_IDS(org.icgc.dcc.song.core.exceptions.ServerErrors.UNPUBLISHED_FILE_IDS) ANALYSIS_MISSING_FILES(org.icgc.dcc.song.core.exceptions.ServerErrors.ANALYSIS_MISSING_FILES) SUPPRESSED(org.icgc.dcc.song.server.model.enums.AnalysisStates.SUPPRESSED) AnalysisStates(org.icgc.dcc.song.server.model.enums.AnalysisStates) InfoSearchRequest(org.icgc.dcc.song.server.repository.search.InfoSearchRequest) NonNull(lombok.NonNull) Collection(java.util.Collection) lombok.val(lombok.val) SearchTerm.createMultiSearchTerms(org.icgc.dcc.song.server.repository.search.SearchTerm.createMultiSearchTerms) MultiValueMap(org.springframework.util.MultiValueMap) SEQUENCING_READ_REPOSITORY_CREATE_RECORD(org.icgc.dcc.song.core.exceptions.ServerErrors.SEQUENCING_READ_REPOSITORY_CREATE_RECORD) Responses.ok(org.icgc.dcc.song.core.utils.Responses.ok) VariantCall(org.icgc.dcc.song.server.model.experiment.VariantCall) CompositeEntity(org.icgc.dcc.song.server.model.entity.composites.CompositeEntity) AnalysisRepository(org.icgc.dcc.song.server.repository.AnalysisRepository) SEQUENCING_READ_NOT_FOUND(org.icgc.dcc.song.core.exceptions.ServerErrors.SEQUENCING_READ_NOT_FOUND) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Collectors.toImmutableList(org.icgc.dcc.common.core.util.stream.Collectors.toImmutableList) ANALYSIS_MISSING_SAMPLES(org.icgc.dcc.song.core.exceptions.ServerErrors.ANALYSIS_MISSING_SAMPLES) VARIANT_CALL_NOT_FOUND(org.icgc.dcc.song.core.exceptions.ServerErrors.VARIANT_CALL_NOT_FOUND) ResponseEntity(org.springframework.http.ResponseEntity) ANALYSIS_REPOSITORY_CREATE_RECORD(org.icgc.dcc.song.core.exceptions.ServerErrors.ANALYSIS_REPOSITORY_CREATE_RECORD) IdSearchRequest(org.icgc.dcc.song.server.repository.search.IdSearchRequest) ServerException.buildServerException(org.icgc.dcc.song.core.exceptions.ServerException.buildServerException)

Example 35 with NonNull

use of lombok.NonNull in project nd4j by deeplearning4j.

the class MulticastTransport method init.

@Override
public void init(@NonNull VoidConfiguration voidConfiguration, @NonNull Clipboard clipboard, @NonNull NodeRole role, @NonNull String localIp, int localPort, short shardIndex) {
    if (voidConfiguration.getTtl() < 1)
        throw new ND4JIllegalStateException("For MulticastTransport you should have TTL >= 1, it won't work otherwise");
    if (voidConfiguration.getMulticastNetwork() == null || voidConfiguration.getMulticastNetwork().isEmpty())
        throw new ND4JIllegalStateException("For MulticastTransport you should provide IP from multicast network available/allowed in your environment, i.e.: 224.0.1.1");
    // shutdown hook
    super.init(voidConfiguration, clipboard, role, localIp, localPort, shardIndex);
    this.voidConfiguration = voidConfiguration;
    this.nodeRole = role;
    this.clipboard = clipboard;
    context = new Aeron.Context();
    driver = MediaDriver.launchEmbedded();
    context.aeronDirectoryName(driver.aeronDirectoryName());
    aeron = Aeron.connect(context);
    this.shardIndex = shardIndex;
    multicastChannelUri = "aeron:udp?endpoint=" + voidConfiguration.getMulticastNetwork() + ":" + voidConfiguration.getMulticastPort();
    if (voidConfiguration.getMulticastInterface() != null && !voidConfiguration.getMulticastInterface().isEmpty())
        multicastChannelUri = multicastChannelUri + "|interface=" + voidConfiguration.getMulticastInterface();
    multicastChannelUri = multicastChannelUri + "|ttl=" + voidConfiguration.getTtl();
    if (voidConfiguration.getNumberOfShards() < 0)
        voidConfiguration.setNumberOfShards(voidConfiguration.getShardAddresses().size());
    switch(nodeRole) {
        case BACKUP:
        case SHARD:
            /*
                    In case of Shard, unicast address for communication is known in advance
                 */
            if (ip == null) {
                ip = localIp;
                port = voidConfiguration.getUnicastPort();
            }
            unicastChannelUri = "aeron:udp?endpoint=" + ip + ":" + port;
            log.info("Shard unicast URI: {}/{}", unicastChannelUri, voidConfiguration.getStreamId());
            // this channel will be used to receive batches from Clients
            subscriptionForShards = aeron.addSubscription(unicastChannelUri, voidConfiguration.getStreamId());
            // this channel will be used to send completion reports back to Clients
            publicationForClients = aeron.addPublication(multicastChannelUri, voidConfiguration.getStreamId() + 1);
            // this channel will be used for communication with other Shards
            publicationForShards = aeron.addPublication(multicastChannelUri, voidConfiguration.getStreamId() + 2);
            // this channel will be used to receive messages from other Shards
            subscriptionForClients = aeron.addSubscription(multicastChannelUri, voidConfiguration.getStreamId() + 2);
            messageHandlerForShards = new FragmentAssembler((buffer, offset, length, header) -> shardMessageHandler(buffer, offset, length, header));
            messageHandlerForClients = new FragmentAssembler(((buffer, offset, length, header) -> internalMessageHandler(buffer, offset, length, header)));
            break;
        case CLIENT:
            ip = localIp;
            /*
                    In case of Client, unicast will be one of shards, picked up with random
                 */
            // FIXME: we don't want that
            // ArrayUtil.getRandomElement(configuration.getShardAddresses());
            String rts = voidConfiguration.getShardAddresses().get(0);
            String[] split = rts.split(":");
            if (split.length == 1) {
                ip = rts;
                port = voidConfiguration.getUnicastPort();
            } else {
                ip = split[0];
                port = Integer.valueOf(split[1]);
            }
            unicastChannelUri = "aeron:udp?endpoint=" + ip + ":" + port;
            // unicastChannelUri = "aeron:udp?endpoint=" + ip  + ":" + (configuration.getUnicastPort()) ;
            log.info("Client unicast URI: {}/{}", unicastChannelUri, voidConfiguration.getStreamId());
            /*
                 this channel will be used to send batches to Shards, it's 1:1 channel to one of the Shards
                */
            publicationForShards = aeron.addPublication(unicastChannelUri, voidConfiguration.getStreamId());
            // this channel will be used to receive completion reports from Shards
            subscriptionForClients = aeron.addSubscription(multicastChannelUri, voidConfiguration.getStreamId() + 1);
            messageHandlerForClients = new FragmentAssembler((buffer, offset, length, header) -> clientMessageHandler(buffer, offset, length, header));
            break;
        default:
            log.warn("Unknown role passed: {}", nodeRole);
            throw new RuntimeException();
    }
    // if that's local spark run - we don't need this
    if (voidConfiguration.getNumberOfShards() == 1 && nodeRole == NodeRole.SHARD)
        shutdownSilent();
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) Slf4j(lombok.extern.slf4j.Slf4j) Aeron(io.aeron.Aeron) ND4JIllegalStateException(org.nd4j.linalg.exception.ND4JIllegalStateException) NonNull(lombok.NonNull) Clipboard(org.nd4j.parameterserver.distributed.logic.completion.Clipboard) NodeRole(org.nd4j.parameterserver.distributed.enums.NodeRole) FragmentAssembler(io.aeron.FragmentAssembler) VoidConfiguration(org.nd4j.parameterserver.distributed.conf.VoidConfiguration) CloseHelper(org.agrona.CloseHelper) MeaningfulMessage(org.nd4j.parameterserver.distributed.messages.MeaningfulMessage) VoidMessage(org.nd4j.parameterserver.distributed.messages.VoidMessage) ND4JIllegalStateException(org.nd4j.linalg.exception.ND4JIllegalStateException) Aeron(io.aeron.Aeron) FragmentAssembler(io.aeron.FragmentAssembler)

Aggregations

NonNull (lombok.NonNull)52 List (java.util.List)31 Collectors (java.util.stream.Collectors)22 Map (java.util.Map)20 Slf4j (lombok.extern.slf4j.Slf4j)18 ArrayList (java.util.ArrayList)17 Collection (java.util.Collection)17 HashMap (java.util.HashMap)16 lombok.val (lombok.val)14 Collections (java.util.Collections)13 Duration (java.time.Duration)11 Nullable (javax.annotation.Nullable)11 TimeoutTimer (io.pravega.common.TimeoutTimer)10 Set (java.util.Set)10 CompletableFuture (java.util.concurrent.CompletableFuture)10 Function (java.util.function.Function)10 Futures (io.pravega.common.concurrent.Futures)9 Getter (lombok.Getter)9 Preconditions (com.google.common.base.Preconditions)8 Strings (com.google.common.base.Strings)8