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 for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why a database needs its own security model | Why database security exists |
| Who attacks a database, and STRIDE applied to it | Threat model, STRIDE |
| SCRAM, md5, certificates, LDAP, Kerberos/GSSAPI, IAM, peer | Authentication |
pg_hba.conf line order and its traps | pg_hba.conf |
Roles, groups, INHERIT, SET ROLE, MySQL roles | Roles |
| Schema, table, column grants, default privileges | Least privilege |
SECURITY DEFINER, search_path, CVE-2018-1058, views | Functions and search_path |
RLS policies, FORCE, BYPASSRLS, tenant settings | Row-Level Security |
Classic, blind, second-order, ORDER BY injection | SQL injection |
sslmode=verify-full, TLS versions, rotation | Encryption in transit |
Vault dynamic credentials, IAM tokens, .env | Secrets management |
pgAudit classes, log_statement, MySQL audit | Audit logging |
| Masking prod data for dev and test | Masking and anonymization |
| Backups, network, superuser, extensions | Operational exposure |
| Every engine side by side, knobs and error codes | Per-engine behaviour, Mechanics |
| Fixed code in Go and Laravel | Solving the classic problems |
| Detection, breach runbook, PCI/GDPR/HIPAA/SOC 2 | Monitoring, Incident response, Compliance |
| A checklist to apply today | Hardening checklist |
| Services, replicas, shards | In architecture |
| Reproduce injection, RLS bypass and pgAudit | Lab |
Everything in one minute
The four attackers and what stops each.
| Attacker | Typical path in | What it gets without controls | Control that stops it |
|---|---|---|---|
| External attacker | Port 5432/3306 open to the internet, weak or reused password | Everything the login role can do | Private network, listen_addresses, pg_hba.conf, SCRAM/certs/IAM, TLS |
| Compromised application | SQL injection, remote code execution, leaked .env | Everything the app's role can do, from inside the trusted network | Least-privilege role, bind parameters, RLS, no DDL rights, egress limits |
| Insider (malicious or careless) | Legitimate DBA, developer or support access | Bulk reads, quiet edits, deleted traces | Named accounts, separation of duties, pgAudit to an append-only store, break-glass |
| Thief of a copy | Backup bucket, disk snapshot, dev database with prod data | All data, offline, with unlimited time | Encrypted backups with separate keys, masked non-prod copies, access logs on storage |
The layers, outside in.
| Layer | PostgreSQL | MySQL 8.4 | Failure looks like |
|---|---|---|---|
| Network | listen_addresses, security groups, private subnet | bind_address, security groups | Database reachable from the internet |
| Transport | ssl = on, hostssl, client sslmode=verify-full | require_secure_transport=ON, --ssl-mode=VERIFY_IDENTITY | Password or data sniffed; man-in-the-middle |
| Authentication | pg_hba.conf + scram-sha-256 / cert / ldap / gss / peer | caching_sha2_password, X.509, LDAP (Enterprise), IAM on RDS | trust lines, shared passwords, md5 hashes |
| Authorization | Roles, GRANT, default privileges | Accounts 'user'@'host', roles, GRANT | App connects as owner or superuser |
| Rows | RLS policies | No native RLS (views, app filter) | One tenant reads another's rows |
| Query | Bind parameters, format('%I') | Prepared statements | SQL injection |
| Audit | pgAudit, log_connections, log_statement | Enterprise Audit audit_log, general log | No evidence after a breach |
| Copies | Encrypted backups, masked clones | Same | Breach through a backup or staging |
The ten things to do first.
| # | Do this |
|---|---|
| 1 | No database port on the internet: private subnet, security group allows the app tier only |
| 2 | password_encryption = scram-sha-256, no trust, no md5, no password lines in pg_hba.conf |
| 3 | Clients use sslmode=verify-full (PostgreSQL) or VERIFY_IDENTITY (MySQL) |
| 4 | The application role owns nothing, has no CREATE, no superuser, no BYPASSRLS, only the DML it needs |
| 5 | Every value is a bind parameter; every identifier comes from an allowlist |
| 6 | RLS with FORCE ROW LEVEL SECURITY on tenant tables as the second wall |
| 7 | Credentials from a secret manager (Vault dynamic roles, IAM tokens), rotated, never in git |
| 8 | pgAudit (role, ddl, plus object audit on sensitive tables) shipped off the box |
| 9 | Backups encrypted with a key the database admins cannot read; non-prod gets masked data |
| 10 | Named 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 default | Secure setting |
|---|---|
One postgres/root login shared by app, migrations and humans | One 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 only | Application filter + RLS + constraints |
log_statement = 'all' "for audit" | pgAudit with chosen classes, shipped to an append-only store |
| Prod snapshot restored into staging | Masked 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
- "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.
- "We use an ORM, so we cannot have SQL injection." ORMs bind values, but every raw escape hatch (
DB::raw,whereRaw,orderByRaw,fmt.SprintfintoQuery) 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." - "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 / version | Change | Why it matters |
|---|---|---|
| PostgreSQL 10 | scram-sha-256 authentication added | md5 hashes stolen from pg_authid can be replayed; SCRAM ones cannot |
| MySQL 8.0 | caching_sha2_password becomes the default plugin | Old 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' queries | Origin of today's search_path and "secure schema usage pattern" advice |
| PostgreSQL 14 | password_encryption default becomes scram-sha-256 | New passwords are SCRAM unless you change it |
| PostgreSQL 15 | public schema no longer grants CREATE to PUBLIC | Upgraded clusters keep the old, unsafe grant until you revoke it |
| MySQL 8.4 | mysql_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–19 | MD5 password support deprecated with md5_password_warnings; OAuth authentication method; log_connections takes a list of aspects | Plan 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
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.
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, offlineReal 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.
| Attacker | Capability assumed | Primary control | Detection |
|---|---|---|---|
| External | Network reach, password guessing, known CVEs | Private network, SCRAM/cert/IAM, patching | Failed-auth spikes in logs (28P01, MySQL 1045) |
| Compromised app | Runs arbitrary SQL as the app role | Least privilege, RLS, bind parameters, no file/program privileges | pgAudit READ on sensitive tables, query anomalies, error-rate spikes (42501, syntax errors) |
| Insider | Valid admin access | Named accounts, separation of duties, break-glass superuser | pgAudit ROLE/DDL, alerts on COPY ... TO, off-box logs |
| Copy thief | Offline access to files | Backup encryption with separate keys, masking for non-prod | Storage 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".
| STRIDE | Database threat | Control | PostgreSQL / MySQL knob |
|---|---|---|---|
| Spoofing | Logging in as another role; a fake server collecting passwords | Strong auth, server certificate verification | scram-sha-256, cert, sslmode=verify-full; caching_sha2_password, VERIFY_IDENTITY |
| Tampering | Changing rows through injection or an over-privileged role; editing data in transit | Least privilege, bind parameters, TLS, constraints | GRANT only DML needed, hostssl, require_secure_transport |
| Repudiation | "I never ran that DELETE" with a shared login | Named accounts, audit trail off the box | pgAudit, log_line_prefix with %u %d, MySQL audit_log |
| Information Disclosure | Reading other tenants' rows, columns with PII, backups, error messages | RLS, column grants, masking, encrypted backups, generic errors | CREATE POLICY, GRANT SELECT (col), PostgreSQL Anonymizer, MySQL Enterprise Data Masking |
| Denial of Service | Expensive queries, connection exhaustion, lock-holding transactions | Timeouts, connection limits, pooling | statement_timeout, CONNECTION LIMIT per role, max_user_connections (MySQL) |
| Elevation of Privilege | SECURITY DEFINER + search_path hijack, COPY ... PROGRAM, untrusted extension | Secure search_path, no superuser for apps, vetted extensions | SET search_path = ..., pg_temp, revoke CREATE on public, pg_execute_server_program only for DBAs |
Authentication
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."
| Method | PostgreSQL | MySQL 8.4 | Use it for | Watch out |
|---|---|---|---|---|
| Trust | trust | (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 password | password | mysql_clear_password (LDAP/PAM) | Only inside TLS | Readable on the wire without TLS |
| MD5 challenge | md5 (deprecated) | mysql_native_password (disabled in 8.4, removed in 9.0) | Legacy only | Hash is a password-equivalent |
| SCRAM / SHA-2 | scram-sha-256 | caching_sha2_password (default) | Default for apps and humans | Old drivers; MySQL needs TLS or RSA key exchange |
| Client certificate | cert, or clientcert=verify-full on any hostssl line | REQUIRE X509 / REQUIRE SUBJECT | Services, mTLS meshes | Rotation and revocation (CRL) are your job |
| LDAP | ldap (simple bind or search+bind) | LDAP plugins (Enterprise) | Humans with corporate accounts | Password passes to the server; use TLS (ldaps/ldaptls) |
| Kerberos / GSSAPI / AD | gss (also hostgssenc encryption), sspi | authentication_kerberos (Enterprise) | Single sign-on in AD shops | Keytab handling, clock skew |
| OS user | peer (local socket), ident | auth_socket | Local admin on the database host | Only for the local socket |
| Cloud IAM token | Amazon RDS/Aurora IAM DB auth (rds_iam role), Azure Entra ID, Google Cloud SQL IAM | Same, via plugins on each cloud | Services without stored passwords | Token lifetime, connection rate |
| OAuth 2.0 | oauth (PostgreSQL 18+) | (none built in) | SSO for humans and tools | Bearer token in clear text without TLS |
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 doesReal 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)
-- 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();-- 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: 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.
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| Pitfall | Why it hurts | Fix |
|---|---|---|
| Broad line above a narrow one | The broad line wins; the strict line is dead | Narrow, specific lines first; reject lines before broad allows |
trust for 127.0.0.1 | Anything on the host (a compromised app container sharing the network namespace, an SSH tunnel) is any role | peer on the socket, scram-sha-256 on TCP |
host instead of hostssl | Same line accepts plaintext TCP | hostssl for every remote line; add hostnossl all all 0.0.0.0/0 reject |
0.0.0.0/0 allow lines | Combined with listen_addresses='*' the world can try passwords | Only app subnets; network ACLs as the outer wall |
all all for replication | replication is a special database keyword; all does not match it | Explicit host replication replicator 10.0.5.0/24 scram-sha-256 |
| Edits never reloaded or reloaded with a typo | Old rules keep applying; a parse error on reload keeps the old file | Check SELECT * FROM pg_hba_file_rules WHERE error IS NOT NULL; before reload |
# 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 rejectThe 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.
-- 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-- 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 defaultReal 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.
-- 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| Need | Grant | Do not grant |
|---|---|---|
| Web app | USAGE on schema, DML on its tables, USAGE on sequences | Ownership, CREATE, TRUNCATE, REFERENCES, superuser, BYPASSRLS |
| Migrations (CI) | Owner role via SET ROLE shop_owner, short-lived credentials | Superuser (unless an extension truly needs it) |
| Read-only analytics | SELECT on views or columns without PII | pg_read_all_data on clusters with PII outside RLS |
| Monitoring agent | pg_monitor | Superuser "because the exporter asked for it" |
| Support staff | SELECT on a masked view | Base tables |
| Backups | pg_read_all_data or a dedicated owner, plus REPLICATION for physical | Interactive 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."
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 SUPERUSERReal 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:
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 everythingViews 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.
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.
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 path | Who | Fix |
|---|---|---|
| Table owner | App connects as shop_owner | FORCE ROW LEVEL SECURITY; better, app never owns tables |
Superuser / BYPASSRLS | Admin tools, backup roles, "temporary" grants | No superuser for apps; audit BYPASSRLS grants (SELECT rolname FROM pg_roles WHERE rolbypassrls) |
| Default view | View owned by the table owner | security_invoker = true on views over RLS tables |
SECURITY DEFINER function | Owned by the table owner | Filter inside the function, or make it SECURITY INVOKER |
| Session-level tenant setting with pooling | PgBouncer transaction mode, Laravel Octane | Transaction-local set_config(…, true) per request |
| Tenant value from the client | X-Tenant-ID trusted as-is | Derive tenant from the authenticated identity on the server |
| Referential checks | Unique/foreign keys reveal existence | Include 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
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 / API | Placeholder | Server-side separation |
|---|---|---|
Go database/sql + pgx stdlib | $1 | Yes (extended protocol) |
| Go pgx native | $1, or pgx.NamedArgs with @name | Yes by default (QueryExecModeCacheStatement); simple protocol interpolates client-side |
Go go-sql-driver/mysql | ? | Yes unless interpolateParams=true |
| Laravel query builder / Eloquent | ? or :name via PDO | PDO prepares; MySQL emulates by default, still escaped by PDO |
JDBC PreparedStatement | ? | Yes |
| psql / plpgsql | $1 with EXECUTE … USING | Yes |
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):
| Class | Payload idea | What it gets | Notes |
|---|---|---|---|
| Classic / tautology | ' OR '1'='1 | All rows of the query | Login bypass, data dump |
| Union-based | ' UNION SELECT email, password_hash FROM users-- | Other tables in the same response | Needs same column count and types |
| Error-based | ' AND 1=CAST((SELECT password_hash FROM users LIMIT 1) AS int)-- | Data inside the error message | Why errors must not reach the client |
| Boolean blind | ' AND substr((SELECT …),1,1)='a'-- | One bit per request from a changed response | Fully automated by tools |
| Time-based blind | '; SELECT pg_sleep(5)-- or ' AND 1=(SELECT 1 FROM pg_sleep(5))-- | One bit per request from latency | MySQL: SLEEP(5), BENCHMARK() |
| Stacked queries | '; DROP TABLE orders;-- | Any statement the role may run | PostgreSQL simple protocol allows several statements; extended protocol does not |
| Second-order | Name stored as x'); DELETE FROM …--, later concatenated by a batch job | Fires in a different code path, often with more privileges | Every input source, including the database itself, is untrusted |
| Out-of-band | COPY (SELECT …) TO PROGRAM 'curl …', MySQL LOAD_FILE/INTO OUTFILE, SQL Server xp_cmdshell | Exfiltration or OS commands | Blocked by not having file/program privileges |
Identifier / ORDER BY | ?sort=(CASE WHEN … THEN name ELSE price END) | Blind data via sort order | Bindings do not apply; allowlist |
LIKE wildcard | q=% or q=_%_%_%… | Full scans, data enumeration | Escape %, _, \ in the bound value |
| Stored procedure / dynamic SQL | EXECUTE 'SELECT … ' || p_name inside PL/pgSQL, PREPARE stmt FROM CONCAT(…) in MySQL | Same as classic, hidden from app review | format('%I', …)/%L, EXECUTE … USING |
| ORM raw fragments | whereRaw("x = '$v'"), orderByRaw($request->sort), DB::raw | Same as classic | Bind inside raw fragments; allowlist identifiers |
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
-- 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'// 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()// 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 setting | Encrypts | Verifies CA | Verifies host | Stops MITM |
|---|---|---|---|---|
disable / MySQL DISABLED | No | No | No | No |
prefer (libpq, Laravel default) / MySQL PREFERRED | If server offers | No | No | No |
require / REQUIRED | Yes | No | No | No |
verify-ca / VERIFY_CA | Yes | Yes | No | Only with a private CA |
verify-full / VERIFY_IDENTITY | Yes | Yes | Yes | Yes |
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# 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: 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.pemEncryption 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
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| Approach | Lifetime | Leak impact | Operational cost |
|---|---|---|---|
| Password in source code | Forever | Everyone with repo access, forever | None, until the breach |
.env / env var from CI secret | Until someone rotates | Anyone who sees env or logs | Low; rotation is manual |
| Secret manager static secret (AWS Secrets Manager, Vault KV) with rotation | Rotation interval | Until next rotation | Medium; app must reload |
| Vault dynamic role | Lease TTL (minutes–hours) | One service instance, until lease end | Medium; app must renew or reconnect |
| IAM / Entra / Cloud SQL IAM token | 15 minutes (RDS) | Token only | Low with SDK helpers; connection-rate limits |
| Client certificate from internal CA | Cert lifetime (days) | Until expiry or CRL | Needs 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."
-- 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 log | PostgreSQL | MySQL 8.4 | Why |
|---|---|---|---|
| Logins, failures | log_connections, failed auth always logged | audit_log connection events, connection_control plugin | Brute force, credential stuffing |
| Privilege changes | pgAudit ROLE | Enterprise Audit filter on GRANT | Persistence after compromise |
| Schema changes | pgAudit DDL | Enterprise Audit, log_bin | Tampering, backdoors (triggers, functions) |
| Sensitive reads | Object audit via pgaudit.role | Enterprise Audit filters per table | PII exfiltration |
| Admin sessions | Per-role pgaudit.log = 'all' for humans | Filter by user | Insider actions |
| Errors | log_min_error_statement = error | Error log | Injection 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.
-- 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.
-- 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
| Feature | PostgreSQL | MySQL 8.4 / InnoDB | SQL Server | Oracle | SQLite | MongoDB | CockroachDB | Redis |
|---|---|---|---|---|---|---|---|---|
| Default password auth | SCRAM-SHA-256 | caching_sha2_password | SQL logins / Windows (Kerberos) | Password verifiers / Kerberos | None (file permissions) | SCRAM-SHA-256 | SCRAM-SHA-256 | ACL users (requirepass legacy) |
| Host-based rules | pg_hba.conf | 'user'@'host' | Firewall + logins | sqlnet.ora, listener | OS | net.bindIp, IP allowlists | hba.conf-like cluster setting | bind, protected-mode |
| Roles / groups | Yes, with INHERIT/SET | Yes (8.0+) | Server + database roles | Roles | No | Built-in + custom roles | Yes | ACL categories |
| Column grants | Yes | Yes | Yes | Yes | No | Projection via views | Yes | No |
| Row-level security | RLS policies | No | RLS predicates | VPD / DBMS_RLS | No | No (views, $redact) | Yes (v25.2+) | No |
| Audit | pgAudit, logs | Enterprise Audit (audit_log); Percona/MariaDB plugins | SQL Server Audit | Unified Auditing | None | Enterprise auditLog | Audit logging per table | ACL LOG |
| TLS server verify knob | sslmode=verify-full | --ssl-mode=VERIFY_IDENTITY | Encrypt=Strict, TrustServerCertificate=false | TCPS + wallet | n/a | tls=true + CA | sslmode=verify-full | --tls + CA |
| Masking | PostgreSQL Anonymizer (extension) | Enterprise Data Masking | Dynamic Data Masking | Data Redaction | No | Atlas / app | No | No |
Defaults that bite
| Product | Default | Risk | Change to |
|---|---|---|---|
libpq / Laravel pgsql | sslmode=prefer | Silent fallback to plaintext, no server check | verify-full |
Docker postgres image | POSTGRES_HOST_AUTH_METHOD unset → SCRAM, but trust used in many tutorials | trust for all hosts | Never set trust |
| PostgreSQL ≤ 14 clusters (and upgrades) | CREATE on public to PUBLIC | CVE-2018-1058-style trojans | REVOKE CREATE ON SCHEMA public FROM PUBLIC |
| PostgreSQL functions | EXECUTE to PUBLIC | SECURITY DEFINER reachable by all | Revoke in the same transaction as CREATE FUNCTION |
| MySQL | local_infile off in 8.0+, but often re-enabled | Client-side file read | Keep off |
| PDO MySQL | ATTR_EMULATE_PREPARES = true | Client-side interpolation (still escaped) | false where driver supports it |
| MongoDB < 3.6 | Bound to all interfaces, no auth | Anyone on the network reads and deletes data | bindIp, security.authorization: enabled |
| Redis | protected-mode yes but no password if bound | Unauthenticated CONFIG SET dir → file write | ACLs, TLS, private network |
Mechanics
Every knob in one table Must-know
| Knob | Where | Secure value | Notes |
|---|---|---|---|
listen_addresses | postgresql.conf | Private IP(s) only | Restart required |
password_encryption | postgresql.conf | scram-sha-256 | Affects new passwords only |
md5_password_warnings | postgresql.conf (18+) | on | Warns on md5 use |
ssl, ssl_min_protocol_version | postgresql.conf | on, TLSv1.2 or TLSv1.3 | Reload re-reads cert files |
ssl_ca_file, ssl_crl_file | postgresql.conf | Internal CA, CRL | For cert / clientcert |
log_connections, log_disconnections | postgresql.conf | On | Evidence for incidents |
log_line_prefix | postgresql.conf | '%m [%p] %q%u@%d %r %a ' | User, db, host, app in every line |
log_statement | postgresql.conf | ddl (pgAudit for the rest) | all logs bound values |
shared_preload_libraries | postgresql.conf | pgaudit (plus others) | Restart required |
pgaudit.log, pgaudit.role | postgresql.conf / role | role, ddl + object audit | Superuser-only to change |
row_security | session | on (default) | off makes filtered queries error |
search_path | role / function | "$user", app for apps; pg_temp last in definer functions | Schema-qualify in privileged code |
statement_timeout, idle_in_transaction_session_timeout | role | Seconds, not unlimited | DoS and lock-holding |
require_secure_transport | MySQL | ON | Error 3159 for plaintext |
tls_version | MySQL | TLSv1.2,TLSv1.3 | ALTER INSTANCE RELOAD TLS |
local_infile, secure_file_priv | MySQL | OFF, a dedicated directory or NULL | File read/write |
default_authentication_plugin / authentication_policy | MySQL | caching_sha2_password | 8.4 uses authentication_policy |
Error codes you will see Important
| Code | Engine | Meaning | Usually means |
|---|---|---|---|
28000 invalid_authorization_specification | PostgreSQL | no pg_hba.conf entry for host … or reject | Wrong network, wrong TLS mode, missing line |
28P01 invalid_password | PostgreSQL | password authentication failed for user "…" | Wrong password, expired VALID UNTIL, brute force |
42501 insufficient_privilege | PostgreSQL | permission denied for table …; also new row violates row-level security policy for table "…" | Missing grant, or an RLS WITH CHECK failure |
42601 syntax_error | PostgreSQL | Syntax error | In production traffic: injection probing |
57014 query_canceled | PostgreSQL | statement_timeout hit | Slow or time-based blind injection |
1045 ER_ACCESS_DENIED_ERROR (28000) | MySQL | Access denied for user '%s'@'%s' (using password: %s) | Wrong password or host part |
1142 ER_TABLEACCESS_DENIED_ERROR | MySQL | %s command denied to user … | Missing table grant |
1227 ER_SPECIFIC_ACCESS_DENIED_ERROR | MySQL | Needs a privilege like SUPER | Admin operation from app role |
3159 ER_SECURE_TRANSPORT_REQUIRED | MySQL | Insecure transport prohibited | Client without TLS |
How a statement is authorized
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 logSolving the classic problems
The injectable endpoint
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Bind parameters | $1/? and arguments; builder methods | Removes the class for values | Does not cover identifiers |
| Allowlist identifiers | Map client keys to fixed column names | Small, reviewable | Every new sort key is a code change (good) |
| Quote identifiers | format('%I'), pgx.Identifier.Sanitize, Laravel grammar | Correct quoting | Quoting is not authorization: still allowlist |
| Least-privilege role | No DDL, no file/program, no other schemas | Limits damage of any remaining hole | Needs a separate migration role |
| Generic errors | Log details, return "internal error" | Kills error-based injection | Needs good server logs |
| WAF / RASP | Pattern blocking at the edge | Catches noise and scanners | Bypassable; never the fix |
Go, before (compiles, runs, and is injectable through q and sort):
// 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):
// 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
// 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
// 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Split roles | shop_owner (NOLOGIN, migrations via SET ROLE), shop_app (DML), shop_ro | Injection cannot DROP, ALTER, COPY … PROGRAM | Two connection configs (app vs migrate) |
| Default privileges | ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner … | New tables are usable without manual grants | Must be set per creating role |
| Separate Laravel connection for migrations | DB_USERNAME for app, migrate --database=pgsql_owner in CI | App never holds DDL rights | CI secret for the owner |
// 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 --forceA tenant reads another tenant's rows
| Solution | How | Advantage | Cost |
|---|---|---|---|
| App-level scope | Global scope / repository adds tenant_id | Simple, portable | One missed query leaks |
| RLS behind it | Policy on current_setting('app.tenant_id'), FORCE | Missed query returns nothing | PostgreSQL-specific; setting must be per transaction |
| Tenant in keys | Composite PK/FK (tenant_id, id) | Cross-tenant joins impossible | Wider indexes |
| Separate schema/database | Per-tenant isolation | Strongest | Operations at scale (Multi-Tenancy) |
// 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
// 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
-- 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
// 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
| Signal | Source | Likely cause | Response |
|---|---|---|---|
Burst of 28P01 / MySQL 1045 | Server log | Brute force, credential stuffing | Block source, check pg_hba.conf, rotate |
| Successful login from a new IP / ASN / hour | log_connections, cloud logs | Stolen credentials | Verify, kill session (pg_terminate_backend), rotate |
42601 syntax errors from the app role | Server log, APM | Injection probing | Find the endpoint from application_name/trace id |
Many 57014 or very long pg_sleep | pg_stat_activity, log | Time-based blind injection | Same; add statement_timeout |
SELECT volume on PII tables jumps | pgAudit object audit, pg_stat_user_tables.seq_scan | Exfiltration | Throttle, investigate role |
New role, GRANT, ALTER ROLE … SUPERUSER | pgAudit ROLE | Persistence | Page immediately |
| New function, trigger, extension | pgAudit DDL | Backdoor | Diff schema against migrations |
COPY … TO, pg_read_file | pgAudit READ/FUNCTION | Bulk export | Page |
| Connections from outside app subnet | VPC flow logs | Exposure | Fix security group |
-- 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.
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| Step | PostgreSQL command / artefact |
|---|---|
| Lock a role | ALTER ROLE shop_app NOLOGIN; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'shop_app'; |
| List recent role changes | Search pgAudit CLASS=ROLE in the log store |
| Find rogue objects | SELECT 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 data | PITR to a timestamp before the first malicious statement (Backup, PITR & DR) |
Compliance mapping
| Control on this page | PCI DSS v4.x | GDPR | HIPAA Security Rule (45 CFR 164.312) | SOC 2 (Trust Services Criteria) |
|---|---|---|---|---|
| Least privilege, roles, RLS | Restrict access to cardholder data by business need to know | Art. 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 superuser | Identify users and authenticate access | Art. 32 | Unique user identification, person or entity authentication | Logical access, user provisioning |
TLS verify-full | Protect cardholder data with strong cryptography during transmission | Art. 32 "encryption of personal data" | (e)(1) Transmission security | Encryption in transit |
| Encryption at rest, backup encryption | Protect stored account data | Art. 32 | Encryption and decryption (Addressable) | Encryption at rest |
| pgAudit, log protection | Log and monitor all access to system components and cardholder data | Art. 32 ability to test and evaluate; Art. 33 breach evidence | (b) Audit controls: "record and examine activity" | Monitoring of controls, logging |
| Masking for non-prod | Do not use live PANs in test environments | Art. 32 "pseudonymisation"; data minimisation | Minimum necessary | Confidentiality |
| Incident response | Incident response plan | Art. 33 notification within 72 hours | Security incident procedures | Incident response |
| Hardening, patching | Secure configurations, vulnerability management | Art. 32 | Risk management | Change 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
| Area | Check | How to verify |
|---|---|---|
| Network | No public IP; SG allows app subnet only | Cloud console; nmap from outside fails |
| Network | listen_addresses is not * on a host with a public interface | SHOW listen_addresses; |
| Auth | No trust, password, md5 lines | SELECT * FROM pg_hba_file_rules WHERE auth_method IN ('trust','password','md5'); |
| Auth | No md5 hashes stored | SELECT rolname FROM pg_authid WHERE rolpassword LIKE 'md5%'; |
| Auth | hostnossl … reject present | pg_hba_file_rules |
| TLS | Server ssl=on, min TLS 1.2; clients verify-full | SHOW ssl; SELECT * FROM pg_stat_ssl; |
| Roles | App role not owner, not superuser, no BYPASSRLS, no CREATEROLE | pg_roles query above |
| Schema | CREATE on public revoked | SELECT has_schema_privilege('public', 'public', 'CREATE'); |
| Functions | SECURITY DEFINER functions set search_path | SELECT proname FROM pg_proc WHERE prosecdef AND proconfig IS NULL; |
| RLS | Tenant tables have RLS enabled and forced | SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class WHERE relkind='r'; |
| Views | Views over RLS tables use security_invoker | SELECT relname, reloptions FROM pg_class WHERE relkind='v'; |
| Extensions | Only reviewed extensions; no untrusted languages for apps | SELECT * FROM pg_extension; |
| Audit | pgAudit loaded, logs shipped off-host | SHOW shared_preload_libraries; SHOW pgaudit.log; |
| Secrets | No credentials in repo history; rotation ≤ 90 days or dynamic | gitleaks; Vault lease TTLs |
| Copies | Backups encrypted, restore tested, non-prod masked | Backup tool config; staging sample |
| Patching | Minor version current | SELECT version(); vs release notes |
| MySQL | require_secure_transport=ON, no mysql_native_password, FILE granted to nobody, local_infile=OFF | SHOW GLOBAL VARIABLES, mysql.user |
Choosing controls
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Single app, single PostgreSQL | Split owner/app roles, bind parameters, verify-full, private network | pgAudit role, ddl | Covers the top three attackers cheaply |
| Multi-tenant SaaS (shared tables) | App scope + RLS FORCE + transaction-local tenant | (tenant_id, id) keys, restrictive policy | A missed filter is the most likely leak |
| Regulated data (PCI, HIPAA) | Column grants, encryption (encryption-in-use), object audit | Masked non-prod, quarterly access review | Auditors ask for evidence, not intentions |
| Many microservices | One role per service, Vault dynamic creds or IAM | Service mesh mTLS + cert auth | Blast radius and attribution per service |
| Managed cloud (RDS, Cloud SQL, Azure) | IAM auth, no public access, provider audit flags | Secrets Manager rotation | Uses the platform's identity and logs |
| BI / analysts | Read replica, shop_ro on masked views | Per-person accounts via SSO/LDAP | Humans should not hold the app's role |
| Legacy app you cannot rewrite | Least privilege + WAF + pgAudit object audit | statement_timeout, alert on 42601 | Contain what you cannot fix yet |
| MySQL shop | caching_sha2_password, roles, REQUIRE SSL, views for tenant filtering | Percona/MariaDB audit plugin or Enterprise Audit | No 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.
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 secondsCross-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×
| Load | What changes | Security consequence |
|---|---|---|
| 1× (one app, one DB) | Two roles, static secret in a secret manager | Manual rotation is fine; pgAudit on one box |
| 10× (pooler, replicas, a few services) | PgBouncer, read replicas, BI access | Pooler 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 nodes | Dynamic 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.
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 postgresCREATE 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.
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_PIDExperiment 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:
# 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 usersExperiment 3: RLS and four bypass attempts.
-- 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.
-- 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.
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;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.
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
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
| Threat model | External, compromised app, insider, copy thief: one control each |
| STRIDE | Spoofing→auth, Tampering→privilege+TLS, Repudiation→audit, Disclosure→RLS/masking, DoS→timeouts, EoP→search_path/superuser |
| Auth | scram-sha-256; no trust/password/md5; certs or IAM for services; peer for local admin |
pg_hba.conf | First match wins, no fall-through; hostnossl … reject; check pg_hba_file_rules |
| Roles | Owner NOLOGIN, app DML-only, humans named; WITH INHERIT FALSE, SET TRUE for admin elevation |
| Grants | Revoke PUBLIC defaults; column grants for PII; ALTER DEFAULT PRIVILEGES |
| Definer functions | SET search_path = trusted, pg_temp; revoke EXECUTE from PUBLIC in the same transaction |
| RLS | ENABLE + FORCE; NULLIF(current_setting(…, true), ''); transaction-local set_config |
| Injection | Bind values; allowlist identifiers; format('%I')/pgx.Identifier; generic errors |
| TLS | verify-full/VERIFY_IDENTITY; ssl_min_protocol_version = TLSv1.2; reload to rotate certs |
| Secrets | Vault dynamic roles or IAM tokens; never in git; rotate with pool recycling |
| Audit | pgAudit role, ddl + object audit on PII; logs off-host; superusers need set_user/break-glass |
| Copies | Encrypted backups with separate keys; masked non-prod |
| Breach | Contain, preserve, scope, eradicate, rotate, recover, notify (GDPR 72 h) |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Threat model | List of assets, entry points, attackers and the control for each path |
| STRIDE | Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege (Microsoft SDL) |
| Insider | Someone with legitimate access who misuses it or makes a damaging mistake |
| Stolen backup | Any copy (dump, snapshot, replica, staging) obtained outside the database's controls |
| Defence in depth | Several independent layers so one failure does not expose data |
| SCRAM-SHA-256 | Salted 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_encryption | PostgreSQL setting choosing how new passwords are hashed |
caching_sha2_password | MySQL 8 default SHA-256 authentication plugin |
mysql_native_password | Legacy MySQL plugin; disabled in 8.4, removed in 9.0 |
| Certificate authentication | cert method or clientcert=verify-full: the client's TLS certificate identifies the role |
| LDAP | Directory-based password check (simple bind or search+bind) |
| Kerberos / GSSAPI | Ticket-based single sign-on (gss, hostgssenc); SSPI on Windows |
| IAM database authentication | Cloud-issued short-lived token used as the password (RDS: 15 minutes) |
| Peer | Local-socket method mapping the OS user to the database role |
| Trust | Method that accepts any connection without credentials |
pg_hba.conf | Host-based authentication rules; first match wins |
pg_hba_file_rules | View showing the parsed pg_hba.conf, including errors |
hostssl / hostnossl | pg_hba.conf types matching TCP with / without TLS |
reject | pg_hba.conf method that refuses matching connections |
| Role | PostgreSQL principal; with LOGIN it is a user, without it a group |
INHERIT / NOINHERIT | Whether a member automatically uses a granted role's privileges |
SET ROLE | Switch the session's current role to one you are a member of |
| Least privilege | Give each principal only the rights its job needs |
GRANT / REVOKE | Add / remove privileges on databases, schemas, tables, columns, functions |
| Column grant | GRANT SELECT (col, …): privilege limited to listed columns |
PUBLIC | Pseudo-role meaning every role; receives some default privileges |
ALTER DEFAULT PRIVILEGES | Grants applied automatically to objects a role creates later |
SECURITY DEFINER / SECURITY INVOKER | Function runs with owner's / caller's privileges |
search_path | Ordered schema list for resolving unqualified names |
pg_temp | Session temp schema; must be last in definer functions' search_path |
| CVE-2018-1058 | PostgreSQL advisory on like-named objects in public hijacking queries |
security_invoker / security_barrier | View 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 SECURITY | Turn RLS on / apply it to the table owner too |
BYPASSRLS | Role attribute that skips all RLS policies |
USING / WITH CHECK | Policy expressions for visible/targeted rows / new rows |
PERMISSIVE / RESTRICTIVE | Policies combined with OR / AND |
current_setting / set_config | Read / write a configuration parameter, here the tenant id |
| SQL injection | Untrusted data becoming part of SQL syntax (CWE-89) |
| CWE-89 | MITRE's weakness entry for SQL injection |
| Union-based / error-based | Injection that reads data through UNION / error messages |
| Blind / time-based | Injection that infers data from response differences / latency |
| Second-order injection | Stored payload that fires when later concatenated elsewhere |
| Stacked queries | Several statements in one injected string |
ORDER BY / identifier injection | Injection through column, table or direction names, where bindings do not apply |
| Parameterized query / prepared statement / bind | SQL text with placeholders, values sent separately |
quote_ident / format('%I') | PostgreSQL identifier quoting; %L/quote_literal for literals |
| Allowlist | Fixed map of acceptable identifiers or values |
pgx.Identifier | pgx type whose Sanitize() quotes identifiers |
| Stored procedure injection | Injection inside a procedure that builds dynamic SQL with EXECUTE |
| Mass assignment | Request fields writing unexpected columns; Laravel #[Fillable] prevents it |
whereRaw / orderByRaw / DB::raw | Laravel raw fragments; safe only with bindings and allowlists |
sslmode | libpq TLS mode: disable, allow, prefer, require, verify-ca, verify-full |
verify-full | Verify server cert chain and host name |
ssl_min_protocol_version | Lowest TLS version the server accepts (default TLSv1.2) |
require_secure_transport | MySQL setting rejecting non-TLS connections |
| Certificate rotation | Replacing TLS certs; PostgreSQL re-reads on reload, MySQL ALTER INSTANCE RELOAD TLS |
| Encryption at rest | Data encrypted on disk; see encryption-in-use page |
| Vault database secrets engine | Issues dynamic database credentials with leases; static roles rotate passwords |
| Dynamic secrets / lease | Short-lived credential and its expiry contract |
| Rotation | Replacing a credential on a schedule or after exposure |
| pgAudit | PostgreSQL extension for session and object audit logging |
pgaudit.log / pgaudit.role | Session audit classes / role whose grants select object audit |
log_statement | PostgreSQL statement logging: none, ddl, mod, all |
log_connections / log_line_prefix | Connection logging / per-line context (user, db, host) |
MySQL Enterprise Audit (audit_log) | Commercial MySQL audit plugin with JSON filters |
| Data masking | Hiding or replacing sensitive values, dynamically or in copies |
| Anonymization / pseudonymisation | Irreversible removal of identity / reversible replacement with a separate key |
| PostgreSQL Anonymizer | Extension for declarative masking (SECURITY LABEL … MASKED WITH) |
listen_addresses | PostgreSQL interfaces that accept TCP connections |
| Security group / bastion | Cloud firewall rule set / hardened jump host for admin access |
| Superuser | Role that bypasses all checks; break-glass only |
pg_execute_server_program / pg_read_server_files | Predefined roles for COPY … PROGRAM / server file reads |
| Trusted extension | Extension installable by non-superusers with CREATE on the database |
| Incident response | Detect, contain, preserve, scope, eradicate, rotate, recover, notify, learn |
| PCI DSS / GDPR / HIPAA / SOC 2 | Card data standard / EU data protection law / US health data rule / AICPA attestation |
| CIS Benchmark | Per-version configuration checklist from the Center for Internet Security |
| NIST SP 800-53 AU | Audit and Accountability control family (AU-2, AU-3, AU-9, AU-11, AU-12) |
APP_KEY / encrypted cast | Laravel encryption key / Eloquent cast encrypting a column value |
28P01 / 28000 / 42501 | PostgreSQL invalid password / authorization specification / insufficient privilege |
1045 / 3159 | MySQL access denied / insecure transport prohibited |
| Hardening checklist | Verifiable list of secure settings and how to check each |
References
- OWASP Cheat Sheet Series: SQL Injection Prevention, Query Parameterization, Database Security
- MITRE: CWE-89: Improper Neutralization of Special Elements used in an SQL Command
- Microsoft: Threat Modeling Tool threats (STRIDE)
- PostgreSQL documentation (current, 19): The pg_hba.conf File, Authentication Methods, Password Authentication, Certificate Authentication, LDAP, GSSAPI, Peer, User Name Maps, OAuth, pg_hba_file_rules, Role Attributes, Role Membership, Predefined Roles, Privileges, GRANT, ALTER DEFAULT PRIVILEGES, Schemas, CREATE FUNCTION, CREATE VIEW, CREATE EXTENSION, Row Security Policies, CREATE POLICY, Secure TCP/IP Connections with SSL, libpq SSL Support, Connections and Authentication settings, Error Reporting and Logging, PL/pgSQL dynamic commands, String functions, Error codes
- PostgreSQL wiki: A Guide to CVE-2018-1058: Protect Your Search Path; PostgreSQL source: execMain.c, auth.c
- pgAudit: README; PostgreSQL Anonymizer: documentation
- MySQL 8.4 Reference Manual (read via web.archive.org): Caching SHA-2 Pluggable Authentication, Native Pluggable Authentication, Using Roles, Password Management, Using Encrypted Connections, MySQL Enterprise Audit, MySQL Enterprise Data Masking, Security Guidelines, Server Error Reference
- HashiCorp Vault: Database secrets engine, PostgreSQL database secrets engine
- AWS: IAM database authentication for MariaDB, MySQL, and PostgreSQL
- NIST SP 800-53 Rev. 5 AU family (summary): csf.tools AU; CIS: PostgreSQL Benchmarks
- Compliance: GDPR Art. 32, GDPR Art. 33, 45 CFR 164.312 (eCFR), PCI DSS (PCI SSC), AICPA SOC 2
- Laravel 13: Database: Getting Started, Query Builder, Eloquent (mass assignment), Eloquent: Mutators & Casting (encrypted casts), laravel/laravel config/database.php
- Go: Avoiding SQL injection risk,
database/sql, pgx v5