janjaali / sendGrid-mock

SendGrid-Mock serves as a simple server mocking the sendgrid-apis for development purposes.
https://cloud.docker.com/repository/docker/ghashange/sendgrid-mock/general
MIT License
48 stars 19 forks source link

Basic auth being applied to non-static content #80

Closed camerondearien closed 3 months ago

camerondearien commented 3 months ago

I am currently trying to set up sendGrid-mock with basic auth on the static content for the UI and use api key auth for the endpoints. When enabling basic auth it is being applied to both the static content and the endpoints. This is causing issues for the requests as they now need both the api key auth and basic auth.

I am proposing an update to ExpressApp.js to move the enabling of basic auth under the RequestHandler.

const path = require('path');
const express = require('express');
const basicAuth = require('express-basic-auth');
const { rateLimit } = require('express-rate-limit');
const { loggerFactory } = require('./logger/log4js');
const RequestHandler = require('./RequestHandler');

const logger = loggerFactory('ExpressApp');

const setupExpressApp = (
  mailHandler, 
  apiAuthentication, 
  mockedApiAuthenticationKey, 
  rateLimitConfiguration,
) => {

  const app = express();

  if (rateLimitConfiguration.enabled) {

    const rateLimitWindowInMs = rateLimitConfiguration.windowInMs;
    const rateLimitMaxRequests = rateLimitConfiguration.maxRequests;

    logger.info(`Rate limit enabled with ${rateLimitMaxRequests} requests per ${rateLimitWindowInMs} ms.`);

    const definedRateLimit = rateLimit({
      windowMs: rateLimitWindowInMs,
      max: rateLimitMaxRequests,
      standardHeaders: true,
    });

    app.use(definedRateLimit);  

  } else {
    logger.warn('Rate limit is disabled!');
  }

  // Request handler for non-static requests.
  RequestHandler(app, mockedApiAuthenticationKey, mailHandler);

  if (apiAuthentication.enabled) {
    app.use(basicAuth({ challenge: true, users: apiAuthentication.users }));
  }

  // Static content.
  app.use(express.static(path.join(__dirname, '../../dist')));
  app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '../../dist', 'index.html'));
  });

  return app;
};

module.exports = {
  setupExpressApp,
};

This would have the effect of being able to enable basic auth for the static UI content and having only api key auth on the non-static requests.

If this is something you think would add value I'm more than happy to put up a PR for it.

janjaali commented 3 months ago

Yes, that sounds very reasonable and would be a great addition to this project. Just to confirm, we would end up in the following authentication support matrix:

Component No authentication Basic Auth API Key
UI x x
Backend x x
camerondearien commented 3 months ago

Yup! That would be what we would end up with!