Skip to content

Database Security: Threat Model, Roles, RLS, Injection, Audit ​

"A SQL injection attack occurs when untrusted data (usually strings) becomes part of a query's SQL syntax, modifying the logic of the SQL request." — OWASP, SQL Injection Prevention Cheat Sheet

Summary: A database is attacked from four directions (the internet, your own application, your own staff, and copies of its files), and each direction has its own control: network and authentication, least privilege and bind parameters, audit, and encrypted, masked copies. Focus: Threat model and STRIDE, authentication (SCRAM, certificates, LDAP/Kerberos, IAM tokens, peer), pg_hba.conf, roles and grants, SECURITY DEFINER and search_path, RLS, every SQL injection class and its fix in Go and Laravel, TLS, secrets, pgAudit, masking, backups, hardening and incident response. Learning goal: Draw the threat model for your own database, give the application a role that cannot do more than its job, remove injection from your code paths, and prove afterwards who did what.

This page is the complete reference for securing a relational database you run or rent: who attacks it and how, every authentication method PostgreSQL and MySQL offer, how pg_hba.conf picks one, roles and least privilege down to columns, the search_path trojan horse, Row-Level Security as a second wall, all the SQL injection classes (classic, union, error-based, blind, second-order, identifier and ORDER BY, stored-procedure), TLS settings that actually authenticate the server, secrets with Vault and IAM tokens, audit logging with pgAudit and MySQL Enterprise Audit, masking for non-production, backup and network exposure, superuser and extension hygiene, monitoring, a compliance map and an incident-response runbook. It deliberately does not re-teach its neighbours: encryption at rest, column encryption and homomorphic encryption are in Encryption at Rest, in Transit & in Use; tenant isolation strategies (schema per tenant, database per tenant) are in Multi-Tenancy Strategies; backup mechanics are in Backup, PITR & Disaster Recovery; the generic CIA triad and STRIDE are in Security Foundations; and the general OWASP list is in OWASP Top 10.

Page map ​

If you are looking forGo to
The whole topic in three tablesEverything in one minute
Why a database needs its own security modelWhy database security exists
Who attacks a database, and STRIDE applied to itThreat model, STRIDE
SCRAM, md5, certificates, LDAP, Kerberos/GSSAPI, IAM, peerAuthentication
pg_hba.conf line order and its trapspg_hba.conf
Roles, groups, INHERIT, SET ROLE, MySQL rolesRoles
Schema, table, column grants, default privilegesLeast privilege
SECURITY DEFINER, search_path, CVE-2018-1058, viewsFunctions and search_path
RLS policies, FORCE, BYPASSRLS, tenant settingsRow-Level Security
Classic, blind, second-order, ORDER BY injectionSQL injection
sslmode=verify-full, TLS versions, rotationEncryption in transit
Vault dynamic credentials, IAM tokens, .envSecrets management
pgAudit classes, log_statement, MySQL auditAudit logging
Masking prod data for dev and testMasking and anonymization
Backups, network, superuser, extensionsOperational exposure
Every engine side by side, knobs and error codesPer-engine behaviour, Mechanics
Fixed code in Go and LaravelSolving the classic problems
Detection, breach runbook, PCI/GDPR/HIPAA/SOC 2Monitoring, Incident response, Compliance
A checklist to apply todayHardening checklist
Services, replicas, shardsIn architecture
Reproduce injection, RLS bypass and pgAuditLab

Everything in one minute ​

The four attackers and what stops each.

AttackerTypical path inWhat it gets without controlsControl that stops it
External attackerPort 5432/3306 open to the internet, weak or reused passwordEverything the login role can doPrivate network, listen_addresses, pg_hba.conf, SCRAM/certs/IAM, TLS
Compromised applicationSQL injection, remote code execution, leaked .envEverything the app's role can do, from inside the trusted networkLeast-privilege role, bind parameters, RLS, no DDL rights, egress limits
Insider (malicious or careless)Legitimate DBA, developer or support accessBulk reads, quiet edits, deleted tracesNamed accounts, separation of duties, pgAudit to an append-only store, break-glass
Thief of a copyBackup bucket, disk snapshot, dev database with prod dataAll data, offline, with unlimited timeEncrypted backups with separate keys, masked non-prod copies, access logs on storage

The layers, outside in.

LayerPostgreSQLMySQL 8.4Failure looks like
Networklisten_addresses, security groups, private subnetbind_address, security groupsDatabase reachable from the internet
Transportssl = on, hostssl, client sslmode=verify-fullrequire_secure_transport=ON, --ssl-mode=VERIFY_IDENTITYPassword or data sniffed; man-in-the-middle
Authenticationpg_hba.conf + scram-sha-256 / cert / ldap / gss / peercaching_sha2_password, X.509, LDAP (Enterprise), IAM on RDStrust lines, shared passwords, md5 hashes
AuthorizationRoles, GRANT, default privilegesAccounts 'user'@'host', roles, GRANTApp connects as owner or superuser
RowsRLS policiesNo native RLS (views, app filter)One tenant reads another's rows
QueryBind parameters, format('%I')Prepared statementsSQL injection
AuditpgAudit, log_connections, log_statementEnterprise Audit audit_log, general logNo evidence after a breach
CopiesEncrypted backups, masked clonesSameBreach through a backup or staging

The ten things to do first.

#Do this
1No database port on the internet: private subnet, security group allows the app tier only
2password_encryption = scram-sha-256, no trust, no md5, no password lines in pg_hba.conf
3Clients use sslmode=verify-full (PostgreSQL) or VERIFY_IDENTITY (MySQL)
4The application role owns nothing, has no CREATE, no superuser, no BYPASSRLS, only the DML it needs
5Every value is a bind parameter; every identifier comes from an allowlist
6RLS with FORCE ROW LEVEL SECURITY on tenant tables as the second wall
7Credentials from a secret manager (Vault dynamic roles, IAM tokens), rotated, never in git
8pgAudit (role, ddl, plus object audit on sensitive tables) shipped off the box
9Backups encrypted with a key the database admins cannot read; non-prod gets masked data
10Named human accounts, no shared postgres/root, superuser only via break-glass

Why database security exists ​

The application already has login, sessions and authorization checks, so why secure the database separately? Because the database is the place where all the data sits together, and it has its own front door. Anyone who reaches that door with a valid role does not pass through your application's checks at all. Application bugs (an injection, a missing WHERE tenant_id) also turn the application into an attacker with the application's database rights. Database security makes sure that each way in reaches only what it must.

Convenient defaultSecure setting
One postgres/root login shared by app, migrations and humansOne role per service and per human, each with only its grants
listen_addresses = '*', port open "for debugging"Private network, bastion or SSO proxy for humans
sslmode=prefer (libpq default), DB_SSLMODE=prefer (Laravel default)sslmode=verify-full with the CA pinned
Credentials in .env committed "just once"Short-lived credentials from Vault or IAM
Filters in application code onlyApplication filter + RLS + constraints
log_statement = 'all' "for audit"pgAudit with chosen classes, shipped to an append-only store
Prod snapshot restored into stagingMasked or synthetic data for every non-prod environment

The analogy we reuse on this page: a bank building. The fence and the street door are the network (listen_addresses, security groups). The guard who checks your ID at the door is authentication (pg_hba.conf, SCRAM, certificates). Your keycard opens only some floors and rooms: roles and GRANT. Inside the vault, each safe-deposit box opens only for its owner: Row-Level Security. The teller only accepts the bank's own printed form, never a note you wrote yourself: bind parameters instead of string-built SQL. The CCTV that the staff cannot switch off is the audit log. And the copies of the ledger sent to the archive are locked boxes with a different key: encrypted backups. A thief who goes around the building to the archive needs none of the other doors, which is why every layer matters.

Three common misunderstandings, up front ​

  1. "The database is in a private network, so it is safe." The most common attacker on a private database is your own compromised application, and it is already inside the network. Network isolation stops the first attacker in the table above, not the other three.
  2. "We use an ORM, so we cannot have SQL injection." ORMs bind values, but every raw escape hatch (DB::raw, whereRaw, orderByRaw, fmt.Sprintf into Query) and every dynamic column name is outside that protection. Laravel's own docs say it "cannot guarantee that any query using raw expressions is protected against SQL injection vulnerabilities."
  3. "RLS means the application no longer needs tenant checks." RLS is the second wall. Owners and superusers bypass it, a missing tenant setting can fail open if the policy is written carelessly, and referential checks skip it. Keep the application filter and add RLS behind it.

Where the practice comes from ​

SQL injection was catalogued by MITRE as CWE-89, "Improper Neutralization of Special Elements used in an SQL Command": "The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component." OWASP's cheat sheets turned the fix into a short rule: bind values, and use "fixed application-owned choices for dynamic table names, column names, sort order (ASC, DESC), etc." Microsoft's Security Development Lifecycle contributed the STRIDE threat categories, which this page applies to a database.

The engines moved their defaults over time, and the versions matter when you read old advice:

Year / versionChangeWhy it matters
PostgreSQL 10scram-sha-256 authentication addedmd5 hashes stolen from pg_authid can be replayed; SCRAM ones cannot
MySQL 8.0caching_sha2_password becomes the default pluginOld clients that only speak mysql_native_password fail to connect
2018 (all supported PostgreSQL)CVE-2018-1058: like-named objects in public hijack other users' queriesOrigin of today's search_path and "secure schema usage pattern" advice
PostgreSQL 14password_encryption default becomes scram-sha-256New passwords are SCRAM unless you change it
PostgreSQL 15public schema no longer grants CREATE to PUBLICUpgraded clusters keep the old, unsafe grant until you revoke it
MySQL 8.4mysql_native_password disabled by default"The mysql_native_password authentication plugin is deprecated as of MySQL 8.0.34, disabled by default in MySQL 8.4, and removed as of MySQL 9.0.0."
PostgreSQL 18–19MD5 password support deprecated with md5_password_warnings; OAuth authentication method; log_connections takes a list of aspectsPlan the md5 → SCRAM migration now

Two control catalogues are quoted in audits: the CIS PostgreSQL Benchmark (a configuration checklist per major version; CIS lists versions up to PostgreSQL 18 as of this writing, the content itself is member-only, so this page does not attribute items to it) and NIST SP 800-53 family AU (Audit and Accountability): AU-2 Event Logging, AU-3 Content of Audit Records, AU-9 Protection of Audit Information, AU-11 Audit Record Retention, AU-12 Audit Record Generation.

Threat model ​

Databaseroles, RLS, data,WAL, logs, keysExternal attackerinternet scan, stolen credsCompromised appSQL injection, RCE, SSRFInsiderDBA, developer, supportStolen backup / diskS3 bucket, snapshot, laptopprivate network, TLSpg_hba, SCRAM / IAM / certleast-privilege role, RLSbind parameters, no DDLnamed accounts, break-glasspgAudit to off-host storeencrypted backups, KMSmasked non-prod copiesattacker (red) -> control that must stop it (amber) -> asset

The four attackers Must-know ​

In plain words: before choosing controls, write down who might attack the database and how they would get in. Each attacker needs a different lock.

Common misunderstanding: "Our threat is hackers on the internet." The other three are at least as likely and harder to see: an application turned against its own database by injection, a staff account used beyond its purpose, and a backup or snapshot left readable.

Definition: a threat model lists assets (data, credentials, keys, logs), entry points (network listener, application connection, admin access, copies), attackers and their capabilities, and the control that stops each path. For a database the assets are the rows, the role passwords or certificates, the WAL and backups, the audit logs, and any keys that decrypt columns.

text
     Attacker                      Path                                   What they hold afterwards
1    External attacker             scan 0.0.0.0/0:5432 -> try postgres/postgres   a login, if a weak password or trust line exists
2    Compromised application       ?q=x' UNION SELECT email,password_hash FROM users--   the app role's rights, from inside the VPC
3    Insider                       psql as shared "postgres" -> COPY customers TO '/tmp/c.csv'   everything, with no named trace
4    Thief of a copy               s3://backups/prod-2026-11-24.dump left public    the whole database, offline

Real scenarios: a staging database restored from production and exposed with a default password; an analytics read replica with listen_addresses = '*' for a BI tool; a support engineer's laptop with a CSV export; a CI pipeline that prints DATABASE_URL in logs; a Laravel app connecting as root so that one injection can DROP DATABASE.

AttackerCapability assumedPrimary controlDetection
ExternalNetwork reach, password guessing, known CVEsPrivate network, SCRAM/cert/IAM, patchingFailed-auth spikes in logs (28P01, MySQL 1045)
Compromised appRuns arbitrary SQL as the app roleLeast privilege, RLS, bind parameters, no file/program privilegespgAudit READ on sensitive tables, query anomalies, error-rate spikes (42501, syntax errors)
InsiderValid admin accessNamed accounts, separation of duties, break-glass superuserpgAudit ROLE/DDL, alerts on COPY ... TO, off-box logs
Copy thiefOffline access to filesBackup encryption with separate keys, masking for non-prodStorage access logs, bucket policies

STRIDE applied to a database Important ​

In plain words: STRIDE is a checklist of six ways things go wrong. Walk each one against the database and write the concrete threat and control.

Common misunderstanding: "STRIDE is for drawing diagrams of web apps." It applies to any component with an interface and data; the database has both.

Definition: Microsoft's threat-modelling tool defines the six categories; for Tampering it says: "Involves the malicious modification of data. Examples include unauthorized changes made to persistent data, such as that held in a database, and the alteration of data as it flows between two computers over an open network, such as the Internet".

STRIDEDatabase threatControlPostgreSQL / MySQL knob
SpoofingLogging in as another role; a fake server collecting passwordsStrong auth, server certificate verificationscram-sha-256, cert, sslmode=verify-full; caching_sha2_password, VERIFY_IDENTITY
TamperingChanging rows through injection or an over-privileged role; editing data in transitLeast privilege, bind parameters, TLS, constraintsGRANT only DML needed, hostssl, require_secure_transport
Repudiation"I never ran that DELETE" with a shared loginNamed accounts, audit trail off the boxpgAudit, log_line_prefix with %u %d, MySQL audit_log
Information DisclosureReading other tenants' rows, columns with PII, backups, error messagesRLS, column grants, masking, encrypted backups, generic errorsCREATE POLICY, GRANT SELECT (col), PostgreSQL Anonymizer, MySQL Enterprise Data Masking
Denial of ServiceExpensive queries, connection exhaustion, lock-holding transactionsTimeouts, connection limits, poolingstatement_timeout, CONNECTION LIMIT per role, max_user_connections (MySQL)
Elevation of PrivilegeSECURITY DEFINER + search_path hijack, COPY ... PROGRAM, untrusted extensionSecure search_path, no superuser for apps, vetted extensionsSET search_path = ..., pg_temp, revoke CREATE on public, pg_execute_server_program only for DBAs

Authentication ​

Clientapp / psqlNetwork + TLSlisten_addressessslmode=verify-fullpg_hba.conffirst matching linetype, db, user, addrAuthenticatescram-sha-256, certldap, gss, peer, IAMRole+ inherited rolesGRANT checkschema USAGE,table / columnRLS policiesUSING filters rowsWITH CHECK on writeRowsonly the allowed onesno match / reject: 28000denied: 42501Connection time (once per session)Query time (every statement)Superuser and BYPASSRLS skip the RLS box; the table owner skips it unless FORCE ROW LEVEL SECURITY.

Authentication methods Must-know ​

In plain words: authentication answers "who is this connection?". PostgreSQL can check a password, a client certificate, an operating-system user, or ask an outside system (LDAP, Kerberos, OAuth, AWS IAM).

Common misunderstanding: "A password is a password." md5 and scram-sha-256 both ask for a password, but a stolen md5 hash is enough to log in to PostgreSQL's md5 method, while a stolen SCRAM verifier is not. And password sends it in clear text.

Definition: the PostgreSQL manual lists trust, password (scram-sha-256, md5, password), GSSAPI, SSPI, ident, peer, LDAP, certificate, PAM, BSD and OAuth. On SCRAM it says: "This is the most secure of the currently provided methods, but it is not supported by older client libraries." On md5: "Support for MD5-encrypted passwords is deprecated and will be removed in a future release of PostgreSQL."

MethodPostgreSQLMySQL 8.4Use it forWatch out
Trusttrust(none; --skip-grant-tables is the equivalent disaster)Nothing in production"allows anyone that can connect … to login as any PostgreSQL user they wish"
Clear passwordpasswordmysql_clear_password (LDAP/PAM)Only inside TLSReadable on the wire without TLS
MD5 challengemd5 (deprecated)mysql_native_password (disabled in 8.4, removed in 9.0)Legacy onlyHash is a password-equivalent
SCRAM / SHA-2scram-sha-256caching_sha2_password (default)Default for apps and humansOld drivers; MySQL needs TLS or RSA key exchange
Client certificatecert, or clientcert=verify-full on any hostssl lineREQUIRE X509 / REQUIRE SUBJECTServices, mTLS meshesRotation and revocation (CRL) are your job
LDAPldap (simple bind or search+bind)LDAP plugins (Enterprise)Humans with corporate accountsPassword passes to the server; use TLS (ldaps/ldaptls)
Kerberos / GSSAPI / ADgss (also hostgssenc encryption), sspiauthentication_kerberos (Enterprise)Single sign-on in AD shopsKeytab handling, clock skew
OS userpeer (local socket), identauth_socketLocal admin on the database hostOnly for the local socket
Cloud IAM tokenAmazon RDS/Aurora IAM DB auth (rds_iam role), Azure Entra ID, Google Cloud SQL IAMSame, via plugins on each cloudServices without stored passwordsToken lifetime, connection rate
OAuth 2.0oauth (PostgreSQL 18+)(none built in)SSO for humans and toolsBearer token in clear text without TLS
text
     SCRAM-SHA-256 exchange (RFC 7677), PostgreSQL
1    client -> server   username, client nonce
2    server -> client   salt, iteration count, combined nonce   (from pg_authid verifier)
3    client             derives SaltedPassword, ClientProof = ClientKey XOR ClientSignature
4    client -> server   ClientProof
5    server             verifies proof against StoredKey; never sees the password
6    server -> client   ServerSignature  -> client verifies the server also knew the verifier
     -- a stolen verifier does not let an attacker compute ClientProof; an md5 hash does

Real scenarios: migrating a 2015-era cluster where pg_authid.rolpassword still starts with md5; a Laravel app on PHP 8.3 with a modern pdo_pgsql that handles SCRAM fine; a Java 8 app with an old JDBC driver that cannot, forcing a driver upgrade first; an AWS RDS service using IAM tokens so no password exists to leak.

Fix: migrate md5 to SCRAM (PostgreSQL)

sql
-- 1. Find roles whose stored password is still md5
SELECT rolname FROM pg_authid WHERE rolpassword LIKE 'md5%';

-- 2. Make new passwords SCRAM (default since PostgreSQL 14)
ALTER SYSTEM SET password_encryption = 'scram-sha-256';
SELECT pg_reload_conf();

-- 3. Reset each password (psql's \password hashes client-side)
\password shop_app

-- 4. In pg_hba.conf, replace md5 with scram-sha-256, then reload
SELECT pg_reload_conf();
sql
-- MySQL 8.4: move an account off mysql_native_password
ALTER USER 'shop_app'@'10.0.%' IDENTIFIED WITH caching_sha2_password BY 'new-long-random';
SELECT user, host, plugin FROM mysql.user WHERE plugin = 'mysql_native_password';

IAM database tokens and certificates Important ​

In plain words: instead of a password that lives forever, the service asks the cloud for a short-lived token (or presents a certificate) and uses that to log in.

Common misunderstanding: "IAM auth means the whole session is controlled by IAM." AWS says "The token is only used for authentication and doesn't affect the session after it is established." Revoking the IAM permission does not kill open connections.

Definition: Amazon RDS IAM database authentication generates a token with AWS Signature Version 4; "Each token has a lifetime of 15 minutes." The database role is created normally and granted rds_iam (PostgreSQL) or created IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS' (MySQL). AWS also notes that CloudWatch and CloudTrail do not log IAM database authentication, so database-side connection logging remains your evidence.

go
// Go: build an RDS IAM token per new connection (aws-sdk-go-v2 rds/auth).
// pgx calls BeforeConnect for every physical connection, so tokens never expire mid-pool.
cfg.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
	tok, err := auth.BuildAuthToken(ctx, endpoint, region, "shop_app", awsCreds)
	if err != nil {
		return err
	}
	cc.Password = tok
	return nil
}

Certificate authentication pairs naturally with service meshes and internal PKI: hostssl all shop_app 10.0.0.0/16 cert matches the certificate's CN to the role, and clientname=DN plus a user-name map allows full distinguished names.

pg_hba.conf: the first matching line wins Must-know ​

In plain words: pg_hba.conf is a list of rules read top to bottom. The first rule that matches the connection decides how it must authenticate, and if that fails, nothing else is tried.

Common misunderstanding: "If SCRAM fails, PostgreSQL falls back to the next line." It does not:

"The first record with a matching connection type, client address, requested database, and user name is used to perform authentication. There is no “fall-through” or “backup”: if one record is chosen and the authentication fails, subsequent records are not considered. If no record matches, access is denied." — PostgreSQL documentation, The pg_hba.conf File

Definition: each line is type database user address method [options]. Types: local (Unix socket), host (TCP, TLS or not), hostssl (TCP with TLS only), hostnossl, hostgssenc, hostnogssenc. database and user accept all, sameuser, samerole, +group, @file and regular expressions starting with /. address accepts CIDR, samehost, samenet, all. Changes take effect on pg_reload_conf(); the view pg_hba_file_rules shows how the server parsed each line, including errors.

text
     pg_hba.conf (top to bottom)                                    connection: user=shop_app from 10.0.3.7 over TLS
1    local   all       postgres                    peer            -- not local: skip
2    host    all       all        10.0.0.0/8       md5             -- MATCHES first: md5 chosen
3    hostssl shop      shop_app   10.0.3.0/24      scram-sha-256   -- never reached
4    host    all       all        0.0.0.0/0        reject
     -- line 2 was meant as "legacy", but it shadows the stricter line 3 for every 10.x client
PitfallWhy it hurtsFix
Broad line above a narrow oneThe broad line wins; the strict line is deadNarrow, specific lines first; reject lines before broad allows
trust for 127.0.0.1Anything on the host (a compromised app container sharing the network namespace, an SSH tunnel) is any rolepeer on the socket, scram-sha-256 on TCP
host instead of hostsslSame line accepts plaintext TCPhostssl for every remote line; add hostnossl all all 0.0.0.0/0 reject
0.0.0.0/0 allow linesCombined with listen_addresses='*' the world can try passwordsOnly app subnets; network ACLs as the outer wall
all all for replicationreplication is a special database keyword; all does not match itExplicit host replication replicator 10.0.5.0/24 scram-sha-256
Edits never reloaded or reloaded with a typoOld rules keep applying; a parse error on reload keeps the old fileCheck SELECT * FROM pg_hba_file_rules WHERE error IS NOT NULL; before reload
text
# A hardened pg_hba.conf for an application cluster
# TYPE     DATABASE      USER          ADDRESS          METHOD
local      all           postgres                       peer
hostnossl  all           all           0.0.0.0/0        reject
hostnossl  all           all           ::/0             reject
hostssl    shop          shop_app      10.0.3.0/24      scram-sha-256
hostssl    shop          +dba          10.0.9.10/32     cert   clientname=DN map=dba
hostssl    replication   replicator    10.0.5.0/24      scram-sha-256
host       all           all           0.0.0.0/0        reject

The connection error for a missing line is SQLSTATE 28000 with no pg_hba.conf entry for host "…", user "…", database "…", no encryption; a wrong password is 28P01 with password authentication failed for user "…". MySQL's equivalent is error 1045 (ER_ACCESS_DENIED_ERROR, SQLSTATE 28000): Access denied for user '%s'@'%s' (using password: %s). MySQL has no pg_hba.conf; the host part of 'user'@'host' plays that role.

Authorization: roles and least privilege ​

Roles, groups and inheritance Must-know ​

In plain words: a role is a name that can hold privileges. A role that can log in is a "user"; a role that only collects privileges for others is a "group". Members can use a group's privileges automatically (inherit) or by switching to it (SET ROLE).

Common misunderstanding: "CREATEROLE is harmless." In PostgreSQL 16+ it is narrower than before, but it still lets a role create and manage other roles; treat it as an admin privilege. And superuser is not a role attribute to hand out: "A database superuser bypasses all permission checks, except the right to log in. This is a dangerous privilege and should not be used carelessly".

Definition: PostgreSQL roles have attributes (LOGIN, SUPERUSER, CREATEDB, CREATEROLE, REPLICATION, BYPASSRLS, INHERIT/NOINHERIT, CONNECTION LIMIT, VALID UNTIL) and memberships. Since PostgreSQL 16 each membership grant carries INHERIT and SET options (GRANT admin TO joe WITH INHERIT TRUE, SET FALSE). Predefined roles give narrow powers without superuser: pg_read_all_data, pg_write_all_data (neither bypasses RLS), pg_monitor, pg_signal_backend, pg_maintain, pg_read_server_files, pg_write_server_files, pg_execute_server_program. MySQL 8.4 has roles too (CREATE ROLE, GRANT role TO user, SET DEFAULT ROLE, mandatory_roles, activate_all_roles_on_login); accounts are 'user'@'host' pairs.

sql
-- PostgreSQL: one owner, one app role, one read-only role, humans via groups
CREATE ROLE shop_owner NOLOGIN;                         -- owns schema and tables; nobody logs in as it
CREATE ROLE shop_rw NOLOGIN;                            -- group: DML on app tables
CREATE ROLE shop_ro NOLOGIN;                            -- group: SELECT only
CREATE ROLE shop_app LOGIN PASSWORD 'from-vault' CONNECTION LIMIT 200 IN ROLE shop_rw;
CREATE ROLE alice LOGIN IN ROLE shop_ro;                -- human, read-only by default
CREATE ROLE dba NOLOGIN;  GRANT dba TO alice WITH INHERIT FALSE, SET TRUE;  -- must SET ROLE dba explicitly
sql
-- MySQL 8.4
CREATE ROLE 'shop_rw', 'shop_ro';
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shop_rw';
GRANT SELECT ON shop.* TO 'shop_ro';
CREATE USER 'shop_app'@'10.0.3.%' IDENTIFIED WITH caching_sha2_password BY '…' REQUIRE SSL;
GRANT 'shop_rw' TO 'shop_app'@'10.0.3.%';
SET DEFAULT ROLE 'shop_rw' TO 'shop_app'@'10.0.3.%';    -- roles are inactive at login unless default

Real scenarios: an on-call engineer who normally reads but can SET ROLE dba during an incident, which pgAudit records as MISC_SET; a reporting tool given pg_read_all_data that unexpectedly sees nothing on RLS tables (correct: it does not bypass RLS); a MySQL user who gets "command denied" because the role was granted but never activated.

Least privilege: schema, table, column, default privileges Must-know ​

In plain words: give each role the smallest set of rights that lets it do its job, and nothing that would help an attacker who takes it over.

Common misunderstanding: "The app needs to own its tables to run migrations." Migrations run as a separate, short-lived owner role from CI; the running app needs only DML. The OWASP Database Security cheat sheet: "The account should not be the owner of the database as this can lead to privilege escalation vulnerabilities."

Definition: PostgreSQL checks privileges per object: CONNECT on the database, USAGE (and CREATE) on the schema, SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/MAINTAIN on tables, per-column SELECT/INSERT/UPDATE/REFERENCES, USAGE on sequences, EXECUTE on functions. Some objects grant to PUBLIC by default: CONNECT and TEMPORARY on databases, EXECUTE on functions, USAGE on languages and types. ALTER DEFAULT PRIVILEGES sets the grants for objects that a given role creates in the future.

sql
-- Lock the doors that are open by default
REVOKE ALL ON DATABASE shop FROM PUBLIC;
GRANT CONNECT ON DATABASE shop TO shop_rw, shop_ro;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;              -- needed on clusters upgraded from <= 14
CREATE SCHEMA app AUTHORIZATION shop_owner;
GRANT USAGE ON SCHEMA app TO shop_rw, shop_ro;

-- Table and column grants
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA app TO shop_rw;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA app TO shop_rw;
REVOKE SELECT ON app.customers FROM shop_ro;
GRANT SELECT (id, name, country, created_at) ON app.customers TO shop_ro;   -- no email, phone, national_id

-- Future tables created by the migration owner get the same grants
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT ON TABLES TO shop_ro;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;

-- Inspect
SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_name = 'customers';
SELECT has_column_privilege('shop_ro', 'app.customers', 'email', 'SELECT');   -- false
NeedGrantDo not grant
Web appUSAGE on schema, DML on its tables, USAGE on sequencesOwnership, CREATE, TRUNCATE, REFERENCES, superuser, BYPASSRLS
Migrations (CI)Owner role via SET ROLE shop_owner, short-lived credentialsSuperuser (unless an extension truly needs it)
Read-only analyticsSELECT on views or columns without PIIpg_read_all_data on clusters with PII outside RLS
Monitoring agentpg_monitorSuperuser "because the exporter asked for it"
Support staffSELECT on a masked viewBase tables
Backupspg_read_all_data or a dedicated owner, plus REPLICATION for physicalInteractive login

The MySQL errors for missing grants are 1142 (ER_TABLEACCESS_DENIED_ERROR: %s command denied to user '%s'@'%s' for table '%s') and 1227 (ER_SPECIFIC_ACCESS_DENIED_ERROR); PostgreSQL raises SQLSTATE 42501 permission denied for table ….

SECURITY DEFINER, SECURITY INVOKER and search_path hijacking Must-know ​

In plain words: a SECURITY DEFINER function runs with its owner's rights, like a setuid program. If it looks up names through a search_path that an attacker can write to, the attacker can plant a table or function with the same name and make the privileged code use it.

Common misunderstanding: "Only superusers can exploit this." Any role that can create objects in a schema on the victim's search_path (historically public, and always the session's own pg_temp) can set the trap; the victim's privileges do the damage.

Definition: the manual: "Because a SECURITY DEFINER function is executed with the privileges of the user that owns it, care is needed to ensure that the function cannot be misused. For security, search_path should be set to exclude any schemas writable by untrusted users." The temporary schema "is searched first by default, and is normally writable by anyone", so write pg_temp last. SECURITY INVOKER (the default) runs with the caller's rights. CVE-2018-1058 named the general attack: "a malicious user could insert a trojan-horse function that, when executed by a superuser, grants escalated privileges to the malicious user."

text
     Attacker (role mallory, can CREATE in public)       Victim (role dba, superuser)
1    CREATE FUNCTION public.lower(varchar) RETURNS text
       AS $$ ALTER ROLE mallory SUPERUSER; SELECT ...$$
       LANGUAGE sql;      -- exact-type match beats pg_catalog.lower(text)
2                                                        -- default search_path: "$user", public
                                                         -- (pg_catalog is searched first, but varchar is an exact match)
3                                                        SELECT * FROM users WHERE lower(email) = 'x';
4                                                        -- runs mallory's lower() as superuser
5    mallory is now SUPERUSER

Real scenarios: a SECURITY DEFINER function check_password() that reads pwds and is fooled by a temp table named pwds; an extension script installed into a schema where application users can create objects; a maintenance cron that runs as superuser with the default search_path in an upgraded cluster.

Fix:

sql
CREATE FUNCTION app.transfer(from_id bigint, to_id bigint, amount bigint)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = app, pg_temp                 -- trusted schema(s), then pg_temp last
AS $$
BEGIN
  UPDATE app.accounts SET balance = balance - amount WHERE id = from_id AND balance >= amount;
  IF NOT FOUND THEN RAISE EXCEPTION 'insufficient funds'; END IF;
  UPDATE app.accounts SET balance = balance + amount WHERE id = to_id;
END $$;
REVOKE ALL ON FUNCTION app.transfer(bigint, bigint, bigint) FROM PUBLIC;   -- functions are EXECUTE to PUBLIC by default
GRANT EXECUTE ON FUNCTION app.transfer(bigint, bigint, bigint) TO shop_rw;

-- Session-level protection for admin scripts
SET search_path = pg_catalog, pg_temp;         -- or schema-qualify everything

Views are the same question. A view runs its base-table access with the view owner's rights by default, and applies the owner's RLS policies; PostgreSQL 15+ WITH (security_invoker = true) makes it use the caller's privileges and policies. WITH (security_barrier) stops a caller's leaky function in the WHERE from seeing rows the view would hide. Use security_invoker on any view that sits over an RLS table.

Row-Level Security Must-know ​

In plain words: RLS makes the database itself add "and this row belongs to you" to every query on a table, so a query that forgets the tenant filter still returns only the caller's rows.

Common misunderstanding: "Enabling RLS protects the table." With no policies, RLS denies everything to normal roles, but the table owner, superusers and BYPASSRLS roles still see every row. If your app connects as the owner, enabling RLS changes nothing unless you also FORCE it.

"If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified." — PostgreSQL documentation, Row Security Policies

Definition: ALTER TABLE … ENABLE ROW LEVEL SECURITY turns it on; CREATE POLICY name ON table [AS PERMISSIVE|RESTRICTIVE] [FOR ALL|SELECT|INSERT|UPDATE|DELETE] [TO role] USING (expr) WITH CHECK (expr). USING filters rows the command can see or target; WITH CHECK validates new rows from INSERT/UPDATE. Permissive policies combine with OR, restrictive ones with AND, and "there needs to be at least one permissive policy". "Superusers and roles with the BYPASSRLS attribute always bypass the row security system when accessing a table. Table owners normally bypass row security as well, though a table owner can choose to be subject to row security with ALTER TABLE ... FORCE ROW LEVEL SECURITY." Referential integrity checks "always bypass row security", which can leak existence through unique or foreign-key errors. row_security = off makes a query error out instead of being filtered, which pg_dump uses so a backup never silently misses rows.

sql
ALTER TABLE app.invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE app.invoices FORCE ROW LEVEL SECURITY;           -- owner is filtered too

CREATE POLICY tenant_isolation ON app.invoices
  USING      (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint);

-- Defence in depth: a restrictive policy that also requires the app role
CREATE POLICY only_app_role ON app.invoices AS RESTRICTIVE
  USING (current_user IN ('shop_app', 'shop_owner'));

current_setting('app.tenant_id', true) returns NULL when the setting was never set in the session, so the comparison is NULL and no row passes (fail closed). After a transaction-local set_config(…, true) ends, the setting reads back as the empty string, and ''::bigint raises an error; NULLIF(…, '') keeps the fail-closed behaviour.

text
     Request A (tenant 7) on pooled conn #3              Request B (tenant 9) on the same conn #3 later
1    BEGIN;
2    SELECT set_config('app.tenant_id', '7', true);     -- transaction-local
3    SELECT * FROM invoices;   -- tenant 7 rows only
4    COMMIT;                   -- setting disappears
5                                                        BEGIN;   -- forgot to set tenant (bug)
6                                                        SELECT * FROM invoices;   -- NULL tenant -> 0 rows, not tenant 7's
     -- with set_config(..., false) (session-level) step 6 would show tenant 7's invoices
RLS bypass pathWhoFix
Table ownerApp connects as shop_ownerFORCE ROW LEVEL SECURITY; better, app never owns tables
Superuser / BYPASSRLSAdmin tools, backup roles, "temporary" grantsNo superuser for apps; audit BYPASSRLS grants (SELECT rolname FROM pg_roles WHERE rolbypassrls)
Default viewView owned by the table ownersecurity_invoker = true on views over RLS tables
SECURITY DEFINER functionOwned by the table ownerFilter inside the function, or make it SECURITY INVOKER
Session-level tenant setting with poolingPgBouncer transaction mode, Laravel OctaneTransaction-local set_config(…, true) per request
Tenant value from the clientX-Tenant-ID trusted as-isDerive tenant from the authenticated identity on the server
Referential checksUnique/foreign keys reveal existenceInclude tenant_id in unique keys; generic error messages

Per engine: PostgreSQL RLS as above. SQL Server has Row-Level Security with security predicates (filter and block). Oracle has Virtual Private Database (DBMS_RLS). MySQL and MariaDB have no row-level policies; use views with SQL SECURITY DEFINER plus a WHERE on a session variable, or enforce in the application. CockroachDB documents row-level security from v25.2; MongoDB has no row-level policies in the server (Atlas Data API rules and field-level redaction via $redact exist). How RLS fits the tenancy choices is on Multi-Tenancy Strategies.

SQL injection ​

Concatenation: input becomes codeBind parameters: input stays datainput q =x' OR '1'='1"... WHERE name = '" + q + "'"WHERE name = 'x' OR '1'='1'parser sees ORevery row returnedEscaping alone does not fix: second-order input, ORDER BY / table names, LIKE wildcards,dynamic SQL in functions (EXECUTE), raw ORM fragments: each needs its own rule.same input qsent separatelyParse: SELECT ... WHERE name = $1text fixed before values existBind: $1 = the whole stringExecute: comparezero rows matchIdentifiers (ORDER BY columns, table names) cannot be $n parameters:map them through an allowlist, then quote with format('%I') or pgx.Identifier.

What injection is, and why bind parameters stop it Must-know ​

In plain words: if you build SQL by gluing user input into the text, the input can contain SQL. Bind parameters send the text and the values separately, so the database parses the text before any value exists and the value can never become code.

Common misunderstanding: "Escaping quotes is enough." Escaping depends on the connection's character set, standard_conforming_strings, the context (string, number, identifier, LIKE pattern) and on every developer remembering. OWASP calls manual escaping "STRONGLY DISCOURAGED". Bind parameters remove the problem instead of patching it.

Definition: with the PostgreSQL extended query protocol a driver sends Parse (SQL text with $1, $2), Bind (values), Execute. The parser and planner work on the text alone. MySQL's binary protocol (COM_STMT_PREPARE/COM_STMT_EXECUTE) works the same way. Some drivers interpolate client-side instead (PDO with ATTR_EMULATE_PREPARES = true, which is the PDO default for MySQL; pgx in QueryExecModeSimpleProtocol); they escape correctly for the connection, but the separation is weaker, so keep server-side preparing where you can. Bind parameters work only for values: never for table names, column names, ASC/DESC, LIMIT in some engines, or SQL keywords.

Driver / APIPlaceholderServer-side separation
Go database/sql + pgx stdlib$1Yes (extended protocol)
Go pgx native$1, or pgx.NamedArgs with @nameYes by default (QueryExecModeCacheStatement); simple protocol interpolates client-side
Go go-sql-driver/mysql?Yes unless interpolateParams=true
Laravel query builder / Eloquent? or :name via PDOPDO prepares; MySQL emulates by default, still escaped by PDO
JDBC PreparedStatement?Yes
psql / plpgsql$1 with EXECUTE … USINGYes

The injection classes Must-know ​

In plain words: attackers have many ways to use the same hole: get all rows, glue another query on, read errors, ask yes/no questions one at a time, or plant input that explodes later.

Common misunderstanding: "Our endpoint does not show query results, so injection is harmless." Blind injection reads the database one bit per request from timing or from a changed response, and automated tools do millions of requests.

Definition and examples (PostgreSQL syntax):

ClassPayload ideaWhat it getsNotes
Classic / tautology' OR '1'='1All rows of the queryLogin bypass, data dump
Union-based' UNION SELECT email, password_hash FROM users--Other tables in the same responseNeeds same column count and types
Error-based' AND 1=CAST((SELECT password_hash FROM users LIMIT 1) AS int)--Data inside the error messageWhy errors must not reach the client
Boolean blind' AND substr((SELECT …),1,1)='a'--One bit per request from a changed responseFully automated by tools
Time-based blind'; SELECT pg_sleep(5)-- or ' AND 1=(SELECT 1 FROM pg_sleep(5))--One bit per request from latencyMySQL: SLEEP(5), BENCHMARK()
Stacked queries'; DROP TABLE orders;--Any statement the role may runPostgreSQL simple protocol allows several statements; extended protocol does not
Second-orderName stored as x'); DELETE FROM …--, later concatenated by a batch jobFires in a different code path, often with more privilegesEvery input source, including the database itself, is untrusted
Out-of-bandCOPY (SELECT …) TO PROGRAM 'curl …', MySQL LOAD_FILE/INTO OUTFILE, SQL Server xp_cmdshellExfiltration or OS commandsBlocked by not having file/program privileges
Identifier / ORDER BY?sort=(CASE WHEN … THEN name ELSE price END)Blind data via sort orderBindings do not apply; allowlist
LIKE wildcardq=% or q=_%_%_%…Full scans, data enumerationEscape %, _, \ in the bound value
Stored procedure / dynamic SQLEXECUTE 'SELECT … ' || p_name inside PL/pgSQL, PREPARE stmt FROM CONCAT(…) in MySQLSame as classic, hidden from app reviewformat('%I', …)/%L, EXECUTE … USING
ORM raw fragmentswhereRaw("x = '$v'"), orderByRaw($request->sort), DB::rawSame as classicBind inside raw fragments; allowlist identifiers
text
     Second-order injection
1    POST /signup  name = "bob'); UPDATE users SET role='admin' WHERE email='eve@x.io';--"
2    INSERT INTO users(name, email) VALUES ($1, $2)          -- bound: stored safely, byte for byte
3    ... two days later, a nightly report job ...
4    sql := "INSERT INTO report(line) VALUES ('" + user.Name + "')"   -- trusts data "from our own DB"
5    the stored payload runs as the report job's role (often the owner)

Real scenarios: a search page with ?sort= passed into ORDER BY; an admin export that builds WHERE id IN (…) by joining strings; a reporting job that trusts names already in the database; a PL/pgSQL function that builds a partition name from a parameter; a Laravel whereRaw written for a quick fix.

Per engine: every engine is vulnerable to concatenated SQL. What differs is the blast radius: PostgreSQL superusers can run COPY … PROGRAM; MySQL FILE privilege allows LOAD_FILE and SELECT … INTO OUTFILE (OWASP: "Disable the FILE privilege for all users"); SQL Server xp_cmdshell; SQLite ATTACH DATABASE can create files; MongoDB is immune to SQL but has operator injection ({"$ne": null} in a JSON body) and $where JavaScript; Redis has command injection through string-built Lua or inline commands.

Fix: values, identifiers, procedures Must-know ​

sql
-- Values: bind them. In PL/pgSQL dynamic SQL, use EXECUTE ... USING
EXECUTE 'SELECT count(*) FROM app.orders WHERE customer_id = $1' INTO n USING p_customer_id;

-- Identifiers: allowlist first, then quote. %I = quote_ident, %L = quote_nullable
IF p_month NOT IN ('2026_10', '2026_11') THEN RAISE EXCEPTION 'bad partition'; END IF;
EXECUTE format('SELECT count(*) FROM app.%I WHERE status = $1', 'orders_' || p_month) INTO n USING 'paid';

SELECT quote_ident('Foo bar');            -- "Foo bar"
SELECT quote_literal(E'O\'Reilly');       -- 'O''Reilly'
go
// database/sql: the value is an argument, never part of the string.
rows, err := db.QueryContext(ctx, `SELECT id, name FROM products WHERE name = $1`, name)

// SECURITY RISK, from go.dev's own example:
// rows, err := db.Query(fmt.Sprintf("SELECT * FROM user WHERE id = %s", id))

// Identifiers: map, then quote with pgx.
col, ok := map[string]string{"price": "price_cents", "name": "name"}[sortKey]
if !ok {
	return errBadSort
}
sqlText := "SELECT id FROM products ORDER BY " + pgx.Identifier{col}.Sanitize()
php
// Laravel: values are bound automatically by the builder...
$rows = DB::table('products')->where('name', $name)->get();
// ...and inside raw fragments only when you pass the bindings array.
$rows = DB::select('select * from products where name = ?', [$name]);
$rows = DB::table('products')->whereRaw('lower(name) = lower(?)', [$name])->get();

// Identifiers: Laravel quotes column names but does not validate them.
$column = ['price' => 'price_cents', 'name' => 'name'][$request->query('sort')] ?? 'name';
$rows = DB::table('products')->orderBy($column, $request->query('dir') === 'desc' ? 'desc' : 'asc')->get();

"PDO does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns." — Laravel 13 documentation, Database: Query Builder

Mass assignment is the ORM cousin of injection. It does not change SQL syntax, but it lets a request choose which columns to write. Laravel: "A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect." Declare #[Fillable([...])] (Laravel 13 attribute) and pass validated arrays, never $request->all().

Encryption in transit ​

TLS with server verification Must-know ​

In plain words: TLS hides the traffic and proves the server is the real one. The second part only happens if the client checks the server certificate and its host name.

Common misunderstanding: "sslmode=require means secure." It encrypts, but it does not check who is on the other side, so a man-in-the-middle can present any certificate and read everything, including a password sent with password or LDAP auth.

"The default value for sslmode is prefer. As is shown in the table, this makes no sense from a security point of view, and it only promises performance overhead if possible." — PostgreSQL documentation, SSL Support (libpq)

Definition: libpq sslmode: disable, allow, prefer (default), require (encrypt, no verification, unless a root CA file exists), verify-ca (chain checked), verify-full (chain and host name against SAN/CN; "recommended in most security-sensitive environments"). sslrootcert names the CA; sslrootcert=system uses the OS trust store. Server: ssl = on, ssl_cert_file, ssl_key_file, ssl_ca_file (for client certs), ssl_crl_file, ssl_min_protocol_version (default TLSv1.2), ssl_ciphers. Certificates are re-read on reload, so rotation is pg_reload_conf(), not a restart; a bad file on reload keeps the old configuration and logs an error. MySQL: require_secure_transport=ON (else error 3159 ER_SECURE_TRANSPORT_REQUIRED: "Connections using insecure transport are prohibited while --require_secure_transport=ON"), tls_version, ALTER INSTANCE RELOAD TLS for rotation, per-account REQUIRE SSL|X509|SUBJECT|ISSUER, clients --ssl-mode=VERIFY_IDENTITY.

Client settingEncryptsVerifies CAVerifies hostStops MITM
disable / MySQL DISABLEDNoNoNoNo
prefer (libpq, Laravel default) / MySQL PREFERREDIf server offersNoNoNo
require / REQUIREDYesNoNoNo
verify-ca / VERIFY_CAYesYesNoOnly with a private CA
verify-full / VERIFY_IDENTITYYesYesYesYes
text
     Man-in-the-middle with sslmode=require
1    app  -> "db.internal:5432"   DNS or ARP spoofed to 10.0.3.66 (attacker)
2    attacker presents a self-signed cert        -- require: accepted, no check
3    app sends SCRAM proof / or cleartext password for ldap|password methods
4    attacker relays to real db, reads and can alter every row in flight
     -- verify-full: step 2 fails with "certificate verify failed" / host name mismatch
text
# Laravel .env (PostgreSQL)
DB_SSLMODE=verify-full
DB_SSLROOTCERT=/etc/ssl/certs/db-ca.pem      # add 'sslrootcert' => env('DB_SSLROOTCERT') to the pgsql connection
# Laravel .env (MySQL): config/database.php passes MYSQL_ATTR_SSL_CA to PDO
MYSQL_ATTR_SSL_CA=/etc/ssl/certs/db-ca.pem
go
// Go: fail fast on a DSN that does not authenticate the server.
// DATABASE_URL=postgres://shop_app@db.internal:5432/shop?sslmode=verify-full&sslrootcert=/etc/ssl/db-ca.pem

Encryption at rest (TDE, disk encryption, pgcrypto, Laravel encrypted casts, envelope encryption with KMS) is covered on Encryption at Rest, in Transit & in Use. One rule belongs here: disk encryption protects against a stolen disk, not against a stolen login, because the database decrypts for every authenticated session.

Secrets management ​

Dynamic credentials, rotation and the .env problem Must-know ​

In plain words: the database password is a key to everything the role can do. Keep it out of code and git, make it short-lived, unique per service, and rotate it without downtime.

Common misunderstanding: "Environment variables are secure." They are better than source code, but they leak into crash reports, phpinfo(), /proc/<pid>/environ, CI logs, container inspect output and child processes. They are a delivery mechanism, not a secret store.

Definition: HashiCorp Vault's database secrets engine creates a database role on demand with a lease and drops it when the lease expires: "services that need to access a database no longer need to hardcode credentials: they can request them from Vault". Static roles keep one database user and rotate its password on a schedule. Vault's own root credential should be rotated with rotate-root so no human knows it.

"Since every service is accessing the database with unique credentials, it makes auditing much easier when questionable data access is discovered." — HashiCorp Vault documentation, Database secrets engine

text
vault write database/config/shop \
    plugin_name=postgresql-database-plugin \
    connection_url="postgresql://{{username}}:{{password}}@db.internal:5432/shop?sslmode=verify-full" \
    allowed_roles="shop-app" username="vault_admin" password="..." \
    password_authentication="scram-sha-256"

vault write database/roles/shop-app db_name=shop default_ttl=1h max_ttl=24h \
    creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}' IN ROLE shop_rw;"

vault write -force database/rotate-root/shop
vault read database/creds/shop-app        # -> username v-app-shop-app-x1y2, password, lease_id, lease_duration=1h
ApproachLifetimeLeak impactOperational cost
Password in source codeForeverEveryone with repo access, foreverNone, until the breach
.env / env var from CI secretUntil someone rotatesAnyone who sees env or logsLow; rotation is manual
Secret manager static secret (AWS Secrets Manager, Vault KV) with rotationRotation intervalUntil next rotationMedium; app must reload
Vault dynamic roleLease TTL (minutes–hours)One service instance, until lease endMedium; app must renew or reconnect
IAM / Entra / Cloud SQL IAM token15 minutes (RDS)Token onlyLow with SDK helpers; connection-rate limits
Client certificate from internal CACert lifetime (days)Until expiry or CRLNeeds PKI and rotation automation

Rotation without downtime: create the new credential, let new connections use it, keep the old one valid until pool connections recycle (pgxpool MaxConnLifetime, Laravel workers restarted by deploy), then revoke. Never put the owner or a superuser password in the application's environment.

Audit logging ​

pgAudit, log_statement and MySQL Enterprise Audit Must-know ​

In plain words: an audit log answers "who did what, when, from where" in a form an investigator can search and an attacker cannot erase.

Common misunderstanding: "log_statement = 'all' is an audit log." It logs what the client sent, not what the server did, it misses statements with syntax errors, it logs bound values for extended protocol (PII and secrets in logs), and the DBA can turn it off.

"The standard logging facility shows what the user requested, while pgAudit focuses on the details of what happened while the database was satisfying the request." — pgAudit README

Definition: pgAudit is loaded through shared_preload_libraries and CREATE EXTENSION pgaudit. Session audit logs by class through pgaudit.log: READ (SELECT, COPY from), WRITE (INSERT, UPDATE, DELETE, TRUNCATE, COPY to), FUNCTION (function calls and DO), ROLE (GRANT, REVOKE, CREATE/ALTER/DROP ROLE), DDL, MISC, MISC_SET (e.g. SET ROLE), ALL, with -class to exclude. Object audit logs only relations the role named in pgaudit.role has privileges on, down to columns. Other knobs: pgaudit.log_relation (one entry per table), pgaudit.log_parameter, pgaudit.log_catalog, pgaudit.log_level, pgaudit.log_client. Entries look like AUDIT: SESSION,33,2,DDL,CREATE TABLE,TABLE,public.important_table,CREATE TABLE important_table (id INT) with fields AUDIT_TYPE, STATEMENT_ID, SUBSTATEMENT_ID, CLASS, COMMAND, OBJECT_TYPE, OBJECT_NAME, STATEMENT, PARAMETER. Two caveats from the README: audit is "best-effort and not transactional", and "It is not possible to reliably audit superusers with pgAudit."

sql
-- postgresql.conf
-- shared_preload_libraries = 'pgaudit'
-- log_line_prefix = '%m [%p] %q%u@%d %r %a '      -- time, pid, user@db, remote host, application
-- log_connections = 'authentication,authorization'  -- PostgreSQL 18+ list form; 'on' in older versions
-- log_disconnections = on
CREATE EXTENSION pgaudit;
ALTER SYSTEM SET pgaudit.log = 'role, ddl';          -- every privilege and schema change
ALTER SYSTEM SET pgaudit.log_relation = on;
ALTER SYSTEM SET pgaudit.role = 'auditor';
SELECT pg_reload_conf();

-- Object audit: log every read of the sensitive columns, by anyone
CREATE ROLE auditor NOLOGIN;
GRANT SELECT (email, phone, national_id) ON app.customers TO auditor;
GRANT UPDATE, DELETE ON app.payments TO auditor;

-- A role-specific profile (settings are per role, not inherited)
ALTER ROLE alice SET pgaudit.log = 'read, write, role, ddl';
What to logPostgreSQLMySQL 8.4Why
Logins, failureslog_connections, failed auth always loggedaudit_log connection events, connection_control pluginBrute force, credential stuffing
Privilege changespgAudit ROLEEnterprise Audit filter on GRANTPersistence after compromise
Schema changespgAudit DDLEnterprise Audit, log_binTampering, backdoors (triggers, functions)
Sensitive readsObject audit via pgaudit.roleEnterprise Audit filters per tablePII exfiltration
Admin sessionsPer-role pgaudit.log = 'all' for humansFilter by userInsider actions
Errorslog_min_error_statement = errorError logInjection probing (42601 syntax errors)

MySQL: "MySQL Enterprise Audit is an extension included in MySQL Enterprise Edition, a commercial product", implemented by the audit_log plugin with JSON filters (audit_log_filter_set_filter, audit_log_filter_set_user). Community alternatives: Percona's audit log plugin, MariaDB's server_audit. Managed clouds: Amazon RDS supports pgAudit and the MariaDB audit plugin for MySQL; Azure and Google Cloud SQL expose pgAudit as a flag. SQL Server has SQL Server Audit; Oracle has Unified Auditing; MongoDB Enterprise has auditLog.

Where logs go matters more than which tool writes them. Ship them off the host in near real time (syslog/journald to a collector, CloudWatch, a SIEM), to storage the database admins cannot delete (object lock, separate account). NIST SP 800-53 AU-9 is "Protection of Audit Information"; an audit log on the same disk, writable by the same superuser, protects nothing.

Masking and anonymization for non-production ​

Masked copies, not production dumps Important ​

In plain words: developers and testers need realistic data, not real people's data. Replace names, emails, phones and IDs with fakes that keep the shape.

Common misunderstanding: "Staging is internal, so a prod copy is fine." Staging has weaker passwords, more people with access, debug endpoints and older patches; it is where breaches start. And "anonymised" data that keeps exact birth dates and postcodes can often be re-identified.

Definition: masking hides values on read (dynamic: XXXX-XXXX-1234 for some roles) or rewrites them in a copy (static). Pseudonymisation replaces identifiers with consistent tokens that can be reversed with a separately held key (GDPR Art. 32 names "the pseudonymisation and encryption of personal data" as a security measure). Anonymisation irreversibly removes the link to the person (generalisation, noise, synthetic data). Tools: PostgreSQL Anonymizer ("an extension to mask or replace personally identifiable information (PII) or commercially sensitive data from a Postgres database", with SECURITY LABEL … IS 'MASKED WITH FUNCTION anon.fake_email()', dynamic masking and pg_dump_anon), MySQL Enterprise Data Masking and De-Identification (mask_inner(), mask_outer(), gen_rnd_email(); Enterprise only), SQL Server Dynamic Data Masking, Oracle Data Redaction.

sql
-- PostgreSQL Anonymizer (static masking of a staging copy)
CREATE EXTENSION anon;
SECURITY LABEL FOR anon ON COLUMN app.customers.email    IS 'MASKED WITH FUNCTION anon.fake_email()';
SECURITY LABEL FOR anon ON COLUMN app.customers.phone    IS 'MASKED WITH FUNCTION anon.partial(phone, 2, $$******$$, 2)';
SECURITY LABEL FOR anon ON COLUMN app.customers.national_id IS 'MASKED WITH VALUE NULL';
SELECT anon.anonymize_database();      -- run on the copy, never on production

-- Plain SQL alternative for a quick refresh job
UPDATE app.customers SET
  email = 'user' || id || '@example.test',
  phone = NULL,
  national_id = NULL,
  name  = 'Customer ' || id;

Laravel: seed non-prod with factories (Customer::factory()->count(10_000)->create()) instead of restores; if a restore is unavoidable, run the masking job before anyone gets access.

Operational exposure: backups, network, superuser, extensions ​

Backup security Important ​

In plain words: a backup is a complete copy of the database with none of its access controls. Whoever reads the file reads everything.

Common misunderstanding: "Backups are encrypted because the bucket is encrypted." Server-side bucket encryption protects against stolen disks at the cloud provider; anyone with s3:GetObject still gets plaintext.

Definition: protect backups with client-side encryption (pgBackRest repo1-cipher-type=aes-256-cbc, WAL-G with libsodium/KMS keys, pg_dump | age/gpg), keys stored outside the backup account, bucket policies that deny public access and deletion (object lock for ransomware), separate credentials for the backup role (pg_read_all_data or REPLICATION, no interactive login), and restore tests in an isolated network. Mechanics of backups and PITR are on Backup, PITR & Disaster Recovery.

Network exposure Must-know ​

In plain words: the fewest machines possible should be able to even reach the database port.

Common misunderstanding: "pg_hba.conf already restricts who can log in." It decides after the TCP connection is accepted. Every scanner on the internet can still try passwords, hit pre-auth bugs and fill connection slots. The manual: listen_addresses "controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces."

Definition: listen_addresses (default localhost), port, MySQL bind_address; cloud security groups / firewall rules allowing only the app subnet; private subnets with no public IP (PubliclyAccessible = false on RDS); humans connect through a bastion host, SSM Session Manager, an identity-aware proxy (Teleport, Cloud SQL Auth Proxy, AWS RDS IAM + SSM) or a VPN, never directly. Admin web tools (pgAdmin, phpMyAdmin) stay behind SSO. Egress controls on the database host stop COPY … PROGRAM 'curl …' exfiltration.

Superuser hygiene and extension risks Must-know ​

In plain words: superuser is not "admin"; it is "the database trusts this session completely", including reading server files and running programs as the postgres OS user.

Common misunderstanding: "We need superuser for the app because an extension asked for it." Most needs have a predefined role (pg_monitor, pg_signal_backend, pg_maintain) or a trusted extension that a database owner can install.

Definition: superuser bypasses every privilege check and RLS, can COPY … TO/FROM PROGRAM (also granted by pg_execute_server_program), read files (pg_read_server_files, pg_read_file()), load C code via CREATE EXTENSION of untrusted extensions or LOAD, and change shared_preload_libraries. Extensions marked trusted can be installed by any role with CREATE on the database; their objects are owned by the bootstrap superuser. The manual warns that a careless extension script plus "trojan-horse objects" in search_path can give a user superuser, so install extensions only into schemas where untrusted users cannot CREATE. MySQL equivalents: SUPER (deprecated in favour of dynamic privileges like SYSTEM_VARIABLES_ADMIN, CONNECTION_ADMIN), FILE, PROCESS, SHUTDOWN.

sql
-- Who can do too much?
SELECT rolname, rolsuper, rolcreaterole, rolcreatedb, rolbypassrls, rolreplication
FROM pg_roles WHERE rolsuper OR rolcreaterole OR rolbypassrls OR rolreplication;

SELECT r.rolname, m.rolname AS member_of
FROM pg_auth_members am JOIN pg_roles r ON r.oid = am.member JOIN pg_roles m ON m.oid = am.roleid
WHERE m.rolname IN ('pg_execute_server_program', 'pg_read_server_files', 'pg_write_server_files');

SELECT extname, extversion, nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace;

Rules: the postgres superuser logs in only via peer on the socket or a break-glass procedure (sealed credential, two people, alert on use); managed services give you an rds_superuser/cloudsqlsuperuser-style role that is not a true superuser, keep that for DBAs only; review extensions like dependencies (dblink and postgres_fdw open network paths, plpython3u/plperlu are untrusted languages that run OS code).

Per-engine behaviour ​

What each database really offers ​

FeaturePostgreSQLMySQL 8.4 / InnoDBSQL ServerOracleSQLiteMongoDBCockroachDBRedis
Default password authSCRAM-SHA-256caching_sha2_passwordSQL logins / Windows (Kerberos)Password verifiers / KerberosNone (file permissions)SCRAM-SHA-256SCRAM-SHA-256ACL users (requirepass legacy)
Host-based rulespg_hba.conf'user'@'host'Firewall + loginssqlnet.ora, listenerOSnet.bindIp, IP allowlistshba.conf-like cluster settingbind, protected-mode
Roles / groupsYes, with INHERIT/SETYes (8.0+)Server + database rolesRolesNoBuilt-in + custom rolesYesACL categories
Column grantsYesYesYesYesNoProjection via viewsYesNo
Row-level securityRLS policiesNoRLS predicatesVPD / DBMS_RLSNoNo (views, $redact)Yes (v25.2+)No
AuditpgAudit, logsEnterprise Audit (audit_log); Percona/MariaDB pluginsSQL Server AuditUnified AuditingNoneEnterprise auditLogAudit logging per tableACL LOG
TLS server verify knobsslmode=verify-full--ssl-mode=VERIFY_IDENTITYEncrypt=Strict, TrustServerCertificate=falseTCPS + walletn/atls=true + CAsslmode=verify-full--tls + CA
MaskingPostgreSQL Anonymizer (extension)Enterprise Data MaskingDynamic Data MaskingData RedactionNoAtlas / appNoNo

Defaults that bite ​

ProductDefaultRiskChange to
libpq / Laravel pgsqlsslmode=preferSilent fallback to plaintext, no server checkverify-full
Docker postgres imagePOSTGRES_HOST_AUTH_METHOD unset → SCRAM, but trust used in many tutorialstrust for all hostsNever set trust
PostgreSQL ≤ 14 clusters (and upgrades)CREATE on public to PUBLICCVE-2018-1058-style trojansREVOKE CREATE ON SCHEMA public FROM PUBLIC
PostgreSQL functionsEXECUTE to PUBLICSECURITY DEFINER reachable by allRevoke in the same transaction as CREATE FUNCTION
MySQLlocal_infile off in 8.0+, but often re-enabledClient-side file readKeep off
PDO MySQLATTR_EMULATE_PREPARES = trueClient-side interpolation (still escaped)false where driver supports it
MongoDB < 3.6Bound to all interfaces, no authAnyone on the network reads and deletes databindIp, security.authorization: enabled
Redisprotected-mode yes but no password if boundUnauthenticated CONFIG SET dir → file writeACLs, TLS, private network

Mechanics ​

Every knob in one table Must-know ​

KnobWhereSecure valueNotes
listen_addressespostgresql.confPrivate IP(s) onlyRestart required
password_encryptionpostgresql.confscram-sha-256Affects new passwords only
md5_password_warningspostgresql.conf (18+)onWarns on md5 use
ssl, ssl_min_protocol_versionpostgresql.confon, TLSv1.2 or TLSv1.3Reload re-reads cert files
ssl_ca_file, ssl_crl_filepostgresql.confInternal CA, CRLFor cert / clientcert
log_connections, log_disconnectionspostgresql.confOnEvidence for incidents
log_line_prefixpostgresql.conf'%m [%p] %q%u@%d %r %a 'User, db, host, app in every line
log_statementpostgresql.confddl (pgAudit for the rest)all logs bound values
shared_preload_librariespostgresql.confpgaudit (plus others)Restart required
pgaudit.log, pgaudit.rolepostgresql.conf / rolerole, ddl + object auditSuperuser-only to change
row_securitysessionon (default)off makes filtered queries error
search_pathrole / function"$user", app for apps; pg_temp last in definer functionsSchema-qualify in privileged code
statement_timeout, idle_in_transaction_session_timeoutroleSeconds, not unlimitedDoS and lock-holding
require_secure_transportMySQLONError 3159 for plaintext
tls_versionMySQLTLSv1.2,TLSv1.3ALTER INSTANCE RELOAD TLS
local_infile, secure_file_privMySQLOFF, a dedicated directory or NULLFile read/write
default_authentication_plugin / authentication_policyMySQLcaching_sha2_password8.4 uses authentication_policy

Error codes you will see Important ​

CodeEngineMeaningUsually means
28000 invalid_authorization_specificationPostgreSQLno pg_hba.conf entry for host … or rejectWrong network, wrong TLS mode, missing line
28P01 invalid_passwordPostgreSQLpassword authentication failed for user "…"Wrong password, expired VALID UNTIL, brute force
42501 insufficient_privilegePostgreSQLpermission denied for table …; also new row violates row-level security policy for table "…"Missing grant, or an RLS WITH CHECK failure
42601 syntax_errorPostgreSQLSyntax errorIn production traffic: injection probing
57014 query_canceledPostgreSQLstatement_timeout hitSlow or time-based blind injection
1045 ER_ACCESS_DENIED_ERROR (28000)MySQLAccess denied for user '%s'@'%s' (using password: %s)Wrong password or host part
1142 ER_TABLEACCESS_DENIED_ERRORMySQL%s command denied to user …Missing table grant
1227 ER_SPECIFIC_ACCESS_DENIED_ERRORMySQLNeeds a privilege like SUPERAdmin operation from app role
3159 ER_SECURE_TRANSPORT_REQUIREDMySQLInsecure transport prohibitedClient without TLS

How a statement is authorized ​

text
1    connection accepted on listen_addresses       (network)
2    TLS handshake; client verifies server cert    (verify-full)
3    pg_hba.conf: first matching line -> method    (or 28000)
4    method authenticates the role                 (or 28P01)
5    session starts with role + inherited privileges; SET ROLE may switch
6    statement parsed with search_path             (name resolution: trojans live here)
7    privilege check per object and column         (or 42501)
8    RLS: USING added to scans; WITH CHECK on new rows (unless owner w/o FORCE, superuser, BYPASSRLS)
9    executor runs; pgAudit hooks log by class/object
10   result returned; errors returned as SQLSTATE only to the app, details to the log

Solving the classic problems ​

The injectable endpoint ​

SolutionHowAdvantageCost / limitation
Bind parameters$1/? and arguments; builder methodsRemoves the class for valuesDoes not cover identifiers
Allowlist identifiersMap client keys to fixed column namesSmall, reviewableEvery new sort key is a code change (good)
Quote identifiersformat('%I'), pgx.Identifier.Sanitize, Laravel grammarCorrect quotingQuoting is not authorization: still allowlist
Least-privilege roleNo DDL, no file/program, no other schemasLimits damage of any remaining holeNeeds a separate migration role
Generic errorsLog details, return "internal error"Kills error-based injectionNeeds good server logs
WAF / RASPPattern blocking at the edgeCatches noise and scannersBypassable; never the fix

Go, before (compiles, runs, and is injectable through q and sort):

go
// Package main is the INJECTABLE version of a product search endpoint.
// It compiles and runs, and it is exactly the shape that SQL injection
// scanners (and attackers) look for. Do not copy it.
//
//	DATABASE_URL=postgres://app:secret@localhost:5432/shop go run ./before
//	curl "localhost:8080/products?q=x'%20OR%20'1'='1&sort=price"
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)

type product struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Price int64  `json:"price_cents"`
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Println("DATABASE_URL not set; nothing to do")
		return
	}
	// Anti-pattern 1: the DSN usually points at the table owner or a
	// superuser, so whatever is injected runs with full rights.
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	http.HandleFunc("GET /products", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query().Get("q")
		sort := r.URL.Query().Get("sort")
		if sort == "" {
			sort = "name"
		}
		// Anti-pattern 2: user input concatenated into SQL text.
		//   q    = x' OR '1'='1          -> every row (classic / tautology)
		//   q    = x' UNION SELECT ...   -> other tables (union-based)
		//   sort = (CASE WHEN (SELECT substr(password_hash,1,1) FROM users
		//          LIMIT 1)='a' THEN name ELSE price::text END)
		//                                -> one bit per request (blind, boolean)
		query := fmt.Sprintf(
			"SELECT id, name, price_cents FROM products WHERE name ILIKE '%%%s%%' ORDER BY %s LIMIT 50",
			q, sort)
		rows, err := db.QueryContext(r.Context(), query)
		if err != nil {
			// Anti-pattern 3: the database error goes back to the caller,
			// which turns a blind injection into an error-based one.
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var out []product
		for rows.Next() {
			var p product
			if err := rows.Scan(&p.ID, &p.Name, &p.Price); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			out = append(out, p)
		}
		_ = json.NewEncoder(w).Encode(out)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Go, after (bind parameters, ORDER BY allowlist, verify-full enforced, tenant set per transaction for RLS, errors kept server-side):

go
// Package main is the FIXED product search endpoint. Values travel as bind
// parameters ($1, $2), never as SQL text; the ORDER BY column and direction
// come from an allowlist; the connection uses a least-privilege role over
// verify-full TLS; every request runs in a transaction that sets the tenant
// for RLS; database errors are logged, not returned.
//
//	DATABASE_URL='postgres://shop_app@db.internal:5432/shop?sslmode=verify-full&sslrootcert=/etc/ssl/db-ca.pem' go run ./after
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"

	_ "github.com/jackc/pgx/v5/stdlib"
)

type product struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Price int64  `json:"price_cents"`
}

// sortColumns maps what the client may send to SQL the application owns.
// Identifiers cannot be bind parameters, so this map IS the defence.
var sortColumns = map[string]string{
	"name":   "name",
	"price":  "price_cents",
	"newest": "created_at",
}

func orderBy(sortKey, dir string) (string, error) {
	if sortKey == "" {
		sortKey = "name"
	}
	col, ok := sortColumns[sortKey]
	if !ok {
		return "", errors.New("unknown sort key")
	}
	if dir != "desc" {
		return col + " ASC, id ASC", nil
	}
	return col + " DESC, id DESC", nil
}

// requireVerifyFull refuses to start with a DSN that would accept an
// unauthenticated server (sslmode=disable/allow/prefer/require).
func requireVerifyFull(dsn string) error {
	u, err := url.Parse(dsn)
	if err != nil {
		return err
	}
	if u.Query().Get("sslmode") != "verify-full" {
		return errors.New("DATABASE_URL must use sslmode=verify-full")
	}
	return nil
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Println("DATABASE_URL not set; nothing to do")
		return
	}
	if err := requireVerifyFull(dsn); err != nil {
		log.Fatal(err)
	}
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	http.HandleFunc("GET /products", func(w http.ResponseWriter, r *http.Request) {
		tenantID, err := strconv.ParseInt(r.Header.Get("X-Tenant-ID"), 10, 64) // set by the auth middleware in a real app
		if err != nil {
			http.Error(w, "bad tenant", http.StatusBadRequest)
			return
		}
		ob, err := orderBy(r.URL.Query().Get("sort"), r.URL.Query().Get("dir"))
		if err != nil {
			http.Error(w, "bad sort", http.StatusBadRequest)
			return
		}
		out, err := search(r.Context(), db, tenantID, r.URL.Query().Get("q"), ob)
		if err != nil {
			log.Printf("search failed: %v", err) // details stay in the server log
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		_ = json.NewEncoder(w).Encode(out)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func search(ctx context.Context, db *sql.DB, tenantID int64, q, orderBy string) ([]product, error) {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
	if err != nil {
		return nil, err
	}
	defer tx.Rollback() //nolint:errcheck // no-op after Commit

	// set_config(..., true) is transaction-local: it disappears at COMMIT,
	// so a pooled connection never carries one tenant into the next request.
	if _, err := tx.ExecContext(ctx,
		`SELECT set_config('app.tenant_id', $1, true)`, strconv.FormatInt(tenantID, 10)); err != nil {
		return nil, err
	}

	// orderBy came from the allowlist; q and the limit are bind parameters.
	// The RLS policy on products adds "tenant_id = current_setting(...)".
	rows, err := tx.QueryContext(ctx,
		`SELECT id, name, price_cents FROM products
		  WHERE name ILIKE '%' || $1 || '%'
		  ORDER BY `+orderBy+` LIMIT $2`, q, 50)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []product
	for rows.Next() {
		var p product
		if err := rows.Scan(&p.ID, &p.Name, &p.Price); err != nil {
			return nil, err
		}
		out = append(out, p)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return out, tx.Commit()
}

Laravel, before (string-built DB::select, whereRaw with interpolation, orderByRaw from the request, create($request->all())):

php
<?php

// app/Http/Controllers/ProductController.php — the INJECTABLE version.
// Every line marked "UNSAFE" is a pattern a code review must reject.
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

final class ProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $q = $request->query('q', '');
        $sort = $request->query('sort', 'name');

        // UNSAFE: the value is interpolated into SQL text.
        // q = x' OR '1'='1  returns every row; q = x' UNION SELECT ... reads other tables.
        $rows = DB::select("SELECT id, name, price_cents FROM products WHERE name ILIKE '%{$q}%' ORDER BY {$sort} LIMIT 50");

        return response()->json($rows);
    }

    public function search(Request $request): JsonResponse
    {
        // UNSAFE: bindings do not exist for raw fragments. whereRaw with
        // interpolation and orderByRaw with a request value are both injectable.
        $rows = DB::table('products')
            ->whereRaw("category = '".$request->input('category')."'")
            ->orderByRaw($request->input('sort', 'name'))
            ->get();

        return response()->json($rows);
    }

    public function register(Request $request): JsonResponse
    {
        // UNSAFE: mass assignment. With #[Unguarded] (or an empty $guarded) on
        // User, a request body containing "is_admin": true makes an admin.
        $user = User::create($request->all());

        return response()->json($user, 201);
    }
}

Laravel, after (builder bindings, Rule::in allowlist, bound raw fragment, validated mass assignment):

php
<?php

// app/Http/Controllers/ProductController.php — the FIXED version.
// Values are bound by PDO; identifiers and sort directions come from an
// allowlist; mass assignment goes through validated, fillable fields.
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

final class ProductController extends Controller
{
    /** Client-facing sort key => column the application owns. */
    private const SORTABLE = [
        'name' => 'name',
        'price' => 'price_cents',
        'newest' => 'created_at',
    ];

    public function index(Request $request): JsonResponse
    {
        $data = $request->validate([
            'q' => ['nullable', 'string', 'max:100'],
            'sort' => ['nullable', Rule::in(array_keys(self::SORTABLE))],
            'dir' => ['nullable', Rule::in(['asc', 'desc'])],
        ]);

        // The search text is a binding; LIKE wildcards in it are escaped so
        // "%" from the user does not turn into a full scan.
        $needle = addcslashes($data['q'] ?? '', '%_\\');

        $rows = DB::table('products')
            ->select(['id', 'name', 'price_cents'])
            ->where('name', 'ilike', '%'.$needle.'%')
            ->orderBy(self::SORTABLE[$data['sort'] ?? 'name'], $data['dir'] ?? 'asc')
            ->orderBy('id')
            ->limit(50)
            ->get();

        return response()->json($rows);
    }

    public function search(Request $request): JsonResponse
    {
        $category = $request->validate(['category' => ['required', 'string', 'max:50']])['category'];

        // A raw fragment is fine when every value in it is a "?" binding.
        $rows = DB::table('products')
            ->whereRaw('lower(category) = lower(?)', [$category])
            ->orderBy('name')
            ->get();

        return response()->json($rows);
    }

    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:12'],
        ]);

        // User declares #[Fillable(['name', 'email', 'password'])]; is_admin is
        // never fillable and is only changed by an explicit, audited admin action.
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        return response()->json($user->only(['id', 'name', 'email']), 201);
    }
}

The application connects as the owner or a superuser ​

SolutionHowAdvantageCost
Split rolesshop_owner (NOLOGIN, migrations via SET ROLE), shop_app (DML), shop_roInjection cannot DROP, ALTER, COPY … PROGRAMTwo connection configs (app vs migrate)
Default privilegesALTER DEFAULT PRIVILEGES FOR ROLE shop_owner …New tables are usable without manual grantsMust be set per creating role
Separate Laravel connection for migrationsDB_USERNAME for app, migrate --database=pgsql_owner in CIApp never holds DDL rightsCI secret for the owner
php
// config/database.php: a second connection used only by CI for migrations
'pgsql_owner' => [
    'driver' => 'pgsql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'laravel'),
    'username' => env('DB_OWNER_USERNAME'),   // shop_owner, never given to the running app
    'password' => env('DB_OWNER_PASSWORD'),
    'charset' => 'utf8',
    'search_path' => 'app',
    'sslmode' => env('DB_SSLMODE', 'verify-full'),
],
// CI: php artisan migrate --database=pgsql_owner --force

A tenant reads another tenant's rows ​

SolutionHowAdvantageCost
App-level scopeGlobal scope / repository adds tenant_idSimple, portableOne missed query leaks
RLS behind itPolicy on current_setting('app.tenant_id'), FORCEMissed query returns nothingPostgreSQL-specific; setting must be per transaction
Tenant in keysComposite PK/FK (tenant_id, id)Cross-tenant joins impossibleWider indexes
Separate schema/databasePer-tenant isolationStrongestOperations at scale (Multi-Tenancy)
go
// Package main shows the pgx-native tools for the two places where bind
// parameters do not reach: identifiers and per-tenant session state.
//
//	DATABASE_URL='postgres://shop_app@localhost:5432/shop?sslmode=verify-full' go run ./rls
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// archiveTables is the allowlist; pgx.Identifier.Sanitize is the second
// belt that quotes the name exactly like quote_ident / format('%I').
var archiveTables = map[string]bool{"orders_2025": true, "orders_2026": true}

func countArchive(ctx context.Context, pool *pgxpool.Pool, table string) (int64, error) {
	if !archiveTables[table] {
		return 0, fmt.Errorf("table %q not allowed", table)
	}
	sqlText := "SELECT count(*) FROM " + pgx.Identifier{"archive", table}.Sanitize()
	var n int64
	err := pool.QueryRow(ctx, sqlText).Scan(&n)
	return n, err
}

// withTenant runs fn inside a transaction whose RLS tenant is set with a
// bind parameter. If fn forgets a WHERE tenant_id = ..., the policy still
// filters; if the setting is missing, the policy sees NULL and returns no rows.
func withTenant(ctx context.Context, pool *pgxpool.Pool, tenantID int64, fn func(pgx.Tx) error) error {
	return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx, "SELECT set_config('app.tenant_id', $1, true)", fmt.Sprint(tenantID)); err != nil {
			return err
		}
		return fn(tx)
	})
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Println("DATABASE_URL not set; nothing to do")
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cfg, err := pgxpool.ParseConfig(dsn)
	if err != nil {
		log.Fatal(err)
	}
	cfg.MaxConnLifetime = 10 * time.Minute // short-lived creds (Vault, IAM) need recycled connections
	pool, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()

	err = withTenant(ctx, pool, 42, func(tx pgx.Tx) error {
		var visible int64
		// No tenant filter here on purpose: RLS adds it.
		if err := tx.QueryRow(ctx, "SELECT count(*) FROM invoices").Scan(&visible); err != nil {
			return err
		}
		log.Printf("tenant 42 sees %d invoices", visible)
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}

	if _, err := countArchive(ctx, pool, "orders_2025; DROP TABLE users"); err != nil {
		log.Printf("rejected as expected: %v", err)
	}
	n, err := countArchive(ctx, pool, "orders_2025")
	if err != nil && !errors.Is(err, context.Canceled) {
		log.Printf("archive count failed: %v", err)
	}
	log.Printf("archive.orders_2025 has %d rows", n)
}
php
<?php

// app/Http/Middleware/ScopeDatabaseToTenant.php
// Runs the request inside one transaction and sets the PostgreSQL RLS tenant
// with a bound, transaction-local setting. The app connects as a role that is
// neither the table owner nor BYPASSRLS, so the policy cannot be skipped.
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

final class ScopeDatabaseToTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        $tenantId = (string) $request->user()->tenant_id;

        return DB::transaction(function () use ($request, $next, $tenantId) {
            // is_local = true: the value vanishes at COMMIT/ROLLBACK, so a
            // persistent connection (Octane, pgBouncer) cannot leak it.
            DB::select("SELECT set_config('app.tenant_id', ?, true)", [$tenantId]);

            return $next($request);
        });
    }
}

// Policy installed by a migration (run as the table owner, not the app role):
//
//   ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
//   ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
//   CREATE POLICY tenant_isolation ON invoices
//     USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)
//     WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint);
//
// NULLIF matters: after a transaction-local setting ends, the parameter reads
// back as '' (not NULL), and ''::bigint would raise an error instead of
// returning no rows.

Secrets in code and .env ​

Move to a secret manager or IAM tokens; scan the repo history (gitleaks, trufflehog) and rotate anything found, because a deleted line stays in git history and in every clone. In Go, read credentials at connect time (pgxpool.Config.BeforeConnect) so rotation needs no restart. In Laravel, keep .env out of the web root and out of images, php artisan config:cache in the build, and do not log config('database').

Sensitive columns readable by everyone ​

sql
-- Column grants for humans and BI; encrypted values for the app's most sensitive fields
REVOKE SELECT ON app.customers FROM shop_ro;
GRANT SELECT (id, name, country, created_at) ON app.customers TO shop_ro;
CREATE VIEW app.customers_support WITH (security_invoker = true) AS
  SELECT id, name, left(email, 2) || '***@' || split_part(email, '@', 2) AS email_masked FROM app.customers;
php
<?php

// app/Models/Customer.php — column-level protection in the application:
// only listed fields are mass assignable, PII is encrypted with APP_KEY
// before it reaches the database, and serialisation hides secrets.
namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['name', 'email', 'phone', 'national_id'])]
class Customer extends Model
{
    /** Never returned by toArray()/toJson(). */
    protected $hidden = ['national_id'];

    protected function casts(): array
    {
        return [
            // Encrypted at rest inside the row; the column must be TEXT and
            // can no longer be searched or indexed by value.
            'phone' => 'encrypted',
            'national_id' => 'encrypted',
        ];
    }
}

Evidence after the fact ​

Install pgAudit with role, ddl globally, object audit on PII tables, per-role all for human admins, and ship logs off the host. Test it: run the Lab's pgAudit experiment and confirm the entries reach the SIEM, not only the local file.

Monitoring for attacks ​

SignalSourceLikely causeResponse
Burst of 28P01 / MySQL 1045Server logBrute force, credential stuffingBlock source, check pg_hba.conf, rotate
Successful login from a new IP / ASN / hourlog_connections, cloud logsStolen credentialsVerify, kill session (pg_terminate_backend), rotate
42601 syntax errors from the app roleServer log, APMInjection probingFind the endpoint from application_name/trace id
Many 57014 or very long pg_sleeppg_stat_activity, logTime-based blind injectionSame; add statement_timeout
SELECT volume on PII tables jumpspgAudit object audit, pg_stat_user_tables.seq_scanExfiltrationThrottle, investigate role
New role, GRANT, ALTER ROLE … SUPERUSERpgAudit ROLEPersistencePage immediately
New function, trigger, extensionpgAudit DDLBackdoorDiff schema against migrations
COPY … TO, pg_read_filepgAudit READ/FUNCTIONBulk exportPage
Connections from outside app subnetVPC flow logsExposureFix security group
sql
-- Live view: who is connected, from where, doing what
SELECT pid, usename, client_addr, application_name, backend_start, state, left(query, 80)
FROM pg_stat_activity WHERE backend_type = 'client backend' ORDER BY backend_start;
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'suspicious_role';

Database observability in general (metrics, slow queries, dashboards) is on Database Observability.

Incident response for a database breach ​

The runbook Must-know ​

In plain words: when you suspect a breach: stop the bleeding, keep the evidence, find out what was touched, close the hole, and tell the people the law says you must tell.

Common misunderstanding: "Restore from backup and move on." Restoring first destroys evidence, and the attacker may have planted roles, functions or triggers that the backup also contains.

text
     Database breach runbook
1    Detect      alert: pgAudit ROLE event "ALTER ROLE x SUPERUSER" at 03:12
2    Contain     revoke network path (security group), ALTER ROLE ... NOLOGIN, pg_terminate_backend
3    Preserve    snapshot disk + copy server and audit logs to a separate account (read-only)
4    Scope       which roles, which tables, which time window: pgAudit OBJECT/READ entries, pg_stat_statements
5    Eradicate   drop rogue roles/functions/triggers/extensions; diff schema vs migrations; patch the hole (injection, exposed port)
6    Rotate      every credential the attacker could have seen: app roles, Vault root, IAM keys, TLS keys, APP_KEY if columns were read
7    Recover     restore or PITR to before the first malicious change if data was altered; verify integrity
8    Notify      legal/DPO: GDPR Art. 33 "not later than 72 hours" to the supervisory authority; PCI/HIPAA per contract and rule
9    Learn       blameless review; add the missing control and its alert
StepPostgreSQL command / artefact
Lock a roleALTER ROLE shop_app NOLOGIN; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'shop_app';
List recent role changesSearch pgAudit CLASS=ROLE in the log store
Find rogue objectsSELECT proname, prosecdef, proowner::regrole FROM pg_proc WHERE pronamespace NOT IN ('pg_catalog'::regnamespace, 'information_schema'::regnamespace); and SELECT tgname, tgrelid::regclass FROM pg_trigger WHERE NOT tgisinternal;
Check grants drift\dp app.*, SELECT * FROM pg_roles WHERE rolsuper OR rolbypassrls;
Recover dataPITR to a timestamp before the first malicious statement (Backup, PITR & DR)

Compliance mapping ​

Control on this pagePCI DSS v4.xGDPRHIPAA Security Rule (45 CFR 164.312)SOC 2 (Trust Services Criteria)
Least privilege, roles, RLSRestrict access to cardholder data by business need to knowArt. 32 confidentiality of processing systems(a)(1) Access control: "allow access only to those persons or software programs that have been granted access rights"Logical access controls (Security criteria)
Strong auth, named accounts, no shared superuserIdentify users and authenticate accessArt. 32Unique user identification, person or entity authenticationLogical access, user provisioning
TLS verify-fullProtect cardholder data with strong cryptography during transmissionArt. 32 "encryption of personal data"(e)(1) Transmission securityEncryption in transit
Encryption at rest, backup encryptionProtect stored account dataArt. 32Encryption and decryption (Addressable)Encryption at rest
pgAudit, log protectionLog and monitor all access to system components and cardholder dataArt. 32 ability to test and evaluate; Art. 33 breach evidence(b) Audit controls: "record and examine activity"Monitoring of controls, logging
Masking for non-prodDo not use live PANs in test environmentsArt. 32 "pseudonymisation"; data minimisationMinimum necessaryConfidentiality
Incident responseIncident response planArt. 33 notification within 72 hoursSecurity incident proceduresIncident response
Hardening, patchingSecure configurations, vulnerability managementArt. 32Risk managementChange and configuration management

Clause numbers are given only where this page read the text (GDPR Art. 32/33, HIPAA 164.312); PCI DSS and SOC 2 rows name the obligation, not a requirement number.

Hardening checklist ​

AreaCheckHow to verify
NetworkNo public IP; SG allows app subnet onlyCloud console; nmap from outside fails
Networklisten_addresses is not * on a host with a public interfaceSHOW listen_addresses;
AuthNo trust, password, md5 linesSELECT * FROM pg_hba_file_rules WHERE auth_method IN ('trust','password','md5');
AuthNo md5 hashes storedSELECT rolname FROM pg_authid WHERE rolpassword LIKE 'md5%';
Authhostnossl … reject presentpg_hba_file_rules
TLSServer ssl=on, min TLS 1.2; clients verify-fullSHOW ssl; SELECT * FROM pg_stat_ssl;
RolesApp role not owner, not superuser, no BYPASSRLS, no CREATEROLEpg_roles query above
SchemaCREATE on public revokedSELECT has_schema_privilege('public', 'public', 'CREATE');
FunctionsSECURITY DEFINER functions set search_pathSELECT proname FROM pg_proc WHERE prosecdef AND proconfig IS NULL;
RLSTenant tables have RLS enabled and forcedSELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class WHERE relkind='r';
ViewsViews over RLS tables use security_invokerSELECT relname, reloptions FROM pg_class WHERE relkind='v';
ExtensionsOnly reviewed extensions; no untrusted languages for appsSELECT * FROM pg_extension;
AuditpgAudit loaded, logs shipped off-hostSHOW shared_preload_libraries; SHOW pgaudit.log;
SecretsNo credentials in repo history; rotation ≤ 90 days or dynamicgitleaks; Vault lease TTLs
CopiesBackups encrypted, restore tested, non-prod maskedBackup tool config; staging sample
PatchingMinor version currentSELECT version(); vs release notes
MySQLrequire_secure_transport=ON, no mysql_native_password, FILE granted to nobody, local_infile=OFFSHOW GLOBAL VARIABLES, mysql.user

Choosing controls ​

SituationRecommendedExtra techniqueReason
Single app, single PostgreSQLSplit owner/app roles, bind parameters, verify-full, private networkpgAudit role, ddlCovers the top three attackers cheaply
Multi-tenant SaaS (shared tables)App scope + RLS FORCE + transaction-local tenant(tenant_id, id) keys, restrictive policyA missed filter is the most likely leak
Regulated data (PCI, HIPAA)Column grants, encryption (encryption-in-use), object auditMasked non-prod, quarterly access reviewAuditors ask for evidence, not intentions
Many microservicesOne role per service, Vault dynamic creds or IAMService mesh mTLS + cert authBlast radius and attribution per service
Managed cloud (RDS, Cloud SQL, Azure)IAM auth, no public access, provider audit flagsSecrets Manager rotationUses the platform's identity and logs
BI / analystsRead replica, shop_ro on masked viewsPer-person accounts via SSO/LDAPHumans should not hold the app's role
Legacy app you cannot rewriteLeast privilege + WAF + pgAudit object auditstatement_timeout, alert on 42601Contain what you cannot fix yet
MySQL shopcaching_sha2_password, roles, REQUIRE SSL, views for tenant filteringPercona/MariaDB audit plugin or Enterprise AuditNo RLS; compensate with views and app scope

In architecture: from a single process to a distributed system ​

Database security is about who holds which credential and what that credential can reach. As the system grows, credentials multiply and paths lengthen, so the design question becomes: how many roles, who issues them, and where is the evidence?

Monolith: one process, one database ​

How it shows up: one Laravel or Go app, one database, often one credential. The dangerous default is that the same credential runs migrations, serves requests and is used by humans.

Simplest correct usage: two roles (owner for migrations from CI, app for DML), verify-full, private network, bind parameters everywhere, an allowlist for sorting, pgAudit role, ddl.

Example (simple): a shop's GET /products?sort=price goes through the After.php controller above; the app role cannot DROP anything even if a raw query slips through review.

Example (complex): a B2B monolith with shared tables for 400 tenants: the auth middleware derives tenant_id from the session, ScopeDatabaseToTenant sets it per transaction, every tenant table has FORCE ROW LEVEL SECURITY, and support staff use a masked security_invoker view under their own LDAP-authenticated accounts.

Modular monolith and multiple databases ​

How it shows up: modules share one PostgreSQL cluster but own schemas. Security boundaries follow ownership: module billing gets role billing_app with USAGE on schema billing only; catalog cannot read billing.cards.

Example: a module that needs another module's data calls its public API or reads a published view (GRANT SELECT ON billing.invoice_summary TO reporting_app), never the base tables. One cluster, many roles, schema-level grants make the module boundary enforceable instead of conventional.

Microservices ​

What survives: each service has its own database (or schema) and its own role; credentials are per service and short-lived. What changes: there are now dozens of credentials, so issuing them must be automated (Vault dynamic roles, IAM, SPIFFE certificates) and attribution comes for free: the role name in log_line_prefix names the service.

text
1  order-svc  starts -> Vault auth (Kubernetes SA JWT) -> database/creds/orders-app -> role v-k8s-orders-7f3a (TTL 1h)
2  order-svc  connects with sslmode=verify-full; pg_hba: hostssl orders +orders_rw 10.20.0.0/16 scram-sha-256
3  payment-svc never receives orders credentials; it consumes OrderCreated events
4  incident: pgAudit shows v-k8s-orders-7f3a reading customers.email -> the exact pod and deploy
5  revoke: vault lease revoke -prefix database/creds/orders-app -> roles dropped within seconds

Cross-service data flows (events, CDC) carry data out of the database's controls: PII in messages needs the treatment on Messaging Security.

Distributed data: replicas, caches and shards ​

Read replicas copy every row, including those RLS hides, and physical replicas share roles and pg_hba.conf rules only if you copy the files: harden them identically, and remember a replica used by BI is a second front door. Caches (Redis) hold query results outside RLS and grants: key by tenant and protect Redis with ACLs and TLS. Logical replication / CDC ships rows to other systems with the publisher's view, not the subscriber's. Sharded or distributed SQL (Citus, CockroachDB, Spanner) multiplies nodes: every node needs the same TLS, auth and audit configuration, managed as code. Multi-region adds data-residency rules (GDPR transfers) to the threat model. See Replication & Failover.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesSecurity consequence
1× (one app, one DB)Two roles, static secret in a secret managerManual rotation is fine; pgAudit on one box
10× (pooler, replicas, a few services)PgBouncer, read replicas, BI accessPooler must not keep session state (tenant settings per transaction); replicas hardened identically; per-service roles; logs centralised
100× (many services, shards, regions)Hundreds of credentials and nodesDynamic credentials or IAM only; config as code with policy checks; SIEM detections on audit streams; per-region keys and residency

The rule at every size: one credential per actor, as little as it needs, as short-lived as possible, and every use leaves a trace that its holder cannot erase.

Lab ​

Expected output is in comments. Error texts are the ones the PostgreSQL source and docs print. All psql calls run inside the container (docker exec), so only Docker and Go are needed on the host. This lab is a desk-checked script: run it and compare, rather than trusting the comments blindly.

Setup. A PostgreSQL 17 image with pgAudit, and the Go snippets.

bash
mkdir dbsec-lab && cd dbsec-lab
cat > Dockerfile <<'EOF'
FROM postgres:17
RUN apt-get update && apt-get install -y --no-install-recommends postgresql-17-pgaudit && rm -rf /var/lib/apt/lists/*
EOF
docker build -t pg-audit .
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 pg-audit \
  -c shared_preload_libraries=pgaudit -c log_line_prefix='%m [%p] %q%u@%d ' -c log_connections=on
docker exec -it pg psql -U postgres
sql
CREATE DATABASE shop;
\c shop
CREATE ROLE shop_owner NOLOGIN;
CREATE ROLE shop_app LOGIN PASSWORD 'app';
CREATE SCHEMA app AUTHORIZATION shop_owner;
SET ROLE shop_owner;
CREATE TABLE app.products (id bigserial PRIMARY KEY, name text, price_cents bigint, created_at timestamptz DEFAULT now());
CREATE TABLE app.users (id bigserial PRIMARY KEY, email text, password_hash text);
CREATE TABLE app.invoices (id bigserial PRIMARY KEY, tenant_id bigint NOT NULL, amount_cents bigint NOT NULL);
INSERT INTO app.products(name, price_cents) VALUES ('pen', 100), ('book', 1500);
INSERT INTO app.users(email, password_hash) VALUES ('admin@shop.test', 'argon2id$...secret');
INSERT INTO app.invoices(tenant_id, amount_cents) VALUES (1, 100), (1, 200), (2, 999);
RESET ROLE;
GRANT USAGE ON SCHEMA app TO shop_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON app.products, app.invoices TO shop_app;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA app TO shop_app;
ALTER ROLE shop_app SET search_path = app;

Experiment 1: the injectable endpoint. Point the "before" program at the owner-like superuser (as many apps do), then inject.

bash
cd docs/snippets/database/database-security/go
go build -o /tmp/dbsec-before ./before && go build -o /tmp/dbsec-after ./after
DATABASE_URL='postgres://postgres:pg@localhost:5432/shop?search_path=app' /tmp/dbsec-before &
BEFORE_PID=$!
curl -s "localhost:8080/products?q=zzz%27%20UNION%20SELECT%20id,email||%27:%27||password_hash,0%20FROM%20app.users--%20"
# [{"id":1,"name":"admin@shop.test:argon2id$...secret","price_cents":0}]     <- union-based injection
curl -s "localhost:8080/products?q=x&sort=(SELECT%201/0)"
# ERROR: division by zero (SQLSTATE 22012)                                   <- error reaches the client
kill $BEFORE_PID

Experiment 2: the fix. Run "after" as shop_app. It refuses a DSN without verify-full; the lab container has no server certificate, so for the lab only comment out the requireVerifyFull call and rebuild /tmp/dbsec-after, then:

bash
# lab only: rebuild after commenting out requireVerifyFull, because the container has no server certificate
DATABASE_URL='postgres://shop_app:app@localhost:5432/shop?sslmode=disable' /tmp/dbsec-after &
AFTER_PID=$!
curl -s -H 'X-Tenant-ID: 1' "localhost:8080/products?q=zzz%27%20UNION%20SELECT%201,2,3--%20"
# null                                       <- the payload is a search string; nothing matches
curl -s -H 'X-Tenant-ID: 1' "localhost:8080/products?sort=(SELECT%201/0)"
# bad sort                                   <- allowlist
kill $AFTER_PID
docker exec -e PGPASSWORD=app pg psql -h localhost -U shop_app -d shop -c "SELECT * FROM app.users"
# ERROR:  permission denied for table users  (SQLSTATE 42501)  <- even a remaining hole cannot read users

Experiment 3: RLS and four bypass attempts.

sql
-- as postgres
ALTER TABLE app.invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON app.invoices
  USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint);

SET ROLE shop_app;
SELECT count(*) FROM app.invoices;                         -- 0   (no tenant set: fail closed)
SELECT set_config('app.tenant_id', '1', false);
SELECT count(*) FROM app.invoices;                         -- 2
INSERT INTO app.invoices(tenant_id, amount_cents) VALUES (2, 1);
-- ERROR:  new row violates row-level security policy for table "invoices"
RESET ROLE;

-- Bypass attempt A: the owner, without FORCE
SET ROLE shop_owner; SELECT count(*) FROM app.invoices;    -- 3   (owner bypasses)
RESET ROLE; ALTER TABLE app.invoices FORCE ROW LEVEL SECURITY;
SET ROLE shop_owner; SELECT count(*) FROM app.invoices;    -- 2   (now filtered too: tenant 1 is still set in this session)
RESET ROLE;

-- Bypass attempt B: a view owned by the owner
SET ROLE shop_owner;
CREATE VIEW app.all_invoices AS SELECT * FROM app.invoices;
RESET ROLE;
GRANT SELECT ON app.all_invoices TO shop_app;
ALTER TABLE app.invoices NO FORCE ROW LEVEL SECURITY;      -- simulate the common "owner not forced" state
SET ROLE shop_app; SELECT set_config('app.tenant_id', '1', false);
SELECT count(*) FROM app.all_invoices;                     -- 3   (view runs as owner: leak)
RESET ROLE;
ALTER VIEW app.all_invoices SET (security_invoker = true);
SET ROLE shop_app; SELECT count(*) FROM app.all_invoices;  -- 2   (caller's policies apply)
RESET ROLE; ALTER TABLE app.invoices FORCE ROW LEVEL SECURITY;

-- Bypass attempt C: BYPASSRLS
CREATE ROLE reporting LOGIN BYPASSRLS; GRANT USAGE ON SCHEMA app TO reporting; GRANT SELECT ON app.invoices TO reporting;
SET ROLE reporting; SELECT count(*) FROM app.invoices;     -- 3
RESET ROLE; ALTER ROLE reporting NOBYPASSRLS;

-- Bypass attempt D: session-level tenant left on a pooled connection
SET ROLE shop_app;
SELECT set_config('app.tenant_id', '2', false);            -- request for tenant 2, session-level (bug)
-- ... connection returned to the pool, next request for tenant 1 forgets to set it ...
SELECT count(*) FROM app.invoices;                         -- 1   (tenant 2's row served to tenant 1)
BEGIN; SELECT set_config('app.tenant_id', '1', true); SELECT count(*) FROM app.invoices; COMMIT;   -- 2
RESET ROLE;

Experiment 4: search_path trojan.

sql
-- as postgres
CREATE ROLE mallory LOGIN; GRANT CREATE ON SCHEMA public TO mallory;   -- the pre-15 default, recreated
SET ROLE mallory;
CREATE FUNCTION public.lower(varchar) RETURNS text LANGUAGE sql AS $$ SELECT 'pwned'::text $$;
RESET ROLE;
SET search_path = public, pg_catalog;
SELECT lower('ABC'::varchar);        -- pwned   (exact type match in public wins)
SET search_path = pg_catalog, public;
SELECT lower('ABC'::varchar);        -- pwned   (still! different argument types are compared regardless of schema order)
SET search_path = pg_catalog;        -- remove every schema untrusted roles can write to
SELECT lower('ABC'::varchar);        -- abc
REVOKE CREATE ON SCHEMA public FROM mallory; DROP FUNCTION public.lower(varchar);
RESET search_path;

Experiment 5: reading pgAudit.

sql
CREATE EXTENSION pgaudit;
ALTER SYSTEM SET pgaudit.log = 'role, ddl';
ALTER SYSTEM SET pgaudit.role = 'auditor';
SELECT pg_reload_conf();
CREATE ROLE auditor NOLOGIN;
GRANT SELECT (password_hash) ON app.users TO auditor;
GRANT SELECT ON app.users TO shop_app;                     -- ROLE class
SET ROLE shop_app; SELECT email FROM app.users;            -- not logged: auditor has no grant on email
SELECT password_hash FROM app.users; RESET ROLE;           -- OBJECT,READ logged
REVOKE SELECT ON app.users FROM shop_app;
bash
docker logs pg 2>&1 | grep AUDIT
# Shape of the lines you should see (statement ids and exact text are illustrative):
# ... postgres@shop LOG:  AUDIT: SESSION,5,1,ROLE,GRANT,,,GRANT SELECT ON app.users TO shop_app,<not logged>
# ... postgres@shop LOG:  AUDIT: OBJECT,7,1,READ,SELECT,TABLE,app.users,SELECT password_hash FROM app.users,<not logged>
# %u in log_line_prefix is the session user: after SET ROLE it still says postgres,
# which is why logging SET ROLE (pgAudit class MISC_SET) matters for attribution.
# ... postgres@shop LOG:  AUDIT: SESSION,8,1,ROLE,REVOKE,,,REVOKE SELECT ON app.users FROM shop_app,<not logged>

Read each line as: who (log_line_prefix user@db), audit type (SESSION vs OBJECT), statement and sub-statement ids, class, command, object type and name, statement text, parameters. The email read did not appear because object audit follows the auditor role's column grants.

Experiment 6: pg_hba order.

bash
docker exec pg sh -c "sed -i '1i host all all all trust' /var/lib/postgresql/data/pg_hba.conf"
docker exec pg psql -U postgres -c "SELECT pg_reload_conf();"
docker exec -e PGPASSWORD=wrong pg psql -h localhost -U shop_app -d shop -c "SELECT current_user"
#  current_user
# --------------
#  shop_app          <- wrong password accepted: the trust line matched first
docker exec pg psql -U postgres -c "SELECT line_number, type, database, user_name, address, auth_method FROM pg_hba_file_rules;"
docker exec pg sh -c "sed -i '1d' /var/lib/postgresql/data/pg_hba.conf" && docker exec pg psql -U postgres -c "SELECT pg_reload_conf();"
docker exec -e PGPASSWORD=wrong pg psql -h localhost -U shop_app -d shop -c "SELECT 1"
# FATAL:  password authentication failed for user "shop_app"     (SQLSTATE 28P01)

Common misconceptions ​

BeliefReality
"A private network makes the database safe"The compromised app and insiders are already inside; network is one layer of four
"ORMs prevent SQL injection"Only for bound values; raw fragments and dynamic identifiers are still injectable
"Escaping input is as good as binding"Escaping is context- and charset-dependent; OWASP calls it strongly discouraged
"Stored procedures prevent injection"Only if they do not build dynamic SQL; EXECUTE with concatenation is injectable inside the procedure
"sslmode=require is secure"It encrypts but does not authenticate the server; use verify-full
"Enabling RLS protects the table"Owner, superuser and BYPASSRLS still bypass; use FORCE and a non-owner app role
"md5 and SCRAM are equivalent passwords"An md5 hash is a password-equivalent for md5 auth; SCRAM verifiers are not; md5 is deprecated
"log_statement = 'all' is an audit trail"It logs requests, not object-level actions, misses syntax errors, logs bound values and is controlled by the DBA
"Environment variables are a secret store"They leak through logs, crash dumps, /proc, CI output; use a secret manager or IAM
"Encrypted disks protect against breaches"They protect stolen disks; every authenticated session sees plaintext
"Backups are internal, so not a risk"A backup is the whole database with no access controls
"Superuser is needed for monitoring"pg_monitor exists for exactly that
"Staging with prod data is fine because it is internal"Staging is weaker; mask or synthesise

Cheat sheet ​

TopicRemember
Threat modelExternal, compromised app, insider, copy thief: one control each
STRIDESpoofing→auth, Tampering→privilege+TLS, Repudiation→audit, Disclosure→RLS/masking, DoS→timeouts, EoP→search_path/superuser
Authscram-sha-256; no trust/password/md5; certs or IAM for services; peer for local admin
pg_hba.confFirst match wins, no fall-through; hostnossl … reject; check pg_hba_file_rules
RolesOwner NOLOGIN, app DML-only, humans named; WITH INHERIT FALSE, SET TRUE for admin elevation
GrantsRevoke PUBLIC defaults; column grants for PII; ALTER DEFAULT PRIVILEGES
Definer functionsSET search_path = trusted, pg_temp; revoke EXECUTE from PUBLIC in the same transaction
RLSENABLE + FORCE; NULLIF(current_setting(…, true), ''); transaction-local set_config
InjectionBind values; allowlist identifiers; format('%I')/pgx.Identifier; generic errors
TLSverify-full/VERIFY_IDENTITY; ssl_min_protocol_version = TLSv1.2; reload to rotate certs
SecretsVault dynamic roles or IAM tokens; never in git; rotate with pool recycling
AuditpgAudit role, ddl + object audit on PII; logs off-host; superusers need set_user/break-glass
CopiesEncrypted backups with separate keys; masked non-prod
BreachContain, preserve, scope, eradicate, rotate, recover, notify (GDPR 72 h)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Your pg_hba.conf has host all all 10.0.0.0/8 md5 above hostssl shop shop_app 10.0.3.0/24 scram-sha-256. A client from 10.0.3.7 connects. Which line applies and why does it matter? Must-know ​

Answer

Answer: The first line, because the first matching record is used and there is no fall-through. The stricter hostssl + SCRAM line is dead for every 10.x client, so plaintext and md5 are accepted. Put specific lines first and add hostnossl … reject. See pg_hba.conf.

2 — Why is a stolen md5 hash worse than a stolen SCRAM verifier? Important ​

Answer

Answer: With md5 auth the stored hash is all the client needs to answer the challenge, so the hash is a password-equivalent. SCRAM's stored key cannot produce the client proof. See Authentication methods.

3 — The app connects as the table owner, and you enable RLS with a tenant policy. A query without a tenant filter still returns every tenant's rows. Why, and what are two fixes? Must-know ​

Answer

Answer: Table owners bypass RLS unless FORCE ROW LEVEL SECURITY is set. Fix with FORCE, and better, connect as a non-owner role with only DML. See Row-Level Security.

4 — You bind every value with $1, but ?sort= goes into ORDER BY. Is the endpoint safe? Must-know ​

Answer

Answer: No. Identifiers cannot be bind parameters, so ORDER BY injection (including boolean-blind via CASE) is possible. Map the sort key through an allowlist, then quote. See injection classes.

5 — What is second-order SQL injection, and why do bind parameters at insert time not prevent it? Important ​

Answer

Answer: The payload is stored safely, then a different code path reads it and concatenates it into SQL. The second path is the bug; treat data from your own database as untrusted and bind there too. See injection classes.

6 — A SECURITY DEFINER function reads table pwds without schema qualification. How can a low-privilege user abuse it, and what is the fix? Good to know ​

Answer

Answer: By creating a temp table (or a table in a writable schema earlier in search_path) named pwds. Fix with SET search_path = trusted_schema, pg_temp on the function and revoke EXECUTE from PUBLIC. See SECURITY DEFINER.

7 — What does sslmode=require fail to protect against, and which mode does? Must-know ​

Answer

Answer: A man-in-the-middle with any certificate, because it does not verify the server. verify-full checks the chain and host name. See TLS.

8 — Why does the RLS tenant setting need to be transaction-local in a pooled application? Important ​

Answer

Answer: A session-level setting survives on the pooled connection, so the next request that forgets to set it inherits the previous tenant. Transaction-local set_config(…, true) disappears at commit and the policy then fails closed. See Lab experiment 3.

9 — Name two reasons log_statement = 'all' is not an audit log. Important ​

Answer

Answer: It logs what was requested, not the objects touched (dynamic SQL hides names); it misses syntax errors; it logs bound values; superusers can change it. pgAudit adds class/object logging. See Audit logging.

10 — During a suspected breach, why should you not immediately restore from the latest backup? Important ​

Answer

Answer: It destroys evidence and the backup may already contain the attacker's roles, functions or triggers. Contain and preserve first, scope with the audit log, then restore to a point before the first malicious change. See Incident response.

Glossary ​

TermMeaning
Threat modelList of assets, entry points, attackers and the control for each path
STRIDESpoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege (Microsoft SDL)
InsiderSomeone with legitimate access who misuses it or makes a damaging mistake
Stolen backupAny copy (dump, snapshot, replica, staging) obtained outside the database's controls
Defence in depthSeveral independent layers so one failure does not expose data
SCRAM-SHA-256Salted challenge-response password method (RFC 7677); PostgreSQL default since 14
md5 (auth method)Legacy PostgreSQL password method; stored hash is a password-equivalent; deprecated
password_encryptionPostgreSQL setting choosing how new passwords are hashed
caching_sha2_passwordMySQL 8 default SHA-256 authentication plugin
mysql_native_passwordLegacy MySQL plugin; disabled in 8.4, removed in 9.0
Certificate authenticationcert method or clientcert=verify-full: the client's TLS certificate identifies the role
LDAPDirectory-based password check (simple bind or search+bind)
Kerberos / GSSAPITicket-based single sign-on (gss, hostgssenc); SSPI on Windows
IAM database authenticationCloud-issued short-lived token used as the password (RDS: 15 minutes)
PeerLocal-socket method mapping the OS user to the database role
TrustMethod that accepts any connection without credentials
pg_hba.confHost-based authentication rules; first match wins
pg_hba_file_rulesView showing the parsed pg_hba.conf, including errors
hostssl / hostnosslpg_hba.conf types matching TCP with / without TLS
rejectpg_hba.conf method that refuses matching connections
RolePostgreSQL principal; with LOGIN it is a user, without it a group
INHERIT / NOINHERITWhether a member automatically uses a granted role's privileges
SET ROLESwitch the session's current role to one you are a member of
Least privilegeGive each principal only the rights its job needs
GRANT / REVOKEAdd / remove privileges on databases, schemas, tables, columns, functions
Column grantGRANT SELECT (col, …): privilege limited to listed columns
PUBLICPseudo-role meaning every role; receives some default privileges
ALTER DEFAULT PRIVILEGESGrants applied automatically to objects a role creates later
SECURITY DEFINER / SECURITY INVOKERFunction runs with owner's / caller's privileges
search_pathOrdered schema list for resolving unqualified names
pg_tempSession temp schema; must be last in definer functions' search_path
CVE-2018-1058PostgreSQL advisory on like-named objects in public hijacking queries
security_invoker / security_barrierView options: use caller's privileges and RLS / prevent leaky predicate pushdown
Row-level security (RLS)Policies that filter rows per role and command
ENABLE / FORCE ROW LEVEL SECURITYTurn RLS on / apply it to the table owner too
BYPASSRLSRole attribute that skips all RLS policies
USING / WITH CHECKPolicy expressions for visible/targeted rows / new rows
PERMISSIVE / RESTRICTIVEPolicies combined with OR / AND
current_setting / set_configRead / write a configuration parameter, here the tenant id
SQL injectionUntrusted data becoming part of SQL syntax (CWE-89)
CWE-89MITRE's weakness entry for SQL injection
Union-based / error-basedInjection that reads data through UNION / error messages
Blind / time-basedInjection that infers data from response differences / latency
Second-order injectionStored payload that fires when later concatenated elsewhere
Stacked queriesSeveral statements in one injected string
ORDER BY / identifier injectionInjection through column, table or direction names, where bindings do not apply
Parameterized query / prepared statement / bindSQL text with placeholders, values sent separately
quote_ident / format('%I')PostgreSQL identifier quoting; %L/quote_literal for literals
AllowlistFixed map of acceptable identifiers or values
pgx.Identifierpgx type whose Sanitize() quotes identifiers
Stored procedure injectionInjection inside a procedure that builds dynamic SQL with EXECUTE
Mass assignmentRequest fields writing unexpected columns; Laravel #[Fillable] prevents it
whereRaw / orderByRaw / DB::rawLaravel raw fragments; safe only with bindings and allowlists
sslmodelibpq TLS mode: disable, allow, prefer, require, verify-ca, verify-full
verify-fullVerify server cert chain and host name
ssl_min_protocol_versionLowest TLS version the server accepts (default TLSv1.2)
require_secure_transportMySQL setting rejecting non-TLS connections
Certificate rotationReplacing TLS certs; PostgreSQL re-reads on reload, MySQL ALTER INSTANCE RELOAD TLS
Encryption at restData encrypted on disk; see encryption-in-use page
Vault database secrets engineIssues dynamic database credentials with leases; static roles rotate passwords
Dynamic secrets / leaseShort-lived credential and its expiry contract
RotationReplacing a credential on a schedule or after exposure
pgAuditPostgreSQL extension for session and object audit logging
pgaudit.log / pgaudit.roleSession audit classes / role whose grants select object audit
log_statementPostgreSQL statement logging: none, ddl, mod, all
log_connections / log_line_prefixConnection logging / per-line context (user, db, host)
MySQL Enterprise Audit (audit_log)Commercial MySQL audit plugin with JSON filters
Data maskingHiding or replacing sensitive values, dynamically or in copies
Anonymization / pseudonymisationIrreversible removal of identity / reversible replacement with a separate key
PostgreSQL AnonymizerExtension for declarative masking (SECURITY LABEL … MASKED WITH)
listen_addressesPostgreSQL interfaces that accept TCP connections
Security group / bastionCloud firewall rule set / hardened jump host for admin access
SuperuserRole that bypasses all checks; break-glass only
pg_execute_server_program / pg_read_server_filesPredefined roles for COPY … PROGRAM / server file reads
Trusted extensionExtension installable by non-superusers with CREATE on the database
Incident responseDetect, contain, preserve, scope, eradicate, rotate, recover, notify, learn
PCI DSS / GDPR / HIPAA / SOC 2Card data standard / EU data protection law / US health data rule / AICPA attestation
CIS BenchmarkPer-version configuration checklist from the Center for Internet Security
NIST SP 800-53 AUAudit and Accountability control family (AU-2, AU-3, AU-9, AU-11, AU-12)
APP_KEY / encrypted castLaravel encryption key / Eloquent cast encrypting a column value
28P01 / 28000 / 42501PostgreSQL invalid password / authorization specification / insufficient privilege
1045 / 3159MySQL access denied / insecure transport prohibited
Hardening checklistVerifiable list of secure settings and how to check each

References ​

Built by Morteza Negahi