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
6 changes: 6 additions & 0 deletions changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ Changes log
first scope outermost. `McpRequestContext.transportResponse()` gives the transport
response.
- 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 (#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
Expand Down
58 changes: 55 additions & 3 deletions org.restlet/src/main/java/org/restlet/resource/ServerResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,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 @@ -312,13 +313,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<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<>(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 (see {@link #getInfo()}) and
Expand Down Expand Up @@ -362,7 +398,15 @@ protected boolean hasPreconditions() {
* </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.
* {@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 @@ -1751,7 +1795,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.
* 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,124 @@
/**
* 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.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;

/**
* 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 Server server;

@BeforeEach
void setUp() throws Exception {
Engine.clearThreadLocalVariables();
Engine.register();
Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(null));

Context context = new Context();
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));
server = new Server(context, Protocol.HTTP, 0, router);
server.start();
}

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

private String put(String path, String conditionalHeader) throws IOException {
try (Socket socket = new Socket("localhost", server.getActualPort())) {
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