Initial project source
这个提交包含在:
+359
@@ -0,0 +1,359 @@
|
||||
#!/usr/bin/env ruby
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "digest"
|
||||
require "pathname"
|
||||
require "yaml"
|
||||
require "strscan"
|
||||
|
||||
unless ARGV.empty? || ARGV == ["--catalog-only"]
|
||||
warn "data-contract verification failed: expected no arguments or exactly one --catalog-only"
|
||||
exit 1
|
||||
end
|
||||
catalog_only = ARGV == ["--catalog-only"]
|
||||
|
||||
root = Pathname.new(__dir__).join("../..").realpath
|
||||
rules = YAML.safe_load(root.join("contracts/datagov/data-and-api-rules.yml").read)
|
||||
catalog = YAML.safe_load(root.join(rules.dig("migrations", "catalog")).read)
|
||||
sample = YAML.safe_load(root.join("contracts/datagov/samples/integration-contract-probe.yml").read)
|
||||
|
||||
def fail_check(message)
|
||||
warn "data-contract verification failed: #{message}"
|
||||
exit 1
|
||||
end
|
||||
|
||||
# Bounded SR07 structural grammar, not a MySQL execution substitute.
|
||||
# Literal tokens are preserved; comments cannot satisfy column or constraint checks.
|
||||
def sr07_tokens(sql)
|
||||
scanner = StringScanner.new(sql)
|
||||
tokens = []
|
||||
until scanner.eos?
|
||||
if scanner.scan(/\s+|--[^\n]*(?:\n|\z)|#[^\n]*(?:\n|\z)/)
|
||||
next
|
||||
elsif scanner.peek(2) == "/*"
|
||||
fail_check("SR07 executable/hint comment forbidden") if scanner.peek(3).match?(%r{/\*[!+]})
|
||||
fail_check("SR07 unterminated comment") unless scanner.scan(%r{/\*.*?\*/}m)
|
||||
elsif token = scanner.scan(/'(?:[^'\\]|'')*'/)
|
||||
tokens << token
|
||||
elsif token = scanner.scan(/\x60[a-zA-Z_][a-zA-Z0-9_]*\x60/)
|
||||
tokens << token[1...-1].downcase
|
||||
elsif token = scanner.scan(/[a-zA-Z_][a-zA-Z0-9_]*|\d+|<>|>=|<=|[(),;=<>+*-]/)
|
||||
tokens << token.downcase
|
||||
else
|
||||
fail_check("SR07 unsupported SQL token")
|
||||
end
|
||||
end
|
||||
tokens
|
||||
end
|
||||
|
||||
def sr07_tables(sql)
|
||||
tokens = sr07_tokens(sql)
|
||||
tables = {}
|
||||
suffix = sr07_tokens("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin;")
|
||||
until tokens.empty?
|
||||
fail_check("SR07 only explicit CREATE TABLE is allowed") unless tokens.shift(2) == %w[create table]
|
||||
name = tokens.shift
|
||||
fail_check("SR07 invalid/duplicate table") unless name && name.match?(/\A[a-z][a-z0-9_]*\z/) && !tables.key?(name)
|
||||
fail_check("SR07 missing table body") unless tokens.shift == "("
|
||||
parts = []; part = []; depth = 1
|
||||
until tokens.empty?
|
||||
token = tokens.shift
|
||||
depth += 1 if token == "("
|
||||
depth -= 1 if token == ")"
|
||||
if depth.zero?
|
||||
fail_check("SR07 empty definition") if part.empty?
|
||||
parts << part
|
||||
break
|
||||
elsif depth == 1 && token == ","
|
||||
fail_check("SR07 empty definition") if part.empty?
|
||||
parts << part; part = []
|
||||
else
|
||||
part << token
|
||||
end
|
||||
end
|
||||
fail_check("SR07 unbalanced body") unless depth.zero?
|
||||
fail_check("SR07 engine/row format/collation drift") unless tokens.shift(suffix.length) == suffix
|
||||
tables[name] = parts
|
||||
end
|
||||
tables
|
||||
end
|
||||
|
||||
sr07_allowed = {
|
||||
"db/migration/governance/V20260920.158__create_asset_identity_composition.sql" => "20260920.158",
|
||||
"db/migration/governance/V20260920.159__create_asset_financial_batch.sql" => "20260920.159",
|
||||
"db/migration/dataproduct/V20260920.160__create_dataset_content.sql" => "20260920.160",
|
||||
"db/migration/dataproduct/V20260920.161__create_dataset_annotation.sql" => "20260920.161"
|
||||
}.freeze
|
||||
sr07_profiles = {}
|
||||
sr07_table_owners = {}
|
||||
rules.fetch("sr07MigrationProfiles").each do |profile|
|
||||
path = profile.fetch("path")
|
||||
fail_check("unknown/duplicate SR07 migration profile") unless profile.fetch("profile") == "SR07_V1" &&
|
||||
sr07_allowed[path] == profile.fetch("version") && !sr07_profiles.key?(path)
|
||||
fail_check("empty SR07 table profile") if profile.fetch("tables").empty?
|
||||
profile.fetch("tables").each do |table, shape|
|
||||
fail_check("duplicate SR07 table profile") if sr07_table_owners.key?(table)
|
||||
fail_check("unknown SR07 shape property") unless shape.keys.sort == %w[checks columns indexes primaryKey].sort
|
||||
fail_check("empty SR07 columns/constraints") if shape.fetch("columns").empty? || shape.fetch("checks").empty?
|
||||
fail_check("missing SR07 primary key") unless sr07_tokens(shape.fetch("primaryKey"))[0, 2] == %w[primary key]
|
||||
sr07_table_owners[table] = path
|
||||
end
|
||||
sr07_profiles[path] = profile
|
||||
end
|
||||
fail_check("SR07 profiles must exactly cover four approved migrations") unless sr07_profiles.keys.sort == sr07_allowed.keys.sort
|
||||
|
||||
def verify_sr07(sql, profile)
|
||||
actual = sr07_tables(sql)
|
||||
expected = profile.fetch("tables")
|
||||
fail_check("SR07 missing/extra table") unless actual.keys.sort == expected.keys.sort
|
||||
expected.each do |table, shape|
|
||||
definitions = shape.fetch("columns").map { |column, spec| sr07_tokens("#{column} #{spec}") } +
|
||||
[sr07_tokens(shape.fetch("primaryKey"))] +
|
||||
shape.fetch("indexes").map { |index| sr07_tokens(index) } +
|
||||
shape.fetch("checks").map { |check| sr07_tokens(check) }
|
||||
fail_check("SR07 structural mismatch in #{table}") unless actual.fetch(table) == definitions
|
||||
end
|
||||
end
|
||||
|
||||
# Closed domain contracts authorize structure, never a whole-file hash exemption.
|
||||
# Keep identifiers and literal tokens distinct and consume every statement.
|
||||
def domain_statements(sql)
|
||||
tokens = sr07_tokens(sql)
|
||||
result = []; statement = []; depth = 0
|
||||
tokens.each do |token|
|
||||
depth += 1 if token == "("
|
||||
depth -= 1 if token == ")"
|
||||
fail_check("domain unbalanced statement") if depth.negative?
|
||||
if token == ";"
|
||||
fail_check("domain invalid statement terminator") unless depth.zero? && !statement.empty?
|
||||
result << statement; statement = []
|
||||
else
|
||||
statement << token
|
||||
end
|
||||
end
|
||||
fail_check("domain unterminated statement") unless statement.empty? && depth.zero?
|
||||
result
|
||||
end
|
||||
|
||||
def domain_table(statement)
|
||||
fail_check("domain only explicit CREATE TABLE is allowed") unless statement[0, 2] == %w[create table]
|
||||
name = statement[2]
|
||||
fail_check("domain invalid table name/body") unless name&.match?(/\A[a-z][a-z0-9_]*\z/) && statement[3] == "("
|
||||
parts = []; part = []; depth = 1; closing = nil
|
||||
statement.each_with_index do |token, index|
|
||||
next if index < 4
|
||||
depth += 1 if token == "("
|
||||
depth -= 1 if token == ")"
|
||||
if depth.zero?
|
||||
fail_check("domain empty definition") if part.empty?
|
||||
parts << part; closing = index; break
|
||||
elsif depth == 1 && token == ","
|
||||
fail_check("domain empty definition") if part.empty?
|
||||
parts << part; part = []
|
||||
else
|
||||
part << token
|
||||
end
|
||||
end
|
||||
fail_check("domain missing table body end") unless closing
|
||||
[name, parts, statement[(closing + 1)..]]
|
||||
end
|
||||
|
||||
domain_allowed = {
|
||||
"db/migration/dataproduct/V20260921.166__create_dataset_input_registration.sql" => ["20260921.166", "dataproduct", %w[svc_dataset_input_registration], []],
|
||||
"db/migration/governance/V20260921.167__create_asset_compliance_reviews.sql" => ["20260921.167", "governance", %w[sec_compliance_review sec_compliance_revision sec_compliance_evidence sec_compliance_request], []],
|
||||
"db/migration/dataproduct/V20260921.172__support_dataset_annotation_dispute.sql" => ["20260921.172", "dataproduct", %w[svc_dataset_annotation_dispute], %w[svc_dataset_annotation_history svc_dataset_annotation_request]],
|
||||
"db/migration/dataops/V20260921.174__create_dataset_preparation_control.sql" => ["20260921.174", "dataops", %w[dev_dataset_preparation_task dev_dataset_preparation_plan_revision dev_dataset_preparation_command dev_dataset_preparation_run dev_dataset_preparation_artifact dev_dataset_preparation_history], []],
|
||||
"db/migration/governance/V20260921.175__create_asset_identity_source_binding_observation.sql" => ["20260921.175", "governance", %w[asset_identity_source_binding asset_identity_source_observation], []],
|
||||
"db/migration/governance/V20260921.176__create_financial_draft_input.sql" => ["20260921.176", "governance", %w[asset_financial_input asset_financial_input_revision asset_financial_input_operation asset_financial_input_request asset_financial_input_history], []]
|
||||
}.freeze
|
||||
domain_foreign_keys = {
|
||||
"asset_identity_source_observation" => "CONSTRAINT fk_identity_observation_binding FOREIGN KEY (binding_id) REFERENCES asset_identity_source_binding (binding_id)",
|
||||
"asset_financial_input_revision" => "CONSTRAINT fk_fin_revision_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)",
|
||||
"asset_financial_input_operation" => "CONSTRAINT fk_fin_operation_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)",
|
||||
"asset_financial_input_history" => "CONSTRAINT fk_fin_history_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)"
|
||||
}.transform_values { |definition| sr07_tokens(definition) }.freeze
|
||||
domain_profiles = {}; domain_table_owners = {}
|
||||
rules.fetch("closedDomainMigrationProfiles").each do |profile|
|
||||
fail_check("domain unknown profile property") unless profile.keys.sort == %w[profile path version ownerUnit tables alters].sort
|
||||
path = profile.fetch("path"); authority = domain_allowed[path]
|
||||
fail_check("unknown/duplicate domain migration profile") unless authority && profile.fetch("profile") == "CLOSED_DOMAIN_V1" && !domain_profiles.key?(path)
|
||||
fail_check("domain profile identity mismatch") unless [profile.fetch("version"), profile.fetch("ownerUnit")] == authority[0, 2]
|
||||
fail_check("domain profile table set mismatch") unless profile.fetch("tables").keys.sort == authority[2].sort
|
||||
fail_check("domain profile ALTER target set mismatch") unless profile.fetch("alters").map { |alter| alter.fetch("table") } == authority[3]
|
||||
profile.fetch("tables").each do |table, shape|
|
||||
fail_check("domain unknown shape property") unless shape.keys.sort == %w[definitions options]
|
||||
fail_check("domain empty shape") unless shape.values.all? { |value| value.is_a?(String) && !value.strip.empty? }
|
||||
domain_table_owners[table] = path
|
||||
end
|
||||
profile.fetch("alters").each do |alter|
|
||||
fail_check("domain unknown ALTER property") unless alter.keys.sort == %w[clauses table]
|
||||
end
|
||||
domain_profiles[path] = profile
|
||||
end
|
||||
fail_check("domain profiles must exactly cover six approved migrations") unless domain_profiles.keys.sort == domain_allowed.keys.sort
|
||||
|
||||
def verify_domain(sql, profile, foreign_keys)
|
||||
actual = domain_statements(sql)
|
||||
tables = profile.fetch("tables")
|
||||
alters = profile.fetch("alters")
|
||||
fail_check("domain missing/extra statement") unless actual.length == tables.length + alters.length
|
||||
tables.each_with_index do |(table, shape), index|
|
||||
name, definitions, options = domain_table(actual[index])
|
||||
fail_check("domain missing/extra/order table #{table}") unless name == table
|
||||
expected = domain_statements("CREATE TABLE #{table} (#{shape.fetch('definitions')}) #{shape.fetch('options')};")
|
||||
fail_check("domain profile injected statement") unless expected.length == 1
|
||||
_expected_name, expected_definitions, expected_options = domain_table(expected.first)
|
||||
approved = foreign_keys.key?(table) ? [foreign_keys.fetch(table)] : []
|
||||
[definitions, expected_definitions].each do |parts|
|
||||
found = parts.select { |part| part.each_cons(2).any? { |pair| pair == %w[foreign key] } }
|
||||
fail_check("domain foreign key contract mismatch in #{table}") unless found == approved
|
||||
end
|
||||
fail_check("domain structural mismatch in #{table}") unless definitions == expected_definitions && options == expected_options
|
||||
end
|
||||
alters.each_with_index do |alter, index|
|
||||
expected = domain_statements("ALTER TABLE #{alter.fetch('table')} #{alter.fetch('clauses')};")
|
||||
fail_check("domain profile injected ALTER") unless expected.length == 1
|
||||
fail_check("domain ALTER mismatch in #{alter.fetch('table')}") unless actual[tables.length + index] == expected.first
|
||||
end
|
||||
tables.keys
|
||||
end
|
||||
|
||||
expected_prefixes = {
|
||||
"dg_" => "integration",
|
||||
"ing_" => "dataops", "store_" => "dataops", "dev_" => "dataops", "ops_" => "dataops",
|
||||
"std_" => "governance", "md_" => "governance", "dq_" => "governance",
|
||||
"da_" => "governance", "wb_" => "governance",
|
||||
"mdm_" => "governance",
|
||||
"asset_" => "governance", "sec_" => "governance",
|
||||
"svc_" => "dataproduct", "metric_" => "dataproduct"
|
||||
}
|
||||
prefix_owners = rules.dig("database", "prefixOwners")
|
||||
fail_check("table prefix registry drifted from the approved M0 set") unless prefix_owners == expected_prefixes
|
||||
fail_check("V1 must remain single-organization") unless rules.dig("database", "organizationMode") == "SINGLE_ORGANIZATION"
|
||||
fail_check("migrations must be forward-only") unless rules.dig("migrations", "forwardOnly") == true
|
||||
|
||||
migrations = catalog.fetch("migrations")
|
||||
versions = migrations.map { |migration| migration.fetch("version") }
|
||||
fail_check("migration versions must be unique and ordered") unless versions == versions.uniq.sort
|
||||
|
||||
catalog_paths = migrations.map { |migration| migration.fetch("path") }
|
||||
fail_check("SR07 catalog entries missing") unless (sr07_profiles.keys - catalog_paths).empty?
|
||||
fail_check("domain catalog entries missing") unless (domain_profiles.keys - catalog_paths).empty?
|
||||
actual_paths = root.join("db/migration").glob("*/V*.sql").map { |path| path.relative_path_from(root).to_s }.sort
|
||||
if catalog_only
|
||||
fail_check("migration catalog references missing SQL files") unless (catalog_paths - actual_paths).empty?
|
||||
else
|
||||
fail_check("migration catalog does not exactly cover SQL files") unless catalog_paths.sort == actual_paths
|
||||
end
|
||||
|
||||
required_columns = rules.dig("database", "requiredColumns")
|
||||
forbidden_sql = rules.dig("database", "forbiddenSql")
|
||||
fail_check("domain must retain global SQL prohibitions") unless %w[FOREIGN\ KEY DROP\ TABLE TRUNCATE\ TABLE].all? { |token| forbidden_sql.include?(token) }
|
||||
|
||||
# Historical 131 approval: Resource reuses this exact system-owned binding table.
|
||||
# A catalog checksum update alone must never authorize different SQL bytes.
|
||||
private_file_binding = {
|
||||
path: "db/migration/system/V20260921.165__create_private_business_file_binding.sql",
|
||||
version: "20260921.165",
|
||||
owner: "system",
|
||||
table: "sys_oss_business_binding",
|
||||
sha256: "1fe1101329430fd838d63f1c03118b279d3618c278087264c52723be73c97ca5"
|
||||
}.freeze
|
||||
|
||||
# Resource stores this receipt with the existing RCP6 mailbox in one transaction.
|
||||
# Keep the exception bound to this table and reviewed SQL, not all system DDL.
|
||||
workflow_alert_receipt = {
|
||||
path: "db/migration/system/V20261022.252__create_workflow_alert_receipt.sql",
|
||||
version: "20261022.252",
|
||||
owner: "system",
|
||||
table: "sys_workflow_alert_receipt",
|
||||
sha256: "155c58f0cd5621736cafb3ba7890978695e8f8ba1be5ff888e8534808a5bb06c"
|
||||
}.freeze
|
||||
|
||||
migrations.each do |migration|
|
||||
version = migration.fetch("version")
|
||||
owner = migration.fetch("ownerUnit")
|
||||
relative_path = migration.fetch("path")
|
||||
path = root.join(relative_path)
|
||||
fail_check("invalid migration version #{version}") unless version.match?(/\A\d{8}\.\d{3}\z/)
|
||||
fail_check("invalid migration owner #{owner}") unless %w[system integration dataops governance dataproduct].include?(owner)
|
||||
fail_check("migration path escapes the repository") unless path.cleanpath.to_s.start_with?(root.to_s + File::SEPARATOR)
|
||||
fail_check("invalid migration filename #{relative_path}") unless
|
||||
path.basename.to_s.match?(/\AV\d{8}\.\d{3}__[a-z0-9_]+\.sql\z/)
|
||||
filename_version = path.basename.to_s[/\AV(\d{8}\.\d{3})__/, 1]
|
||||
fail_check("migration version/filename mismatch for #{relative_path}") unless filename_version == version
|
||||
fail_check("migration #{version} is in the wrong owner directory") unless path.dirname.basename.to_s == owner
|
||||
actual_sha256 = Digest::SHA256.file(path).hexdigest
|
||||
fail_check("invalid checksum for #{version}") unless migration.fetch("sha256").match?(/\A[0-9a-f]{64}\z/)
|
||||
fail_check("checksum mismatch for #{version}") unless migration.fetch("sha256") == actual_sha256
|
||||
|
||||
sql = path.read
|
||||
domain_profile = domain_profiles[relative_path]
|
||||
forbidden_sql.each do |token|
|
||||
next if domain_profile && token == "FOREIGN KEY" # Granted only after complete structural proof below.
|
||||
fail_check("#{relative_path} contains forbidden SQL #{token}") if sql.match?(/\b#{Regexp.escape(token).gsub("\\ ", "\\s+")}\b/i)
|
||||
end
|
||||
fail_check("#{relative_path} contains a tenant column") if sql.match?(/\btenant_id\b/i)
|
||||
|
||||
created_tables = sql.scan(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-z0-9_]+)/i).flatten
|
||||
if domain_profile
|
||||
fail_check("domain migration identity mismatch") unless [version, owner] == domain_allowed.fetch(relative_path)[0, 2]
|
||||
created_tables = verify_domain(sql, domain_profile, domain_foreign_keys)
|
||||
end
|
||||
approved_private_binding = relative_path == private_file_binding.fetch(:path)
|
||||
if approved_private_binding
|
||||
fail_check("private-file binding migration identity mismatch") unless
|
||||
version == private_file_binding.fetch(:version) && owner == private_file_binding.fetch(:owner)
|
||||
fail_check("private-file binding migration approved checksum mismatch") unless
|
||||
actual_sha256 == private_file_binding.fetch(:sha256)
|
||||
fail_check("private-file binding migration must create exactly the approved table") unless
|
||||
created_tables == [private_file_binding.fetch(:table)]
|
||||
end
|
||||
|
||||
approved_workflow_receipt = relative_path == workflow_alert_receipt.fetch(:path)
|
||||
if approved_workflow_receipt
|
||||
fail_check("workflow mailbox receipt migration identity mismatch") unless
|
||||
version == workflow_alert_receipt.fetch(:version) && owner == workflow_alert_receipt.fetch(:owner)
|
||||
fail_check("workflow mailbox receipt migration checksum mismatch") unless
|
||||
actual_sha256 == workflow_alert_receipt.fetch(:sha256)
|
||||
fail_check("workflow mailbox receipt must create exactly its owned table") unless
|
||||
created_tables == [workflow_alert_receipt.fetch(:table)]
|
||||
end
|
||||
|
||||
profile = sr07_profiles[relative_path]
|
||||
verify_sr07(sql, profile) if profile
|
||||
|
||||
created_tables.each do |table|
|
||||
if domain_table_owners.key?(table) && domain_table_owners[table] != relative_path
|
||||
fail_check("domain table #{table} is declared by the wrong migration")
|
||||
end
|
||||
if sr07_table_owners.key?(table) && sr07_table_owners[table] != relative_path
|
||||
fail_check("SR07 table #{table} is declared by the wrong migration")
|
||||
end
|
||||
next if approved_private_binding && table == private_file_binding.fetch(:table)
|
||||
next if approved_workflow_receipt && table == workflow_alert_receipt.fetch(:table)
|
||||
fail_check("system migration cannot create business tables") if owner == "system"
|
||||
allowed_prefixes = prefix_owners.select { |_prefix, unit| unit == owner }.keys
|
||||
fail_check("#{table} is not owned by #{owner}") unless allowed_prefixes.any? { |prefix| table.start_with?(prefix) }
|
||||
next if table == "dg_schema_history"
|
||||
next if profile # Already checked every real definition against this exact migration/table profile.
|
||||
next if domain_profile # Complete table, options and ALTER contract proved above.
|
||||
|
||||
required_columns.each do |column|
|
||||
fail_check("#{table} is missing #{column}") unless sql.match?(/\b#{Regexp.escape(column)}\b/i)
|
||||
end
|
||||
fail_check("#{table} is missing a primary key") unless sql.match?(/PRIMARY\s+KEY/i)
|
||||
end
|
||||
end
|
||||
|
||||
fail_check("sample must remain non-business") unless sample.fetch("implementedBusinessFeature") == false
|
||||
fail_check("sample REST path is invalid") unless sample.fetch("path").match?(%r{\A/api/[a-z][a-z0-9-]*/v1/[a-z0-9-]+\z})
|
||||
fail_check("sample permission is invalid") unless sample.fetch("permission").match?(/\Aaixun:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9-]+\z/)
|
||||
fail_check("sample idempotency key is invalid") unless sample.fetch("idempotencyKey").match?(/\A[A-Za-z0-9._:-]{16,128}\z/)
|
||||
fail_check("sample error code is outside integration range") unless (110_000..119_999).cover?(sample.fetch("sampleBusinessErrorCode"))
|
||||
fail_check("sample table does not belong to integration") unless sample.fetch("databaseTable").start_with?("dg_")
|
||||
fail_check("sample must not publish Dubbo") unless sample.fetch("dubboPublished") == false
|
||||
fail_check("sample must not require an external component") unless sample.fetch("externalComponentRequired") == false
|
||||
|
||||
scope = catalog_only ? " (catalog-scoped)" : ""
|
||||
puts "Data contract verification passed: #{migrations.size} migrations#{scope}, 15 prefixes, REST/permission/error/idempotency sample valid."
|
||||
在新工单中引用
屏蔽一个用户