Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4.x: metrics and openapi endpoints should be authorized by default #7572

Merged
merged 3 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ static List<Tag> createTags(String pairs) {
@ConfiguredOption("true")
boolean enabled();

/**
* Whether metrics endpoint should be authorized.
*
* @return if metrics are configured to be authorized
*/
@ConfiguredOption
boolean permitAll();

/**
* Hints for role names the user is expected to be in.
*
* @return list of hints
*/
@ConfiguredOption
List<String> roles();

/**
* Key performance indicator metrics settings.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,19 @@ public void filter(ContainerRequestContext request) {
SecurityTracing tracing = SecurityTracing.get();

// create a new security context
SecurityContext securityContext = security()
.contextBuilder(Integer.toString(CONTEXT_COUNTER.incrementAndGet(), Character.MAX_RADIX))
.tracingSpan(tracing.findParent().orElse(null))
.build();

Contexts.context().ifPresent(ctx -> ctx.register(securityContext));
SecurityContext securityContext = Contexts.context()
.flatMap(context -> context.get(SecurityContext.class))
.orElse(null);

if (securityContext == null) {
// create a new security context
securityContext = security()
.contextBuilder(Integer.toString(CONTEXT_COUNTER.incrementAndGet(), Character.MAX_RADIX))
.tracingSpan(tracing.findParent().orElse(null))
.build();
SecurityContext finalSecurityContext = securityContext;
Contexts.context().ifPresent(ctx -> ctx.register(finalSecurityContext));
}

injectionManager.<Ref<SecurityContext>>getInstance((new GenericType<Ref<SecurityContext>>() { }).getType())
.set(securityContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import io.helidon.http.Status;
import io.helidon.webserver.cors.CorsEnabledServiceHelper;
import io.helidon.webserver.http.HttpRouting;
import io.helidon.webserver.http.SecureHandler;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;
import io.helidon.webserver.servicecommon.FeatureSupport;
Expand Down Expand Up @@ -160,6 +161,9 @@ public OpenApiFeatureConfig prototype() {
@Override
public void setup(HttpRouting.Builder routing, HttpRouting.Builder featureRouting) {
String path = prototype().webContext();
if (!config.permitAll()) {
routing.any(path, SecureHandler.authorize(config.roles().toArray(new String[0])));
}
routing.any(path, corsService.processor())
.get(path, this::handle);
config.services().forEach(service -> service.setup(routing, path, this::content));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,20 @@ interface OpenApiFeatureConfigBlueprint extends Prototype.Factory<OpenApiFeature
*/
@ConfiguredOption(provider = true, providerType = OpenApiManagerProvider.class, providerDiscoverServices = false)
Optional<OpenApiManager<?>> manager();

/**
* Whether endpoint should be authorized.
*
* @return if endpoint is configured to be authorized
*/
@ConfiguredOption
boolean permitAll();

/**
* Hints for role names the user is expected to be in.
*
* @return list of hints
*/
@ConfiguredOption
List<String> roles();
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import io.helidon.webserver.http.HttpRouting;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.SecureHandler;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;

Expand Down Expand Up @@ -194,6 +195,9 @@ private void getOrOptionsMatching(MediaType mediaType,
}

private void setUpEndpoints(HttpRules rules) {
if (!metricsConfig.permitAll()) {
rules.any(SecureHandler.authorize(metricsConfig.roles().toArray(new String[0])));
}
// routing to root of metrics
// As of Helidon 4, this is the only path we should need because scope-based or metric-name-based
// selection should use query parameters instead of paths.
Expand Down
1 change: 1 addition & 0 deletions webserver/tests/observe/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@
<modules>
<module>health</module>
<module>observe</module>
<module>security</module>
</modules>
</project>
77 changes: 77 additions & 0 deletions webserver/tests/observe/security/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2023 Oracle and/or its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.helidon.webserver.tests.observe</groupId>
<artifactId>helidon-webserver-tests-observe-project</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>

<artifactId>helidon-webserver-observe-tests-security</artifactId>
<name>Helidon WebServer Tests Observe Metrics</name>

<dependencies>
<dependency>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.security.providers</groupId>
<artifactId>helidon-security-providers-http-auth</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webserver.observe</groupId>
<artifactId>helidon-webserver-observe-metrics</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.openapi</groupId>
<artifactId>helidon-openapi</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webserver.testing.junit5</groupId>
<artifactId>helidon-webserver-testing-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver-security</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webclient</groupId>
<artifactId>helidon-webclient-security</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.webserver.tests.observe.metrics;

import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import io.helidon.common.media.type.MediaTypes;
import io.helidon.http.Status;
import io.helidon.openapi.OpenApiFeature;
import io.helidon.security.EndpointConfig;
import io.helidon.security.Security;
import io.helidon.security.providers.httpauth.HttpBasicAuthProvider;
import io.helidon.security.providers.httpauth.SecureUserStore;
import io.helidon.webclient.http1.Http1Client;
import io.helidon.webclient.http1.Http1ClientResponse;
import io.helidon.webclient.security.WebClientSecurity;
import io.helidon.webserver.WebServerConfig;
import io.helidon.webserver.context.ContextFeature;
import io.helidon.webserver.observe.ObserveFeature;
import io.helidon.webserver.security.SecurityFeature;
import io.helidon.webserver.testing.junit5.ServerTest;
import io.helidon.webserver.testing.junit5.SetUpServer;

import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@ServerTest
class ObserveSecurityTest {
private static final Map<String, MyUser> USERS = new HashMap<>();

private final Http1Client client;

ObserveSecurityTest(URI uri) {
USERS.put("jack", new MyUser("jack", "password".toCharArray(), Set.of("user")));

Security security = Security.builder()
.addProvider(HttpBasicAuthProvider.builder())
.build();

WebClientSecurity securityService = WebClientSecurity.create(security);

client = Http1Client.builder()
.baseUri(uri)
.addService(securityService)
.build();
}

@SetUpServer
static void setup(WebServerConfig.Builder server) {
server.routing(routing -> routing
.addFeature(ObserveFeature.create())
.addFeature(OpenApiFeature.create())
.addFeature(ContextFeature.create())
.addFeature(buildWebSecurity().securityDefaults(SecurityFeature.authenticate()))
.get("/observe/metrics", SecurityFeature.rolesAllowed("user"))
.get("/openapi", SecurityFeature.rolesAllowed("user")));
}

@Test
void testMetrics() {
testSecureEndpoint("/observe/metrics");
}

@Test
void testOpenApi() {
testSecureEndpoint("/openapi");
}

void testSecureEndpoint(String uri) {
try (Http1ClientResponse response = client.get().uri(uri).request()) {
assertThat(response.status(), is(Status.UNAUTHORIZED_401));
}

try (Http1ClientResponse response = client.get()
.uri(uri)
.property(EndpointConfig.PROPERTY_OUTBOUND_ID, "jack")
.property(EndpointConfig.PROPERTY_OUTBOUND_SECRET, "password")
.request()) {
assertThat(response.status(), is(Status.OK_200));
}
}

private static SecurityFeature buildWebSecurity() {
Security security = Security.builder()
.addAuthenticationProvider(
HttpBasicAuthProvider.builder()
.realm("helidon")
.userStore(buildUserStore()),
"http-basic-auth")
.build();
return SecurityFeature.create(security);
}

private static SecureUserStore buildUserStore() {
return login -> Optional.ofNullable(USERS.get(login));
}

private record MyUser(String login, char[] password, Set<String> roles) implements SecureUserStore.User {

@Override
public boolean isPasswordValid(char[] password) {
return Arrays.equals(password(), password);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#
# Copyright (c) 2023 Oracle and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
---
# Currently openapi support only static document
openapi: 3.0.0
info:
title: Helidon OpenApi Secure Tests
description: A very simple application
version: 1.0.0

servers:
- url: http://localhost:8080
description: Local test server

paths:
/greet:
get:
summary: Returns a generic greeting
description: Greets the user generically
responses:
default:
description: Simple JSON containing the greeting
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static SecureHandler authenticate() {
* Create a security handler that enforces authorization.
*
* @param roleHint optional hint for role names the user is expected to be in
* @return a new handler that requires authroization
* @return a new handler that requires authorization
*/
public static SecureHandler authorize(String... roleHint) {
return new SecureHandler(false, true, roleHint);
Expand Down