If you haven't already, first read the previous post about Authentication.

At this point in our app, a user can sign up with their email and password and then log in with the same credentials. Their email may be widely known, but their password should (at least in theory) be a secret. There are two points where that secret can be exposed:

  • data in transit
  • data at rest

Data "in transit" refers to when the data is moving through our app, which usually occurs when it's submitted via a form. Data "at rest" refers to how it's stored in the database. This doesn't just apply to passwords: when dealing with any sensitive data in your application, you want to think about its exposure both in transit and at rest.

Data in transit

A password travels from the user's fingers to our database, and there are three places along the way where someone could see it.

Over the user's shoulder. Look at the password input in the sign-up and login forms (app/views/users/new.html.erb and app/views/sessions/new.html.erb):

<input type="password" name="password" id="password">

type="password" is why you see dots instead of what you typed. It's perhaps more prone to typos now since the user can't see what they're typing, but it's also more secure. Tradeoffs... always tradeoffs. Notice that's all it does: it hides the password from the person behind you, and nothing else.

On the wire. Between the browser and the server, the form's data crosses the internet. The lock icon in your browser's address bar means the connection is HTTPS: everything sent is encrypted on the way, and only the server can read it. Your Codespace already has it. When we deploy our own app, getting the certificate behind that lock is one of the steps.

In the server log. Log in, then look at the bottom of the server log (the terminal running bin/rails server, or log/development.log). You'll see the form's data:

Parameters: {"email" => "ben@example.com", "password" => "[FILTERED]"}

The server log is just a text file of all the application's activity. It's easily read by anyone with access to the server, and often it's also sent to an outside service for debugging. So Rails hides anything that looks like a password before it writes the line. The list of what it hides is in config/initializers/filter_parameter_logging.rb:

Rails.application.config.filter_parameters += [
  :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
]

:passw matches any param whose name contains "passw". If you ever have other data that you want to hide from the log (e.g. payment info), you add its name to this list and restart the server.

We're choosing not to hide the email address. Since it's personally identifiable information, it too may need to be protected. But when debugging, it can be helpful to search the logs for a user by their email. So this choice is a tradeoff, and you'll have to decide what's appropriate for your application.

One more: guessing. The login form answers "yes" or "no" as fast as anyone asks it, and an attacker with a list of common passwords can ask a million times. Real apps slow down after a few wrong answers - a wait, a lockout, a code by email. How many tries and how long a wait is a product call, and it's the cheapest defense you'll ever buy.

Data at rest

We've hidden password data from view in the server log and the browser, but the passwords are still stored in our users table in plain text. Take a look:

bin/rails runner scripts/show_data.rb User

And there, fully visible, are the users' passwords.

It might go without saying, but to be explicitly clear... Storing passwords as plain text in the database is BAD. It's almost inevitable that, at some point, your application will go through a security breach of some kind. You might get hacked, or a backup ends up on a lost laptop, or you rely on another library of code that has a security vulnerability. Try as hard as you can to avoid it, but there's no such thing as 100% secure software. So how you prepare for and respond to a security breach is critically important.

In the case of a breach that exposes your database, you want to be able to state that "yes, our database was compromised, but no sensitive information was accessible". The only way to be able to say so is to encrypt sensitive information (like passwords) so that even if it is accessed, it can never be read. In fact, the data should be encrypted in such a way that even you can't read it. Which also means: if a company can ever email you your password, they're storing it in a way they can read. Run.

Two-way and one-way

Data encryption comes in two common forms: two-way and one-way. In both, the process begins with an algorithm - a recipe - that turns the data into a new value. For example, a trivial encryption technique would be to replace every letter with the next letter in the alphabet. So "apple" becomes "bqqmf". This would be a terrible encryption technique, but it gives you an idea of what encrypting data entails. In practice, we use well-known, industry-approved algorithms that are near impossible to crack.

With two-way encryption, the goal is to secure some data so that only an intended recipient can decrypt it and read the original. Any observers in between only see the encrypted data, which is indecipherable. That's the lock icon: HTTPS is two-way.

With one-way encryption (also called hashing), the goal is to secure some data so that it can never be decrypted and read. Although it can never be read, it can be checked - you can prove you know the original by encrypting it again and seeing that the results match.

Take a moment to think about these two approaches. Which makes the most sense for passwords in the database?

We never need to read a password back. We only need to check that the person logging in knows it. If the database is ever exposed, we want to be able to honestly say that no passwords were accessible. We want one-way.

To play with both, and to see how two-way encryption with a public and a private key keeps the lock icon safe, try this interactive explainer.

bcrypt

In our application, we're going to use a one-way algorithm called bcrypt. It may seem counterintuitive to use a well-known, open-source tool for security, but that's exactly what we want. It's been tested and attacked by experts for decades, and the fact that it's public doesn't make it weaker. There are alternatives, but whichever you choose: unless you're a brilliant mathematician, never write your own.

Open the Gemfile. This is the list of the open-source libraries our application depends on, and they're installed when your Codespace is built (or when you run bundle install). bcrypt is already in it. If you're ever starting your own application from scratch, you'll add it here.

Now see it work. scripts/encryption.rb hashes the secret "puppies" twice, then checks some guesses against the hashes:

secret = "puppies"

first = BCrypt::Password.create(secret)
second = BCrypt::Password.create(secret)
puts first
puts second

puts BCrypt::Password.new(first) == "puppies"
puts BCrypt::Password.new(second) == "puppies"
puts BCrypt::Password.new(first) == "kittens"

Run it:

bin/rails runner scripts/encryption.rb

You get two long, unintelligible strings, then true, true, false. Look closely at the two strings: they're different, even though both came from "puppies". So how can "puppies" check out against both? Each hash has a random value mixed in, called a salt, and the salt is stored inside the hash itself. To check a guess, bcrypt reads the salt back out of the stored hash, hashes the guess with it, and compares. The hash is never decrypted, because it can't be.

The == there looks like a plain comparison, but it isn't: bcrypt is hashing the guess on the right before comparing. If this interests you, there are many more detailed explanations online. For our purposes, it's enough to know that the password can be safely stored, it can never be decrypted, and it can still be checked.

Hashing our passwords

Two edits: hash the password on its way in at sign-up, and check the hash at login.

Sign-up. In users#create (app/controllers/users_controller.rb), the password is assigned straight into its column:

user["password"] = params["password"]

Instead, put it through bcrypt first, exactly the way encryption.rb did with "puppies":

user["password"] = BCrypt::Password.create(params["password"])

Sign up as a new user, then look at the data again. Your new row's password is a long bcrypt string, starting with $2a$, and not what you typed. The password is no longer exposed, and since we used one-way encryption it can never be decrypted - even developers with access have no way of reading user passwords.

And this is the moment to notice: for one line, at the top of create, we do have the password as typed. We could email it to the user right there. We never do: after this line, it should never exist anywhere as typed again.

Login. Log out, then try logging in as the user you just made. It fails: sessions#create is still comparing what you typed with the password column, which is now a hash. Your password isn't "hockey" anymore as far as the database knows. It's $2a$12$.... Change the check to the same comparison encryption.rb made:

# 2. check the password
if user && BCrypt::Password.new(user["password"]) == params["password"]

BCrypt::Password.new reads the stored hash (salt included), and == hashes what was typed with that salt and compares. Log in as your new user again: it works. And a wrong password still fails.

If you fell behind, code-along-complete/2-at-rest/ has these two files finished.

The shortcut: has_secure_password

Every app with passwords does what we just did, so Rails has it built in. It lives in the model, because the model is where the rules for a user belong. Open app/models/user.rb and add one line:

class User < ApplicationRecord
  # Gives the model a password= method that hashes what it is given into the
  # password_digest column, and an authenticate(guess) method that checks a guess
  # against that hash. The plain password column is no longer written.
  has_secure_password
end

It's bcrypt underneath, the same two steps, with two differences:

  • The hash goes in a column called password_digest ("digest" is another word for the hashed value), not password. That's why our users table has that column: has_secure_password expects a column with exactly that name.

  • You don't call BCrypt::Password yourself. Sign-up becomes:

    # the password goes through the model, which hashes it (see app/models/user.rb)
    user.password = params["password"]
    

    This is the one place we don't use the user["column"] style, because password= isn't a column: it's the method has_secure_password gave the model. And login becomes:

    # 2. check the password
    if user && user.authenticate(params["password"])
    

This version, all three files, is in code-along-complete/2-at-rest-has-secure-password/. It's what most Rails apps use. Use one or the other, not both. Either way works; what matters is that you know what the shortcut does for you.

The users who were already here

Now log in as Ben (ben@example.com, tacos123).

If you did it the first way, with BCrypt::Password yourself, the page breaks:

BCrypt::Errors::InvalidHash
invalid hash

Ben's row was saved before any of this existed. His password is still "tacos123" as typed, and BCrypt::Password.new expects a bcrypt hash, so it gives up. (With has_secure_password, it fails more quietly: Ben's password_digest is empty, so there's nothing to check, and he just gets "Nope.") Brian is locked out too.

We made a good change to how we store data, and the rows that were already there didn't come with us. In this app, it's two users. In a real company, it's thousands, and they're your customers. That's known as technical debt.

A note on the future

HTTPS, the two-way encryption behind the lock icon, rests on math that a large enough quantum computer could undo. Traffic recorded today could be read years from now, which is why new standards are already rolling out. Password hashes hold up much better. And AI finds software bugs faster; it doesn't break the math. For you, as a manager, this is a patching and vendor question, not a rewrite.

Logged in?

Our basic authentication scheme is now complete - a user can sign up, we hash their secret password, and we check their credentials on login and respond appropriately. But how does the user stay logged in? Remember that HTTP is stateless - each request has no knowledge of the requests before it. So even when the credentials are right, the server would forget all about it as soon as the next request begins.

How does the app know, request after request, that a user is logged in? To answer that, we need to revisit browser state and learn about another browser tool: cookies (next post).