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

Support for requested URI for web server requests. #5330

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
154 changes: 154 additions & 0 deletions common/http/src/main/java/io/helidon/common/http/Forwarded.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Copyright (c) 2022 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.common.http;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

import static io.helidon.common.http.Http.Header.FORWARDED;

/**
* A representation of the {@link Http.Header#FORWARDED} HTTP header.
*/
public class Forwarded {
private static final System.Logger LOGGER = System.getLogger(Forwarded.class.getName());
private final Optional<String> by;
private final Optional<String> forClient;
private final Optional<String> host;
private final Optional<String> proto;

private Forwarded(String by, String forClient, String host, String proto) {
this.by = Optional.ofNullable(by);
this.forClient = Optional.ofNullable(forClient);
this.host = Optional.ofNullable(host);
this.proto = Optional.ofNullable(proto);
}

/**
* Create forwarded from a value of a single forwarded header, such as {@code by=a.b.c;for=d.e.f;host=host;proto=https}.
*
* @param string string representation of a single forwarded header
* @return forwarded parsed from the string
* @see #create(Headers)
*/
public static Forwarded create(String string) {
// first split by semicolon, as that separates the directives
String[] directives = string.split(";");
String by = null;
String forClient = null;
String host = null;
String proto = null;

for (String directive : directives) {
int index = directive.indexOf('=');
if (index == -1 && !directive.isEmpty()) {
throw new IllegalArgumentException("Invalid Forwarded header");
}
String name = directive.substring(0, index);
String value = unquote(directive.substring(index + 1));

switch (name.toLowerCase(Locale.ROOT)) {
case "by" -> {
by = value;
}
case "for" -> {
forClient = value;
}
case "host" -> {
host = value;
}
case "proto" -> {
proto = value;
}
default -> {
if (LOGGER.isLoggable(System.Logger.Level.DEBUG)) {
String printableName = name.replaceAll("\\p{C}", "?");
String printableValue = value.replaceAll("\\p{C}", "?");

LOGGER.log(System.Logger.Level.DEBUG, "Encountered unknown directive of Forwarded header: \n"
+ printableName + "\nValue:\n" + printableValue);
}
}
}
}
return new Forwarded(by, forClient, host, proto);
}

/**
* Parse forwarded header(s) from the provided headers.
*
* @param headers header to process
* @return list of forwarded headers, will be empty if the header does not exist.
*/
public static List<Forwarded> create(Headers headers) {
List<String> values = headers.values(FORWARDED);
if (values == null || values.isEmpty()) {
return List.of();
tjquinno marked this conversation as resolved.
Show resolved Hide resolved
}

return values.stream()
.flatMap(it -> Arrays.stream(it.split(",")))
.map(String::trim)
.map(Forwarded::create)
.toList();
}

/**
* {@code by} directive of the forwarded header.
*
* @return by directive
*/
public Optional<String> by() {
return by;
}

/**
* {@code for} directive of the forwarded header.
*
* @return for directive
*/
public Optional<String> forClient() {
return forClient;
}

/**
* {@code host} directive of the forwarded header. The host of the original request.
*
* @return host directive
*/
public Optional<String> host() {
return host;
}

/**
* {@code proto} directive of the forwarded header. The protocol of the original request (http or https).
*
* @return proto directive
*/
public Optional<String> proto() {
return proto;
}

private static String unquote(String string) {
if (string.indexOf('"') == 0 && string.lastIndexOf('"') == string.length() - 1) {
return string.substring(1, string.length() - 1);
}
return string;
}
}
27 changes: 26 additions & 1 deletion common/http/src/main/java/io/helidon/common/http/Http.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2021 Oracle and/or its affiliates.
* Copyright (c) 2018, 2022 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.
Expand Down Expand Up @@ -777,6 +777,31 @@ public static final class Header {
* Disclose original information of a client connecting to a web server through an HTTP proxy.
*/
public static final String FORWARDED = "Forwarded";
/**
* The {@code X-Forwarded-For} header name.
* Used to represent the original host requested by a client, when request passed through a proxy server.
*/
public static final String X_FORWARDED_FOR = "X-Forwarded-For";
/**
* The {@code X-Forwarded-Host} header name.
* Used to represent the original host requested by a client, when request passed through a proxy server.
*/
public static final String X_FORWARDED_HOST = "X-Forwarded-Host";
/**
* The {@code X-Forwarded-Port} header name.
* Used to represent the original port requested by a client, when request passed through a proxy server.
*/
public static final String X_FORWARDED_PORT = "X-Forwarded-Port";
/**
* The {@code X-Forwarded-Prefix} header name.
* Used to represent the original path prefix requested by a client, when request passed through a proxy server.
*/
public static final String X_FORWARDED_PREFIX = "X-Forwarded-Prefix";
/**
* The {@code X-Forwarded-Proto} header name.
* Used to represent the original protocol used by a client, when request passed through a proxy server.
*/
public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
/**
* The <code>{@value}</code> header name.
* The email address of the user making the request.
Expand Down
59 changes: 59 additions & 0 deletions common/http/src/main/java/io/helidon/common/http/UriInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright (c) 2022 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.common.http;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;

/**
* Information about URI.
*
* @param scheme Scheme of the request ({@code http}, {@code https})
* @param host Host part of authority of the request
* @param port Port part of authority of the request
* @param path Path of the request
* @param query Query of the request
*/
public record UriInfo(String scheme,
String host,
int port,
String path,
Optional<String> query) {

/**
* Create URI from the information. This operation is expensive.
*
* @return URI to use
*/
public URI toUri() {
tomas-langer marked this conversation as resolved.
Show resolved Hide resolved
try {
return new URI(scheme, authority(), path, query.orElse(null), null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("UriInfo cannot be used to create a URI: " + this, e);
}
}

/**
* Authority (host:port) of this URI.
*
* @return authority
*/
public String authority() {
return host + ":" + port;
}
}
143 changes: 143 additions & 0 deletions common/http/src/test/java/io/helidon/common/http/ForwardedTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Copyright (c) 2022 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.common.http;

import java.util.List;

import org.junit.jupiter.api.Test;

import static io.helidon.config.testing.OptionalMatcher.empty;
import static io.helidon.config.testing.OptionalMatcher.value;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;

class ForwardedTest {
@Test
void testForOnly() {
String header = "for=\"_mdn\"";
Forwarded forwarded = Forwarded.create(header);

assertThat(forwarded.by(), is(empty()));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), value(is("_mdn")));
}

@Test
void testForCaseInsensitive() {
String header = "For=\"[2001:db8:cafe::17]:4711\"";
Forwarded forwarded = Forwarded.create(header);

assertThat(forwarded.by(), is(empty()));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), value(is("[2001:db8:cafe::17]:4711")));
}

@Test
void testForProtoAndBy() {
String header = "for=192.0.2.60;proto=http;by=203.0.113.43";
Forwarded forwarded = Forwarded.create(header);

assertThat(forwarded.by(), value(is("203.0.113.43")));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), value(is("http")));
assertThat(forwarded.forClient(), value(is("192.0.2.60")));
}

@Test
void testAll() {
String header = "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10";
Forwarded forwarded = Forwarded.create(header);

assertThat(forwarded.by(), value(is("203.0.113.43")));
assertThat(forwarded.host(), value(is("10.10.10.10")));
assertThat(forwarded.proto(), value(is("http")));
assertThat(forwarded.forClient(), value(is("192.0.2.60")));
}

@Test
void testMultiValuesCommaSeparated() {
HashHeaders headers = HashHeaders.create();
headers.add(Http.Header.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10,by=\"192.0.2.60\"");
List<Forwarded> forwardedList = Forwarded.create(headers);

assertThat(forwardedList, hasSize(2));
Forwarded forwarded = forwardedList.get(0);

assertThat(forwarded.by(), value(is("203.0.113.43")));
assertThat(forwarded.host(), value(is("10.10.10.10")));
assertThat(forwarded.proto(), value(is("http")));
assertThat(forwarded.forClient(), value(is("192.0.2.60")));

forwarded = forwardedList.get(1);
assertThat(forwarded.by(), value(is("192.0.2.60")));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), is(empty()));
}

@Test
void testMultiValues() {
HashHeaders headers = HashHeaders.create();
headers.add(Http.Header.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10",
"by=\"192.0.2.60\"");
List<Forwarded> forwardedList = Forwarded.create(headers);

assertThat(forwardedList, hasSize(2));
Forwarded forwarded = forwardedList.get(0);

assertThat(forwarded.by(), value(is("203.0.113.43")));
assertThat(forwarded.host(), value(is("10.10.10.10")));
assertThat(forwarded.proto(), value(is("http")));
assertThat(forwarded.forClient(), value(is("192.0.2.60")));

forwarded = forwardedList.get(1);
assertThat(forwarded.by(), value(is("192.0.2.60")));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), is(empty()));
}

@Test
void testMultiValuesAndCommaSeparated() {
HashHeaders headers = HashHeaders.create();
headers.add(Http.Header.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10",
"by=\"192.0.2.60\",for=\"14.22.11.22\"");
List<Forwarded> forwardedList = Forwarded.create(headers);

assertThat(forwardedList, hasSize(3));
Forwarded forwarded = forwardedList.get(0);

assertThat(forwarded.by(), value(is("203.0.113.43")));
assertThat(forwarded.host(), value(is("10.10.10.10")));
assertThat(forwarded.proto(), value(is("http")));
assertThat(forwarded.forClient(), value(is("192.0.2.60")));

forwarded = forwardedList.get(1);
assertThat(forwarded.by(), value(is("192.0.2.60")));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), is(empty()));

forwarded = forwardedList.get(2);
assertThat(forwarded.by(), is(empty()));
assertThat(forwarded.host(), is(empty()));
assertThat(forwarded.proto(), is(empty()));
assertThat(forwarded.forClient(), value(is("14.22.11.22")));
}
}
Loading