diff --git a/changes.md b/changes.md index fe3359fe69..1d319e5d76 100644 --- a/changes.md +++ b/changes.md @@ -157,6 +157,14 @@ Changes log 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 (#1752). + - A conditional write (`If-Match`, `If-None-Match`...) to a resource that supports the method + but cannot be read (for example an annotated `@Put` without GET) was answered 405 (Method + Not Allowed) by the missing GET, used to retrieve the validators, although the method is + supported. The preconditions are now evaluated as for a resource with no known + representation: `If-Match` fails with 412, `If-None-Match` passes. The resource can + override `getInfo()` to provide its validators. Only a resource that declares its methods + (`ServerResource.updateAllowedMethods()`, the annotated methods by default) is concerned + (#1753). - 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 diff --git a/org.restlet/src/main/java/org/restlet/resource/ServerResource.java b/org.restlet/src/main/java/org/restlet/resource/ServerResource.java index 7da4353aa9..743cd61070 100644 --- a/org.restlet/src/main/java/org/restlet/resource/ServerResource.java +++ b/org.restlet/src/main/java/org/restlet/resource/ServerResource.java @@ -250,6 +250,13 @@ protected void doCatch(Throwable throwable) { * retrieving the validators is neither a success (2xx) nor 412 (Precondition Failed): errors * and redirections take precedence over the preconditions.
*
+ * A resource that supports the method but not GET (for example an annotated {@code @Put} only, + * or one that declares its methods with {@link #updateAllowedMethods()}) cannot be read, so no + * validator is known: the preconditions are evaluated as for a resource with no known + * representation ({@code If-Match} fails with 412, {@code If-None-Match} passes). To get real + * conditional writes on such a resource, override {@link #getInfo()} to provide the validators. + *
+ *
* To add a precondition, override {@link #hasPreconditions()} and {@link * #getPreconditionStatus(RepresentationInfo)} rather than this method. * @@ -266,11 +273,7 @@ protected Representation doConditionalHandle() throws ResourceException { RepresentationInfo resultInfo = null; if (existing) { - resultInfo = doGetInfoAndHandleErrors(); - - if (resultInfo != null) { - doConditionalHandle(resultInfo); - } + resultInfo = retrieveValidatorsAndEvaluate(); } else { doConditionalHandle(resultInfo); } @@ -292,6 +295,30 @@ protected Representation doConditionalHandle() throws ResourceException { return result; } + /** + * Retrieves the validators of the current representation of an existing resource and evaluates + * the preconditions against them. + * + * @return The current representation, or null if it could not be retrieved. + */ + private RepresentationInfo retrieveValidatorsAndEvaluate() { + Status before = getStatus(); + RepresentationInfo resultInfo = doGetInfoAndHandleErrors(); + + if (resultInfo != null) { + doConditionalHandle(resultInfo); + } else if (isGetNotAllowed()) { + // The resource supports the method but cannot be read, so no validator is known + // (#1753): the 405 of the missing GET does not concern this request. The + // preconditions are evaluated as for a resource with no known representation. + setStatus(before); + getAllowedMethods().clear(); + doConditionalHandle((RepresentationInfo) null); + } + + return resultInfo; + } + /** * Handles a call by first verifying the optional request conditions. * @@ -325,6 +352,19 @@ private void doConditionalHandle(final RepresentationInfo resultInfo) { } } + /** + * Indicates that retrieving the validators answered 405 because the resource declares that it + * does not support GET, for a request whose method is not GET nor HEAD. + * + * @return True if the validators cannot be retrieved for that reason. + */ + private boolean isGetNotAllowed() { + return Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus()) + && !Method.GET.equals(getMethod()) + && !Method.HEAD.equals(getMethod()) + && isDeclaredUnsupported(Method.GET); + } + /** * Indicates if the resource declares the supported methods (see {@link * #updateAllowedMethods()}) and the given method is not one of them. A resource that declares diff --git a/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java b/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java index 8991412a7b..ab488296d7 100644 --- a/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java +++ b/org.restlet/src/test/java/org/restlet/engine/connector/MethodNotAllowedWireTestCase.java @@ -58,6 +58,15 @@ public void replace(Representation entity) { } } + /** Annotated resource that only writes (#1753). */ + public static class WriteOnlyResource extends ServerResource { + + @Put + public void replace(Representation entity) { + // Accepted. + } + } + private Server server; @BeforeEach @@ -70,6 +79,7 @@ void setUp() throws Exception { org.restlet.routing.Router router = new org.restlet.routing.Router(context); router.attach("/readonly", new Finder(context, ReadOnlyResource.class)); router.attach("/readwrite", new Finder(context, ReadWriteResource.class)); + router.attach("/writeonly", new Finder(context, WriteOnlyResource.class)); server = new Server(context, Protocol.HTTP, 0, router); server.start(); } @@ -121,4 +131,24 @@ void conditionalPut_withAFailingIfMatch_toAResourceThatSupportsIt_stillAnswers41 assertTrue(response.startsWith("HTTP/1.1 412"), response); } + + /** The 405 of the missing GET (used to get the validators) must not hide the PUT (#1753). */ + @Test + void conditionalPut_withAFailingIfMatch_toAWriteOnlyResource_answers412() throws Exception { + String response = put("/writeonly", "If-Match: \"other\"\r\n"); + + assertTrue(response.startsWith("HTTP/1.1 412"), response); + } + + @Test + void conditionalPut_withIfNoneMatchAll_toAWriteOnlyResource_succeeds() throws Exception { + String response = put("/writeonly", "If-None-Match: *\r\n"); + + assertTrue(response.startsWith("HTTP/1.1 2"), response); + } + + @Test + void unconditionalPut_toAWriteOnlyResource_succeeds() throws Exception { + assertTrue(put("/writeonly", "").startsWith("HTTP/1.1 2")); + } } diff --git a/org.restlet/src/test/java/org/restlet/resource/ServerResourceWriteOnlyTestCase.java b/org.restlet/src/test/java/org/restlet/resource/ServerResourceWriteOnlyTestCase.java new file mode 100644 index 0000000000..79889e1d26 --- /dev/null +++ b/org.restlet/src/test/java/org/restlet/resource/ServerResourceWriteOnlyTestCase.java @@ -0,0 +1,177 @@ +/** + * 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.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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 the conditional writes to a resource that cannot be read (#1753): the 405 of the missing + * GET must not hide a PUT that the resource supports. Without validators, the preconditions are + * evaluated as for a resource with no known representation. + */ +class ServerResourceWriteOnlyTestCase { + + private static final Tag CURRENT = new Tag("current", false); + + private static final Tag OTHER = new Tag("other", false); + + /** Annotated resource that only writes. */ + public static class WriteOnlyResource extends ServerResource { + + int putCount; + + @Put + public Representation replace(Representation entity) { + putCount++; + return new StringRepresentation("put-result"); + } + } + + /** Write-only resource that provides its validators through the light hook. */ + public static class WriteOnlyWithInfoResource extends WriteOnlyResource { + + @Override + protected RepresentationInfo getInfo() { + return new RepresentationInfo((org.restlet.data.MediaType) null, CURRENT); + } + } + + /** Write-only resource whose developer sets his own error when asked for the validators. */ + public static class WriteOnlyWithOwnErrorResource extends WriteOnlyResource { + + @Override + protected Representation get() { + setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE); + return null; + } + } + + /** Classic resource: it overrides {@code put()} and declares nothing. */ + static class ClassicWriteOnlyResource extends ServerResource { + + int putCount; + + @Override + protected Representation put(Representation entity) { + putCount++; + return new StringRepresentation("put-result"); + } + } + + @BeforeEach + void setUpEach() { + Engine.clearThreadLocalVariables(); + Engine.register(); + } + + @AfterEach + void tearDownEach() { + Engine.clearThreadLocalVariables(); + } + + private static T put( + T resource, List match, List noneMatch) { + ServerResourcePreconditionsTestCase.init(resource, Method.PUT); + resource.setNegotiated(false); + if (match != null) { + resource.getConditions().setMatch(match); + } + if (noneMatch != null) { + resource.getConditions().setNoneMatch(noneMatch); + } + resource.handle(); + return resource; + } + + // --------------------------------------------------------------------------------------- + // The resource supports PUT but cannot be read: no validator is known + // --------------------------------------------------------------------------------------- + + @Test + void ifMatch_onAWriteOnlyResource_answers412NotTheGet405() { + WriteOnlyResource resource = put(new WriteOnlyResource(), List.of(OTHER), null); + + assertEquals(Status.CLIENT_ERROR_PRECONDITION_FAILED, resource.getStatus()); + assertEquals(0, resource.putCount); + } + + @Test + void ifNoneMatchAll_onAWriteOnlyResource_performsTheWrite() { + WriteOnlyResource resource = put(new WriteOnlyResource(), null, List.of(Tag.ALL)); + + assertTrue(resource.getStatus().isSuccess(), String.valueOf(resource.getStatus())); + assertEquals(1, resource.putCount); + } + + @Test + void ifNoneMatchWithATag_onAWriteOnlyResource_performsTheWrite() { + WriteOnlyResource resource = put(new WriteOnlyResource(), null, List.of(OTHER)); + + assertTrue(resource.getStatus().isSuccess(), String.valueOf(resource.getStatus())); + assertEquals(1, resource.putCount); + } + + // --------------------------------------------------------------------------------------- + // Guards + // --------------------------------------------------------------------------------------- + + @Test + void withoutPreconditions_aWriteOnlyResource_performsTheWrite() { + WriteOnlyResource resource = put(new WriteOnlyResource(), null, null); + + assertTrue(resource.getStatus().isSuccess(), String.valueOf(resource.getStatus())); + assertEquals(1, resource.putCount); + } + + @Test + void aWriteOnlyResourceThatProvidesItsValidators_evaluatesThem() { + WriteOnlyWithInfoResource matching = + put(new WriteOnlyWithInfoResource(), List.of(CURRENT), null); + WriteOnlyWithInfoResource other = + put(new WriteOnlyWithInfoResource(), List.of(OTHER), null); + + assertTrue(matching.getStatus().isSuccess(), String.valueOf(matching.getStatus())); + assertEquals(1, matching.putCount); + assertEquals(Status.CLIENT_ERROR_PRECONDITION_FAILED, other.getStatus()); + assertEquals(0, other.putCount); + } + + /** An error that the developer sets while the validators are retrieved is kept (#129). */ + @Test + void anErrorSetByTheResourceItself_isKept() { + WriteOnlyWithOwnErrorResource resource = + put(new WriteOnlyWithOwnErrorResource(), List.of(OTHER), null); + + assertEquals(Status.SERVER_ERROR_SERVICE_UNAVAILABLE, resource.getStatus()); + assertEquals(0, resource.putCount); + } + + /** The framework does not discover overridden methods: nothing declared, nothing changes. */ + @Test + void aClassicWriteOnlyResourceThatDeclaresNothing_keepsAnswering405() { + ClassicWriteOnlyResource resource = + put(new ClassicWriteOnlyResource(), List.of(OTHER), null); + + assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, resource.getStatus()); + assertEquals(0, resource.putCount); + } +}