diff --git a/Cargo.lock b/Cargo.lock index 27377ace1..39ec92fb0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2750,6 +2750,7 @@ dependencies = [ "pgls_console", "pgls_diagnostics", "pgls_env", + "pgls_matcher", "pgls_text_size", "rustc-hash 2.1.0", "schemars", @@ -2919,6 +2920,15 @@ dependencies = [ "quote", ] +[[package]] +name = "pgls_matcher" +version = "0.0.0" +dependencies = [ + "pgls_console", + "pgls_diagnostics", + "rustc-hash 2.1.0", +] + [[package]] name = "pgls_plpgsql_check" version = "0.0.0" @@ -2998,8 +3008,10 @@ version = "0.0.0" dependencies = [ "insta", "pgls_analyse", + "pgls_configuration", "pgls_console", "pgls_diagnostics", + "pgls_matcher", "pgls_schema_cache", "pgls_test_utils", "serde", @@ -3158,6 +3170,7 @@ dependencies = [ "pgls_fs", "pgls_hover", "pgls_lexer", + "pgls_matcher", "pgls_plpgsql_check", "pgls_query", "pgls_query_ext", diff --git a/Cargo.toml b/Cargo.toml index 9b09e8ea4..46039494c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,7 @@ pgls_lexer = { path = "./crates/pgls_lexer", version = "0.0.0" pgls_lexer_codegen = { path = "./crates/pgls_lexer_codegen", version = "0.0.0" } pgls_lsp = { path = "./crates/pgls_lsp", version = "0.0.0" } pgls_markup = { path = "./crates/pgls_markup", version = "0.0.0" } +pgls_matcher = { path = "./crates/pgls_matcher", version = "0.0.0" } pgls_plpgsql_check = { path = "./crates/pgls_plpgsql_check", version = "0.0.0" } pgls_query = { path = "./crates/pgls_query", version = "0.0.0" } pgls_query_ext = { path = "./crates/pgls_query_ext", version = "0.0.0" } diff --git a/crates/pgls_configuration/Cargo.toml b/crates/pgls_configuration/Cargo.toml index f90c59553..169687bf7 100644 --- a/crates/pgls_configuration/Cargo.toml +++ b/crates/pgls_configuration/Cargo.toml @@ -22,6 +22,7 @@ pgls_analyser = { workspace = true } pgls_console = { workspace = true } pgls_diagnostics = { workspace = true } pgls_env = { workspace = true } +pgls_matcher = { workspace = true } pgls_text_size = { workspace = true } rustc-hash = { workspace = true } schemars = { workspace = true, features = ["indexmap1"], optional = true } diff --git a/crates/pgls_configuration/src/rules/configuration.rs b/crates/pgls_configuration/src/rules/configuration.rs index 6b86fef69..f6a1ea662 100644 --- a/crates/pgls_configuration/src/rules/configuration.rs +++ b/crates/pgls_configuration/src/rules/configuration.rs @@ -58,6 +58,15 @@ impl RuleConfiguration { } } } +impl RuleConfiguration { + /// Get a reference to the typed options if present + pub fn get_options_ref(&self) -> Option<&T> { + match self { + Self::Plain(_) => None, + Self::WithOptions(options) => Some(&options.options), + } + } +} impl Default for RuleConfiguration { fn default() -> Self { Self::Plain(RulePlainConfiguration::Error) diff --git a/crates/pgls_configuration/src/splinter/mod.rs b/crates/pgls_configuration/src/splinter/mod.rs index def25610d..e237ebae5 100644 --- a/crates/pgls_configuration/src/splinter/mod.rs +++ b/crates/pgls_configuration/src/splinter/mod.rs @@ -1,6 +1,8 @@ //! Generated file, do not edit by hand, see `xtask/codegen` #![doc = r" Generated file, do not edit by hand, see `xtask/codegen`"] +mod options; +pub use options::SplinterRuleOptions; mod rules; use biome_deserialize::StringSet; use biome_deserialize_macros::{Merge, Partial}; diff --git a/crates/pgls_configuration/src/splinter/options.rs b/crates/pgls_configuration/src/splinter/options.rs new file mode 100644 index 000000000..aead42670 --- /dev/null +++ b/crates/pgls_configuration/src/splinter/options.rs @@ -0,0 +1,25 @@ +use biome_deserialize_macros::Deserializable; +#[cfg(feature = "schema")] +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Shared options for all splinter rules. +/// +/// These options allow configuring per-rule filtering of database objects. +#[derive(Clone, Debug, Default, Deserialize, Deserializable, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SplinterRuleOptions { + /// A list of glob patterns for database objects to ignore. + /// + /// Patterns use Unix-style globs where: + /// - `*` matches any sequence of characters + /// - `?` matches any single character + /// + /// Each pattern should be in the format `schema.object_name`, for example: + /// - `"public.my_table"` - ignores a specific table + /// - `"audit.*"` - ignores all objects in the audit schema + /// - `"*.audit_*"` - ignores objects with audit_ prefix in any schema + #[serde(default)] + pub ignore: Vec, +} diff --git a/crates/pgls_configuration/src/splinter/rules.rs b/crates/pgls_configuration/src/splinter/rules.rs index 175623034..b10f7978d 100644 --- a/crates/pgls_configuration/src/splinter/rules.rs +++ b/crates/pgls_configuration/src/splinter/rules.rs @@ -165,6 +165,20 @@ impl Rules { } disabled_rules } + #[doc = r" Build matchers for all rules that have ignore patterns configured."] + #[doc = r" Returns a map from rule name (camelCase) to the matcher."] + pub fn get_ignore_matchers( + &self, + ) -> rustc_hash::FxHashMap<&'static str, pgls_matcher::Matcher> { + let mut matchers = rustc_hash::FxHashMap::default(); + if let Some(group) = &self.performance { + matchers.extend(group.get_ignore_matchers()); + } + if let Some(group) = &self.security { + matchers.extend(group.get_ignore_matchers()); + } + matchers + } } #[derive(Clone, Debug, Default, Deserialize, Eq, Merge, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(JsonSchema))] @@ -179,25 +193,26 @@ pub struct Performance { pub all: Option, #[doc = "/// # Auth RLS Initialization Plan /// /// Detects if calls to `current_setting()` and `auth.()` in RLS policies are being unnecessarily re-evaluated for each row /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// with policies as ( /// select /// nsp.nspname as schema_name, /// pb.tablename as table_name, /// pc.relrowsecurity as is_rls_active, /// polname as policy_name, /// polpermissive as is_permissive, -- if not, then restrictive /// (select array_agg(r::regrole) from unnest(polroles) as x(r)) as roles, /// case polcmd /// when 'r' then 'SELECT' /// when 'a' then 'INSERT' /// when 'w' then 'UPDATE' /// when 'd' then 'DELETE' /// when '*' then 'ALL' /// end as command, /// qual, /// with_check /// from /// pg_catalog.pg_policy pa /// join pg_catalog.pg_class pc /// on pa.polrelid = pc.oid /// join pg_catalog.pg_namespace nsp /// on pc.relnamespace = nsp.oid /// join pg_catalog.pg_policies pb /// on pc.relname = pb.tablename /// and nsp.nspname = pb.schemaname /// and pa.polname = pb.policyname /// ) /// select /// 'auth_rls_initplan' as \"name!\", /// 'Auth RLS Initialization Plan' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects if calls to \\`current_setting()\\` and \\`auth.\\()\\` in RLS policies are being unnecessarily re-evaluated for each row' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has a row level security policy \\`%s\\` that re-evaluates current_setting() or auth.\\() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \\`auth.\\()\\` with \\`(select auth.\\())\\`. See \\[docs](https://supabase.com/docs/guides/database/postgres/row-level-security#call-functions-with-select) for more info.', /// schema_name, /// table_name, /// policy_name /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0003_auth_rls_initplan' as \"remediation!\", /// jsonb_build_object( /// 'schema', schema_name, /// 'name', table_name, /// 'type', 'table' /// ) as \"metadata!\", /// format('auth_rls_init_plan_%s_%s_%s', schema_name, table_name, policy_name) as \"cache_key!\" /// from /// policies /// where /// is_rls_active /// -- NOTE: does not include realtime in support of monitoring policies on realtime.messages /// and schema_name not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and ( /// -- Example: auth.uid() /// ( /// qual like '%auth.uid()%' /// and lower(qual) not like '%select auth.uid()%' /// ) /// or ( /// qual like '%auth.jwt()%' /// and lower(qual) not like '%select auth.jwt()%' /// ) /// or ( /// qual like '%auth.role()%' /// and lower(qual) not like '%select auth.role()%' /// ) /// or ( /// qual like '%auth.email()%' /// and lower(qual) not like '%select auth.email()%' /// ) /// or ( /// qual like '%current\\_setting(%)%' /// and lower(qual) not like '%select current\\_setting(%)%' /// ) /// or ( /// with_check like '%auth.uid()%' /// and lower(with_check) not like '%select auth.uid()%' /// ) /// or ( /// with_check like '%auth.jwt()%' /// and lower(with_check) not like '%select auth.jwt()%' /// ) /// or ( /// with_check like '%auth.role()%' /// and lower(with_check) not like '%select auth.role()%' /// ) /// or ( /// with_check like '%auth.email()%' /// and lower(with_check) not like '%select auth.email()%' /// ) /// or ( /// with_check like '%current\\_setting(%)%' /// and lower(with_check) not like '%select current\\_setting(%)%' /// ) /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"authRlsInitplan\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0003_auth_rls_initplan"] #[serde(skip_serializing_if = "Option::is_none")] - pub auth_rls_initplan: Option>, + pub auth_rls_initplan: Option>, #[doc = "/// # Duplicate Index /// /// Detects cases where two ore more identical indexes exist. /// /// ## SQL Query /// /// sql /// ( /// select /// 'duplicate_index' as \"name!\", /// 'Duplicate Index' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects cases where two ore more identical indexes exist.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has identical indexes %s. Drop all except one of them', /// n.nspname, /// c.relname, /// array_agg(pi.indexname order by pi.indexname) /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0009_duplicate_index' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', case /// when c.relkind = 'r' then 'table' /// when c.relkind = 'm' then 'materialized view' /// else 'ERROR' /// end, /// 'indexes', array_agg(pi.indexname order by pi.indexname) /// ) as \"metadata!\", /// format( /// 'duplicate_index_%s_%s_%s', /// n.nspname, /// c.relname, /// array_agg(pi.indexname order by pi.indexname) /// ) as \"cache_key!\" /// from /// pg_catalog.pg_indexes pi /// join pg_catalog.pg_namespace n /// on n.nspname = pi.schemaname /// join pg_catalog.pg_class c /// on pi.tablename = c.relname /// and n.oid = c.relnamespace /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind in ('r', 'm') -- tables and materialized views /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null -- exclude tables owned by extensions /// group by /// n.nspname, /// c.relkind, /// c.relname, /// replace(pi.indexdef, pi.indexname, '') /// having /// count(*) > 1) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"duplicateIndex\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0009_duplicate_index"] #[serde(skip_serializing_if = "Option::is_none")] - pub duplicate_index: Option>, + pub duplicate_index: Option>, #[doc = "/// # Multiple Permissive Policies /// /// Detects if multiple permissive row level security policies are present on a table for the same `role` and `action` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query. /// /// ## SQL Query /// /// sql /// ( /// select /// 'multiple_permissive_policies' as \"name!\", /// 'Multiple Permissive Policies' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects if multiple permissive row level security policies are present on a table for the same \\`role\\` and \\`action\\` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has multiple permissive policies for role \\`%s\\` for action \\`%s\\`. Policies include \\`%s\\`', /// n.nspname, /// c.relname, /// r.rolname, /// act.cmd, /// array_agg(p.polname order by p.polname) /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0006_multiple_permissive_policies' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'multiple_permissive_policies_%s_%s_%s_%s', /// n.nspname, /// c.relname, /// r.rolname, /// act.cmd /// ) as \"cache_key!\" /// from /// pg_catalog.pg_policy p /// join pg_catalog.pg_class c /// on p.polrelid = c.oid /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// join pg_catalog.pg_roles r /// on p.polroles @> array\\[r.oid] /// or p.polroles = array\\[0::oid] /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e', /// lateral ( /// select x.cmd /// from unnest(( /// select /// case p.polcmd /// when 'r' then array\\['SELECT'] /// when 'a' then array\\['INSERT'] /// when 'w' then array\\['UPDATE'] /// when 'd' then array\\['DELETE'] /// when '*' then array\\['SELECT', 'INSERT', 'UPDATE', 'DELETE'] /// else array\\['ERROR'] /// end as actions /// )) x(cmd) /// ) act(cmd) /// where /// c.relkind = 'r' -- regular tables /// and p.polpermissive -- policy is permissive /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and r.rolname not like 'pg_%' /// and r.rolname not like 'supabase%admin' /// and not r.rolbypassrls /// and dep.objid is null -- exclude tables owned by extensions /// group by /// n.nspname, /// c.relname, /// r.rolname, /// act.cmd /// having /// count(1) > 1) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"multiplePermissivePolicies\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0006_multiple_permissive_policies"] #[serde(skip_serializing_if = "Option::is_none")] - pub multiple_permissive_policies: Option>, + pub multiple_permissive_policies: + Option>, #[doc = "/// # No Primary Key /// /// Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale. /// /// ## SQL Query /// /// sql /// ( /// select /// 'no_primary_key' as \"name!\", /// 'No Primary Key' as \"title!\", /// 'INFO' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` does not have a primary key', /// pgns.nspname, /// pgc.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0004_no_primary_key' as \"remediation!\", /// jsonb_build_object( /// 'schema', pgns.nspname, /// 'name', pgc.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'no_primary_key_%s_%s', /// pgns.nspname, /// pgc.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class pgc /// join pg_catalog.pg_namespace pgns /// on pgns.oid = pgc.relnamespace /// left join pg_catalog.pg_index pgi /// on pgi.indrelid = pgc.oid /// left join pg_catalog.pg_depend dep /// on pgc.oid = dep.objid /// and dep.deptype = 'e' /// where /// pgc.relkind = 'r' -- regular tables /// and pgns.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null -- exclude tables owned by extensions /// group by /// pgc.oid, /// pgns.nspname, /// pgc.relname /// having /// max(coalesce(pgi.indisprimary, false)::int) = 0) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"noPrimaryKey\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0004_no_primary_key"] #[serde(skip_serializing_if = "Option::is_none")] - pub no_primary_key: Option>, + pub no_primary_key: Option>, #[doc = "/// # Table Bloat /// /// Detects if a table has excess bloat and may benefit from maintenance operations like vacuum full or cluster. /// /// ## SQL Query /// /// sql /// ( /// with constants as ( /// select current_setting('block_size')::numeric as bs, 23 as hdr, 4 as ma /// ), /// /// bloat_info as ( /// select /// ma, /// bs, /// schemaname, /// tablename, /// (datawidth + (hdr + ma - (case when hdr % ma = 0 then ma else hdr % ma end)))::numeric as datahdr, /// (maxfracsum * (nullhdr + ma - (case when nullhdr % ma = 0 then ma else nullhdr % ma end))) as nullhdr2 /// from ( /// select /// schemaname, /// tablename, /// hdr, /// ma, /// bs, /// sum((1 - null_frac) * avg_width) as datawidth, /// max(null_frac) as maxfracsum, /// hdr + ( /// select 1 + count(*) / 8 /// from pg_stats s2 /// where /// null_frac \\<> 0 /// and s2.schemaname = s.schemaname /// and s2.tablename = s.tablename /// ) as nullhdr /// from pg_stats s, constants /// group by 1, 2, 3, 4, 5 /// ) as foo /// ), /// /// table_bloat as ( /// select /// schemaname, /// tablename, /// cc.relpages, /// bs, /// ceil((cc.reltuples * ((datahdr + ma - /// (case when datahdr % ma = 0 then ma else datahdr % ma end)) + nullhdr2 + 4)) / (bs - 20::float)) as otta /// from /// bloat_info /// join pg_class cc /// on cc.relname = bloat_info.tablename /// join pg_namespace nn /// on cc.relnamespace = nn.oid /// and nn.nspname = bloat_info.schemaname /// and nn.nspname \\<> 'information_schema' /// where /// cc.relkind = 'r' /// and cc.relam = (select oid from pg_am where amname = 'heap') /// ), /// /// bloat_data as ( /// select /// 'table' as type, /// schemaname, /// tablename as object_name, /// round(case when otta = 0 then 0.0 else table_bloat.relpages / otta::numeric end, 1) as bloat, /// case when relpages \\< otta then 0 else (bs * (table_bloat.relpages - otta)::bigint)::bigint end as raw_waste /// from /// table_bloat /// ) /// /// select /// 'table_bloat' as \"name!\", /// 'Table Bloat' as \"title!\", /// 'INFO' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects if a table has excess bloat and may benefit from maintenance operations like vacuum full or cluster.' as \"description!\", /// format( /// 'Table `%s`.`%s` has excessive bloat', /// bloat_data.schemaname, /// bloat_data.object_name /// ) as \"detail!\", /// 'Consider running vacuum full (WARNING: incurs downtime) and tweaking autovacuum settings to reduce bloat.' as \"remediation!\", /// jsonb_build_object( /// 'schema', bloat_data.schemaname, /// 'name', bloat_data.object_name, /// 'type', bloat_data.type /// ) as \"metadata!\", /// format( /// 'table_bloat_%s_%s', /// bloat_data.schemaname, /// bloat_data.object_name /// ) as \"cache_key!\" /// from /// bloat_data /// where /// bloat > 70.0 /// and raw_waste > (20 * 1024 * 1024) -- filter for waste > 200 MB /// order by /// schemaname, /// object_name) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"tableBloat\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: "] #[serde(skip_serializing_if = "Option::is_none")] - pub table_bloat: Option>, + pub table_bloat: Option>, #[doc = "/// # Unindexed foreign keys /// /// Identifies foreign key constraints without a covering index, which can impact database performance. /// /// ## SQL Query /// /// sql /// with foreign_keys as ( /// select /// cl.relnamespace::regnamespace::text as schema_name, /// cl.relname as table_name, /// cl.oid as table_oid, /// ct.conname as fkey_name, /// ct.conkey as col_attnums /// from /// pg_catalog.pg_constraint ct /// join pg_catalog.pg_class cl -- fkey owning table /// on ct.conrelid = cl.oid /// left join pg_catalog.pg_depend d /// on d.objid = cl.oid /// and d.deptype = 'e' /// where /// ct.contype = 'f' -- foreign key constraints /// and d.objid is null -- exclude tables that are dependencies of extensions /// and cl.relnamespace::regnamespace::text not in ( /// 'pg_catalog', 'information_schema', 'auth', 'storage', 'vault', 'extensions' /// ) /// ), /// index_ as ( /// select /// pi.indrelid as table_oid, /// indexrelid::regclass as index_, /// string_to_array(indkey::text, ' ')::smallint\\[] as col_attnums /// from /// pg_catalog.pg_index pi /// where /// indisvalid /// ) /// select /// 'unindexed_foreign_keys' as \"name!\", /// 'Unindexed foreign keys' as \"title!\", /// 'INFO' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Identifies foreign key constraints without a covering index, which can impact database performance.' as \"description!\", /// format( /// 'Table `%s.%s` has a foreign key `%s` without a covering index. This can lead to suboptimal query performance.', /// fk.schema_name, /// fk.table_name, /// fk.fkey_name /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0001_unindexed_foreign_keys' as \"remediation!\", /// jsonb_build_object( /// 'schema', fk.schema_name, /// 'name', fk.table_name, /// 'type', 'table', /// 'fkey_name', fk.fkey_name, /// 'fkey_columns', fk.col_attnums /// ) as \"metadata!\", /// format('unindexed_foreign_keys_%s_%s_%s', fk.schema_name, fk.table_name, fk.fkey_name) as \"cache_key!\" /// from /// foreign_keys fk /// left join index_ idx /// on fk.table_oid = idx.table_oid /// and fk.col_attnums = idx.col_attnums\\[1:array_length(fk.col_attnums, 1)] /// left join pg_catalog.pg_depend dep /// on idx.table_oid = dep.objid /// and dep.deptype = 'e' /// where /// idx.index_ is null /// and fk.schema_name not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null -- exclude tables owned by extensions /// order by /// fk.schema_name, /// fk.table_name, /// fk.fkey_name /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"unindexedForeignKeys\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0001_unindexed_foreign_keys"] #[serde(skip_serializing_if = "Option::is_none")] - pub unindexed_foreign_keys: Option>, + pub unindexed_foreign_keys: Option>, #[doc = "/// # Unused Index /// /// Detects if an index has never been used and may be a candidate for removal. /// /// ## SQL Query /// /// sql /// ( /// select /// 'unused_index' as \"name!\", /// 'Unused Index' as \"title!\", /// 'INFO' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['PERFORMANCE'] as \"categories!\", /// 'Detects if an index has never been used and may be a candidate for removal.' as \"description!\", /// format( /// 'Index \\`%s\\` on table \\`%s.%s\\` has not been used', /// psui.indexrelname, /// psui.schemaname, /// psui.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0005_unused_index' as \"remediation!\", /// jsonb_build_object( /// 'schema', psui.schemaname, /// 'name', psui.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'unused_index_%s_%s_%s', /// psui.schemaname, /// psui.relname, /// psui.indexrelname /// ) as \"cache_key!\" /// /// from /// pg_catalog.pg_stat_user_indexes psui /// join pg_catalog.pg_index pi /// on psui.indexrelid = pi.indexrelid /// left join pg_catalog.pg_depend dep /// on psui.relid = dep.objid /// and dep.deptype = 'e' /// where /// psui.idx_scan = 0 /// and not pi.indisunique /// and not pi.indisprimary /// and dep.objid is null -- exclude tables owned by extensions /// and psui.schemaname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"performance\": { /// \"unusedIndex\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0005_unused_index"] #[serde(skip_serializing_if = "Option::is_none")] - pub unused_index: Option>, + pub unused_index: Option>, } impl Performance { const GROUP_NAME: &'static str = "performance"; @@ -384,6 +399,90 @@ impl Performance { _ => None, } } + #[doc = r" Build matchers for rules in this group that have ignore patterns configured"] + pub fn get_ignore_matchers( + &self, + ) -> rustc_hash::FxHashMap<&'static str, pgls_matcher::Matcher> { + let mut matchers = rustc_hash::FxHashMap::default(); + if let Some(conf) = &self.auth_rls_initplan { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("authRlsInitplan", m); + } + } + } + if let Some(conf) = &self.duplicate_index { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("duplicateIndex", m); + } + } + } + if let Some(conf) = &self.multiple_permissive_policies { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("multiplePermissivePolicies", m); + } + } + } + if let Some(conf) = &self.no_primary_key { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("noPrimaryKey", m); + } + } + } + if let Some(conf) = &self.table_bloat { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("tableBloat", m); + } + } + } + if let Some(conf) = &self.unindexed_foreign_keys { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("unindexedForeignKeys", m); + } + } + } + if let Some(conf) = &self.unused_index { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("unusedIndex", m); + } + } + } + matchers + } } #[derive(Clone, Debug, Default, Deserialize, Eq, Merge, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(JsonSchema))] @@ -398,46 +497,50 @@ pub struct Security { pub all: Option, #[doc = "/// # Exposed Auth Users /// /// Detects if auth.users is exposed to anon or authenticated roles via a view or materialized view in schemas exposed to PostgREST, potentially compromising user data security. /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'auth_users_exposed' as \"name!\", /// 'Exposed Auth Users' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects if auth.users is exposed to anon or authenticated roles via a view or materialized view in schemas exposed to PostgREST, potentially compromising user data security.' as \"description!\", /// format( /// 'View/Materialized View \"%s\" in the public schema may expose \\`auth.users\\` data to anon or authenticated roles.', /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0002_auth_users_exposed' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'view', /// 'exposed_to', array_remove(array_agg(DISTINCT case when pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') then 'anon' when pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') then 'authenticated' end), null) /// ) as \"metadata!\", /// format('auth_users_exposed_%s_%s', n.nspname, c.relname) as \"cache_key!\" /// from /// -- Identify the oid for auth.users /// pg_catalog.pg_class auth_users_pg_class /// join pg_catalog.pg_namespace auth_users_pg_namespace /// on auth_users_pg_class.relnamespace = auth_users_pg_namespace.oid /// and auth_users_pg_class.relname = 'users' /// and auth_users_pg_namespace.nspname = 'auth' /// -- Depends on auth.users /// join pg_catalog.pg_depend d /// on d.refobjid = auth_users_pg_class.oid /// join pg_catalog.pg_rewrite r /// on r.oid = d.objid /// join pg_catalog.pg_class c /// on c.oid = r.ev_class /// join pg_catalog.pg_namespace n /// on n.oid = c.relnamespace /// join pg_catalog.pg_class pg_class_auth_users /// on d.refobjid = pg_class_auth_users.oid /// where /// d.deptype = 'n' /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))) /// -- Exclude self /// and c.relname \\<> '0002_auth_users_exposed' /// -- There are 3 insecure configurations /// and /// ( /// -- Materialized views don't support RLS so this is insecure by default /// (c.relkind in ('m')) -- m for materialized view /// or /// -- Standard View, accessible to anon or authenticated that is security_definer /// ( /// c.relkind = 'v' -- v for view /// -- Exclude security invoker views /// and not ( /// lower(coalesce(c.reloptions::text,'{}'))::text\\[] /// && array\\[ /// 'security_invoker=1', /// 'security_invoker=true', /// 'security_invoker=yes', /// 'security_invoker=on' /// ] /// ) /// ) /// or /// -- Standard View, security invoker, but no RLS enabled on auth.users /// ( /// c.relkind in ('v') -- v for view /// -- is security invoker /// and ( /// lower(coalesce(c.reloptions::text,'{}'))::text\\[] /// && array\\[ /// 'security_invoker=1', /// 'security_invoker=true', /// 'security_invoker=yes', /// 'security_invoker=on' /// ] /// ) /// and not pg_class_auth_users.relrowsecurity /// ) /// ) /// group by /// n.nspname, /// c.relname, /// c.oid) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"authUsersExposed\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0002_auth_users_exposed"] #[serde(skip_serializing_if = "Option::is_none")] - pub auth_users_exposed: Option>, + pub auth_users_exposed: Option>, #[doc = "/// # Extension in Public /// /// Detects extensions installed in the `public` schema. /// /// ## SQL Query /// /// sql /// ( /// select /// 'extension_in_public' as \"name!\", /// 'Extension in Public' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects extensions installed in the \\`public\\` schema.' as \"description!\", /// format( /// 'Extension \\`%s\\` is installed in the public schema. Move it to another schema.', /// pe.extname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0014_extension_in_public' as \"remediation!\", /// jsonb_build_object( /// 'schema', pe.extnamespace::regnamespace, /// 'name', pe.extname, /// 'type', 'extension' /// ) as \"metadata!\", /// format( /// 'extension_in_public_%s', /// pe.extname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_extension pe /// where /// -- plpgsql is installed by default in public and outside user control /// -- confirmed safe /// pe.extname not in ('plpgsql') /// -- Scoping this to public is not optimal. Ideally we would use the postgres /// -- search path. That currently isn't available via SQL. In other lints /// -- we have used has_schema_privilege('anon', 'extensions', 'USAGE') but that /// -- is not appropriate here as it would evaluate true for the extensions schema /// and pe.extnamespace::regnamespace::text = 'public') /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"extensionInPublic\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0014_extension_in_public"] #[serde(skip_serializing_if = "Option::is_none")] - pub extension_in_public: Option>, + pub extension_in_public: Option>, #[doc = "/// # Extension Versions Outdated /// /// Detects extensions that are not using the default (recommended) version. /// /// ## SQL Query /// /// sql /// ( /// select /// 'extension_versions_outdated' as \"name!\", /// 'Extension Versions Outdated' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects extensions that are not using the default (recommended) version.' as \"description!\", /// format( /// 'Extension `%s` is using version `%s` but version `%s` is available. Using outdated extension versions may expose the database to security vulnerabilities.', /// ext.name, /// ext.installed_version, /// ext.default_version /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0022_extension_versions_outdated' as \"remediation!\", /// jsonb_build_object( /// 'extension_name', ext.name, /// 'installed_version', ext.installed_version, /// 'default_version', ext.default_version /// ) as \"metadata!\", /// format( /// 'extension_versions_outdated_%s_%s', /// ext.name, /// ext.installed_version /// ) as \"cache_key!\" /// from /// pg_catalog.pg_available_extensions ext /// join /// -- ignore versions not in pg_available_extension_versions /// -- e.g. residue of pg_upgrade /// pg_catalog.pg_available_extension_versions extv /// on extv.name = ext.name and extv.installed /// where /// ext.installed_version is not null /// and ext.default_version is not null /// and ext.installed_version != ext.default_version /// order by /// ext.name) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"extensionVersionsOutdated\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0022_extension_versions_outdated"] #[serde(skip_serializing_if = "Option::is_none")] - pub extension_versions_outdated: Option>, + pub extension_versions_outdated: + Option>, #[doc = "/// # Foreign Key to Auth Unique Constraint /// /// Detects user defined foreign keys to unique constraints in the auth schema. /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'fkey_to_auth_unique' as \"name!\", /// 'Foreign Key to Auth Unique Constraint' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects user defined foreign keys to unique constraints in the auth schema.' as \"description!\", /// format( /// 'Table `%s`.`%s` has a foreign key `%s` referencing an auth unique constraint', /// n.nspname, -- referencing schema /// c_rel.relname, -- referencing table /// c.conname -- fkey name /// ) as \"detail!\", /// 'Drop the foreign key constraint that references the auth schema.' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c_rel.relname, /// 'foreign_key', c.conname /// ) as \"metadata!\", /// format( /// 'fkey_to_auth_unique_%s_%s_%s', /// n.nspname, -- referencing schema /// c_rel.relname, -- referencing table /// c.conname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_constraint c /// join pg_catalog.pg_class c_rel /// on c.conrelid = c_rel.oid /// join pg_catalog.pg_namespace n /// on c_rel.relnamespace = n.oid /// join pg_catalog.pg_class ref_rel /// on c.confrelid = ref_rel.oid /// join pg_catalog.pg_namespace cn /// on ref_rel.relnamespace = cn.oid /// join pg_catalog.pg_index i /// on c.conindid = i.indexrelid /// where c.contype = 'f' /// and cn.nspname = 'auth' /// and i.indisunique /// and not i.indisprimary) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"fkeyToAuthUnique\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: "] #[serde(skip_serializing_if = "Option::is_none")] - pub fkey_to_auth_unique: Option>, + pub fkey_to_auth_unique: Option>, #[doc = "/// # Foreign Table in API /// /// Detects foreign tables that are accessible over APIs. Foreign tables do not respect row level security policies. /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'foreign_table_in_api' as \"name!\", /// 'Foreign Table in API' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects foreign tables that are accessible over APIs. Foreign tables do not respect row level security policies.' as \"description!\", /// format( /// 'Foreign table \\`%s.%s\\` is accessible over APIs', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0017_foreign_table_in_api' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'foreign table' /// ) as \"metadata!\", /// format( /// 'foreign_table_in_api_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// join pg_catalog.pg_namespace n /// on n.oid = c.relnamespace /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind = 'f' /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))) /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"foreignTableInApi\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0017_foreign_table_in_api"] #[serde(skip_serializing_if = "Option::is_none")] - pub foreign_table_in_api: Option>, + pub foreign_table_in_api: Option>, #[doc = "/// # Function Search Path Mutable /// /// Detects functions where the search_path parameter is not set. /// /// ## SQL Query /// /// sql /// ( /// select /// 'function_search_path_mutable' as \"name!\", /// 'Function Search Path Mutable' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects functions where the search_path parameter is not set.' as \"description!\", /// format( /// 'Function \\`%s.%s\\` has a role mutable search_path', /// n.nspname, /// p.proname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0011_function_search_path_mutable' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', p.proname, /// 'type', 'function' /// ) as \"metadata!\", /// format( /// 'function_search_path_mutable_%s_%s_%s', /// n.nspname, /// p.proname, /// md5(p.prosrc) -- required when function is polymorphic /// ) as \"cache_key!\" /// from /// pg_catalog.pg_proc p /// join pg_catalog.pg_namespace n /// on p.pronamespace = n.oid /// left join pg_catalog.pg_depend dep /// on p.oid = dep.objid /// and dep.deptype = 'e' /// where /// n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null -- exclude functions owned by extensions /// -- Search path not set /// and not exists ( /// select 1 /// from unnest(coalesce(p.proconfig, '{}')) as config /// where config like 'search_path=%' /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"functionSearchPathMutable\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0011_function_search_path_mutable"] #[serde(skip_serializing_if = "Option::is_none")] - pub function_search_path_mutable: Option>, + pub function_search_path_mutable: + Option>, #[doc = "/// # Insecure Queue Exposed in API /// /// Detects cases where an insecure Queue is exposed over Data APIs /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'insecure_queue_exposed_in_api' as \"name!\", /// 'Insecure Queue Exposed in API' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects cases where an insecure Queue is exposed over Data APIs' as \"description!\", /// format( /// 'Table \\`%s.%s\\` is public, but RLS has not been enabled.', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0019_insecure_queue_exposed_in_api' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'rls_disabled_in_public_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// where /// c.relkind in ('r', 'I') -- regular or partitioned tables /// and not c.relrowsecurity -- RLS is disabled /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and n.nspname = 'pgmq' -- tables in the pgmq schema /// and c.relname like 'q_%' -- only queue tables /// -- Constant requirements /// and 'pgmq_public' = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"insecureQueueExposedInApi\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0019_insecure_queue_exposed_in_api"] #[serde(skip_serializing_if = "Option::is_none")] - pub insecure_queue_exposed_in_api: Option>, + pub insecure_queue_exposed_in_api: + Option>, #[doc = "/// # Materialized View in API /// /// Detects materialized views that are accessible over the Data APIs. /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'materialized_view_in_api' as \"name!\", /// 'Materialized View in API' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects materialized views that are accessible over the Data APIs.' as \"description!\", /// format( /// 'Materialized view \\`%s.%s\\` is selectable by anon or authenticated roles', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0016_materialized_view_in_api' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'materialized view' /// ) as \"metadata!\", /// format( /// 'materialized_view_in_api_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// join pg_catalog.pg_namespace n /// on n.oid = c.relnamespace /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind = 'm' /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))) /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"materializedViewInApi\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0016_materialized_view_in_api"] #[serde(skip_serializing_if = "Option::is_none")] - pub materialized_view_in_api: Option>, + pub materialized_view_in_api: Option>, #[doc = "/// # Policy Exists RLS Disabled /// /// Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table. /// /// ## SQL Query /// /// sql /// ( /// select /// 'policy_exists_rls_disabled' as \"name!\", /// 'Policy Exists RLS Disabled' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has RLS policies but RLS is not enabled on the table. Policies include %s.', /// n.nspname, /// c.relname, /// array_agg(p.polname order by p.polname) /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0007_policy_exists_rls_disabled' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'policy_exists_rls_disabled_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_policy p /// join pg_catalog.pg_class c /// on p.polrelid = c.oid /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind = 'r' -- regular tables /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// -- RLS is disabled /// and not c.relrowsecurity /// and dep.objid is null -- exclude tables owned by extensions /// group by /// n.nspname, /// c.relname) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"policyExistsRlsDisabled\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0007_policy_exists_rls_disabled"] #[serde(skip_serializing_if = "Option::is_none")] - pub policy_exists_rls_disabled: Option>, + pub policy_exists_rls_disabled: Option>, #[doc = "/// # RLS Disabled in Public /// /// Detects cases where row level security (RLS) has not been enabled on tables in schemas exposed to PostgREST /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'rls_disabled_in_public' as \"name!\", /// 'RLS Disabled in Public' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects cases where row level security (RLS) has not been enabled on tables in schemas exposed to PostgREST' as \"description!\", /// format( /// 'Table \\`%s.%s\\` is public, but RLS has not been enabled.', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0013_rls_disabled_in_public' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'rls_disabled_in_public_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// where /// c.relkind = 'r' -- regular tables /// -- RLS is disabled /// and not c.relrowsecurity /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))) /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"rlsDisabledInPublic\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0013_rls_disabled_in_public"] #[serde(skip_serializing_if = "Option::is_none")] - pub rls_disabled_in_public: Option>, + pub rls_disabled_in_public: Option>, #[doc = "/// # RLS Enabled No Policy /// /// Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created. /// /// ## SQL Query /// /// sql /// ( /// select /// 'rls_enabled_no_policy' as \"name!\", /// 'RLS Enabled No Policy' as \"title!\", /// 'INFO' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has RLS enabled, but no policies exist', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0008_rls_enabled_no_policy' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'rls_enabled_no_policy_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// left join pg_catalog.pg_policy p /// on p.polrelid = c.oid /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind = 'r' -- regular tables /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// -- RLS is enabled /// and c.relrowsecurity /// and p.polname is null /// and dep.objid is null -- exclude tables owned by extensions /// group by /// n.nspname, /// c.relname) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"rlsEnabledNoPolicy\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0008_rls_enabled_no_policy"] #[serde(skip_serializing_if = "Option::is_none")] - pub rls_enabled_no_policy: Option>, + pub rls_enabled_no_policy: Option>, #[doc = "/// # RLS references user metadata /// /// Detects when Supabase Auth user_metadata is referenced insecurely in a row level security (RLS) policy. /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// with policies as ( /// select /// nsp.nspname as schema_name, /// pb.tablename as table_name, /// polname as policy_name, /// qual, /// with_check /// from /// pg_catalog.pg_policy pa /// join pg_catalog.pg_class pc /// on pa.polrelid = pc.oid /// join pg_catalog.pg_namespace nsp /// on pc.relnamespace = nsp.oid /// join pg_catalog.pg_policies pb /// on pc.relname = pb.tablename /// and nsp.nspname = pb.schemaname /// and pa.polname = pb.policyname /// ) /// select /// 'rls_references_user_metadata' as \"name!\", /// 'RLS references user metadata' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects when Supabase Auth user_metadata is referenced insecurely in a row level security (RLS) policy.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has a row level security policy \\`%s\\` that references Supabase Auth \\`user_metadata\\`. \\`user_metadata\\` is editable by end users and should never be used in a security context.', /// schema_name, /// table_name, /// policy_name /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0015_rls_references_user_metadata' as \"remediation!\", /// jsonb_build_object( /// 'schema', schema_name, /// 'name', table_name, /// 'type', 'table' /// ) as \"metadata!\", /// format('rls_references_user_metadata_%s_%s_%s', schema_name, table_name, policy_name) as \"cache_key!\" /// from /// policies /// where /// schema_name not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and ( /// -- Example: auth.jwt() -> 'user_metadata' /// -- False positives are possible, but it isn't practical to string match /// -- If false positive rate is too high, this expression can iterate /// qual like '%auth.jwt()%user_metadata%' /// or qual like '%current_setting(%request.jwt.claims%)%user_metadata%' /// or with_check like '%auth.jwt()%user_metadata%' /// or with_check like '%current_setting(%request.jwt.claims%)%user_metadata%' /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"rlsReferencesUserMetadata\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0015_rls_references_user_metadata"] #[serde(skip_serializing_if = "Option::is_none")] - pub rls_references_user_metadata: Option>, + pub rls_references_user_metadata: + Option>, #[doc = "/// # Security Definer View /// /// Detects views defined with the SECURITY DEFINER property. These views enforce Postgres permissions and row level security policies (RLS) of the view creator, rather than that of the querying user /// /// Note: This rule requires Supabase roles (anon, authenticated, service_role). /// It will be automatically skipped if these roles don't exist in your database. /// /// ## SQL Query /// /// sql /// ( /// select /// 'security_definer_view' as \"name!\", /// 'Security Definer View' as \"title!\", /// 'ERROR' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Detects views defined with the SECURITY DEFINER property. These views enforce Postgres permissions and row level security policies (RLS) of the view creator, rather than that of the querying user' as \"description!\", /// format( /// 'View \\`%s.%s\\` is defined with the SECURITY DEFINER property', /// n.nspname, /// c.relname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=0010_security_definer_view' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'type', 'view' /// ) as \"metadata!\", /// format( /// 'security_definer_view_%s_%s', /// n.nspname, /// c.relname /// ) as \"cache_key!\" /// from /// pg_catalog.pg_class c /// join pg_catalog.pg_namespace n /// on n.oid = c.relnamespace /// left join pg_catalog.pg_depend dep /// on c.oid = dep.objid /// and dep.deptype = 'e' /// where /// c.relkind = 'v' /// and ( /// pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') /// or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') /// ) /// and substring(pg_catalog.version() from 'PostgreSQL (\\[0-9]+)') >= '15' -- security invoker was added in pg15 /// and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))) /// and n.nspname not in ( /// '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault' /// ) /// and dep.objid is null -- exclude views owned by extensions /// and not ( /// lower(coalesce(c.reloptions::text,'{}'))::text\\[] /// && array\\[ /// 'security_invoker=1', /// 'security_invoker=true', /// 'security_invoker=yes', /// 'security_invoker=on' /// ] /// )) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"securityDefinerView\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=0010_security_definer_view"] #[serde(skip_serializing_if = "Option::is_none")] - pub security_definer_view: Option>, + pub security_definer_view: Option>, #[doc = "/// # Unsupported reg types /// /// Identifies columns using unsupported reg* types outside pg_catalog schema, which prevents database upgrades using pg_upgrade. /// /// ## SQL Query /// /// sql /// ( /// select /// 'unsupported_reg_types' as \"name!\", /// 'Unsupported reg types' as \"title!\", /// 'WARN' as \"level!\", /// 'EXTERNAL' as \"facing!\", /// array\\['SECURITY'] as \"categories!\", /// 'Identifies columns using unsupported reg* types outside pg_catalog schema, which prevents database upgrades using pg_upgrade.' as \"description!\", /// format( /// 'Table \\`%s.%s\\` has a column \\`%s\\` with unsupported reg* type \\`%s\\`.', /// n.nspname, /// c.relname, /// a.attname, /// t.typname /// ) as \"detail!\", /// 'https://supabase.com/docs/guides/database/database-linter?lint=unsupported_reg_types' as \"remediation!\", /// jsonb_build_object( /// 'schema', n.nspname, /// 'name', c.relname, /// 'column', a.attname, /// 'type', 'table' /// ) as \"metadata!\", /// format( /// 'unsupported_reg_types_%s_%s_%s', /// n.nspname, /// c.relname, /// a.attname /// ) AS cache_key /// from /// pg_catalog.pg_attribute a /// join pg_catalog.pg_class c /// on a.attrelid = c.oid /// join pg_catalog.pg_namespace n /// on c.relnamespace = n.oid /// join pg_catalog.pg_type t /// on a.atttypid = t.oid /// join pg_catalog.pg_namespace tn /// on t.typnamespace = tn.oid /// where /// tn.nspname = 'pg_catalog' /// and t.typname in ('regcollation', 'regconfig', 'regdictionary', 'regnamespace', 'regoper', 'regoperator', 'regproc', 'regprocedure') /// and n.nspname not in ('pg_catalog', 'information_schema', 'pgsodium')) /// /// /// ## Configuration /// /// Enable or disable this rule in your configuration: /// /// json /// { /// \"splinter\": { /// \"rules\": { /// \"security\": { /// \"unsupportedRegTypes\": \"warn\" /// } /// } /// } /// } /// /// /// ## Remediation /// /// See: https://supabase.com/docs/guides/database/database-linter?lint=unsupported_reg_types"] #[serde(skip_serializing_if = "Option::is_none")] - pub unsupported_reg_types: Option>, + pub unsupported_reg_types: Option>, } impl Security { const GROUP_NAME: &'static str = "security"; @@ -743,6 +846,167 @@ impl Security { _ => None, } } + #[doc = r" Build matchers for rules in this group that have ignore patterns configured"] + pub fn get_ignore_matchers( + &self, + ) -> rustc_hash::FxHashMap<&'static str, pgls_matcher::Matcher> { + let mut matchers = rustc_hash::FxHashMap::default(); + if let Some(conf) = &self.auth_users_exposed { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("authUsersExposed", m); + } + } + } + if let Some(conf) = &self.extension_in_public { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("extensionInPublic", m); + } + } + } + if let Some(conf) = &self.extension_versions_outdated { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("extensionVersionsOutdated", m); + } + } + } + if let Some(conf) = &self.fkey_to_auth_unique { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("fkeyToAuthUnique", m); + } + } + } + if let Some(conf) = &self.foreign_table_in_api { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("foreignTableInApi", m); + } + } + } + if let Some(conf) = &self.function_search_path_mutable { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("functionSearchPathMutable", m); + } + } + } + if let Some(conf) = &self.insecure_queue_exposed_in_api { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("insecureQueueExposedInApi", m); + } + } + } + if let Some(conf) = &self.materialized_view_in_api { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("materializedViewInApi", m); + } + } + } + if let Some(conf) = &self.policy_exists_rls_disabled { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("policyExistsRlsDisabled", m); + } + } + } + if let Some(conf) = &self.rls_disabled_in_public { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("rlsDisabledInPublic", m); + } + } + } + if let Some(conf) = &self.rls_enabled_no_policy { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("rlsEnabledNoPolicy", m); + } + } + } + if let Some(conf) = &self.rls_references_user_metadata { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("rlsReferencesUserMetadata", m); + } + } + } + if let Some(conf) = &self.security_definer_view { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("securityDefinerView", m); + } + } + } + if let Some(conf) = &self.unsupported_reg_types { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert("unsupportedRegTypes", m); + } + } + } + matchers + } } #[doc = r" Push the configured rules to the analyser"] pub fn push_to_analyser_rules( diff --git a/crates/pgls_matcher/Cargo.toml b/crates/pgls_matcher/Cargo.toml new file mode 100644 index 000000000..a01c9ecb5 --- /dev/null +++ b/crates/pgls_matcher/Cargo.toml @@ -0,0 +1,16 @@ +[package] +authors.workspace = true +categories.workspace = true +description = "Unix shell style pattern matching for Postgres Language Server" +edition.workspace = true +homepage.workspace = true +keywords.workspace = true +license.workspace = true +name = "pgls_matcher" +repository.workspace = true +version = "0.0.0" + +[dependencies] +pgls_console = { workspace = true } +pgls_diagnostics = { workspace = true } +rustc-hash = { workspace = true } diff --git a/crates/pgls_workspace/src/matcher/mod.rs b/crates/pgls_matcher/src/lib.rs similarity index 94% rename from crates/pgls_workspace/src/matcher/mod.rs rename to crates/pgls_matcher/src/lib.rs index 6dbfe11ee..5ee993cb7 100644 --- a/crates/pgls_workspace/src/matcher/mod.rs +++ b/crates/pgls_matcher/src/lib.rs @@ -135,8 +135,8 @@ impl Diagnostic for PatternError { #[cfg(test)] mod test { - use crate::matcher::Matcher; - use crate::matcher::pattern::MatchOptions; + use crate::Matcher; + use crate::pattern::MatchOptions; use std::env; #[test] @@ -145,7 +145,7 @@ mod test { let dir = format!("{}/**/*.rs", current.display()); let mut ignore = Matcher::new(MatchOptions::default()); ignore.add_pattern(&dir).unwrap(); - let path = env::current_dir().unwrap().join("src/workspace.rs"); + let path = env::current_dir().unwrap().join("src/lib.rs"); let result = ignore.matches(path.to_str().unwrap()); assert!(result); @@ -157,7 +157,7 @@ mod test { let dir = format!("{}/**/*.rs", current.display()); let mut ignore = Matcher::new(MatchOptions::default()); ignore.add_pattern(&dir).unwrap(); - let path = env::current_dir().unwrap().join("src/workspace.rs"); + let path = env::current_dir().unwrap().join("src/lib.rs"); let result = ignore.matches_path(path.as_path()); assert!(result); @@ -184,14 +184,14 @@ mod test { #[test] fn matches_single_path() { - let dir = "workspace.rs"; + let dir = "lib.rs"; let mut ignore = Matcher::new(MatchOptions { require_literal_separator: true, case_sensitive: true, require_literal_leading_dot: true, }); ignore.add_pattern(dir).unwrap(); - let path = env::current_dir().unwrap().join("src/workspace.rs"); + let path = env::current_dir().unwrap().join("src/lib.rs"); let result = ignore.matches(path.to_str().unwrap()); assert!(result); diff --git a/crates/pgls_workspace/src/matcher/pattern.rs b/crates/pgls_matcher/src/pattern.rs similarity index 99% rename from crates/pgls_workspace/src/matcher/pattern.rs rename to crates/pgls_matcher/src/pattern.rs index aa38979e5..f45e7f53a 100644 --- a/crates/pgls_workspace/src/matcher/pattern.rs +++ b/crates/pgls_matcher/src/pattern.rs @@ -1,8 +1,6 @@ -use crate::matcher::pattern::CharSpecifier::{CharRange, SingleChar}; -use crate::matcher::pattern::MatchResult::{ - EntirePatternDoesntMatch, Match, SubPatternDoesntMatch, -}; -use crate::matcher::pattern::PatternToken::{ +use crate::pattern::CharSpecifier::{CharRange, SingleChar}; +use crate::pattern::MatchResult::{EntirePatternDoesntMatch, Match, SubPatternDoesntMatch}; +use crate::pattern::PatternToken::{ AnyChar, AnyExcept, AnyPattern, AnyRecursiveSequence, AnySequence, AnyWithin, Char, }; use std::error::Error; diff --git a/crates/pgls_splinter/Cargo.toml b/crates/pgls_splinter/Cargo.toml index e42d9a51c..a3246cba4 100644 --- a/crates/pgls_splinter/Cargo.toml +++ b/crates/pgls_splinter/Cargo.toml @@ -11,12 +11,14 @@ repository.workspace = true version = "0.0.0" [dependencies] -pgls_analyse.workspace = true -pgls_diagnostics.workspace = true -pgls_schema_cache.workspace = true -serde.workspace = true -serde_json.workspace = true -sqlx.workspace = true +pgls_analyse.workspace = true +pgls_configuration.workspace = true +pgls_diagnostics.workspace = true +pgls_matcher.workspace = true +pgls_schema_cache.workspace = true +serde.workspace = true +serde_json.workspace = true +sqlx.workspace = true [dev-dependencies] insta.workspace = true diff --git a/crates/pgls_splinter/src/lib.rs b/crates/pgls_splinter/src/lib.rs index 7552c744e..73450fc59 100644 --- a/crates/pgls_splinter/src/lib.rs +++ b/crates/pgls_splinter/src/lib.rs @@ -6,6 +6,7 @@ pub mod rule; pub mod rules; use pgls_analyse::{AnalysisFilter, RegistryVisitor, RuleMeta}; +use pgls_configuration::splinter::Rules; use pgls_schema_cache::SchemaCache; use sqlx::PgPool; @@ -17,6 +18,8 @@ pub use rule::SplinterRule; pub struct SplinterParams<'a> { pub conn: &'a PgPool, pub schema_cache: Option<&'a SchemaCache>, + /// Optional rules configuration for per-rule database object filtering + pub rules_config: Option<&'a Rules>, } /// Visitor that collects enabled splinter rules based on filter @@ -133,8 +136,30 @@ pub async fn run_splinter( tx.commit().await?; - // Convert results to diagnostics - let diagnostics: Vec = results.into_iter().map(Into::into).collect(); + let mut diagnostics: Vec = results.into_iter().map(Into::into).collect(); + + if let Some(rules_config) = params.rules_config { + let rule_matchers = rules_config.get_ignore_matchers(); + + if !rule_matchers.is_empty() { + diagnostics.retain(|diag| { + let rule_name = diag.category.name().split('/').next_back().unwrap_or(""); + + if let Some(matcher) = rule_matchers.get(rule_name) { + if let (Some(schema), Some(name)) = + (&diag.advices.schema, &diag.advices.object_name) + { + let object_identifier = format!("{schema}.{name}"); + + if matcher.matches(&object_identifier) { + return false; + } + } + } + true + }); + } + } Ok(diagnostics) } diff --git a/crates/pgls_splinter/tests/diagnostics.rs b/crates/pgls_splinter/tests/diagnostics.rs index 2764200db..316fce687 100644 --- a/crates/pgls_splinter/tests/diagnostics.rs +++ b/crates/pgls_splinter/tests/diagnostics.rs @@ -1,4 +1,6 @@ use pgls_analyse::AnalysisFilter; +use pgls_configuration::rules::RuleConfiguration; +use pgls_configuration::splinter::{Performance, Rules, SplinterRuleOptions}; use pgls_console::fmt::{Formatter, HTML}; use pgls_diagnostics::{Diagnostic, LogCategory, Visit}; use pgls_splinter::{SplinterParams, run_splinter}; @@ -64,6 +66,7 @@ impl TestSetup<'_> { SplinterParams { conn: self.test_db, schema_cache: None, + rules_config: None, }, &filter, ) @@ -248,6 +251,7 @@ async fn missing_roles_runs_generic_checks_only(test_db: PgPool) { SplinterParams { conn: &test_db, schema_cache: None, + rules_config: None, }, &filter, ) @@ -271,6 +275,7 @@ async fn missing_roles_runs_generic_checks_only(test_db: PgPool) { SplinterParams { conn: &test_db, schema_cache: None, + rules_config: None, }, &filter, ) @@ -282,3 +287,187 @@ async fn missing_roles_runs_generic_checks_only(test_db: PgPool) { "Expected to detect generic issues (no primary key) even without Supabase roles" ); } + +#[sqlx::test(migrator = "pgls_test_utils::MIGRATIONS")] +async fn ignore_filtering_filters_matching_objects(test_db: PgPool) { + // Create multiple tables without primary keys + sqlx::raw_sql( + r#" + CREATE TABLE public.ignored_table (name text); + CREATE TABLE public.another_ignored (name text); + CREATE TABLE public.not_ignored (name text); + "#, + ) + .execute(&test_db) + .await + .expect("Failed to create test tables"); + + // First, run without any ignore config - should get diagnostics for all 3 tables + let filter = AnalysisFilter::default(); + let diagnostics_without_ignore = run_splinter( + SplinterParams { + conn: &test_db, + schema_cache: None, + rules_config: None, + }, + &filter, + ) + .await + .expect("Failed to run splinter checks"); + + // Filter to only noPrimaryKey diagnostics + let no_pk_diagnostics: Vec<_> = diagnostics_without_ignore + .iter() + .filter(|d| d.category.name().contains("noPrimaryKey")) + .collect(); + + assert_eq!( + no_pk_diagnostics.len(), + 3, + "Expected 3 noPrimaryKey diagnostics without ignore config, got {}", + no_pk_diagnostics.len() + ); + + // Now run with ignore config that filters out some tables + let rules_config = Rules { + recommended: None, + all: None, + performance: Some(Performance { + recommended: None, + all: None, + auth_rls_initplan: None, + duplicate_index: None, + multiple_permissive_policies: None, + no_primary_key: Some(RuleConfiguration::WithOptions( + pgls_configuration::rules::RuleWithOptions { + level: pgls_configuration::rules::RulePlainConfiguration::Warn, + options: SplinterRuleOptions { + ignore: vec![ + "public.ignored_table".to_string(), + "public.another_*".to_string(), // glob pattern + ], + }, + }, + )), + table_bloat: None, + unindexed_foreign_keys: None, + unused_index: None, + }), + security: None, + }; + + let diagnostics_with_ignore = run_splinter( + SplinterParams { + conn: &test_db, + schema_cache: None, + rules_config: Some(&rules_config), + }, + &filter, + ) + .await + .expect("Failed to run splinter checks with ignore config"); + + // Filter to only noPrimaryKey diagnostics + let no_pk_diagnostics_filtered: Vec<_> = diagnostics_with_ignore + .iter() + .filter(|d| d.category.name().contains("noPrimaryKey")) + .collect(); + + assert_eq!( + no_pk_diagnostics_filtered.len(), + 1, + "Expected 1 noPrimaryKey diagnostic after ignore filtering (only public.not_ignored), got {}", + no_pk_diagnostics_filtered.len() + ); + + // Verify the remaining diagnostic is for public.not_ignored + let remaining = &no_pk_diagnostics_filtered[0]; + assert_eq!( + remaining.advices.schema.as_deref(), + Some("public"), + "Expected schema 'public'" + ); + assert_eq!( + remaining.advices.object_name.as_deref(), + Some("not_ignored"), + "Expected object_name 'not_ignored'" + ); +} + +#[sqlx::test(migrator = "pgls_test_utils::MIGRATIONS")] +async fn ignore_filtering_with_schema_wildcard(test_db: PgPool) { + // Create a schema and tables + sqlx::raw_sql( + r#" + CREATE SCHEMA audit; + CREATE TABLE audit.log1 (data text); + CREATE TABLE audit.log2 (data text); + CREATE TABLE public.regular_table (data text); + "#, + ) + .execute(&test_db) + .await + .expect("Failed to create test tables"); + + // Run with ignore config that filters out all audit schema tables + let rules_config = Rules { + recommended: None, + all: None, + performance: Some(Performance { + recommended: None, + all: None, + auth_rls_initplan: None, + duplicate_index: None, + multiple_permissive_policies: None, + no_primary_key: Some(RuleConfiguration::WithOptions( + pgls_configuration::rules::RuleWithOptions { + level: pgls_configuration::rules::RulePlainConfiguration::Warn, + options: SplinterRuleOptions { + ignore: vec!["audit.*".to_string()], + }, + }, + )), + table_bloat: None, + unindexed_foreign_keys: None, + unused_index: None, + }), + security: None, + }; + + let filter = AnalysisFilter::default(); + let diagnostics = run_splinter( + SplinterParams { + conn: &test_db, + schema_cache: None, + rules_config: Some(&rules_config), + }, + &filter, + ) + .await + .expect("Failed to run splinter checks"); + + // Filter to only noPrimaryKey diagnostics + let no_pk_diagnostics: Vec<_> = diagnostics + .iter() + .filter(|d| d.category.name().contains("noPrimaryKey")) + .collect(); + + // Should only have the public.regular_table diagnostic + assert_eq!( + no_pk_diagnostics.len(), + 1, + "Expected 1 noPrimaryKey diagnostic (audit tables should be ignored), got {}", + no_pk_diagnostics.len() + ); + + assert_eq!( + no_pk_diagnostics[0].advices.schema.as_deref(), + Some("public"), + "Expected remaining diagnostic to be in public schema" + ); + assert_eq!( + no_pk_diagnostics[0].advices.object_name.as_deref(), + Some("regular_table"), + "Expected remaining diagnostic to be for regular_table" + ); +} diff --git a/crates/pgls_workspace/Cargo.toml b/crates/pgls_workspace/Cargo.toml index 5264208f5..49d6ecb08 100644 --- a/crates/pgls_workspace/Cargo.toml +++ b/crates/pgls_workspace/Cargo.toml @@ -28,6 +28,7 @@ pgls_env = { workspace = true } pgls_fs = { workspace = true, features = ["serde"] } pgls_hover = { workspace = true } pgls_lexer = { workspace = true } +pgls_matcher = { workspace = true } pgls_plpgsql_check = { workspace = true } pgls_query = { workspace = true } pgls_query_ext = { workspace = true } diff --git a/crates/pgls_workspace/src/lib.rs b/crates/pgls_workspace/src/lib.rs index 025bacab8..fafec400e 100644 --- a/crates/pgls_workspace/src/lib.rs +++ b/crates/pgls_workspace/src/lib.rs @@ -7,7 +7,6 @@ pub mod configuration; pub mod diagnostics; pub mod dome; pub mod features; -pub mod matcher; pub mod settings; pub mod workspace; diff --git a/crates/pgls_workspace/src/matcher/LICENCE-APACHE b/crates/pgls_workspace/src/matcher/LICENCE-APACHE deleted file mode 100644 index 4aca254d7..000000000 --- a/crates/pgls_workspace/src/matcher/LICENCE-APACHE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright (c) 2023 Biome Developers and Contributors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - diff --git a/crates/pgls_workspace/src/matcher/LICENSE-MIT b/crates/pgls_workspace/src/matcher/LICENSE-MIT deleted file mode 100644 index 17eebcc23..000000000 --- a/crates/pgls_workspace/src/matcher/LICENSE-MIT +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2014 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - diff --git a/crates/pgls_workspace/src/settings.rs b/crates/pgls_workspace/src/settings.rs index 9125b7642..99dbb6fbc 100644 --- a/crates/pgls_workspace/src/settings.rs +++ b/crates/pgls_workspace/src/settings.rs @@ -25,9 +25,9 @@ use sqlx::postgres::PgConnectOptions; use crate::{ WorkspaceError, - matcher::Matcher, workspace::{ProjectKey, WorkspaceData}, }; +use pgls_matcher::Matcher; #[derive(Debug, Default)] /// The information tracked for each project diff --git a/xtask/codegen/src/generate_configuration.rs b/xtask/codegen/src/generate_configuration.rs index 2824974e5..e5361e9cf 100644 --- a/xtask/codegen/src/generate_configuration.rs +++ b/xtask/codegen/src/generate_configuration.rs @@ -172,9 +172,21 @@ fn generate_lint_mod_file(tool: &ToolConfig) -> String { let generated_file = tool.generated_file().trim_end_matches(".rs"); let generated_file_ident = Ident::new(generated_file, Span::call_site()); + // For splinter, we need to include the options module + let options_module = if tool.name == "splinter" { + quote! { + mod options; + pub use options::SplinterRuleOptions; + } + } else { + quote! {} + }; + let content = quote! { //! Generated file, do not edit by hand, see `xtask/codegen` + #options_module + mod #generated_file_ident; use biome_deserialize::StringSet; @@ -288,6 +300,34 @@ fn generate_lint_rules_file( } let category_prefix = tool.category_prefix(); + + // Generate get_ignore_matchers() method for splinter only + // We need to generate this method separately in each group struct + // because we need direct access to the rule configurations + let get_ignore_matchers_method = if tool.name == "splinter" { + // Generate code to call each group's get_ignore_matchers method + let mut group_matcher_code = Vec::new(); + for group_ident in group_idents.iter() { + group_matcher_code.push(quote! { + if let Some(group) = &self.#group_ident { + matchers.extend(group.get_ignore_matchers()); + } + }); + } + + quote! { + /// Build matchers for all rules that have ignore patterns configured. + /// Returns a map from rule name (camelCase) to the matcher. + pub fn get_ignore_matchers(&self) -> rustc_hash::FxHashMap<&'static str, pgls_matcher::Matcher> { + let mut matchers = rustc_hash::FxHashMap::default(); + #( #group_matcher_code )* + matchers + } + } + } else { + quote! {} + }; + let rules_struct_content = quote! { //! Generated file, do not edit by hand, see `xtask/codegen` @@ -425,6 +465,8 @@ fn generate_lint_rules_file( #( #group_as_disabled_rules )* disabled_rules } + + #get_ignore_matchers_method } #( #struct_groups )* @@ -476,6 +518,9 @@ fn generate_lint_group_struct( let mut get_rule_configuration_line = Vec::new(); let mut get_severity_lines = Vec::new(); + // For splinter, generate code to build matchers from ignore patterns + let mut splinter_ignore_matcher_lines = Vec::new(); + for (index, (rule, metadata)) in rules.iter().enumerate() { let summary = extract_summary_from_docs(metadata.docs); let rule_position = Literal::u8_unsuffixed(index as u8); @@ -496,10 +541,28 @@ fn generate_lint_group_struct( #rule }); - // For splinter rules, use () as options since they don't have configurable options + // For splinter, generate code to check each rule's ignore patterns + if tool_name == "splinter" { + let rule_str = Literal::string(rule); + splinter_ignore_matcher_lines.push(quote! { + if let Some(conf) = &self.#rule_identifier { + if let Some(options) = conf.get_options_ref() { + if !options.ignore.is_empty() { + let mut m = pgls_matcher::Matcher::new(pgls_matcher::MatchOptions::default()); + for p in &options.ignore { + let _ = m.add_pattern(p); + } + matchers.insert(#rule_str, m); + } + } + } + }); + } + + // For splinter rules, use SplinterRuleOptions for the shared ignore patterns // For linter rules, use pgls_analyser::options::#rule_name let rule_option_type = if tool_name == "splinter" { - quote! { () } + quote! { crate::splinter::SplinterRuleOptions } } else { quote! { pgls_analyser::options::#rule_name } }; @@ -552,6 +615,20 @@ fn generate_lint_group_struct( let group_pascal_ident = Ident::new(&to_capitalized(group), Span::call_site()); + // For splinter, generate get_ignore_matchers method + let get_ignore_matchers_group_method = if tool_name == "splinter" { + quote! { + /// Build matchers for rules in this group that have ignore patterns configured + pub fn get_ignore_matchers(&self) -> rustc_hash::FxHashMap<&'static str, pgls_matcher::Matcher> { + let mut matchers = rustc_hash::FxHashMap::default(); + #( #splinter_ignore_matcher_lines )* + matchers + } + } + } else { + quote! {} + }; + quote! { #[derive(Clone, Debug, Default, Deserialize, Eq, Merge, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(JsonSchema))] @@ -652,6 +729,8 @@ fn generate_lint_group_struct( _ => None } } + + #get_ignore_matchers_group_method } } } diff --git a/xtask/codegen/src/generate_splinter.rs b/xtask/codegen/src/generate_splinter.rs index 6dc94bd0e..79616821a 100644 --- a/xtask/codegen/src/generate_splinter.rs +++ b/xtask/codegen/src/generate_splinter.rs @@ -90,8 +90,8 @@ fn extract_metadata_from_sql(sql_path: &Path, category: &str) -> Result