Prepara ambiente XWMS isolato e documenta gli stati UDC
This commit is contained in:
147
tools/isolate_local_clones.py
Normal file
147
tools/isolate_local_clones.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""Retarget restored modules and provision a login restricted to the two clones.
|
||||
|
||||
Administrative one-off setup, not an application migration. Original definitions
|
||||
are recorded under ignored local_setup/; no original database is altered.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from prepare_local_clones import ROOT, REPORT, PAIRS, ADMIN_CONFIG, identifier, literal, rows, snapshot
|
||||
from db_config import load_db_config, build_dsn_from_config
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
LOGIN = "xwms_local_app"
|
||||
QUARANTINE = {
|
||||
"Xwmsdb": {"vPreparaPackingListOld", "vXTracciaOld"},
|
||||
"SAMA1_Xwmstest": {"ab_viewExport_Sommatorie_2019", "ViewOrdinidiProduzioneMultiLottoElenco",
|
||||
"send_email_on_error", "USP_IMPORT_TRACE_FILE"},
|
||||
}
|
||||
|
||||
|
||||
def retarget(sql):
|
||||
for old, new in PAIRS.items():
|
||||
# Exact identifier tokens only: also handles bracketed/quoted identifiers.
|
||||
sql = re.sub(r"(?i)(?<![\w])" + re.escape(old) + r"(?![\w])", new, sql)
|
||||
return sql
|
||||
|
||||
|
||||
def alter(sql):
|
||||
result, n = re.subn(r"(?i)\bCREATE(?:\s+OR\s+ALTER)?\s+(PROCEDURE|PROC|VIEW|FUNCTION|TRIGGER)\b",
|
||||
r"ALTER \1", sql, count=1)
|
||||
if n != 1:
|
||||
raise RuntimeError("Unsupported module definition")
|
||||
return result
|
||||
|
||||
|
||||
def inert_view(conn, qualified):
|
||||
columns = rows(conn, """SELECT c.name,t.name type_name,c.max_length,c.precision,c.scale
|
||||
FROM sys.columns c JOIN sys.types t ON c.system_type_id=t.user_type_id
|
||||
WHERE c.object_id=OBJECT_ID(""" + literal(qualified) + ") ORDER BY c.column_id")
|
||||
expressions = []
|
||||
for c in columns:
|
||||
t = c["type_name"]
|
||||
if t in ("varchar", "char", "binary", "varbinary", "nvarchar", "nchar"):
|
||||
n = c["max_length"]
|
||||
length = "max" if n == -1 else str(n // 2 if t.startswith("n") else n)
|
||||
t += "(" + length + ")"
|
||||
elif t in ("numeric", "decimal"):
|
||||
t += "(" + str(c["precision"]) + "," + str(c["scale"]) + ")"
|
||||
elif t in ("datetime2", "datetimeoffset", "time"):
|
||||
t += "(" + str(c["scale"]) + ")"
|
||||
expressions.append("CAST(NULL AS " + t + ") AS " + identifier(c["name"]))
|
||||
if not expressions:
|
||||
raise RuntimeError("No columns for quarantined view " + qualified)
|
||||
return "ALTER VIEW " + qualified + " AS SELECT " + ",".join(expressions) + " WHERE 1=0"
|
||||
|
||||
|
||||
def main():
|
||||
config = load_db_config(ADMIN_CONFIG)
|
||||
config["database"] = "master"
|
||||
engine = create_engine(build_dsn_from_config(config).replace("mssql+aioodbc:", "mssql+pyodbc:"),
|
||||
isolation_level="AUTOCOMMIT", connect_args={"timeout": 10}, hide_parameters=True)
|
||||
plan = []
|
||||
with engine.connect() as conn:
|
||||
assert conn.exec_driver_sql("SELECT CAST(SERVERPROPERTY('MachineName') AS nvarchar(128))").scalar_one() == "HOMESERVER"
|
||||
output = ROOT / "db_connection.json"
|
||||
if output.exists() or conn.exec_driver_sql("SELECT SUSER_ID(?)", (LOGIN,)).scalar_one() is not None:
|
||||
raise RuntimeError("Existing app config/login: manual reconciliation required before setup")
|
||||
for source, target in PAIRS.items():
|
||||
assert conn.exec_driver_sql("SELECT state_desc FROM sys.databases WHERE name=?", (target,)).scalar_one() == "ONLINE"
|
||||
snap = snapshot(conn, target)
|
||||
baseline = json.loads((REPORT / (source + "_before.json")).read_text())
|
||||
assert snap["tables"] == baseline["tables"], "Clone rows differ before isolation"
|
||||
(REPORT / (target + "_before_isolation.json")).write_text(json.dumps(snap, indent=2), encoding="utf-8")
|
||||
for m in snap["modules"]:
|
||||
if m["definition"] is None:
|
||||
raise RuntimeError("Encrypted module cannot be audited")
|
||||
qualified = identifier(m["schema_name"]) + "." + identifier(m["name"])
|
||||
new = retarget(m["definition"])
|
||||
quarantined = m["name"] in QUARANTINE[target]
|
||||
if quarantined:
|
||||
if m["type"].strip() == "V":
|
||||
sql = inert_view(conn, qualified)
|
||||
permission = "SELECT"
|
||||
elif m["name"] == "send_email_on_error":
|
||||
sql = "ALTER PROCEDURE " + qualified + " AS THROW 51090, 'External email disabled in XWMS TEST', 1;"
|
||||
permission = "EXECUTE"
|
||||
else:
|
||||
sql = "ALTER PROCEDURE " + qualified + " @sTraceFile varchar(4000) AS THROW 51090, 'External file operations disabled in XWMS TEST', 1;"
|
||||
permission = "EXECUTE"
|
||||
elif new != m["definition"]:
|
||||
sql = alter(new)
|
||||
permission = None
|
||||
else:
|
||||
continue
|
||||
plan.append(dict(database=target, object=qualified, sql=sql, permission=permission,
|
||||
ansi=m["uses_ansi_nulls"], quoted=m["uses_quoted_identifier"]))
|
||||
(REPORT / "isolation_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
|
||||
# One transaction for both clones, with no changes to original modules.
|
||||
conn.exec_driver_sql("BEGIN TRANSACTION")
|
||||
try:
|
||||
for p in plan:
|
||||
conn.exec_driver_sql("USE " + identifier(p["database"]))
|
||||
conn.exec_driver_sql("SET ANSI_NULLS " + ("ON" if p["ansi"] else "OFF"))
|
||||
conn.exec_driver_sql("SET QUOTED_IDENTIFIER " + ("ON" if p["quoted"] else "OFF"))
|
||||
conn.exec_driver_sql(p["sql"])
|
||||
if p["permission"]:
|
||||
conn.exec_driver_sql("DENY " + p["permission"] + " ON OBJECT::" + p["object"] + " TO public")
|
||||
for target in PAIRS.values():
|
||||
conn.exec_driver_sql("USE " + identifier(target))
|
||||
deps = rows(conn, """SELECT referenced_server_name,referenced_database_name FROM
|
||||
sys.sql_expression_dependencies WHERE referenced_server_name IS NOT NULL OR
|
||||
(referenced_database_name IS NOT NULL AND referenced_database_name NOT IN ('Xwmsdb','SAMA1_Xwmstest'))""")
|
||||
if deps:
|
||||
raise RuntimeError("External dependencies remain: " + repr(deps))
|
||||
conn.exec_driver_sql("COMMIT")
|
||||
except Exception:
|
||||
conn.exec_driver_sql("IF @@TRANCOUNT>0 ROLLBACK")
|
||||
raise
|
||||
conn.exec_driver_sql("USE [master]")
|
||||
if conn.exec_driver_sql("SELECT SUSER_ID(?)", (LOGIN,)).scalar_one() is not None:
|
||||
raise RuntimeError("Login already exists: do not reset credentials automatically")
|
||||
password = secrets.token_urlsafe(40) + "aA1!"
|
||||
conn.exec_driver_sql("""DECLARE @pwd nvarchar(128)=?;
|
||||
DECLARE @sql nvarchar(max)=N'CREATE LOGIN [xwms_local_app] WITH PASSWORD='
|
||||
+ QUOTENAME(@pwd,'''') + N', DEFAULT_DATABASE=[Xwmsdb], CHECK_POLICY=ON, CHECK_EXPIRATION=OFF';
|
||||
EXEC sys.sp_executesql @sql;""", (password,))
|
||||
for target in PAIRS.values():
|
||||
conn.exec_driver_sql("USE " + identifier(target))
|
||||
conn.exec_driver_sql("CREATE USER " + identifier(LOGIN) + " FOR LOGIN " + identifier(LOGIN))
|
||||
for role in ("db_datareader", "db_datawriter"):
|
||||
conn.exec_driver_sql("ALTER ROLE " + identifier(role) + " ADD MEMBER " + identifier(LOGIN))
|
||||
conn.exec_driver_sql("GRANT EXECUTE, VIEW DEFINITION TO " + identifier(LOGIN))
|
||||
conn.exec_driver_sql("REVOKE CONNECT FROM guest")
|
||||
output = ROOT / "db_connection.json"
|
||||
if output.exists():
|
||||
raise RuntimeError("Do not overwrite existing local config")
|
||||
app_config = dict(config, server="HOMESERVER", database="Xwmsdb", user=LOGIN, password=password,
|
||||
query_profiler={"enabled": False,"slow_ms": 0,"sql_limit": 4000})
|
||||
output.write_text(json.dumps(app_config, indent=2), encoding="utf-8")
|
||||
print("ISOLATED", len(plan), "modules; restricted application login created; local config written")
|
||||
print("Original databases untouched. Configuration and full reports are Git-ignored.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user