feat(filters): allowlist mode for filename filters
- filter rules gain mode ('exclude'|'allow'); nearest allow rule governs a
directory subtree, extensions outside it are filtered before fetch
- filename_extension() now requires a well-formed suffix, so dated names like
'CRA_V3.1手册_2024-07-31_en' no longer fake an extension; extensionless
files are never filtered
- API accepts {mode, extensions}; UI editor becomes grouped format chips with
keep/exclude modes (keep-list default: docs/text/scripts/images)
- migration 000036 + integration tests for allow, nesting and restore
This commit is contained in:
@@ -15,7 +15,7 @@ func (s *Store) ListFilenameFilterRules(ctx context.Context, connectionID string
|
||||
if connectionID == "" || len(connectionID) > 36 {
|
||||
return nil, governance.ErrInvalidFilenameFilter
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT source_connection_id,directory_path,excluded_extensions,updated_by,updated_at
|
||||
rows, err := s.db.Query(ctx, `SELECT source_connection_id,directory_path,mode,excluded_extensions,updated_by,updated_at
|
||||
FROM filename_filter_rules WHERE source_connection_id=$1 ORDER BY LENGTH(directory_path),directory_path`, connectionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list filename filters: %w", err)
|
||||
@@ -24,7 +24,7 @@ FROM filename_filter_rules WHERE source_connection_id=$1 ORDER BY LENGTH(directo
|
||||
result := make([]governance.FilenameFilterRule, 0)
|
||||
for rows.Next() {
|
||||
var rule governance.FilenameFilterRule
|
||||
if err := rows.Scan(&rule.ConnectionID, &rule.DirectoryPath, &rule.ExcludedExtensions, &rule.UpdatedBy, &rule.UpdatedAt); err != nil {
|
||||
if err := rows.Scan(&rule.ConnectionID, &rule.DirectoryPath, &rule.Mode, &rule.ExcludedExtensions, &rule.UpdatedBy, &rule.UpdatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan filename filter: %w", err)
|
||||
}
|
||||
result = append(result, rule)
|
||||
@@ -39,13 +39,17 @@ func (s *Store) MutateFilenameFilterRuleWithOperation(ctx context.Context, reque
|
||||
if err := request.Validate(); err != nil {
|
||||
return governance.FilenameFilterRule{}, false, err
|
||||
}
|
||||
if request.Mode == "" {
|
||||
request.Mode = governance.FilenameFilterExclude
|
||||
}
|
||||
fingerprint, err := operationFingerprint(struct {
|
||||
ConnectionID string `json:"connection_id"`
|
||||
DirectoryPath string `json:"directory_path"`
|
||||
Mode string `json:"mode"`
|
||||
ExcludedExtensions []string `json:"excluded_extensions"`
|
||||
OperatorRef string `json:"operator_ref"`
|
||||
Clear bool `json:"clear"`
|
||||
}{request.ConnectionID, request.DirectoryPath, request.ExcludedExtensions, request.OperatorRef, request.Clear})
|
||||
}{request.ConnectionID, request.DirectoryPath, request.Mode, request.ExcludedExtensions, request.OperatorRef, request.Clear})
|
||||
if err != nil {
|
||||
return governance.FilenameFilterRule{}, false, err
|
||||
}
|
||||
@@ -87,17 +91,17 @@ WHERE head.source_connection_id=$1 AND node.node_type='folder' AND node.relative
|
||||
return governance.FilenameFilterRule{}, fmt.Errorf("clear filename filter: %w", err)
|
||||
}
|
||||
} else {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO filename_filter_rules(source_connection_id,directory_path,excluded_extensions,updated_by,created_at,updated_at)
|
||||
VALUES($1,$2,$3,$4,$5,$5)
|
||||
ON CONFLICT(source_connection_id,directory_path) DO UPDATE SET excluded_extensions=EXCLUDED.excluded_extensions,updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
|
||||
request.ConnectionID, request.DirectoryPath, request.ExcludedExtensions, request.OperatorRef, request.Now); err != nil {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO filename_filter_rules(source_connection_id,directory_path,mode,excluded_extensions,updated_by,created_at,updated_at)
|
||||
VALUES($1,$2,$5,$3,$4,$6,$6)
|
||||
ON CONFLICT(source_connection_id,directory_path) DO UPDATE SET mode=EXCLUDED.mode,excluded_extensions=EXCLUDED.excluded_extensions,updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
|
||||
request.ConnectionID, request.DirectoryPath, request.ExcludedExtensions, request.OperatorRef, request.Mode, request.Now); err != nil {
|
||||
return governance.FilenameFilterRule{}, fmt.Errorf("write filename filter: %w", err)
|
||||
}
|
||||
}
|
||||
if err := reconcileFilenameFilters(ctx, tx, request.ConnectionID, request.Now); err != nil {
|
||||
return governance.FilenameFilterRule{}, err
|
||||
}
|
||||
return governance.FilenameFilterRule{ConnectionID: request.ConnectionID, DirectoryPath: request.DirectoryPath, ExcludedExtensions: request.ExcludedExtensions, UpdatedBy: request.OperatorRef, UpdatedAt: request.Now}, nil
|
||||
return governance.FilenameFilterRule{ConnectionID: request.ConnectionID, DirectoryPath: request.DirectoryPath, Mode: request.Mode, ExcludedExtensions: request.ExcludedExtensions, UpdatedBy: request.OperatorRef, UpdatedAt: request.Now}, nil
|
||||
}
|
||||
|
||||
func reconcileFilenameFilters(ctx context.Context, tx pgx.Tx, connectionID string, now time.Time) error {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// Whitelist mode: the nearest allow rule governs a file; unlisted extensions
|
||||
// are filtered while extensionless and fake-extension names always pass.
|
||||
func TestFilenameFilterAllowModeKeepsOnlySelectedExtensions(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-allow','dingtalk','白名单测试',true);
|
||||
INSERT INTO source_catalog_snapshots(id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
|
||||
VALUES('snapshot-allow','conn-allow',repeat('a',64),'白名单测试',6,2,4,NOW());
|
||||
INSERT INTO source_catalog_nodes(snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash,size_bytes,sort_order,direct_child_count,subtree_file_count,subtree_bytes)
|
||||
VALUES('snapshot-allow','root-allow',NULL,'folder','白名单测试','',repeat('a',64),NULL,-1,1,4,40),
|
||||
('snapshot-allow','folder-allow','root-allow','folder','资料','资料',repeat('b',64),NULL,0,4,4,40),
|
||||
('snapshot-allow','allow-pdf','folder-allow','file','手册.pdf','资料/手册.pdf',repeat('c',64),10,0,0,1,10),
|
||||
('snapshot-allow','allow-zip','folder-allow','file','固件.zip','资料/固件.zip',repeat('d',64),10,1,0,1,10),
|
||||
('snapshot-allow','allow-readme','folder-allow','file','README','资料/README',repeat('e',64),10,2,0,1,10),
|
||||
('snapshot-allow','allow-versioned','folder-allow','file','CRA_V3.1手册','资料/CRA_V3.1手册',repeat('f',64),10,3,0,1,10);
|
||||
INSERT INTO source_catalog_heads(source_connection_id,snapshot_id,activated_at) VALUES('conn-allow','snapshot-allow',NOW());`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 9, 15, 3, 0, 0, 0, time.UTC)
|
||||
rule, replayed, err := store.MutateFilenameFilterRuleWithOperation(ctx, governance.FilenameFilterMutation{
|
||||
ConnectionID: "conn-allow", Mode: governance.FilenameFilterAllow, ExcludedExtensions: []string{"pdf"}, OperatorRef: "admin", Now: now,
|
||||
}, "op-allow-set")
|
||||
if err != nil || replayed || rule.Mode != "allow" || len(rule.ExcludedExtensions) != 1 {
|
||||
t.Fatalf("set rule=%#v replayed=%v err=%v", rule, replayed, err)
|
||||
}
|
||||
page, err := store.ListCatalogNodes(ctx, governance.CatalogNodeFilter{ConnectionID: "conn-allow", ParentNodeID: "folder-allow", Limit: 50})
|
||||
if err != nil || page.Total != 3 {
|
||||
t.Fatalf("allow page=%#v err=%v", page, err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, item := range page.Items {
|
||||
names[item.Name] = true
|
||||
}
|
||||
if !names["手册.pdf"] || !names["README"] || !names["CRA_V3.1手册"] || names["固件.zip"] {
|
||||
t.Fatalf("allow page names=%v", names)
|
||||
}
|
||||
|
||||
// A deeper directory rule overrides the source-wide whitelist only below it.
|
||||
if _, _, err := store.MutateFilenameFilterRuleWithOperation(ctx, governance.FilenameFilterMutation{
|
||||
ConnectionID: "conn-allow", DirectoryPath: "资料", Mode: governance.FilenameFilterAllow, ExcludedExtensions: []string{"pdf", "zip"}, OperatorRef: "admin", Now: now.Add(time.Minute),
|
||||
}, "op-allow-nested"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err = store.ListCatalogNodes(ctx, governance.CatalogNodeFilter{ConnectionID: "conn-allow", ParentNodeID: "folder-allow", Limit: 50})
|
||||
if err != nil || page.Total != 4 {
|
||||
t.Fatalf("nested allow page=%#v err=%v", page, err)
|
||||
}
|
||||
{
|
||||
found := false
|
||||
for _, item := range page.Items {
|
||||
if item.Name == "固件.zip" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("nested allow must include zip page=%#v", page)
|
||||
}
|
||||
}
|
||||
|
||||
// Clearing the nested rule restores nearest-wins to the source whitelist.
|
||||
if _, _, err := store.MutateFilenameFilterRuleWithOperation(ctx, governance.FilenameFilterMutation{
|
||||
ConnectionID: "conn-allow", DirectoryPath: "资料", Mode: governance.FilenameFilterAllow, OperatorRef: "admin", Clear: true, Now: now.Add(2 * time.Minute),
|
||||
}, "op-allow-clear"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err = store.ListCatalogNodes(ctx, governance.CatalogNodeFilter{ConnectionID: "conn-allow", ParentNodeID: "folder-allow", Limit: 50})
|
||||
if err != nil || page.Total != 3 {
|
||||
t.Fatalf("cleared page=%#v err=%v", page, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Restore the 000035 exclude-only evaluator and loose extension parser.
|
||||
-- Allow rules cannot be expressed as a blocklist, so they are dropped.
|
||||
DELETE FROM filename_filter_rules WHERE mode = 'allow';
|
||||
|
||||
CREATE OR REPLACE FUNCTION filename_extension(p_name TEXT) RETURNS TEXT AS $$
|
||||
SELECT CASE
|
||||
WHEN COALESCE(p_name, '') ~ '\.[^.]+$'
|
||||
THEN LOWER(SUBSTRING(p_name FROM '\.([^.]+)$'))
|
||||
ELSE ''
|
||||
END
|
||||
$$ LANGUAGE SQL IMMUTABLE PARALLEL SAFE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION filename_is_filtered(
|
||||
p_connection_id VARCHAR(36), p_relative_path TEXT, p_name TEXT
|
||||
) RETURNS BOOLEAN AS $$
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM filename_filter_rules rule
|
||||
CROSS JOIN LATERAL UNNEST(rule.excluded_extensions) extension
|
||||
WHERE rule.source_connection_id = p_connection_id
|
||||
AND (rule.directory_path = ''
|
||||
OR p_relative_path LIKE rule.directory_path || '/%')
|
||||
AND extension = filename_extension(p_name)
|
||||
)
|
||||
$$ LANGUAGE SQL STABLE PARALLEL SAFE;
|
||||
|
||||
ALTER TABLE filename_filter_rules DROP COLUMN IF EXISTS mode;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Filename filters gain a mode: 'allow' turns a rule into a whitelist (the
|
||||
-- nearest matching allow rule governs a file and only listed extensions may
|
||||
-- be ingested), 'exclude' keeps the legacy additive blocklist. Both modes can
|
||||
-- coexist; a file must pass both. Files with no recognizable extension are
|
||||
-- never filtered (extensionless names, dates-with-dots, "手册 V2.1" style).
|
||||
ALTER TABLE filename_filter_rules
|
||||
ADD COLUMN mode VARCHAR(10) NOT NULL DEFAULT 'exclude'
|
||||
CHECK (mode IN ('exclude', 'allow'));
|
||||
|
||||
-- Only well-formed suffixes count as extensions; 'CRA_V3.1手册_2024-07-31_en'
|
||||
-- style names with stray dots no longer produce fake extensions.
|
||||
CREATE OR REPLACE FUNCTION filename_extension(p_name TEXT) RETURNS TEXT AS $$
|
||||
SELECT CASE
|
||||
WHEN COALESCE(p_name, '') ~ '\.[^.]+$'
|
||||
AND LOWER(SUBSTRING(p_name FROM '\.([^.]+)$')) ~ '^[a-z0-9][a-z0-9_-]{0,15}$'
|
||||
THEN LOWER(SUBSTRING(p_name FROM '\.([^.]+)$'))
|
||||
ELSE ''
|
||||
END
|
||||
$$ LANGUAGE SQL IMMUTABLE PARALLEL SAFE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION filename_is_filtered(
|
||||
p_connection_id VARCHAR(36), p_relative_path TEXT, p_name TEXT
|
||||
) RETURNS BOOLEAN AS $$
|
||||
WITH nearest_allow AS (
|
||||
SELECT rule.excluded_extensions AS extensions
|
||||
FROM filename_filter_rules rule
|
||||
WHERE rule.source_connection_id = p_connection_id
|
||||
AND rule.mode = 'allow'
|
||||
AND (rule.directory_path = ''
|
||||
OR p_relative_path LIKE rule.directory_path || '/%')
|
||||
ORDER BY LENGTH(rule.directory_path) DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT CASE
|
||||
WHEN filename_extension(p_name) = '' THEN FALSE
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM filename_filter_rules rule
|
||||
CROSS JOIN LATERAL UNNEST(rule.excluded_extensions) extension
|
||||
WHERE rule.source_connection_id = p_connection_id
|
||||
AND rule.mode = 'exclude'
|
||||
AND (rule.directory_path = ''
|
||||
OR p_relative_path LIKE rule.directory_path || '/%')
|
||||
AND extension = filename_extension(p_name)
|
||||
) THEN TRUE
|
||||
WHEN EXISTS (SELECT 1 FROM nearest_allow)
|
||||
THEN NOT EXISTS (SELECT 1 FROM nearest_allow
|
||||
WHERE filename_extension(p_name) = ANY(extensions))
|
||||
ELSE FALSE
|
||||
END
|
||||
$$ LANGUAGE SQL STABLE PARALLEL SAFE;
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 35 {
|
||||
t.Fatalf("migration count = %d, want 35", len(migrations))
|
||||
if len(migrations) != 36 {
|
||||
t.Fatalf("migration count = %d, want 36", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
Reference in New Issue
Block a user