diff --git a/changes.md b/changes.md index 443d6e3c8f..9c5a2d38f5 100644 --- a/changes.md +++ b/changes.md @@ -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. diff --git a/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java b/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java index 9c628c6fb5..4df25ba1e3 100644 --- a/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java +++ b/org.restlet.java/org.restlet/src/main/java/org/restlet/resource/ServerResource.java @@ -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; @@ -348,13 +349,48 @@ private void doConditionalHandle(final RepresentationInfo resultInfo) { 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 allowed = getAllowedMethods(); + + if (allowed == null) { + return false; + } + + // Keep the allowed methods as they were: they are only written for a 405. + Set previous = new HashSet(allowed); + + try { + updateAllowedMethods(); + Set declared = getAllowedMethods(); + return !declared.isEmpty() && !declared.contains(method); + } finally { + Set 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 @@ -403,7 +439,17 @@ protected boolean hasPreconditions() { * * * 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.
+ *
+ * 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. @@ -1833,7 +1879,15 @@ public void setStatus(Status status, Throwable throwable, String message) { /** * 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.
+ *
+ * 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(); diff --git a/org.restlet.java/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java b/org.restlet.java/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java new file mode 100644 index 0000000000..476b96c60e --- /dev/null +++ b/org.restlet.java/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java @@ -0,0 +1,129 @@ +/** + * Copyright 2005-2026 Qlik + *

+ * 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 + *

+ * 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); + } +} diff --git a/org.restlet.java/org.restlet/src/test/java/org/restlet/resource/ServerResourceMethodNotAllowedTestCase.java b/org.restlet.java/org.restlet/src/test/java/org/restlet/resource/ServerResourceMethodNotAllowedTestCase.java new file mode 100644 index 0000000000..082d4baf1e --- /dev/null +++ b/org.restlet.java/org.restlet/src/test/java/org/restlet/resource/ServerResourceMethodNotAllowedTestCase.java @@ -0,0 +1,246 @@ +/** + * Copyright 2005-2026 Qlik + *

+ * 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 + *

+ * Restlet is a registered trademark of QlikTech International AB. + */ +package org.restlet.resource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.restlet.data.Method; +import org.restlet.data.Status; +import org.restlet.data.Tag; +import org.restlet.engine.Engine; +import org.restlet.representation.Representation; +import org.restlet.representation.RepresentationInfo; +import org.restlet.representation.StringRepresentation; + +/** + * Tests that a method that the resource does not support answers 405 (Method Not Allowed) and not + * 412 (Precondition Failed) or 428 (Precondition Required) (#1752): RFC 9110 section 13.2.1 + * requires a server to ignore the preconditions when the response without them would be neither a + * success nor a 412. + */ +class ServerResourceMethodNotAllowedTestCase { + + private static final Tag CURRENT = new Tag("current", false); + + private static final Tag OTHER = new Tag("other", false); + + private static Representation current() { + StringRepresentation result = new StringRepresentation("body"); + result.setTag(CURRENT); + return result; + } + + /** Annotated resource that only reads. */ + public static class ReadOnlyResource extends ServerResource { + + @Get + public Representation read() { + return current(); + } + } + + /** Annotated resource that reads and replaces. */ + public static class ReadWriteResource extends ServerResource { + + int putCount; + + @Get + public Representation read() { + return current(); + } + + @Put + public Representation replace(Representation entity) { + putCount++; + return new StringRepresentation("put-result"); + } + } + + /** Classic resource: it overrides {@code get()} and declares nothing. */ + static class ClassicResource extends ServerResource { + + @Override + protected Representation get() { + return current(); + } + } + + /** Classic resource whose developer declares the supported methods. */ + static class DeclaringClassicResource extends ClassicResource { + + @Override + public void updateAllowedMethods() { + getAllowedMethods().clear(); + getAllowedMethods().addAll(Set.of(Method.GET, Method.HEAD)); + } + } + + /** The recipe of the Javadoc of {@code getPreconditionStatus}: 428 for a write. */ + public static class ConditionalWritesResource extends ReadOnlyResource { + + private boolean isWrite() { + return Method.PUT.equals(getMethod()) + || Method.PATCH.equals(getMethod()) + || Method.DELETE.equals(getMethod()); + } + + @Override + protected boolean hasPreconditions() { + return super.hasPreconditions() || isWrite(); + } + + @Override + protected Status getPreconditionStatus(RepresentationInfo info) { + if (isWrite() && !getConditions().hasSome()) { + return Status.CLIENT_ERROR_PRECONDITION_REQUIRED; + } + return super.getPreconditionStatus(info); + } + } + + /** Same recipe on a resource that supports PUT. */ + public static class WritableConditionalResource extends ConditionalWritesResource { + + @Put + public Representation replace(Representation entity) { + return new StringRepresentation("put-result"); + } + } + + @BeforeEach + void setUpEach() { + Engine.clearThreadLocalVariables(); + Engine.register(); + } + + @AfterEach + void tearDownEach() { + Engine.clearThreadLocalVariables(); + } + + private static T handled(T resource, Method method, Tag ifMatch) { + ServerResourcePreconditionsTestCase.init(resource, method); + resource.setNegotiated(false); + if (ifMatch != null) { + resource.getConditions().setMatch(List.of(ifMatch)); + } + resource.handle(); + return resource; + } + + // --------------------------------------------------------------------------------------- + // The method is not declared: 405 wins over the failing precondition + // --------------------------------------------------------------------------------------- + + @ParameterizedTest + @ValueSource(strings = {"PUT", "DELETE", "POST", "PATCH"}) + void failingIfMatch_onAMethodTheResourceDoesNotSupport_answers405(String method) { + ReadOnlyResource resource = handled(new ReadOnlyResource(), Method.valueOf(method), OTHER); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus(), method); + } + + @Test + void failingIfNoneMatchAll_onAMethodTheResourceDoesNotSupport_answers405() { + ReadOnlyResource resource = + ServerResourcePreconditionsTestCase.init(new ReadOnlyResource(), Method.PUT); + resource.getConditions().setNoneMatch(List.of(Tag.ALL)); + + resource.handle(); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus()); + } + + @Test + void the405_listsTheSupportedMethods() { + ReadOnlyResource resource = handled(new ReadOnlyResource(), Method.PUT, OTHER); + + assertTrue(resource.getAllowedMethods().contains(Method.GET)); + assertFalse(resource.getAllowedMethods().contains(Method.PUT)); + } + + @Test + void the428Recipe_onAMethodTheResourceDoesNotSupport_answers405() { + ConditionalWritesResource resource = + handled(new ConditionalWritesResource(), Method.PUT, null); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus()); + } + + @Test + void aClassicResourceThatDeclaresItsMethods_gets405() { + DeclaringClassicResource resource = + handled(new DeclaringClassicResource(), Method.PUT, OTHER); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus()); + } + + // --------------------------------------------------------------------------------------- + // Guards: nothing changes where the method is supported or where nothing is declared + // --------------------------------------------------------------------------------------- + + @Test + void failingIfMatch_onASupportedMethod_stillAnswers412WithoutAnAllowHeader() { + ReadWriteResource resource = handled(new ReadWriteResource(), Method.PUT, OTHER); + + assertEquals(Status.CLIENT_ERROR_PRECONDITION_FAILED, resource.getStatus()); + assertEquals(0, resource.putCount); + assertTrue(resource.getAllowedMethods().isEmpty(), "no Allow on a 412"); + } + + @Test + void matchingIfMatch_onASupportedMethod_performsTheWrite() { + ReadWriteResource resource = handled(new ReadWriteResource(), Method.PUT, CURRENT); + + assertEquals(1, resource.putCount); + } + + @Test + void get_withMatchingIfNoneMatch_stillAnswers304() { + ReadWriteResource resource = + ServerResourcePreconditionsTestCase.init(new ReadWriteResource(), Method.GET); + resource.getConditions().setNoneMatch(List.of(CURRENT)); + + resource.handle(); + + assertEquals(Status.REDIRECTION_NOT_MODIFIED, resource.getStatus()); + } + + /** The framework does not discover overridden methods: nothing declared, nothing changes. */ + @Test + void aClassicResourceThatDeclaresNothing_keepsAnswering412() { + ClassicResource resource = handled(new ClassicResource(), Method.PUT, OTHER); + + assertEquals(Status.CLIENT_ERROR_PRECONDITION_FAILED, resource.getStatus()); + } + + @Test + void the428Recipe_onASupportedMethod_stillAnswers428() { + WritableConditionalResource resource = + handled(new WritableConditionalResource(), Method.PUT, null); + + assertEquals(Status.CLIENT_ERROR_PRECONDITION_REQUIRED, resource.getStatus()); + } + + @Test + void withoutPreconditions_aMethodTheResourceDoesNotSupport_stillAnswers405() { + ReadOnlyResource resource = handled(new ReadOnlyResource(), Method.PUT, null); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus()); + } +}