=== How to fix it in Node.js

The following code is vulnerable to SSRF as it opens a URL defined by untrusted data.

==== Noncompliant code example

[source,javascript,diff-id=1,diff-type=noncompliant]
----
const axios = require('axios');
const express = require('express');

const app = express();

app.get('/example', async (req, res) => {
    try {
        await axios.get(req.query.url); // Noncompliant
        res.send("OK");
    } catch (err) {
        console.error(err);
        res.send("ERROR");
    }
})
----

==== Compliant solution

[source,javascript,diff-id=1,diff-type=compliant]
----
const axios = require('axios');
const express = require('express');

const schemesList = ["http:", "https:"];
const domainsList = ["trusted1.example.com", "trusted2.example.com"];

app.get('/example', async (req, res) => {
    const url = (new URL(req.query.url));

    if (schemesList.includes(url.protocol) && domainsList.includes(url.hostname)) {
        try {
            await axios.get(url);
            res.send("OK");
        } catch (err) {
            console.error(err);
            res.send("ERROR");
        }
    }else {
        res.send("INVALID_URL");
    }
})
----

include::../../common/fix/how-does-this-work.adoc[]

The compliant code example uses such an approach.

=== Pitfalls

include::../../common/pitfalls/starts-with.adoc[]
