Skip to content
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
1 change: 1 addition & 0 deletions changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Changes log

- 2.6.2 (??-??-2026)
- Bugs fixed
- A request whose preconditions fail (`If-Match`, `If-None-Match`...) with a method that the resource does not support is now answered 405 (Method Not Allowed) with the `Allow` header, instead of 412 (Precondition Failed) or of the status of a custom precondition such as 428, as RFC 9110 section 13.2.1 requires. The supported methods are the ones declared by `ServerResource.updateAllowedMethods()`, the annotated methods by default; a resource that declares nothing is not changed. Issue #1752.
- An `If-Range` header carrying a date is now honoured only if that date is a strong validator, as RFC 9110 section 13.1.5 requires: a `Last-Modified` less than one second older than the response is weak, so the range is ignored and the whole entity is sent instead of a partial content. Issue #1742.
- `DefaultSslContextFactory` now uses the JVM default algorithms for the trust manager (`TrustManagerFactory.getDefaultAlgorithm()`, `PKIX`) and the key manager (`KeyManagerFactory.getDefaultAlgorithm()`) instead of the obsolete `SunX509`, unless the `ssl.TrustManagerFactory.algorithm` or `ssl.KeyManagerFactory.algorithm` system property, the `trustManagerAlgorithm` or `keyManagerAlgorithm` parameter, or the setters say otherwise. A valid certificate chain that is not in order is no longer rejected with a "Certificate chaining error". The `PKIX` validation is the standard one, and stricter than `SunX509` on unusual chains: set the trust manager algorithm to `SunX509` to get the previous behavior. Issue #1397.
- `Redirector.getTargetRef()` now removes the dot segments (`.` and `..`) of the target URI (RFC 3986, section 5.2.4), so the `Location` header of a client redirection and the URI of a server redirection are normalized. Relative-path targets such as `../x` are left untouched, as they need their base reference. A reverse proxy built on `http://backend/root/{rr}` now resolves a `..` found in the remaining part itself, which it did not before the request reached the backend. Issue #238.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
Expand Down Expand Up @@ -114,7 +115,7 @@
* {@link #init(Context, Request, Response)}() method will be invoked right
* after the creation of the resource.
*/
public ServerResource() {

Check warning on line 118 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Change the visibility of this constructor to "protected".

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo3&open=AaInwGCDsnfCWoUvzgo3&pullRequest=1756
}

/**
Expand Down Expand Up @@ -348,13 +349,48 @@

if (status != null) {
if (status.isError()) {
doError(status);
// RFC 9110 section 13.2.1: a failure that does not depend on the
// preconditions, such as a method that the resource does not
// support, takes precedence.
doError(isDeclaredUnsupported(getMethod()) ? Status.CLIENT_ERROR_METHOD_NOT_ALLOWED : status);
} else {
setStatus(status);
}
}
}

/**
* Indicates if the resource declares the supported methods (see
* {@link #updateAllowedMethods()}) and the given method is not one of them.
* A resource that declares nothing, such as one that overrides the methods of
* this class without annotating them, is not guessed at: the method is then
* not considered as unsupported.
*
* @param method The request method.
* @return True if the supported methods are declared and do not contain the
* method.
*/
private boolean isDeclaredUnsupported(Method method) {
Set<Method> allowed = getAllowedMethods();

if (allowed == null) {
return false;
}

// Keep the allowed methods as they were: they are only written for a 405.
Set<Method> previous = new HashSet<Method>(allowed);

try {
updateAllowedMethods();
Set<Method> declared = getAllowedMethods();
return !declared.isEmpty() && !declared.contains(method);
} finally {
Set<Method> current = getAllowedMethods();
current.clear();
current.addAll(previous);
}
}

/**
* Indicates if the request carries preconditions to evaluate before handling
* the call. If so, the validators of the current representation are retrieved
Expand Down Expand Up @@ -403,7 +439,17 @@
* </pre>
*
* Note that the validators of the resource are retrieved before this method is
* invoked (see {@link #getInfo()}), so the 428 costs one call to it.
* invoked (see {@link #getInfo()}), so the 428 costs one call to it.<br>
* <br>
* If the status returned is an error but the resource declares its supported
* methods (see {@link #updateAllowedMethods()}) without the method of the
* request, the answer is {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}
* instead: RFC 9110 section 13.2.1 gives precedence to the failures that do
* not depend on the preconditions. It is the case of the annotated methods,
* which are the declaration by default. A resource that overrides the methods
* of this class instead of annotating them declares nothing, and is not
* guessed at: it can override {@link #updateAllowedMethods()} to declare
* them.
*
* @param resultInfo The current representation of the resource, or null if the
* resource does not exist.
Expand Down Expand Up @@ -527,7 +573,7 @@
* @return The response entity.
* @throws ResourceException
*/
protected Representation doHandle(MethodAnnotationInfo annotationInfo, Variant variant) throws ResourceException {

Check failure on line 576 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 26 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo4&open=AaInwGCDsnfCWoUvzgo4&pullRequest=1756
Representation result = null;
Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes();

Expand Down Expand Up @@ -635,7 +681,7 @@
* @return The response entity.
* @throws ResourceException
*/
protected Representation doHandle(Variant variant) throws ResourceException {

Check failure on line 684 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 31 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo5&open=AaInwGCDsnfCWoUvzgo5&pullRequest=1756
Representation result = null;
Method method = getMethod();

Expand Down Expand Up @@ -961,10 +1007,10 @@
return this.variants;
}

private List<Variant> getVariantsFromAnnotations(Method method) {

Check failure on line 1010 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 32 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo6&open=AaInwGCDsnfCWoUvzgo6&pullRequest=1756
final List<Variant> result = new ArrayList<>();

for (AnnotationInfo annotationInfo : getAnnotations()) {

Check warning on line 1013 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Reduce the total number of break and continue statements in this loop to use at most one.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo2&open=AaInwGCDsnfCWoUvzgo2&pullRequest=1756
if (!(annotationInfo instanceof MethodAnnotationInfo methodAnnotationInfo)) {
continue;
}
Expand Down Expand Up @@ -1059,7 +1105,7 @@
getResponse().setEntity(result);
}

} catch (Throwable t) {

Check warning on line 1108 in org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Catch Exception instead of Throwable.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaInwGCDsnfCWoUvzgo7&open=AaInwGCDsnfCWoUvzgo7&pullRequest=1756
doCatch(t);
} finally {
finishHandling();
Expand Down Expand Up @@ -1833,7 +1879,15 @@
/**
* Invoked when the list of allowed methods needs to be updated. The
* {@link #getAllowedMethods()} or the {@link #setAllowedMethods(Set)} methods
* should be used. The default implementation lists the annotated methods.
* should be used. The default implementation lists the annotated methods.<br>
* <br>
* This is the declaration of the methods that the resource supports: it is
* written in the "Allow" header of a 405 response, and a request that fails
* its preconditions with a method that is not declared is answered with a 405
* instead (see {@link #getPreconditionStatus(RepresentationInfo)}). An empty
* declaration means that nothing is declared. A resource that overrides the
* methods of this class (such as {@link #put(Representation)}) instead of
* annotating them should override this method to declare them.
*/
public void updateAllowedMethods() {
getAllowedMethods().clear();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* Copyright 2005-2026 Qlik
*<p>
* The content of this file is subject to the terms of the Apache 2.0 open
* source license available at https://www.opensource.org/licenses/apache-2.0
*<p>
* Restlet is a registered trademark of QlikTech International AB.
*/
package org.restlet.engine.connector;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Server;
import org.restlet.data.Protocol;
import org.restlet.data.Tag;
import org.restlet.engine.Engine;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Finder;
import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;
import org.restlet.routing.Router;

/**
* Tests, on the wire, that a conditional write to a method that the resource does not support is
* answered 405 with an "Allow" header, and not 412 (RFC 9110 section 13.2.1, #1752).
*/
class MethodNotAllowedWireTestCase {

private static final int TIMEOUT_MS = 10_000;

/** Annotated resource that only reads. */
public static class ReadOnlyResource extends ServerResource {

@Get
public Representation read() {
StringRepresentation result = new StringRepresentation("body");
result.setTag(new Tag("current", false));
return result;
}
}

/** Annotated resource that reads and replaces. */
public static class ReadWriteResource extends ReadOnlyResource {

@Put
public void replace(Representation entity) {
// Accepted.
}
}

private Component component;

private Server server;

@BeforeEach
void setUp() throws Exception {
Engine.clearThreadLocalVariables();
Engine.register();

component = new Component();
server = component.getServers().add(Protocol.HTTP, 0);
Context context = component.getContext().createChildContext();
Router router = new Router(context);
router.attach("/readonly", new Finder(context, ReadOnlyResource.class));
router.attach("/readwrite", new Finder(context, ReadWriteResource.class));
component.getDefaultHost().attachDefault(router);
component.start();
}

@AfterEach
void tearDown() throws Exception {
if (component != null) {
component.stop();
}
Engine.clearThreadLocalVariables();
}

private String put(String path, String conditionalHeader) throws IOException {
try (Socket socket = new Socket("localhost", server.getEphemeralPort())) {
socket.setSoTimeout(TIMEOUT_MS);
OutputStream out = socket.getOutputStream();
out.write(
("PUT "
+ path
+ " HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\n"
+ "Content-Type: text/plain\r\n"
+ conditionalHeader
+ "Connection: close\r\n\r\nbody")
.getBytes(StandardCharsets.ISO_8859_1));
out.flush();
return new String(socket.getInputStream().readAllBytes(), StandardCharsets.ISO_8859_1);
}
}

@Test
void conditionalPut_toAReadOnlyResource_answers405WithAllow() throws Exception {
String response = put("/readonly", "If-Match: \"other\"\r\n");

assertTrue(response.startsWith("HTTP/1.1 405"), response);
String lower = response.toLowerCase(Locale.ROOT);
assertTrue(lower.contains("\r\nallow: "), response);
assertTrue(lower.contains("get"), response);
}

@Test
void unconditionalPut_toAReadOnlyResource_answers405() throws Exception {
assertTrue(put("/readonly", "").startsWith("HTTP/1.1 405"));
}

@Test
void conditionalPut_withAFailingIfMatch_toAResourceThatSupportsIt_stillAnswers412()
throws Exception {
String response = put("/readwrite", "If-Match: \"other\"\r\n");

assertTrue(response.startsWith("HTTP/1.1 412"), response);
}
}
Loading
Loading