-
Notifications
You must be signed in to change notification settings - Fork 7
Add a new annotation and an interceptor to control and check content … #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
aaab5d2
Add a new annotation and an interceptor to control and check content …
bvasseur-urw df2adc6
Add unit test for contentControlFeature
bvasseur-urw 173d4f6
Add a ContentControlFeatureFactory to give control of the default max…
bvasseur-urw 8f77c6d
Add readme doc about the ContentControlFeature
bvasseur-urw d922c43
Add a fail fast for the content control feature if the content length…
bvasseur-urw ec1660f
add unit test for jersey content size limit
bvasseur-urw f6a9e0f
Add unit test for sizelimitinginputstream for more coverage
bvasseur-urw 295ce44
Add a unit test for the content control feature with GET request
bvasseur-urw 0c05d1d
Refacto ContentControlFeature pour ne pas générer une exception à cha…
bvasseur-urw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -47,7 +47,7 @@ | |
</dependency> | ||
</dependencies> | ||
|
||
|
||
<dependencyManagement> | ||
<dependencies> | ||
<dependency> | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
176 changes: 176 additions & 0 deletions
176
...-jersey/src/main/java/com/coreoz/plume/jersey/security/control/ContentControlFeature.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
package com.coreoz.plume.jersey.security.control; | ||
|
||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.lang.reflect.AnnotatedElement; | ||
|
||
import jakarta.inject.Singleton; | ||
import jakarta.ws.rs.WebApplicationException; | ||
import jakarta.ws.rs.container.DynamicFeature; | ||
import jakarta.ws.rs.container.ResourceInfo; | ||
import jakarta.ws.rs.core.FeatureContext; | ||
import jakarta.ws.rs.core.HttpHeaders; | ||
import jakarta.ws.rs.core.Response; | ||
import jakarta.ws.rs.ext.ReaderInterceptor; | ||
import jakarta.ws.rs.ext.ReaderInterceptorContext; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
@Singleton | ||
public class ContentControlFeature implements DynamicFeature { | ||
benoitvasseur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private static final Logger logger = LoggerFactory.getLogger(ContentControlFeature.class); | ||
public static final int DEFAULT_MAX_SIZE = 500 * 1024; // 500 KB | ||
private final Integer maxSize; | ||
|
||
public ContentControlFeature(int maxSize) { | ||
this.maxSize = maxSize; | ||
} | ||
|
||
public ContentControlFeature() { | ||
this.maxSize = DEFAULT_MAX_SIZE; | ||
} | ||
|
||
public Integer getContentSizeLimit() { | ||
if (maxSize == null) { | ||
return DEFAULT_MAX_SIZE; | ||
} | ||
return maxSize; | ||
} | ||
|
||
@Override | ||
public void configure(ResourceInfo resourceInfo, FeatureContext context) { | ||
addContentSizeFilter(resourceInfo.getResourceMethod(), context); | ||
} | ||
|
||
private void addContentSizeFilter(AnnotatedElement annotatedElement, FeatureContext methodResourcecontext) { | ||
ContentSizeLimit contentSizeLimit = annotatedElement.getAnnotation(ContentSizeLimit.class); | ||
methodResourcecontext.register(new ContentSizeLimitInterceptor( | ||
contentSizeLimit != null ? contentSizeLimit.value() : maxSize | ||
)); | ||
} | ||
|
||
public static class ContentSizeLimitInterceptor implements ReaderInterceptor { | ||
|
||
private final int maxSize; | ||
|
||
public ContentSizeLimitInterceptor(int maxSize) { | ||
this.maxSize = maxSize; | ||
} | ||
|
||
// https://stackoverflow.com/questions/24516444/best-way-to-make-jersey-2-x-refuse-requests-with-incorrect-content-length | ||
@Override | ||
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException { | ||
Integer headerContentLength; | ||
try { | ||
headerContentLength = Integer.parseInt(context.getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH)); | ||
} catch (NumberFormatException e) { | ||
throw new WebApplicationException( | ||
Response.status(Response.Status.LENGTH_REQUIRED) | ||
.entity("Content-Length header is missing or invalid.") | ||
.build() | ||
); | ||
} | ||
benoitvasseur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (headerContentLength > maxSize) { | ||
throw new WebApplicationException( | ||
Response.status(Response.Status.REQUEST_ENTITY_TOO_LARGE) | ||
.entity("Content size limit exceeded.") | ||
.build() | ||
); | ||
} | ||
|
||
final InputStream contextInputStream = context.getInputStream(); | ||
context.setInputStream(new SizeLimitingInputStream(contextInputStream, headerContentLength)); | ||
|
||
return context.proceed(); | ||
} | ||
|
||
public static final class SizeLimitingInputStream extends InputStream { | ||
private long length = 0; | ||
private int mark = 0; | ||
|
||
private final int maxSize; | ||
|
||
private final InputStream delegateInputStream; | ||
|
||
public SizeLimitingInputStream(InputStream delegateInputStream, int maxSize) { | ||
this.delegateInputStream = delegateInputStream; | ||
this.maxSize = maxSize; | ||
} | ||
|
||
@Override | ||
public int read() throws IOException { | ||
final int read = delegateInputStream.read(); | ||
readAndCheck(read != -1 ? 1 : 0); | ||
return read; | ||
} | ||
|
||
@Override | ||
public int read(final byte[] b) throws IOException { | ||
final int read = delegateInputStream.read(b); | ||
readAndCheck(read != -1 ? read : 0); | ||
return read; | ||
} | ||
|
||
@Override | ||
public int read(final byte[] b, final int off, final int len) throws IOException { | ||
final int read = delegateInputStream.read(b, off, len); | ||
readAndCheck(read != -1 ? read : 0); | ||
return read; | ||
} | ||
|
||
@Override | ||
public long skip(final long n) throws IOException { | ||
final long skip = delegateInputStream.skip(n); | ||
readAndCheck(skip != -1 ? skip : 0); | ||
return skip; | ||
} | ||
|
||
@Override | ||
public int available() throws IOException { | ||
return delegateInputStream.available(); | ||
} | ||
|
||
@Override | ||
public void close() throws IOException { | ||
delegateInputStream.close(); | ||
} | ||
|
||
@Override | ||
public synchronized void mark(final int readlimit) { | ||
mark += readlimit; | ||
delegateInputStream.mark(readlimit); | ||
} | ||
|
||
@Override | ||
public synchronized void reset() throws IOException { | ||
this.length = 0; | ||
readAndCheck(mark); | ||
delegateInputStream.reset(); | ||
} | ||
|
||
@Override | ||
public boolean markSupported() { | ||
return delegateInputStream.markSupported(); | ||
} | ||
|
||
private void readAndCheck(final long read) { | ||
this.length += read; | ||
|
||
if (this.length > maxSize) { | ||
try { | ||
this.close(); | ||
} catch (IOException e) { | ||
logger.error("Error while closing the input stream", e); | ||
} | ||
throw new WebApplicationException( | ||
Response.status(Response.Status.REQUEST_ENTITY_TOO_LARGE) | ||
.entity("Content size limit exceeded.") | ||
.build() | ||
); | ||
} | ||
} | ||
} | ||
} | ||
} |
21 changes: 21 additions & 0 deletions
21
.../src/main/java/com/coreoz/plume/jersey/security/control/ContentControlFeatureFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package com.coreoz.plume.jersey.security.control; | ||
|
||
import org.glassfish.hk2.api.Factory; | ||
|
||
public class ContentControlFeatureFactory implements Factory<ContentControlFeature> { | ||
private final Integer maxSize; | ||
|
||
public ContentControlFeatureFactory(int maxSize) { | ||
this.maxSize = maxSize; | ||
} | ||
|
||
@Override | ||
public ContentControlFeature provide() { | ||
return new ContentControlFeature(maxSize); | ||
} | ||
|
||
@Override | ||
public void dispose(ContentControlFeature instance) { | ||
// unused | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
...e-web-jersey/src/main/java/com/coreoz/plume/jersey/security/control/ContentSizeLimit.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package com.coreoz.plume.jersey.security.control; | ||
|
||
import static java.lang.annotation.ElementType.METHOD; | ||
import static java.lang.annotation.ElementType.TYPE; | ||
import static java.lang.annotation.RetentionPolicy.RUNTIME; | ||
|
||
import java.lang.annotation.Documented; | ||
import java.lang.annotation.Retention; | ||
import java.lang.annotation.Target; | ||
|
||
|
||
/** | ||
* Modify the default Content size limit handled by the backend | ||
*/ | ||
@Documented | ||
@Retention (RUNTIME) | ||
@Target({TYPE, METHOD}) | ||
public @interface ContentSizeLimit { | ||
|
||
/** | ||
* The maximum size of the content in bytes | ||
*/ | ||
int value(); | ||
} |
77 changes: 77 additions & 0 deletions
77
plume-web-jersey/src/test/java/com/coreoz/plume/jersey/control/ContentSizeLimitTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package com.coreoz.plume.jersey.control; | ||
|
||
import org.junit.Test; | ||
|
||
import jakarta.ws.rs.client.Entity; | ||
import jakarta.ws.rs.core.Application; | ||
import jakarta.ws.rs.core.HttpHeaders; | ||
import jakarta.ws.rs.core.MediaType; | ||
import jakarta.ws.rs.core.Response; | ||
import jakarta.ws.rs.client.Invocation.Builder; | ||
|
||
import org.glassfish.jersey.server.ResourceConfig; | ||
import org.glassfish.jersey.test.JerseyTest; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
|
||
import com.coreoz.plume.jersey.security.control.ContentControlFeature; | ||
import com.coreoz.plume.jersey.security.control.ContentControlFeatureFactory; | ||
|
||
public class ContentSizeLimitTest extends JerseyTest { | ||
|
||
@Override | ||
protected Application configure() { | ||
ResourceConfig config = new ResourceConfig(TestContentSizeResource.class); | ||
config.register(ContentControlFeature.class); | ||
return config; | ||
} | ||
|
||
@Test | ||
public void checkContentSize_withBody_whenWithinDefaultLimit_shouldReturn200() { | ||
byte[] data = "12345".getBytes(); | ||
Response response = target("/test/upload-default").request().post(Entity.entity(data, MediaType.APPLICATION_OCTET_STREAM)); | ||
assertEquals(200, response.getStatus()); | ||
} | ||
|
||
@Test | ||
public void checkContentSize_withBody_whenBeyondDefaultLimit_shouldReturn413() { | ||
// Generate a byte array of ContentControlFeature.DEFAULT_MAX_SIZE + 1 | ||
byte[] data = new byte[ContentControlFeature.DEFAULT_MAX_SIZE + 1]; | ||
Builder request = target("/test/upload-default").request(); | ||
Entity<byte[]> entity = Entity.entity(data, MediaType.APPLICATION_OCTET_STREAM); | ||
assertEquals(Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode(), request.post(entity).getStatus()); | ||
} | ||
|
||
@Test | ||
public void checkContentSize_withBody_whenContentLengthIsWrong_shouldReturn411() { | ||
// Generate a byte array of ContentControlFeature.DEFAULT_MAX_SIZE + 1 | ||
Builder request = target("/test/upload-default").request(); | ||
request.header(HttpHeaders.CONTENT_LENGTH, null); | ||
assertEquals(Response.Status.LENGTH_REQUIRED.getStatusCode(), request.post(null).getStatus()); | ||
} | ||
|
||
@Test | ||
public void checkContentSize_withBody_whenWithinCustomLimit_shouldReturn200() { | ||
byte[] data = "12345".getBytes(); | ||
Response response = target("/test/upload-custom").request().post(Entity.entity(data, MediaType.APPLICATION_OCTET_STREAM)); | ||
assertEquals(200, response.getStatus()); | ||
} | ||
|
||
@Test | ||
public void checkContentSize_withBody_whenBeyondCustomLimit_shouldReturn413() { | ||
// Generate a byte array of CUSTOM_MAX_SIZE + 1 | ||
byte[] data = new byte[TestContentSizeResource.CUSTOM_MAX_SIZE + 1]; | ||
Builder request = target("/test/upload-custom").request(); | ||
Entity<byte[]> entity = Entity.entity(data, MediaType.APPLICATION_OCTET_STREAM); | ||
assertEquals(Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode(), request.post(entity).getStatus()); | ||
} | ||
|
||
@Test | ||
public void checkMaxSize_whenCustomControlFeature_shouldSuccess() { | ||
// Custom max size | ||
Integer customMaxSize = 300; | ||
ContentControlFeatureFactory contentControlFeatureFactory = new ContentControlFeatureFactory(customMaxSize); | ||
ContentControlFeature contentControlFeature = contentControlFeatureFactory.provide(); | ||
assertEquals(customMaxSize, contentControlFeature.getContentSizeLimit()); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.