Search in sources :

Example 1 with Nullable

use of io.micronaut.core.annotation.Nullable in project micronaut-gcp by micronaut-projects.

the class InvokerHttpServer method start.

@Override
public EmbeddedServer start() {
    if (running.compareAndSet(false, true)) {
        int retryCount = 0;
        while (retryCount <= 3) {
            try {
                this.server = new Server(port);
                ServletContextHandler servletContextHandler = new ServletContextHandler();
                servletContextHandler.setContextPath("/");
                server.setHandler(NotFoundHandler.forServlet(servletContextHandler));
                HttpFunction httpFunction = new HttpFunction() {

                    @Override
                    protected ApplicationContext buildApplicationContext(@Nullable Object context) {
                        ApplicationContext ctx = InvokerHttpServer.this.getApplicationContext();
                        this.applicationContext = ctx;
                        return ctx;
                    }
                };
                HttpServlet servlet = new HttpServlet() {

                    @Override
                    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
                        try {
                            httpFunction.service(new HttpRequestImpl(req), new HttpResponseImpl(resp));
                        } catch (Exception e) {
                            throw new ServletException(e);
                        }
                    }
                };
                ServletHolder servletHolder = new ServletHolder(servlet);
                servletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
                servletContextHandler.addServlet(servletHolder, "/*");
                server.start();
                logServerInfo();
                break;
            } catch (BindException e) {
                if (randomPort) {
                    this.port = SocketUtils.findAvailableTcpPort();
                    retryCount++;
                } else {
                    throw new ServerStartupException(e.getMessage(), e);
                }
            } catch (Exception e) {
                throw new ServerStartupException("Error starting Google Cloud Function server: " + e.getMessage(), e);
            }
        }
    }
    return this;
}
Also used : Server(org.eclipse.jetty.server.Server) EmbeddedServer(io.micronaut.runtime.server.EmbeddedServer) HttpServlet(javax.servlet.http.HttpServlet) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletException(javax.servlet.ServletException) HttpServerException(io.micronaut.http.server.exceptions.HttpServerException) ServerStartupException(io.micronaut.http.server.exceptions.ServerStartupException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ApplicationContext(io.micronaut.context.ApplicationContext) MultipartConfigElement(javax.servlet.MultipartConfigElement) ServerStartupException(io.micronaut.http.server.exceptions.ServerStartupException) HttpFunction(io.micronaut.gcp.function.http.HttpFunction) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Nullable(io.micronaut.core.annotation.Nullable)

Example 2 with Nullable

use of io.micronaut.core.annotation.Nullable in project micronaut-security by micronaut-projects.

the class InterceptUrlMapRule method check.

/**
 * If no configured pattern matches the request, return {@link SecurityRuleResult#UNKNOWN}.
 * Reads the rules in order. The first matched rule will be used for determining authorization.
 *
 * @param request The current request
 * @param routeMatch The matched route
 * @param authentication The user authentication. Null if not authenticated
 * @return The result
 */
@Override
public Publisher<SecurityRuleResult> check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Authentication authentication) {
    final String path = request.getUri().getPath();
    final HttpMethod httpMethod = request.getMethod();
    Predicate<InterceptUrlMapPattern> exactMatch = p -> pathMatcher.matches(p.getPattern(), path) && p.getHttpMethod().isPresent() && httpMethod.equals(p.getHttpMethod().get());
    Predicate<InterceptUrlMapPattern> uriPatternMatchOnly = p -> pathMatcher.matches(p.getPattern(), path) && !p.getHttpMethod().isPresent();
    Optional<InterceptUrlMapPattern> matchedPattern = getPatternList().stream().filter(exactMatch).findFirst();
    // if we don't get an exact match try to find a match by the uri pattern
    if (!matchedPattern.isPresent()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No url map pattern exact match found for path [{}] and method [{}]. Searching in patterns with no defined method.", path, httpMethod);
        }
        matchedPattern = getPatternList().stream().filter(uriPatternMatchOnly).findFirst();
        if (LOG.isDebugEnabled()) {
            if (matchedPattern.isPresent()) {
                LOG.debug("Url map pattern found for path [{}]. Comparing roles.", path);
            } else {
                LOG.debug("No url map pattern match found for path [{}]. Returning unknown.", path);
            }
        }
    }
    return Mono.from(matchedPattern.map(pattern -> compareRoles(pattern.getAccess(), getRoles(authentication))).orElse(Mono.just(SecurityRuleResult.UNKNOWN)));
}
Also used : HttpMethod(io.micronaut.http.HttpMethod) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) Publisher(org.reactivestreams.Publisher) LoggerFactory(org.slf4j.LoggerFactory) Authentication(io.micronaut.security.authentication.Authentication) PathMatcher(io.micronaut.core.util.PathMatcher) Mono(reactor.core.publisher.Mono) AntPathMatcher(io.micronaut.core.util.AntPathMatcher) InterceptUrlMapPattern(io.micronaut.security.config.InterceptUrlMapPattern) List(java.util.List) Nullable(io.micronaut.core.annotation.Nullable) RolesFinder(io.micronaut.security.token.RolesFinder) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) RouteMatch(io.micronaut.web.router.RouteMatch) Inject(jakarta.inject.Inject) InterceptUrlMapPattern(io.micronaut.security.config.InterceptUrlMapPattern) HttpMethod(io.micronaut.http.HttpMethod)

Example 3 with Nullable

use of io.micronaut.core.annotation.Nullable in project micronaut-test by micronaut-projects.

the class AbstractMicronautExtension method beforeEach.

/**
 * To be called by the different implementations before each test method.
 *
 * @param context The test context
 * @param testInstance The test instance
 * @param method The test method
 * @param propertyAnnotations The {@code @Property} annotations found in the test method, if any
 */
protected void beforeEach(C context, @Nullable Object testInstance, @Nullable AnnotatedElement method, List<Property> propertyAnnotations) {
    int testCount = (int) testProperties.compute("micronaut.test.count", (k, oldCount) -> (int) (oldCount != null ? oldCount : 0) + 1);
    if (method != null) {
        if (propertyAnnotations != null && !propertyAnnotations.isEmpty()) {
            for (Property property : propertyAnnotations) {
                final String name = property.name();
                oldValues.put(name, testProperties.put(name, property.value()));
            }
        } else {
            oldValues.forEach((k, v) -> testProperties.put(k, v));
        }
        if (testAnnotationValue.rebuildContext() && testCount > 1) {
            stopEmbeddedApplication();
            if (applicationContext.isRunning()) {
                applicationContext.stop();
            }
            applicationContext = builder.build();
            startApplicationContext();
            startEmbeddedApplication();
        } else if (!oldValues.isEmpty()) {
            final Map<String, Object> diff = applicationContext.getEnvironment().refreshAndDiff();
            refreshScope.onRefreshEvent(new RefreshEvent(diff));
        }
    }
    if (testInstance != null) {
        if (applicationContext != null) {
            if (refreshScope != null) {
                refreshScope.onRefreshEvent(new RefreshEvent(Collections.singletonMap(TestActiveCondition.ACTIVE_MOCKS, "changed")));
            }
            applicationContext.inject(testInstance);
            alignMocks(context, testInstance);
        }
    }
}
Also used : java.util(java.util) TestContext(io.micronaut.test.context.TestContext) RefreshEvent(io.micronaut.runtime.context.scope.refresh.RefreshEvent) ArrayUtils(io.micronaut.core.util.ArrayUtils) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) ApplicationContext(io.micronaut.context.ApplicationContext) TestExecutionListener(io.micronaut.test.context.TestExecutionListener) InstantiationUtils(io.micronaut.core.reflect.InstantiationUtils) Nullable(io.micronaut.core.annotation.Nullable) AnnotationUtils(io.micronaut.test.annotation.AnnotationUtils) NameUtils(io.micronaut.core.naming.NameUtils) Property(io.micronaut.context.annotation.Property) ResourceResolver(io.micronaut.core.io.ResourceResolver) ClassUtils(io.micronaut.core.reflect.ClassUtils) ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) PropertySource(io.micronaut.context.env.PropertySource) PropertySourceLoader(io.micronaut.context.env.PropertySourceLoader) TestActiveCondition(io.micronaut.test.condition.TestActiveCondition) ServiceDefinition(io.micronaut.core.io.service.ServiceDefinition) IOException(java.io.IOException) EmbeddedApplication(io.micronaut.runtime.EmbeddedApplication) StringUtils(io.micronaut.core.util.StringUtils) MicronautTestValue(io.micronaut.test.annotation.MicronautTestValue) RefreshScope(io.micronaut.runtime.context.scope.refresh.RefreshScope) BeanDefinition(io.micronaut.inject.BeanDefinition) TestPropertyProvider(io.micronaut.test.support.TestPropertyProvider) InputStream(java.io.InputStream) AnnotatedElement(java.lang.reflect.AnnotatedElement) RefreshEvent(io.micronaut.runtime.context.scope.refresh.RefreshEvent) Property(io.micronaut.context.annotation.Property)

Example 4 with Nullable

use of io.micronaut.core.annotation.Nullable in project micronaut-redis by micronaut-projects.

the class AbstractRedisClientFactory method redisClient.

/**
 * Creates the {@link RedisClient} from the configuration.
 *
 * @param config The configuration
 * @param optionalClientResources The ClientResources
 * @param mutators The list of mutators
 * @return The {@link RedisClient}
 */
public RedisClient redisClient(AbstractRedisConfiguration config, @Nullable ClientResources optionalClientResources, @Nullable List<ClientResourcesMutator> mutators) {
    ClientResources clientResources = configureClientResources(config, optionalClientResources, mutators);
    if (clientResources == null) {
        return redisClient(config);
    }
    Optional<RedisURI> uri = config.getUri();
    return uri.map(redisURI -> RedisClient.create(clientResources, redisURI)).orElseGet(() -> RedisClient.create(clientResources, config));
}
Also used : ClientResources(io.lettuce.core.resource.ClientResources) RedisURI(io.lettuce.core.RedisURI) List(java.util.List) RedisClient(io.lettuce.core.RedisClient) StatefulRedisConnection(io.lettuce.core.api.StatefulRedisConnection) Nullable(io.micronaut.core.annotation.Nullable) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection) Optional(java.util.Optional) Collections(java.util.Collections) ClientResources(io.lettuce.core.resource.ClientResources) RedisURI(io.lettuce.core.RedisURI)

Example 5 with Nullable

use of io.micronaut.core.annotation.Nullable in project micronaut-security by micronaut-projects.

the class DefaultOpenIdTokenResponseValidator method validateClaims.

/**
 * @param clientConfiguration The OAuth 2.0 client configuration
 * @param openIdProviderMetadata The OpenID provider metadata
 * @param jwt JWT with valida signature
 * @param nonce The persisted nonce value
 * @return the same JWT supplied as a parameter if the claims validation were succesful or empty if not.
 */
@NonNull
protected Optional<JWT> validateClaims(@NonNull OauthClientConfiguration clientConfiguration, @NonNull OpenIdProviderMetadata openIdProviderMetadata, @NonNull JWT jwt, @Nullable String nonce) {
    try {
        JWTClaimsSet claimsSet = jwt.getJWTClaimsSet();
        OpenIdClaims claims = new JWTOpenIdClaims(claimsSet);
        if (genericJwtClaimsValidators.stream().allMatch(validator -> validator.validate(claims, null))) {
            if (openIdClaimsValidators.stream().allMatch(validator -> validator.validate(claims, clientConfiguration, openIdProviderMetadata))) {
                if (nonceClaimValidator == null) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Skipping nonce validation because no bean of type {} present. ", NonceClaimValidator.class.getSimpleName());
                    }
                    return Optional.of(jwt);
                }
                if (nonceClaimValidator.validate(claims, clientConfiguration, openIdProviderMetadata, nonce)) {
                    return Optional.of(jwt);
                } else if (LOG.isErrorEnabled()) {
                    LOG.error("Nonce {} validation failed for claims {}", nonce, claims.getClaims().keySet().stream().map(key -> key + "=" + claims.getClaims().get(key)).collect(Collectors.joining(", ", "{", "}")));
                }
            } else if (LOG.isErrorEnabled()) {
                LOG.error("JWT OpenID specific claims validation failed for provider [{}]", clientConfiguration.getName());
            }
        } else if (LOG.isErrorEnabled()) {
            LOG.error("JWT generic claims validation failed for provider [{}]", clientConfiguration.getName());
        }
    } catch (ParseException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to parse the JWT returned from provider [{}]", clientConfiguration.getName(), e);
        }
    }
    return Optional.empty();
}
Also used : JwkValidator(io.micronaut.security.token.jwt.signature.jwks.JwkValidator) Logger(org.slf4j.Logger) Collection(java.util.Collection) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JwksSignatureConfigurationProperties(io.micronaut.security.token.jwt.signature.jwks.JwksSignatureConfigurationProperties) Singleton(jakarta.inject.Singleton) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) JwksSignature(io.micronaut.security.token.jwt.signature.jwks.JwksSignature) Collectors(java.util.stream.Collectors) OpenIdProviderMetadata(io.micronaut.security.oauth2.client.OpenIdProviderMetadata) NonNull(io.micronaut.core.annotation.NonNull) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) GenericJwtClaimsValidator(io.micronaut.security.token.jwt.validator.GenericJwtClaimsValidator) JWT(com.nimbusds.jwt.JWT) Nullable(io.micronaut.core.annotation.Nullable) JwtValidator(io.micronaut.security.token.jwt.validator.JwtValidator) Map(java.util.Map) OpenIdTokenResponse(io.micronaut.security.oauth2.endpoint.token.response.OpenIdTokenResponse) Optional(java.util.Optional) ParseException(java.text.ParseException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ParseException(java.text.ParseException) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

Nullable (io.micronaut.core.annotation.Nullable)5 Optional (java.util.Optional)3 ApplicationContext (io.micronaut.context.ApplicationContext)2 IOException (java.io.IOException)2 List (java.util.List)2 JWT (com.nimbusds.jwt.JWT)1 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 RedisClient (io.lettuce.core.RedisClient)1 RedisURI (io.lettuce.core.RedisURI)1 StatefulRedisConnection (io.lettuce.core.api.StatefulRedisConnection)1 StatefulRedisPubSubConnection (io.lettuce.core.pubsub.StatefulRedisPubSubConnection)1 ClientResources (io.lettuce.core.resource.ClientResources)1 ApplicationContextBuilder (io.micronaut.context.ApplicationContextBuilder)1 Property (io.micronaut.context.annotation.Property)1 PropertySource (io.micronaut.context.env.PropertySource)1 PropertySourceLoader (io.micronaut.context.env.PropertySourceLoader)1 NonNull (io.micronaut.core.annotation.NonNull)1 ResourceResolver (io.micronaut.core.io.ResourceResolver)1 ServiceDefinition (io.micronaut.core.io.service.ServiceDefinition)1 SoftServiceLoader (io.micronaut.core.io.service.SoftServiceLoader)1