Shannon's Software Engineering Blog

Magic Links



This is Part 2 of the Magic Link System Design Series.

  1. System Design
  2. Magic Links
  3. CSRF with Magic Links
  4. pprof & Load Testing
  5. pprof Analysis
  6. pprof Memory Optimizations
  7. pprof CPU

"Hey Shannon! Your previous post talks about Magic Links but there were no details at all about implementing them!"
- random reader

Hey, I hear you! In the previous post, I gave an example System Design writeup for XYZ Auth to implement Magic Links for the organisation. However, remember that System Design documents are living documents, and the previous post was just to highlight the structure of the document.

In this post we will build upon the System Design in the previous post with details on how Magic Links will be implemented. Specifically, we will create technical artifacts to be placed in the Tactical Design section of the System Design document.

Magic Links are a mechanism for users to access secure resources without needing to enter passwords.

Sequence Diagrams

The best way to explain how Magic Links work is to use Sequence Diagrams.

Sequence Diagram

The above sequence diagram shows the happy path of a Magic Link usage.

  1. Users enter their email in the Login page.
  2. The backend checks if the email exists in the database.
  3. If the email exists, generate an encrypted cookie detailing who the user is.
  4. Create a Magic Link with the encrypted cookie as a URL param.
  5. Send the Magic Link to the user's email address.
  6. User clicks the Magic Link, and upon success, gets redirected to the protected page.

One of the beautiful features of Magic Links is that they use Stateless Cookies. Stateless means that the backend does not need to verify if the content in the Cookie is valid or not; it simply trusts it. This greatly reduces the number of network calls to databases as shown in the sequence diagram above; there is only 1 database call at the beginning, and future visits to protected resources will simply succeed if the Cookie has not expired.

"But won't clients just mutate their Cookies to impersonate other people?"
- concerned reader

In order to prevent manipulation of the Cookie, the Cookie will be encrypted by the server during creation. Only the server has the private key, hence adversaries will not be able to mutate the Cookie to suit their needs. Referring to the System Architecture diagram in the previous post, these private encryption keys will be stored in Vercel's Key-Value stores, such that the backend will have access to them to decrypt / validate incoming requests and their respective Cookies.

Non-Functional Requirements

There are security pitfalls associated with Stateless Cookies, and these need to be captured in the Non-Functional Requirements of a System Design document.

Example Additional requirements:

Check out my new Go library for creating encrypted Cookies!
https://github.com/sh4nnongoh/ironsession