Why My Rust Backend Is Not Allowed to Log In as postgres

A superuser skips row-level security, so a backend that logs in as postgres turns every RLS policy into decoration. How I split the database into three roles, why the password is a file and not an env var, and what the sqlx pool does with it.

Simone Negro, Backend & AI Developer
6 min read

Row-level security looks like the strongest guarantee a database can give you: the rows a user can’t see are filtered out by Postgres itself, whatever query the application sends. Then you read the small print. A superuser skips every policy, and so does the owner of the table. Connect your backend as postgres and all those policies are decoration.

This post is about the database side of the Rust backend I’m building: the three roles I use and why, how the user context reaches the policies through a connection pool, why the password is a file, and a quirk of Postgres settings I ran into while preparing the example. The examples run against a throwaway Postgres with a toy notes table, so the roles and tables here are not the ones I run, but every output is real.

Who sees what

The demo table has three notes, two belonging to user 1 and one to user 2, and a policy that only shows the notes of the current user:

ALTER TABLE notes ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_notes ON notes
  USING (owner_id = NULLIF(current_setting('app.user_id', true), '')::int);

Then the same query, with app.user_id set to 2, as different roles:

RoleRows returned
postgres (superuser)all 3
migrator (owner of the table)all 3
api (the application role)1, the one owned by user 2
api, with no user set0
migrator, after FORCE ROW LEVEL SECURITY1

The first two rows are the point of this post. The policy exists, it’s enabled, and two of the three roles walk straight past it.

Three roles, three jobs

So the database has three roles, and each one is used for exactly one thing:

RoleUsed forWhy it exists
superuserbootstrapping: creating the database and the other roles, oncesomething has to create everything else
ownermigrations, run as a separate step before the backend startsowns the tables, so it can change the schema
applicationeverything the backend does at runtimereads and writes data, and is subject to RLS

The backend only ever knows the third one. It can’t alter a table, it can’t drop a policy, and it can’t turn RLS off, because none of those are things its role is allowed to do.

The obvious shortcut is a single role with FORCE ROW LEVEL SECURITY on every table, which makes the owner obey the policies too. I didn’t take it for two reasons. It only works as long as nobody forgets FORCE on a new table, and forgetting is silent. And the owner can still change the schema, so a bug in the backend, or a compromised dependency, would hold the power to disable the very policies meant to contain it.

Refusing the superuser at startup

Because the application role is the one that matters, the backend’s config validation refuses to start when the configured user is postgres, before any connection is opened. It’s a check that should never fire. That’s the kind I want most.

Passing the user to the policies through a pool

The policy reads app.user_id, a custom setting, so the backend has to set it before each query. The trap is the connection pool. Connections are shared: the one serving this request served someone else’s a moment ago. A session-level SET app.user_id would stay on the connection and leak into the next request that picks it up.

So the setting is local to a transaction. set_config with true as the third argument is the function form of SET LOCAL, and it disappears at COMMIT or ROLLBACK:

async fn count_notes(pool: &PgPool, user_id: i32) -> Result<i64, Box<dyn Error>> {
    let mut tx = pool.begin().await?;
    // `true` = local to this transaction, like SET LOCAL.
    sqlx::query("SELECT set_config('app.user_id', $1, true)")
        .bind(user_id.to_string())
        .execute(&mut *tx)
        .await?;
    let (count,): (i64,) = sqlx::query_as("SELECT count(*) FROM notes")
        .fetch_one(&mut *tx)
        .await?;
    tx.commit().await?;
    Ok(count)
}
user 1 sees 2 notes
user 2 sees 1 notes
without a user: 0 notes

Where it bit me: a setting that comes back empty

My first version of the policy was current_setting('app.user_id', true)::int. The true means “don’t fail if the setting doesn’t exist, return NULL”, and NULL matches nothing, so no user meant no rows. It worked for the first query. Then a query without a user, on a connection that had already served one, failed:

error returned from database: invalid input syntax for type integer: ""

After a transaction that set it locally ends, the setting doesn’t go back to “missing”. On that connection it now exists, with an empty string as its value:

after the commit, value: []

So current_setting(..., true) returns '' instead of NULL, and ''::int is an error. Both behaviours fail closed, which is the part that matters: no context never means “all rows”. But they fail differently, and you should pick one on purpose:

  • Loud: current_setting('app.user_id') without the second argument. No user is always an error, whether the setting was never set or was emptied by a previous transaction.
  • Quiet: NULLIF(current_setting('app.user_id', true), '')::int, as in the demo. No user is always zero rows.

The password is a file, not an environment variable

The application role has a password, and it doesn’t live in the config file or in an environment variable. Environment variables leak in boring ways: child processes inherit them, inspection tools print them, crash reports include them. A file mounted read-only, the way Docker and most orchestrators mount secrets, only exists where it’s needed. The config only holds its path.

Reading it is short, but each line is a decision:

fn read_password_file(path: &Path) -> Result<String, Box<dyn Error>> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read secret {}: {e}", path.display()))?;
    // Only the trailing newline goes: spaces can be part of a password.
    let secret = content.trim_end_matches(['\n', '\r']);
    if secret.is_empty() {
        return Err(format!("secret file {} is empty", path.display()).into());
    }
    Ok(secret.to_string())
}

trim() would be shorter and wrong: it would also strip spaces that belong to the password. Editors and echo add a final newline, so that is all that goes. An empty file is an error, not an empty password. And the messages name the file, never what’s inside it.

One pool, created once, with the password inside

The password is read inside the function that builds the pool, so nothing else in the backend ever holds it:

async fn connect(port: u16, password_file: &Path) -> Result<PgPool, Box<dyn Error>> {
    let password = read_password_file(password_file)?;

    let options = PgConnectOptions::new()
        .host("127.0.0.1")
        .port(port)
        .username("api")
        .password(&password)
        .database("notes_app");

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(3))
        .connect_with(options)
        .await
        .map_err(|e| format!("cannot connect to the database: {e}"))?;

    Ok(pool)
}

acquire_timeout is how long anything waits for a free connection before giving up, and that includes startup. With the database down, the program waits exactly that long and stops:

cannot connect to the database: pool timed out while waiting for an open connection

I searched every error the demo printed for the password. It never appears. One honest limit: the pool keeps a copy of the password, because it needs it to open new connections. My code touches it in one place, which is the best I can do without crates like secrecy that wipe secrets from memory.

What this doesn’t protect

If the backend itself is compromised, the attacker has whatever the application role has: every row of every user, as long as they set app.user_id themselves. RLS limits what a bug can reach by accident. It doesn’t stop code that is actively working against it. And the policies are only as good as the context the backend sets: a request handler that sets the wrong user id gets the wrong user’s rows, with Postgres’s full blessing.

The role is the first security decision

The user your backend logs in with decides whether every other database-level protection applies. I used to think of it as a line in a config file. Now it’s the first thing I check in a new project, and the one check my config refuses to skip. What I’m still unsure about is how much logic belongs in the policies versus the backend. For now they hold the one rule that must never be wrong: whose rows these are.

Row-level security is one part of how I think about privacy in a backend. The other half is what goes into logs and what goes into an audit trail, which is the subject of my GDPR logging write-up.

References