Firestore proxy with Nginx (Use firestore.yourdomain.com instead of firestore.googleapis.com)

We use firestore cloud db to show data to the users on our virtual web platform and mobile applications. After many events we have a problem where some of the users are behind a corporate firewall or they are connected to their companies VPN and the API endpoint https://firestore.googleapis.com somehow is blocked so they cannot use our system at all. Why a company would block *.googleapis.com? I have no idea, except maybe for China.

To overcome this, I’ve set up an Nginx proxy on an Amazon EC2 instance so that the web and mobile clients can send the firestore requests through our domain (firestore.yourdomain.com) instead of firestore.googleapis.com. Here’s the Nginx setup:

server {
    listen 80;

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

     location /index.html {
         try_files $uri $uri/ =404;
     }

     location / {
         resolver 172.0.0.53 ipv6=off;
         proxy_pass https://firestore.googleapis.com;
         proxy_http_version 1.1;
         proxy_connect_timeout 120s;
         proxy_read_timeout 300s;
         proxy_send_timeout 100s;
         proxy_set_header Cache-Control no-cache;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_cache_bypass $http_upgrade;
         proxy_buffering off;
    }
}

So this setup is behind an Amazon load balancer. That’s why it listens to port 80. The actual traffic from the client to the load balancer is secured and then mapped to port 80 of the EC2 instance. You cannot just proxy the TLS encypted traffic to https://firestore.googleapis.com from your domain, you will get an SSL error because the certificate is registered to *.googleapis.com.

Supposing your system is on Amazon:

  • You’ve set up a load balancer with your wildcard certificate (*.yourdomain.com).
  • You mapped firestore.yourdomain.com to your load balancer.
  • You’ve created an instance with the nginx config above.
  • Now you can initialize you js firestore library like this:
import * as app from "firebase/app";
import "firebase/firestore";
import "firebase/database";
import "firebase/storage";
import "firebase/analytics";

const config = {
  apiKey: "yourkey",
  authDomain: "yourdomain.firebaseapp.com",
  databaseURL: "https://yourdatabase.firebaseio.com",
  projectId: "yourprojectId",
  messagingSenderId: "messagingSenderId",
  appId: "yourAppId",
  measurementId: "youMeasurementId",
};

app.initializeApp(config);
app.analytics();

export const firebase = app;
export const db = app.firestore();
db.settings({
  "host": "firestore.yourdomain.com",
  "ssl": true
});

Now you just refresh you browser app and check your XHR requests. They will go through your server. Hope this will help someone as I’ve spent a lot of time finding the right setup.

Happy proxying.

Why Linux is more secure than Windows

I stumbled upon a question on Quora. The question is: How complicated is the code for Microsoft Windows? The person who answered it shared a link to another question: Why windows is less secure than linux? and shared two images. These images are one of the best examples of high complexity leading you to less security. So here is the linux call trace for apache on linux:

This might seem already complex, but wait until you see the call trace for Microsoft IIS on Windows:

The images describe it all. More complexity usually leads to more bugs and more bugs lead to more security problems. Let’s all hope Windows developers refactor Windows so it becomes more like Linux: simple.

Design Patterns

I always read about design patterns. I read and read again and again and again… But the feeling that I have to learn more or understand more never goes away. Every time I dive into a pattern I feel like I’m learning something new about it. So this post is about me trying to grasp design patterns better (again). I started writing this post while spending time around this book: Design Patterns: Elements of Reusable Object-Oriented Software. As the book goes on, I will copy and paste some parts of the book here, while adding my opinions or questions; if I have any. I believe this will strengthen my perception of design patterns and at the same time, it may help some others.

Now, I will try to describe what a design pattern is, with my own (english) words, as I understand it now, at this very moment. Then I will go to wikipedia and/or google and copy and paste the description here and see the difference. I’m hoping there won’t be a huge difference :). Here is my definition of a design pattern:

A design pattern is a method to meet a recurring requirement.

So this is what I came up with. Actually it took me a while. First I had to write it in turkish on paper. Then I had to fix the turkish version, then I had to translate it to english. That was the result. So now I’m googling it and here it is:

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design.

The context of this article is already software engineering and software design so this definition can be shortened to this:

design pattern is a general repeatable solution to a commonly occurring problem.

I think this sounds better than my definition. I especially like the “commonly occuring problem” part. It is much better than “recurring requirement”. I think I will change my definition after this to: “a method to meet a commonly occuring requirement.” Now the main difference is my “method” is their “general repeatable solution” and my “commonly occuring requirement” is their “commonly occuring problem”. A method vs a solution and requirement vs problem. This can be further discussed but both definitions are pretty close to each other in my opinion.

A much simpler definition can be found in the book:

[A design pattern] is a solution to a problem in a context.

Now that we know what a design pattern is, I will list the design patterns I encountered in the book I mentioned above. This part will be mostly copy/pasting the names and definitions. Here is an overview of 23 design patterns:

  • Abstract Factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. For a long time I didn’t know the difference between factory pattern and abstract factory pattern.
  • Adapter: Convert the interface of a class into another interface clients expect.
  • Bridge: Decouple an abstraction from its implementation so that the two can vary independently.
  • Builder: Separate the construction of a complex object from its representation so that the same construction process can create different representations. For example, libraries like doctrine use builder pattern to build sql queries.
  • Chain of Responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Thoughts: for example, this is how django middlewares work. It passes the request to the middleware objects one by one, they all handle it or one of them stops the handling process.
  • Command: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. What are undoable operations? I don’t really understand this definition.
  • Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • Decorator: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Decorator pattern is among the most popular ones, at least for me.
  • Facade: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
  • Factory Method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • Flyweight: Use sharing to support large numbers of fine-grained objects efficiently. I had a personal project once where I wanted to code a grid with java swing. I tried to create an object for each square in the grid and ended up with thousands of objects. It killed the process and it was very very slow rendering it. I’m not sure but this pattern may be the solution to that.
  • Interpreter: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. I’m curious about this one.
  • Iterator: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Mediator: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
  • Memento: Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
  • Observer: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In django framework, the signals are an example of the observer pattern.
  • Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Proxy: Provide a surrogate or placeholder for another object to control access to it.
  • Singleton: Ensure a class only has one instance, and provide a global point of access to it.
  • State: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. I used this one recently where we had 6 different login scenarios. I divided the strategies to 6 classes with an execute(…) method. I had to create the appropriate strategy object from http post data and call the execute method to log the user in.
  • Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  • Visitor: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

After listing them, there is one last thing to do with this list of design patterns: classifying them. There are three main categories: Behavioral, Structural and Creational.

Behavioral patterns describe how the objects communicate with each other and tell us the responsibilities of the objects. These patterns are: Interpreter, Template Method, Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Visitor.

Structural patterns deal with the composition of classes or objects. These patterns are: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.

Creational patterns deal with the process of object creation. These patterns are: Factory Method, Abstract Factory, Builder, Prototype, Singleton.

Even now I feel much better about design patterns. My next quest will be one post for each design pattern. For that, I will probably read the book and support it with some online materials and create a post with the combination of both.