question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

sendRedirect() is encoding uri's that are already encoded

See original GitHub issue

Environment

Using aws-lambda preset

------------------------------
- Operating System: `Darwin`
- Node Version:     `v16.15.1`
- Nuxt Version:     `3.0.0-rc.4`
- Package Manager:  `yarn@1.22.4`
- Builder:          `vite`
- User Config:      `nitro`, `app`, `alias`, `css`, `hooks`
- Runtime Modules:  `-`
- Build Modules:    `-`
------------------------------

Reproduction

Create a /server/api/[...].ts file with the following code, so we can proxy api requests from ournuxturl.com/api to ouractualapi.com


const baseURL = 'https://my.api.com';


import { createError, useBody, appendHeader } from 'h3';

export default defineEventHandler(async event => {

    const method = useMethod(event)
    const params = useQuery(event)
    const body = method !== 'GET' && method !== 'HEAD' ? await useBody(event) : undefined;
    var path = String(event.req.url).substring(4); //.split('/api').join('');
    let originalHeaders = event.req.headers; 

    let lookup = {
        'authorization': 1,
        'user-agent': 1,
        'accept': 1,
    }

    let headers = Object.keys(originalHeaders)
        .reduce(function(set, key) {
            if (!lookup[key]) {
                return set;
            }
            set[key] = originalHeaders[key];
            return set;
        }, {});

    let errorData;
    let response;

    try {
        response = await $fetch.raw(path, {
            headers,
            baseURL,
            method,
            params,
            body
        })
    } catch (error) {
        errorData = error.response._data;
        event.res.statusCode = errorData.statusCode || errorData.status;
        event.res.setHeader("Content-Type", 'application/json');
        event.res.end(JSON.stringify(errorData, null, 2));
        return errorData;
    }

    if(errorData) {
        return errorData;
    }

    // Check how we should proxy
    var fullPath = `${baseURL}${path}`;
    var redirectURL = response.url;

    if(fullPath != redirectURL) {


        console.log('Correct URL to redirect to is', redirectURL);
        return sendRedirect(event, redirectURL, 302)
    }
    
    for (const header of ['content-type', 'cache-control']) {
        if (response.headers.has(header)) {
            appendHeader(event, header, response.headers.get(header));
        }
    }

    return response._data;
})

### Describe the bug

When using sendRedirect() the url we are redirecting to is being encoded which is mangling the intended url if it it already an encoded uri.
this is a problem that was not occurring prior to updating nuxt recently. and is breaking things like AWS S3 SignedURLs as the signature is encoded.


An example url is something like this:

https://storage.s3.us-west-2.amazonaws.com/files/62e9eb262106f7f6ff16b52f/image.png?AWSAccessKeyId=AZIA5ZO5F4R6KA5PSG78&Expires=1662126522&Signature=cRyednjMGj1Jhzpw7LpHwKQBjNQ%3D&response-cache-control=no-cache&response-content-disposition=inline


### Additional context

_No response_

### Logs

_No response_

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
danielroecommented, Sep 2, 2022

I believe that has been resolved in https://github.com/unjs/h3/commit/04b432cf3e67675b6f4e7f3b74e95e475b8b5bfe (h3 version 0.7.19). Would you try upgrading h3 to confirm?

2reactions
pi0commented, Sep 2, 2022

Hi @Hyperblaster Can you please try upgrading lockfile? There is a recent fix that should address this (https://github.com/unjs/h3/commit/04b432cf3e67675b6f4e7f3b74e95e475b8b5bfe)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Servlet response.sendRedirect encoding problems
The sendRedirect() method doesn't encode the query string for you. You've to do it yourself. response.sendRedirect("/path/index.jsp?type=" + ...
Read more >
apache 2.4 - double encode already encoded query string in ...
1 Answer 1 ... This issues a temporary (302) redirect from /home?testStr%3Dhello%26id%3Drad to /home?testStr%253Dhello%2526id%253Drad (doubly ...
Read more >
HTTP URL Percent Encoding - Cisco
Percent-encoding functionality is used whenever URL redirection happens for an HTTP Request packet and the requested URL (original URL) is embedded in ...
Read more >
URI (Java Platform SE 8 ) - Oracle Help Center
To encode non-US-ASCII characters when a URI is required to conform strictly to RFC 2396 by not containing any other characters.
Read more >
Add Redirect form breaks URLs containing spaces or %20
redirect -fix-double-encoding-urls-1451868-26-7.39.patch, 732 bytes ... Drupal already encodes the URL when delivering the page or file, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found