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 @@ -4,6 +4,7 @@ Changes log
- 2.7.1 (??-??-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.
- 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. Issue #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 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
28 changes: 28 additions & 0 deletions org.restlet/src/main/java/org/restlet/resource/ServerResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,20 @@
* and redirections take precedence over the preconditions. This is only done if {@link
* #isIgnoringPreconditionsOnNonSuccess()} is true, which is not the default.<br>
* <br>
* 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.
* <br>
* <br>
* To add a precondition, override {@link #hasPreconditions()} and {@link
* #getPreconditionStatus(RepresentationInfo)} rather than this method.
*
* @return The response entity.
* @throws ResourceException
*/
protected Representation doConditionalHandle() throws ResourceException {

Check failure on line 274 in 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 16 to the 15 allowed.

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

if (!hasPreconditions()) {
return isNegotiated() ? doNegotiatedHandle() : doHandle();
Expand All @@ -274,10 +281,18 @@

RepresentationInfo resultInfo = null;
if (existing) {
Status before = getStatus();
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);
}
} else {
doConditionalHandle(resultInfo);
Expand Down Expand Up @@ -334,6 +349,19 @@
}
}

/**
* 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();
}
Expand Down Expand Up @@ -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"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/**
* 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.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 extends ServerResource> T put(
T resource, List<Tag> match, List<Tag> 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);
}
}
Loading