spring-cloud / spring-cloud/spring-cloud-gateway

Multipart body is missing

Open
#3,959 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

waiting-for-triage
Dominant language
Java
Stars
4.9k
Forks
3.5k
Avg merge
20h 57m
Merged PRs (30d)
8

Description

Hi, everyone!
I'm using Spring Cloud Gateway MVC 4.1.2
I need to validate incoming file in multipart request by checking his magic bytes.
Straight approach doesn't work because after opening a stream from a file it becomes unavailable for further filters. I tried to use caching but it doesn't work either, request body is missing downstream. Is there a workaround or maybe a right approach to do this kind of validation with Spring Cloud Gateway MVC?

Here's my code snippet:

@Bean
    public RouterFunction<ServerResponse> myRoute() {
        return route("gateway").POST(path("/upload"), http("http://localhost:8081")).before(request -> {
            var clonedInputStream = cacheBody(request);
            var clonedRequest = adaptCachedBody().apply(request);
            clonedInputStream.reset();

            try {
                byte[] pdfSignature = {0x25, 0x50, 0x44, 0x46, 0x2D};
                byte[] actualSignature = new byte[pdfSignature.length];
                HttpServletRequest httpServletRequest = request.servletRequest();
                Part file = httpServletRequest.getPart("file");
                file.getInputStream().read(actualSignature);
                if (!Arrays.equals(pdfSignature, actualSignature)) {
                    throw new RuntimeException("Not PDF");
                }
            } catch (IOException | ServletException e) {
                throw new RuntimeException(e);
            }
            return clonedRequest;
        }).build();
    }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the RouterFunction for POST /upload and trace the before filter through cacheBody(), adaptCachedBody(), and the multipart getPart("file") call. Reproduce the request and verify that magic-byte validation can run while the downstream route still receives the multipart body.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.