Skip to content
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

Security Enhancement: Fix Username Vulnerability and Add Admin Access #94

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
58 changes: 33 additions & 25 deletions api/app.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,49 @@
// Cache control settings
const express = require('express');
const cacheControl = require("./config/cacheControl");

// app package loading
let app = require("./src/app-setup");
const app = express();

// Setup the routes
app.get("/api/v1/mail/list", require("./src/api/mailList"));
app.get("/api/v1/mail/getInfo", require("./src/api/mailGetInfo"));
app.get("/api/v1/mail/getHtml", require("./src/api/mailGetHtml"));
const mailList = require("./src/api/mailList");
const mailGetInfo = require("./src/api/mailGetInfo");
const mailGetHtml = require("./src/api/mailGetHtml");

app.get("/api/v1/mail/list", (req, res) => {
console.log("Received /api/v1/mail/list with parameters:", req.query);
mailList(req, res);
});

// Legacy fallback behaviour -
// Note this is to be deprecated (after updating UI)
app.get("/api/v1/mail/getKey", require("./src/api/mailGetInfo"));
app.get("/api/v1/mail/getInfo", (req, res) => {
console.log("Received /api/v1/mail/getInfo with parameters:", req.query);
mailGetInfo(req, res);
});

app.get("/api/v1/mail/getHtml", (req, res) => {
console.log("Received /api/v1/mail/getHtml with parameters:", req.query);
mailGetHtml(req, res);
});

// Static regex
const staticRegex = /static\/(js|css|img)\/(.+)\.([a-zA-Z0-9]+)\.(css|js|png|gif)/g;

// Static folder hosting with cache control
// See express static options: https://expressjs.com/en/4x/api.html#express.static
app.use( app.express.static("public", {
etag: true,
setHeaders: function (res, path, stat) {
if( staticRegex.test(path) ) {
res.set('cache-control', cacheControl.immutable);
} else {
res.set('cache-control', cacheControl.static );
}
}
}) )
app.use(express.static("public", {
etag: true,
setHeaders: function (res, path) {
if (staticRegex.test(path)) {
res.set('cache-control', cacheControl.immutable);
} else {
res.set('cache-control', cacheControl.static);
}
}
}));

// Custom 404 handling - use index.html
app.use(function(req, res) {
res.set('cache-control', cacheControl.static)
res.sendFile(__dirname + '/public/index.html');
app.use(function (req, res) {
res.set('cache-control', cacheControl.static);
res.sendFile(__dirname + '/public/index.html');
});

// Setup the server
var server = app.listen(8000, function () {
console.log("app running on port.", server.address().port);
console.log("app running on port.", server.address().port);
});
1 change: 1 addition & 0 deletions api/config/mailgunConfig.sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
module.exports = {
"apiKey" : "${MAILGUN_API_KEY}",
"emailDomain" : "${MAILGUN_EMAIL_DOMAIN}",
"adminAccessKey" : "${ADMIN_ACCESS_KEY}",
//"corsOrigin" : "*"
}
3 changes: 0 additions & 3 deletions api/public/.gitignore

This file was deleted.

104 changes: 66 additions & 38 deletions api/src/api/mailGetHtml.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,76 @@
// Loading mailgun reader and config
const mailgunReader = require("../mailgunReader");
const mailgunConfig = require("../../config/mailgunConfig");
const cacheControl = require("../../config/cacheControl");

const cacheControl = require("../../config/cacheControl");
const reader = new mailgunReader(mailgunConfig);

/**
* Get and return the etatic email HTML content from the mailgun API, given the mailKey
* Validate the region and key parameters and ensure they contain only allowed characters
*
* @param {String} region
* @param {String} key
*/
function validateParams(region, key) {
console.log("Validating parameters: region=", region, ", key=", key);

if (!region || !key) {
throw new Error("Region or key is undefined or null");
}

// Remove leading/trailing whitespace
region = region.trim();
key = key.trim();

// Validate that only allowed characters are present
if (!/^[a-zA-Z0-9._-]+$/.test(region) || !/^[a-zA-Z0-9._-]+$/.test(key)) {
throw new Error("Invalid region or key");
}

return { region, key };
}

/**
* Get and return the static email HTML content from the mailgun API, given the mailKey
*
* @param {*} req
* @param {*} res
*/
module.exports = function(req, res){

let region = req.query.region
let key = req.query.key

if (region == null || region === ""){
return res.status(400).send('{ "error" : "No `region` param found" }');
}

if (key == null || key === ""){
return res.status(400).send('{ "error" : "No `key` param found" }');
}

reader.getKey({region, key}).then(response => {
let body = response["body-html"] || response["body-plain"]
if( body === undefined || body == null) {
body = 'The kittens found no messages :('
}

// Add JS injection to force all links to open as a new tab
// instead of opening inside the iframe
body += '<script>' +
'let linkArray = document.getElementsByTagName("a");' +
'for (let i=0; i<linkArray.length; ++i) { linkArray[i].target="_blank"; }' +
// eslint-disable-next-line
'<\/script>'

res.set('cache-control', cacheControl.static)
res.status(200).send(body)
})
.catch(e => {
console.error(`Error getting mail HTML for /${region}/${key}: `, e)
res.status(500).send("{error: '"+e+"'}")
});
}
module.exports = function (req, res) {
let region = req.query.region;
let key = req.query.key;

console.log("Received request with region:", region, "and key:", key);

try {
// Validate and sanitize the region and key parameters
const validatedParams = validateParams(region, key);
region = validatedParams.region;
key = validatedParams.key;
} catch (error) {
console.error("Validation error:", error.message);
return res.status(400).send({ error: error.message });
}

reader
.getKey({ region, key })
.then((response) => {
let body = response["body-html"] || response["body-plain"];
if (!body) {
body = "The kittens found no messages :(";
}
// Add JS injection to force all links to open as a new tab
// instead of opening inside the iframe
body +=
"<script>" +
'let linkArray = document.getElementsByTagName("a");' +
'for (let i=0; i<linkArray.length; ++i) { linkArray[i].target="_blank"; }' +
// eslint-disable-next-line
"<\\/script>";
res.set("cache-control", cacheControl.static);
res.status(200).send(body);
})
.catch((e) => {
console.error(`Error getting mail HTML for /${region}/${key}: `, e);
res.status(500).send({ error: "Internal Server Error" });
});
};
94 changes: 51 additions & 43 deletions api/src/api/mailGetInfo.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,66 @@
// Loading mailgun reader and config
const mailgunReader = require("../mailgunReader");
const mailgunConfig = require("../../config/mailgunConfig");
const cacheControl = require("../../config/cacheControl");

const cacheControl = require("../../config/cacheControl");
const reader = new mailgunReader(mailgunConfig);

/**
* Get and return the static email header details from the mailgun API given the mailKey
* Validate the recipient parameter
*
* @param {*} req
* @param {*} res
* @param {String} recipient
*/
module.exports = function(req, res){
function validateRecipient(recipient) {
// Remove leading/trailing whitespace
recipient = recipient.trim();

let region = req.query.region
let key = req.query.key

if (region == null || region === ""){
return res.status(400).send('{ "error" : "No `region` param found" }');
}
// Ensure recipient contains valid characters and ends with the correct domain
const recipientRegex = /^[a-zA-Z0-9._-]+@akunlama\.com$/;
if (!recipientRegex.test(recipient)) {
throw new Error("Invalid recipient format");
}

if (key == null || key === ""){
return res.status(400).send('{ "error" : "No `key` param found" }');
}

reader.getKey({region, key}).then(response => {
let emailDetails = {}

// Format and extract the name of the user
let [name, ...rest] = formatName(response.from)
emailDetails.name = name

// Extract the rest of the email domain after splitting
if (rest[0].length > 0) {
emailDetails.emailAddress = ' <' + rest
}
return recipient;
}

// Extract the subject of the response
emailDetails.subject = response.subject
/**
* Get and return the static email header details from the mailgun API given the mailKey
*
* @param {*} req
* @param {*} res
*/
module.exports = function (req, res) {
let recipient = req.query.recipient;

// Extract the recipients
emailDetails.recipients = response.recipients
try {
recipient = validateRecipient(recipient);
} catch (error) {
return res.status(400).send({ error: error.message });
}

// Return with cache control
res.set('cache-control', cacheControl.static)
res.status(200).send(emailDetails)
})
.catch(e => {
console.error(`Error getting mail metadata info for /${region}/${key}: `, e)
res.status(500).send("{error: '"+e+"'}")
});
}
reader.getKey({ recipient }).then(response => {
let emailDetails = {};
// Format and extract the name of the user
let [name, ...rest] = formatName(response.from);
emailDetails.name = name;
// Extract the rest of the email domain after splitting
if (rest[0].length > 0) {
emailDetails.emailAddress = ' <' + rest;
}
// Extract the subject of the response
emailDetails.subject = response.subject;
// Extract the recipients
emailDetails.recipients = response.recipients;
// Return with cache control
res.set('cache-control', cacheControl.static);
res.status(200).send(emailDetails);
})
.catch(e => {
console.error(`Error getting mail metadata info for ${recipient}: `, e);
res.status(500).send({ error: 'Internal Server Error' });
});
};

function formatName (sender) {
let [name, ...rest] = sender.split(' <')
return [name, rest]
function formatName(sender) {
let [name, ...rest] = sender.split(' <');
return [name, rest];
}
61 changes: 41 additions & 20 deletions api/src/api/mailGetUrl.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,52 @@
// Loading mailgun reader and config
const mailgunReader = require("../mailgunReader");
const mailgunConfig = require("../../config/mailgunConfig");
const cacheControl = require("../../config/cacheControl");
const cacheControl = require("../../config/cacheControl");

const reader = new mailgunReader(mailgunConfig);

/**
* Get and return the URL link from the mailgun API - for the mail gcontent
*
* NOTE - this is to be deprecated
* Validate the URL parameter
*
* @param {String} url
*/
function validateUrl(url) {
// Remove leading/trailing whitespace
url = url.trim();

// Ensure the URL is not empty
if (url === '') {
throw new Error("Invalid URL");
}

return url;
}

/**
* Get and return the URL link from the mailgun API - for the mail content
*
* @param {*} req
* @param {*} res
*/
module.exports = function(req, res){
let params = req.query
let url = params.url
if (url == null || url === ""){
res.status(400).send('{ "error" : "No `url` param found" }');
}

reader.getUrl(url).then(response => {
res.set('cache-control', cacheControl.static)
res.status(200).send(response)
})
.catch(e => {
console.error("Error: ", error)
res.status(500).send("{error: '"+e+"'}")
});
}
module.exports = function (req, res) {
let url = req.query.url;

if (url == null || url === "") {
return res.status(400).send('{ "error" : "No `url` param found" }');
}

try {
url = validateUrl(url);
} catch (error) {
return res.status(400).send({ error: error.message });
}

reader.getUrl(url).then(response => {
res.set('cache-control', cacheControl.static);
res.status(200).send(response);
})
.catch(e => {
console.error("Error: ", e);
res.status(500).send({ error: 'Internal Server Error' });
});
};
Loading