nginx: Using auth_request to secure vhosts

One of our clients recently had a unique use case. They had a Wiki site where they wanted to restrict viewing of posts to only their app’s authorized users. Picture something like a SaaS app where the Wiki site had proprietary content that our client only wanted paying users to access.

The two obvious options to implement this would be:

  • Create a Wiki user for each authorized user - this has the downside that we’d need to maintain two accounts, figure out how to keep users logged into both, and deal with synchronizing account data.
  • Modify the Wiki’s application code to authorize the users in some fashion - this is problematic because it would make upgrading the Wiki software difficult.

Turns out there’s a third option which is much smoother! Nginx has a directive called auth_request which allows nginx to authorize access to a resource based on a 2nd HTTP request.

The way it works is:

  • Your SaaS app is setup at platform.setfive.com where users are authenticated by a Symfony application.
  • You configure your Symfony application to send a cookie back with a wildcard domain of “.setfive.com”
  • Your wiki is running at wiki.setfive.com and configured to authorize requests to platform.setfive.com/is-authenticated
  • Now, when users request wiki.setfive.com their browser will send your Symfony authentication cookie, nginx will make a request to platform.setfive.com/is-authenticated, and if they’re authenticated they’ll be granted access to your wiki.

The nginx config for this is pretty straightforward as well. One thing to note is this module is not standard so on Ubuntu you do need to install the nginx-extras package to enable it.

server {
    server_name wiki.setfive.com;

    listen 443 ssl;
    ssl_certificate /etc/httpd/ssl/setfive-ssl.chained.crt;
    ssl_certificate_key /etc/httpd/ssl/setfive-ssl.key;

    ssl_session_cache shared:le_nginx_SSL:1m;
    ssl_session_timeout 1440m;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";

    root /var/www/html/wiki;
    index index.php;

    auth_request /is-authenticated;

    location = /is-authenticated {
        internal;
        proxy_pass https://platform.setfive.com/is-authenticated;
        proxy_set_header Content-Length "";
     }

     location / {
        # This is cool because no php is touched for static content.
        # include the "?$args" part so non-default permalinks doesn't break when using query string
        try_files $uri $uri/ /index.php?$args;
     }

    location ~ \.php$ {
      fastcgi_pass   unix:/run/php-fpm/www.sock;
      fastcgi_split_path_info ^(.+\.php)(/.*)$;
      include fastcgi_params;
      fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
      # fastcgi_param  HTTPS              off;
    }

}

Spring Boot: Creating a filter to verify an API key header

Phew! Been awhile but we’re back!

NOTE: There’s a working Spring Boot application demonstrating this at https://github.com/Setfive/spring-demos

For many applications a security and authentication scheme centered around users makes sense since the focus of the application is logged in users taking some sort of action. Imagine a task tracking app, users “create tasks”, “complete tasks”, etc. For these use cases, Spring Boot’s Security system makes it easy to add application security which then provides a “User” model to the rest of the application. This allows your code to do things like “getUser()” in a Controller and have ready access to the currently authenticated user.

But what about applications that don’t have a user based model? Imagine something like an API which provides HTML to PDF conversions. There’s really no concept of “Users” but rather a need to authenticate that requests are coming from authorized partners via something like an API key. So from an application perspective you don’t really want to involve the user management system, there’s no passwords to verify, and obviously the simpler the better.

Turns out its very straightforward to accomplish this with a Spring managed Filter. Full code below:

package com.setfive.demo.apiheaderdemo.filter;
import com.setfive.demo.apiheaderdemo.entity.ApiKey;
import com.setfive.demo.apiheaderdemo.repository.ApiKeyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Component
public class ApiKeyRequestFilter extends GenericFilterBean {

    private static final Logger LOG = LoggerFactory.getLogger(ApiKeyRequestFilter.class);

    private ApiKeyRepository apiKeyRepository;

    public ApiKeyRequestFilter(ApiKeyRepository apiKeyRepository){
        this.apiKeyRepository = apiKeyRepository;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI();

        if(path.startsWith("/api") == false){
            chain.doFilter(request, response);
            return;
        }

        String key = req.getHeader("Key") == null ? "" : req.getHeader("Key");
        LOG.info("Trying key: " + key);

        Optional<ApiKey> apiKeyOptional = this.apiKeyRepository.findOneByKey(key);
        if(apiKeyOptional.isPresent()){
            chain.doFilter(request, response);
        }else{
            HttpServletResponse resp = (HttpServletResponse) response;
            String error = "Invalid API KEY";

            resp.reset();
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentLength(error .length());
            response.getWriter().write(error);
        }

    }

}

The code is pretty straightforward but a couple of highlights are:

  • It’s a Spring Component so that you can inject the repository that you need to check the database to see if the key is valid
  • It’s setup to only activate on URLs which start with “/api” so your other routes wont need to include the Key header
  • If the key is missing or invalid it correctly returns a 401 HTTP response code

That’s about it! As always questions and comments welcome!

What is HIPAA and Why Does it Matter?

The following article is the first part of a series on HIPAA and its impact on certain industries in the United States. This piece aims to define HIPAA, identify 2019 HIPAA regulations and violations, and explain HIPAA compliance. Hopefully, this read will be informational, and especially useful, if you are unfamiliar with HIPAA and it’s applicability. The importance of HIPAA (Health Insurance Portability and Accountability Act) has recently hit the U.S. headlines as a trending topic. Particularly, the impact of HIPAA in the healthcare space has circulated throughout the U.S. media. HIPAA compliance recently became a point of emphasis when the United States government made changes to the act, and its surrounding enforcement, in 2019. While HIPAA was enacted over 23 years ago, the significance of this act has evolved as western society has become increasingly involved with- and dependent upon- technology. When initially implemented, HIPAA served to protect personally identifiable information maintained by healthcare companies.

2019 HIPAA Regulations and Violations

In December 2018, the OCR (Office of Civil Rights) issued a request for information to HIPAA covered entities. The OCR was specifically focused on the current Privacy Rule to confirm that HIPAA was not prohibiting, nor discouraging, any patients from proper care. To instill safety and protection over access to patient’s rights and information, the OCR plans to increase enforcement around the Privacy Rule. The OCR is also optimistic that emphasis on HIPAA compliance will help to fight the opioid crisis in the United States. Additionally, the OCR is concerned with the number of email data breaches due to the major problem of phishing in the healthcare industry. If a company is caught in a violation of HIPAA, or fails to comply, they can be faced with serious fines and even incarceration. To ensure that this does not happen, there are a few fundamental precautions healthcare companies can take to warrant compliancy.

Maintaining HIPAA compliance

To guarantee HIPAA compliance, the first preventive measure every company must take is training their employees on HIPAA compliance. By educating an organization on the dangers of using PHI information for personal benefit, the chance of an accidental HIPAA violation can be greatly minimized. It is crucial for healthcare companies to implement policies around the hardware and electronic services that they share with their business associates. To do so, risk management assessments can be performed on security and storage measurements. A majority of recent HIPAA violations have stemmed from the way patient data is being stored, additionally, there are release forms patients must be provided to sign off on the disclose the use of their personal health information. Some practices failed to distribute updated release forms. By administering mandatory notices, and operating with patient consent, in writing, a large portion of ambiguity and uncertainty around HIPAA compliance can be waived.

Industries Impacted by HIPAA

Over the past twenty years, medical records have been transferred from paper to wireless systems, enhancing the need for IT software and applications. As the demand for IT systems to collect and store data grows, the risk of cyber-attacks presents itself. Since data in the health industry is stored on servers, and not in a cloud, IT providers, as well as mobile application companies, also become liable. Some effective practices to prevent data hacking and fraud include: audits, encryption, data breach notifications, and a recovery plan. In regards to software development, some necessary features to consider are: access control, authorization, and backup data.

HIPAA Enforcement

Last year was a record year for HIPAA enforcement. With total fines and settlements reaching over 28 million dollars, healthcare companies have a lot to think about. Ultimately, it is critical to be educated on HIPAA and how to maintain HIPAA compliance. Whether it is negligence, lack of information, or an unfortunate security hack, even companies in cohesion with the health industry can be liable for a HIPAA violation. Stay tuned for our next blog post as we delve into HIPAA in our local sector of Boston, MA.

15 minutes with Puppeteer

One of Setfive’s New Years Resolutions is to prioritize our internal marketing. In establishing online presence, an initial project included refreshing the @setfive Twitter following list. To do so, we built a list of target accounts that we wanted to follow and then started searching for tools to automate the following. After some research, it appeared the only existing tools were paid with weird, and “sketchy,” pricing models. So, we decided to look at using the Twitter API to implement this list ourselves.

As we started looking at the API, we learned you need to be approved by Twitter to use the API. In addition, you need to implement OAuth to get tokens for write actions on behalf of a user, like following an account. We were only planning to use this tool internally once, so we decided to avoid the API and just automate browser actions via Puppeteer. For the uninitiated, Puppeteer is a library that allows developers to programmatically control Google Chromium, which is Chrome’s open source cousin.

Puppeteer ships as a npm package, so getting started is really just a “npm install,” and you’re off to the races. The Puppeteer docs provide multiple examples, so, I was able to whip up what we needed in a handful of lines of code (see below). Overall, the experience was positive and I’d be happy to use Puppeteer again.

function followBot(params) {

    return new Promise(async (resolve, reject) => {
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();

        await page.goto('https://mobile.twitter.com/login');

        await page.waitFor('[name=\'session[username_or_email]\']');
        await page.$eval('[name=\'session[username_or_email]\']', (el, params) => el.value = params.username, params);
        await page.$eval('[name=\'session[password]\']', (el, params) => el.value = params.password, params);

        await page.$eval('[data-testid=\'LoginForm_Login_Button\'', el => el.click());
        await page.waitFor('main');

        const accounts = fs.readFileSync("targets.txt", "utf8").split("\n");

        for(const account of accounts){

            console.log("Following " + account);

            await page.goto('https://mobile.twitter.com/' + account);
            await page.waitFor('.css-18t94o4');

            await sleep(1000);

            await page.$$eval('div', (elements) => {
                return new Promise(async (resolve, reject) => {
                    elements.forEach(f => {
                        if (f.getAttribute("data-testid") && f.getAttribute("data-testid").indexOf("follow") > -1) {
                            f.click();
                        }
                    });

                    resolve(true);
                });
            });

            await sleep(5000);
        }

        resolve();
    });
}

So why would Puppeteer be interesting to your business?

In 2019 APIs are popular, many business provide access to data and actions through programatic means. However, not all of them do and that’s where Puppeteer provides an advantage. For example, many legacy insurance companies only provide quotes after you fill out a web form, which normally, you’d have to complete manually. If you automated that process with Puppeteer, you’d be able to process quotes at a much faster rate. 24 hours a day, and give yourself a competitive advantage against your competition.

JavaScript or TypeScript for Front End?

Have you ever tried anything other than JavaScript or Typescript for front end and what was the result?

I tried Scala.js a couple of years ago, before TypeScript was popular. The results were mixed, at best. My experience was not recent, but, if I recall correctly, my two biggest stumbling blocks were tooling support and interop with standard JavaScript libraries.

On the tooling side, the major challenge was that scala.js needs to be compiled via the JVM based Scala compiler in order to produce JavaScript. That made integrating with JavaScript build tools like Gulp or Grunt fairly difficult. On top of that, I was sort of stuck writing scala.js in Eclipse since it had the best Scala plugin support. What that meant is that I had to give up IntelliJ’s awesome web development capabilities.

Integrating with third party libraries is a struggle for all of the “compile to JavaScript” solutions. A few years back, scala.js had a pretty rough integration story. Scalajs still relies on typed “facades,” Write facade types for JavaScript APIs to for integration. The problem faced is that there is not “any” type of Scala where you can skirt needing actual type information. These two issues highlight how well TypeScript is implemented in regards to tooling and 3rd party library support. Today, (2019) I think it that TypeScript is really the only effective option for compiling to JavaScript.