Report schema security findings
Run ptah schema security over a live database to review privileges, owners, roles and tables with no row policy, and gate a pull request on the result.
Edge documents the current development build and may describe unreleased behavior. To use those commands, build Ptah from master. For an installed release, select its version in the header.
ptah schema security reads a live database and reports findings over what the
schema declares about access: privileges granted to PUBLIC, tables reachable
by a role with no row-level security (RLS) enabled, routines that run with their
owner’s privileges, objects owned by a role that can log in, overlapping and
empty role memberships, privileges held on objects nothing was observed using,
and roles that can read or change most of the database’s relations.
To match the database engine and installed extension versions against
published advisories, run
ptah db vulnerabilities. These commands
assess separate evidence, and neither gives a general security clearance.
The command refuses a report when the read leaves roles, grants, memberships
or object owners uninspected. When the read does not establish whether an
owner can log in, OWN01 leaves the objects of that owner unchecked and names
the owner under Not checked here:. Unknown access metadata cannot establish
that the database has no security findings.
Each finding is an observation paired with a suggestion, not a verdict. Use the command to put those observations in front of a person, and to gate a pull request once you have decided which of them should never appear again.
The live-database command prints the complete report. When you need to locate
the same class of findings on an entity diagram, ptah viz --security applies
the rules to Go-annotated models and marks the table nodes it can attach to:
Real `ptah viz --security` output connects findings to tables without hiding findings that have no table node.
What to notice: Orders shows two warning codes, products shows an informational code, and the DOT comment retains the SECURITY DEFINER routine finding; the command report remains the complete answer.
Reproduce this output
ptah viz --root-dir docs/site/fixtures/schema-ui/internal/models --format svg --include-columns --security --dialect postgres > schema-security.svgAmber is warning, blue is info, and neutral nodes have no attached finding.
See Visualize the schema
for the Mermaid limitation and the complete diagram-output contract.
Prerequisites: an installed ptah binary (Install Ptah)
and the URL of the database to read. The command registers --db-url,
--fail-on, --format, --reach-error, --reach-warn, --role-usage and
--schemas, and nothing else: there
is no --dialect and no schema-source flag, so it reads a live database and
takes its dialect from the connection. See
Database URLs and dev databases
for the URL forms --db-url accepts.
Starting state
Section titled “Starting state”Findings need an engine that models roles and grants. The examples run against
a PostgreSQL database whose connecting role is ptah. Seed it:
CREATE TABLE customers ( id integer PRIMARY KEY, email text NOT NULL);
CREATE TABLE orders ( id integer PRIMARY KEY, customer_id integer NOT NULL REFERENCES customers (id), total_cents integer NOT NULL DEFAULT 0);
CREATE ROLE reporting LOGIN PASSWORD 'reporting';GRANT SELECT ON orders TO reporting;GRANT SELECT ON customers TO PUBLIC;
CREATE FUNCTION bump(n integer) RETURNS integer LANGUAGE sql SECURITY DEFINER AS $$ SELECT n + 1 $$;Put that database’s URL in DATABASE_URL and substitute your own throughout.
The role names in the output below are the ones this seed creates; a database
whose owning role has another name shows that name instead.
Read the findings
Section titled “Read the findings”ptah schema security --db-url "$DATABASE_URL"Expected output includes:
CODE SEVERITY OBJECT FINDINGOWN01 info role ptah role ptah can log in and owns 2 object(s), so whoever holds its password can drop or alter themPRV01 info table customers table customers is granted to a role and has no row-level security enabled, so a granted role reads every rowPRV01 info table orders table orders is granted to a role and has no row-level security enabled, so a granted role reads every rowPRV02 info routine bump routine bump runs as its owner, so every caller that may execute it acts with the owner's privilegesPRV03 warning table customers privileges on table customers are granted to PUBLIC, which every role holdsroles/read-reach warning role ptah role ptah can read 2 of 2 relations (100%), above the warning threshold of 50%roles/read-reach warning role reporting role reporting can read 2 of 2 relations (100%), above the warning threshold of 50%roles/write-reach warning role ptah role ptah can change the rows of 2 of 2 relations (100%), above the warning threshold of 50%
Suggested: OWN01 ptah: own them with a role that cannot log in and grant membership in it instead PRV01 customers: enable row-level security and declare a policy, or record that the whole table is meant to be readable by these roles PRV01 orders: enable row-level security and declare a policy, or record that the whole table is meant to be readable by these roles PRV02 bump: qualify the object names in its body or pin search_path, and grant EXECUTE only to roles that should act as the owner PRV03 customers: grant to a named role and let members inherit it, so the grant names who holds it roles/read-reach ptah: first take away what detail.reach.sources names, since a revoke on a relation does not narrow it: remove superuser, a role that reads or writes all data and a privilege on every database, and give the relations to an owner the application does not connect as; then grant the role only the relations it needs roles/read-reach reporting: grant the role only the relations it needs, or split it into narrower roles; detail.reach.through names the roles it reaches them through roles/write-reach ptah: first take away what detail.reach.sources names, since a revoke on a relation does not narrow it: remove superuser, a role that reads or writes all data and a privilege on every database, and give the relations to an owner the application does not connect as; then grant the role only the relations it needs
0 error, 4 warning, 4 info
Not checked here: ROL01: no role usage data was supplied; a privilege is not use, and no catalog records which roles read which objectsFindings carry the codes PRV01, PRV02, PRV03, ROL01, ROL03, ROL04,
OWN01, OWN02, roles/read-reach and roles/write-reach.
Schema security findings
carries what each code reports, the severity it uses, and which engines supply
the catalog it reads. Ptah’s migration and SQL linters report under a separate
set of identifiers, enumerated on Lint rules; no
code named on this page appears there.
--format json emits the same three parts as a document, under the keys
findings, summary and skipped_rules. Each finding carries its code,
severity, subject, message, the detail its suggestion names, and the
suggestion itself, so a pipeline can group or diff findings without reading
prose.
What a finding means
Section titled “What a finding means”A finding describes the access the schema declares. It is not a verdict.
OWN01 fires on a default PostgreSQL database because the creating role owns
what it created, and PRV01 fires wherever a table is granted without a row
policy, which is most tables on most databases. Both are info for that reason:
they describe a shape, and a person decides whether that shape is intended here.
A clean report is not a security clearance. The analysis reads what Ptah models, attempts no access, and cannot see a privilege granted on an object outside the schema it read. “Nothing here matched a rule” is the claim it makes. Whether the database is secure is a question this command does not answer, and running it does not replace a security review.
Read the skipped rules
Section titled “Read the skipped rules”A rule that could not run is named with its reason under Not checked here:,
because a skipped rule and a rule that found nothing produce the same finding
list. On a target that models neither roles nor row-level security, that block
is most of the answer. Any SQLite database reports it, an empty one included:
ptah schema security --db-url sqlite://shop.dbExpected output includes:
No security findings.
Not checked here: PRV01: the target does not model row-level security ROL01: no role usage data was supplied; a privilege is not use, and no catalog records which roles read which objects roles/read-reach: the access no object grant states -- superuser, predefined roles, server-wide privileges -- was not read for this source, so a role's reach would be measured short roles/write-reach: the access no object grant states -- superuser, predefined roles, server-wide privileges -- was not read for this source, so a role's reach would be measured shortSupply role usage so ROL01 can run
Section titled “Supply role usage so ROL01 can run”ROL01 reports a role holding privileges on an object it was not observed
using. No catalog records that: a role holding SELECT on a table it has never
read looks identical to one that reads it hourly. The observation is therefore
supplied rather than read. --role-usage takes a JSON file of what something
else saw, such as an audit stream or a proxy log. Save the observations as
role-usage.json:
[{"role": "reporting", "kind": "table", "name": "orders"}]ptah schema security --db-url "$DATABASE_URL" --role-usage role-usage.jsonExpected output includes:
ROL01 warning table customers role ptah holds privileges on table customers, which it was not observed usingROL01 warning table orders role ptah holds privileges on table orders, which it was not observed usingThe file records reporting reading orders, so that grant is not reported.
The owning role ptah is reported because nothing recorded it using anything.
Each of those two lines repeats once per privilege the role holds on the table,
which is why the run prints 14 of them; see Limitations.
An empty list is a different answer from no file at all. It says the window was
observed and nothing used anything, so every grant inside it is unused. Without
the flag, ROL01 reports itself skipped rather than passing quietly.
Measure how much of the database a role reaches
Section titled “Measure how much of the database a role reaches”roles/read-reach counts the tables, views and materialized views a role can
read, and roles/write-reach the ones whose rows it can change, each as a share
of all of them. A role reaches a relation through:
- its own grants on the whole relation, and grants to
PUBLIC; - the roles it is a member of, at any depth: the roles it inherits from through
memberships that each pass privileges on, and the roles it can switch to with
SET ROLEthrough memberships that each allow it, with what those inherit. On PostgreSQL 16 a chain that inherits one link and switches the next reaches no further than the first link; - ownership, which on PostgreSQL carries every privilege on the relation, even one the owner revoked from itself, since it can grant that back;
- a grant on the whole database, on MySQL and MariaDB, as the server applies it, which the next paragraph describes;
- access no grant on a relation states: superuser, membership in
pg_read_all_dataorpg_write_all_data, a privilege on every database such asGRANT SELECT ON *.*except where a MySQL partial revoke takes it away, or, on MySQL and MariaDB, a privilege on a database name pattern that reaches the database, such asGRANT SELECT ON `ab%`.*. A member reaches what a superuser role reaches only if it can switch to that role, because PostgreSQL does not pass the superuser bit on through inheritance.
On MySQL and MariaDB a grant on a database, ON d.*, is a row on a database
name pattern: % and _ are wildcards, \_ and \% match the character
itself, and case counts where lower_case_table_names is 0, the way
the MySQL page describes for a revoke
under such a grant. A name such as app_db is a pattern too. Of all the rows
that reach the database, the server applies one, so a role holding
SELECT ON `ab%`.* and INSERT ON abc.* writes the tables of abc and
reads none of them. A role counts only the privileges of the row the server
applies to a session with that role active, which holds the role’s own rows
and those of the roles it inherits:
- the row on the database’s exact name, where that name has no
%or_; - otherwise, on MySQL, the pattern that sorts first byte for byte:
`q_bc`before`qa%`,`qa%`before`qab%`, and`app%`beforeapp_db; - otherwise, on MariaDB, the row that matches the fewest names: more literal
characters first, and
_before%. MariaDB looks a role andPUBLICup apart and adds what each applies.
A pattern that does not reach the database counts nothing. On MySQL with
partial_revokes on, % and _ are the characters themselves, and a role’s
row on a name holding them reaches the database it names in another case:
SELECT ON `X_Y`.* reaches x_y where lower_case_table_names is 0.
Where Ptah cannot tell which row the server applies, the role counts every row
that may apply, as the limits below say. The order was measured on MySQL 8.4.13
and 26.10.0 and on MariaDB 11.8.9 and 12.3.3.
SELECT is read access; INSERT, UPDATE, DELETE and TRUNCATE are write
access. The write rule leaves materialized views out of its count, since no
role changes their rows. A role that reaches more than --reach-warn percent of the relations
(default 50) is a warning, and more than --reach-error percent an error.
Reaching exactly the threshold is below it. The seed above holds two tables, so
the superuser ptah, which also owns both, reaches both, and reporting
reaches both through its grant on orders and the grant to PUBLIC on
customers.
--reach-error defaults to 100, which no reach exceeds, so by default a broad
reach is a warning and does not fail the run. The role an application runs its
own migrations as owns every table and reaches all of them, and a default that
failed on it would fail nearly every database. To block a role that reaches
more than three quarters of the database, set the error threshold:
ptah schema security --db-url "$DATABASE_URL" --reach-error 75A role that reaches no more than PUBLIC does is not reported, because the
PUBLIC finding already names that reach. On MariaDB a role may be granted to
PUBLIC, and PUBLIC then reaches what that role reaches, and so does every
other role, through a grant on a table or on a whole database alike. A role
named in MySQL’s mandatory_roles counts the same way, since the server grants
it to every account. A MySQL role named PUBLIC is a role like any other, held
only by the roles and accounts it is granted to, and is measured as one.
In --format json, detail.reach carries reached, relations and threshold_percent, the roles
the reach passes through under through, and under sources the access a
revoke on a relation does not narrow, such as superuser held by ptah,
ownership of 2 relations held by ptah or, on MySQL and MariaDB,
SELECT ON `ab%`.* held by reporting. Each rule names the sources of its own
reach, so a role that reads everything through pg_read_all_data and writes
through grants names no source for writing. An owner can grant itself back what a
revoke takes, so the suggestion for such a role is to give the relations to an
owner the application does not connect as. Where a source is a grant on a
database name pattern, the suggestion asks to remove that grant as well.
The rules run on PostgreSQL, MySQL and MariaDB, where the read covers that access. Elsewhere they report themselves skipped, because a reach measured without it reports a superuser as reaching nothing.
Gate a pull request on findings
Section titled “Gate a pull request on findings”--fail-on sets the threshold that controls the exit code, and takes error
(the default), any, or none:
ptah schema security --db-url "$DATABASE_URL" --fail-on anyecho "exit: $?"Expected output includes:
exit: 1See Exit codes for what 0, 1 and 2 mean
across native commands.
Limitations
Section titled “Limitations”- The reach rules count relations, not rows or importance, so on a small
database one grant reaches most of it: in the seed above, a single grant gives
reportingboth tables. - The reach rules do not check
USAGEon the schema. A role holdingSELECTon a table in a schema it cannot use is counted as reaching that table. - A privilege on some columns of a table does not count as reaching the table, so a role granted every column one at a time reads as reaching nothing.
- A view counts as written by a role holding a write privilege on it, whether or not the view is updatable.
- On MySQL and MariaDB the rules measure roles, the principals the role read
covers. A user account that holds broad grants directly is not measured, and
neither is a MySQL role on a host other than
%. A role that holds a login on%is measured through what the login holds, since the read reads that login as it reads a role. Where a role holds an account on another host, throughGRANTof a login or of a role, or holds a name two accounts share, the rules skip that role and every role that holds it. The skip names the account, the roles, and why the read did not read every privilege of the account; the other roles are measured. - On MySQL a session’s account and every role it has active share one lookup of the database-level rows, so a user’s own row, or a second active role, can win over a role’s row. The rules measure each role with only itself and the roles it inherits active.
- A role named in MySQL’s
mandatory_rolesis measured with each role apart from it. UnderSET ROLE ALLits row on a database can win over another role’s pattern, and the session reads less than that role alone: measured on MySQL 8.4.13 and 26.10.0, a session that activates only that role reads what the pattern gives. Where the read cannot readmandatory_roles, or a name in it, or a MySQL role is namedPUBLICbeside a mandatory role, every role may hold roles the read does not state, and the rules skip every role. The skip gives the cause: for a role namedPUBLIC, that it hides which roles every account holds. - Where Ptah cannot tell which of two rows the server applies, the finding
counts every privilege of both, each under its own row, so it may show more
than the server allows. That covers two MariaDB patterns with the same counts
of characters and wildcards, such as
`%_bc`and`_%bc`, which the server orders by an unstable sort, and, on a server withlower_case_table_names=2, two MySQL rows whose order changes when the names are folded. No server withlower_case_table_names=2was measured. - PostgreSQL’s bootstrap superuser is read only when it is not named
postgres: a role read leaves the namepostgresout, so that role is not measured, while a superuser under any other name is. A role that can switch topostgresdoes not reach whatpostgresreaches either. ROL01reports one finding per privilege rather than one per object. A single unused grant on a table carrying seven privileges produces seven identical lines; the run above produces 14 for two tables. Group the JSON output before reading a report.- A
--schemasvalue naming a schema that does not exist reportsNo security findings.and exits0. Check the name againstptah db readbefore trusting an empty report. - An entry in the
--role-usagefile whosekindnames nothing Ptah models is accepted and matches nothing, so every grant reads as unused. Changing"kind": "table"to"kind": "relation"in the file above takes the run from 14ROL01lines to 15, with nothing reported about the unrecognized value. - The target is a live database. There is no
--root-dirand no--schema-file, so a desired schema cannot be analyzed before it is applied.
Exact reference
Section titled “Exact reference”Run ptah schema security --help for the flag set with its environment
variables.
Schema security findings
carries every rule name with its severity and the engines that supply the
catalog it reads, and Exit codes carries the
verb’s row.
Next steps
Section titled “Next steps”- Ready to change the privileges a finding named? Apply directly.
- Want the findings drawn on the schema diagram? Visualize the schema.
- Counting what the same database holds? Count schema objects.