فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

feat(a02): opt-in local-only guarded SQL backup inspect and isolated restore executor

davoodmehraban89 committed Oct 30, 2026 at 19:00 UTC 72bb79d461925be95cf0f33f0f736a47195c732e
1 file changed +363
scripts/a02-isolated-sql-restore.ps1 new
+363
@@ -0,0 +1,363 @@
1 +#requires -Version 5.1
2 +<#
3 +A02: owner-approved, LOCAL-only, isolated SQL Server RESTORE. Not the public wizard.
4 +No SQL install, data mapping/import, remote instance access, WITH REPLACE or DROP.
5 +Use only on a dedicated disposable SQL instance named FINORAMIG.
6 +No owner backup is ever used by public GitHub CI; -Mode Test uses synthetic rows.
7 +#>
8 +[CmdletBinding()]
9 +param(
10 + [ValidateSet('Test', 'Inspect', 'Restore')]
11 + [string]$Mode = 'Test',
12 + [string]$BackupPath = '',
13 + [ValidatePattern('^FINORAMIG$')]
14 + [string]$InstanceName = 'FINORAMIG',
15 + [string]$ConsentPhrase = ''
16 +)
17 +Set-StrictMode -Version Latest
18 +$ErrorActionPreference = 'Stop'
19 +
20 +function Sql-Literal([string]$Value) {
21 + if ([string]::IsNullOrWhiteSpace($Value) -or $Value.IndexOf([char]0) -ge 0) {
22 + throw 'A02_INVALID_SQL_LITERAL'
23 + }
24 + return "N'" + $Value.Replace("'", "''") + "'"
25 +}
26 +
27 +function Assert-LocalPathShape([string]$Value) {
28 + if ([string]::IsNullOrWhiteSpace($Value) -or
29 + $Value -notmatch '^[A-Za-z]:\\' -or
30 + $Value -match '[/\x00-\x1f<>"|?*]' -or
31 + $Value.Substring(2).Contains(':')) {
32 + throw 'A02_UNSAFE_LOCAL_PATH'
33 + }
34 + foreach ($segment in $Value.Substring(3).Split('\')) {
35 + if ([string]::IsNullOrWhiteSpace($segment) -or
36 + $segment -eq '.' -or $segment -eq '..' -or
37 + $segment.EndsWith(' ') -or $segment.EndsWith('.')) {
38 + throw 'A02_AMBIGUOUS_PATH'
39 + }
40 + }
41 + return $Value
42 +}
43 +
44 +function Assert-LocalFilesystemSource([string]$Value) {
45 + $path = Assert-LocalPathShape $Value
46 + $drive = New-Object System.IO.DriveInfo($path.Substring(0, 1))
47 + if ($drive.DriveType -ne [System.IO.DriveType]::Fixed -and
48 + $drive.DriveType -ne [System.IO.DriveType]::Removable) {
49 + throw 'A02_SOURCE_NOT_LOCAL_DISK'
50 + }
51 + $file = New-Object System.IO.FileInfo($path)
52 + if (-not $file.Exists -or $file.Length -le 0 -or $file.Length -gt 4GB) {
53 + throw 'A02_SOURCE_FILE_OR_SIZE_INVALID'
54 + }
55 + if (($file.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
56 + throw 'A02_SOURCE_LINK_DISALLOWED'
57 + }
58 + $parent = $file.Directory
59 + while ($null -ne $parent) {
60 + if (($parent.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
61 + throw 'A02_SOURCE_PARENT_LINK_DISALLOWED'
62 + }
63 + $parent = $parent.Parent
64 + }
65 + return $file.FullName
66 +}
67 +
68 +function New-RandomDatabaseName {
69 + $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
70 + try {
71 + [byte[]]$bytes = New-Object byte[] 16
72 + $rng.GetBytes($bytes)
73 + return 'FinoraHoloo_' + [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
74 + } finally { $rng.Dispose() }
75 +}
76 +
77 +function New-LocalRestorePlan(
78 + [string]$BackupFile, [string]$DataDirectory, [string]$LogDirectory,
79 + [string]$DatabaseName, [object[]]$Files
80 +) {
81 + $null = Assert-LocalPathShape $BackupFile
82 + $null = Assert-LocalPathShape $DataDirectory
83 + $null = Assert-LocalPathShape $LogDirectory
84 + if ($DatabaseName -cnotmatch '^FinoraHoloo_[0-9a-f]{32}$') {
85 + throw 'A02_INVALID_DATABASE_NAME'
86 + }
87 + if ($null -eq $Files -or $Files.Count -lt 2 -or $Files.Count -gt 16) {
88 + throw 'A02_FILELIST_COUNT_UNSUPPORTED'
89 + }
90 + $seen = New-Object 'System.Collections.Generic.HashSet[string]' (
91 + [System.StringComparer]::OrdinalIgnoreCase
92 + )
93 + $moves = @()
94 + $data = 0
95 + $logs = 0
96 + $totalBytes = [long]0
97 + foreach ($file in $Files) {
98 + $logical = [string]$file.LogicalName
99 + $type = [string]$file.Type
100 + [long]$size = $file.Size
101 + if ([string]::IsNullOrWhiteSpace($logical) -or $logical.Length -gt 128 -or
102 + $logical -match '[\x00-\x1f]' -or
103 + -not $seen.Add($logical) -or
104 + $size -le 0 -or $size -gt 2TB) {
105 + throw 'A02_FILELIST_UNSAFE_ENTRY'
106 + }
107 + if ($type -eq 'D') {
108 + $data++
109 + $ext = if ($data -eq 1) { '.mdf' } else { '.ndf' }
110 + $directory = $DataDirectory
111 + } elseif ($type -eq 'L') {
112 + $logs++
113 + $ext = '.ldf'
114 + $directory = $LogDirectory
115 + } else { throw 'A02_UNSUPPORTED_SQL_FILE_TYPE' }
116 + if ($totalBytes -gt [long]::MaxValue - $size) {
117 + throw 'A02_FILELIST_SIZE_OVERFLOW'
118 + }
119 + $totalBytes += $size
120 + $filename = $DatabaseName + '_file' + ($moves.Count + 1).ToString('00') + $ext
121 + $target = [System.IO.Path]::Combine($directory, $filename)
122 + $null = Assert-LocalPathShape $target
123 + $moves += [pscustomobject]@{
124 + Logical = $logical; Target = $target; Type = $type; Bytes = $size
125 + }
126 + }
127 + if ($data -eq 0 -or $logs -eq 0) {
128 + throw 'A02_DATA_AND_LOG_FILES_REQUIRED'
129 + }
130 + $clauses = @($moves | ForEach-Object {
131 + 'MOVE ' + (Sql-Literal $_.Logical) + ' TO ' + (Sql-Literal $_.Target)
132 + })
133 + $sourceSql = 'FROM DISK = ' + (Sql-Literal $BackupFile) +
134 + ' WITH FILE = 1, ' + ($clauses -join ', ')
135 + $guard = 'IF DB_ID(' + (Sql-Literal $DatabaseName) +
136 + ") IS NOT NULL THROW 51001, 'A02_DATABASE_COLLISION', 1;"
137 + $verify = 'RESTORE VERIFYONLY ' + $sourceSql + ';'
138 + $restore = $guard + [Environment]::NewLine +
139 + 'RESTORE DATABASE [' + $DatabaseName + '] ' +
140 + $sourceSql + ', RECOVERY, STATS = 10;'
141 + return [pscustomobject]@{
142 + DatabaseName = $DatabaseName
143 + Moves = @($moves)
144 + TotalBytes = $totalBytes
145 + VerifySql = $verify
146 + RestoreSql = $restore
147 + RestoreExecuted = $false
148 + CanImport = $false
149 + }
150 +}
151 +
152 +function Invoke-SqlRows($Connection, [string]$Sql) {
153 + $cmd = $Connection.CreateCommand()
154 + $cmd.CommandText = $Sql
155 + $cmd.CommandTimeout = 300
156 + $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
157 + $rows = New-Object System.Data.DataTable
158 + try {
159 + [void]$adapter.Fill($rows)
160 + return ,$rows
161 + } finally {
162 + $adapter.Dispose()
163 + $cmd.Dispose()
164 + }
165 +}
166 +
167 +function Invoke-SqlCommand($Connection, [string]$Sql, [int]$Timeout = 1800) {
168 + $cmd = $Connection.CreateCommand()
169 + $cmd.CommandText = $Sql
170 + $cmd.CommandTimeout = $Timeout
171 + try { [void]$cmd.ExecuteNonQuery() }
172 + finally { $cmd.Dispose() }
173 +}
174 +
175 +function Assert-PlanCollisionFree($Connection, $Plan) {
176 + # Only read system catalogs; no CREATE/DROP/ALTER.
177 + $catalog = Invoke-SqlRows $Connection (
178 + 'SELECT name, physical_name FROM sys.master_files;' +
179 + 'SELECT name FROM sys.databases;'
180 + )
181 + # DataAdapter.Fill reads only its first result table. Query DB existence
182 + # separately so a surprising result layout cannot silently pass.
183 + $names = Invoke-SqlRows $Connection 'SELECT name FROM sys.databases'
184 + try {
185 + foreach ($r in $names.Rows) {
186 + if ([string]::Equals([string]$r['name'], $Plan.DatabaseName,
187 + [System.StringComparison]::OrdinalIgnoreCase)) {
188 + throw 'A02_DATABASE_COLLISION'
189 + }
190 + }
191 + foreach ($move in $Plan.Moves) {
192 + if ([System.IO.File]::Exists($move.Target) -or
193 + [System.IO.Directory]::Exists($move.Target)) {
194 + throw 'A02_DESTINATION_FILE_COLLISION'
195 + }
196 + foreach ($row in $catalog.Rows) {
197 + if ([string]::Equals([string]$row['physical_name'], $move.Target,
198 + [System.StringComparison]::OrdinalIgnoreCase)) {
199 + throw 'A02_EXISTING_SQL_FILE_COLLISION'
200 + }
201 + }
202 + }
203 + } finally {
204 + $catalog.Dispose()
205 + $names.Dispose()
206 + }
207 +}
208 +
209 +function Assert-DestinationDiskSpace($Plan) {
210 + # Require at least 2 GiB reserve beyond the logical file sizes per drive.
211 + $required = @{}
212 + foreach ($move in $Plan.Moves) {
213 + $drive = $move.Target.Substring(0, 1).ToUpperInvariant()
214 + if (-not $required.ContainsKey($drive)) { $required[$drive] = [long]0 }
215 + $required[$drive] += [long]$move.Bytes
216 + }
217 + foreach ($drive in $required.Keys) {
218 + $info = New-Object System.IO.DriveInfo($drive)
219 + if ($info.DriveType -ne [System.IO.DriveType]::Fixed -or
220 + -not $info.IsReady -or
221 + $info.AvailableFreeSpace -lt ($required[$drive] + 2GB)) {
222 + throw 'A02_DESTINATION_DISK_INSUFFICIENT'
223 + }
224 + }
225 +}
226 +
227 +function Invoke-SelfTest {
228 + $name = 'FinoraHoloo_0123456789abcdef0123456789abcdef'
229 + $files = @(
230 + [pscustomobject]@{ LogicalName = "Data';DROP DATABASE master;--"; Type = 'D'; Size = 1024 },
231 + [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
232 + )
233 + $p = New-LocalRestorePlan "D:\Private\O'Connor.bak" 'C:\SqlData' 'C:\SqlLog' $name $files
234 + if (-not $p.VerifySql.Contains("O''Connor.bak") -or
235 + -not $p.RestoreSql.Contains("Data'';DROP DATABASE master;--") -or
236 + $p.RestoreSql -match '(?i)\bWITH\s+REPLACE\b' -or
237 + ($p.RestoreSql.Split([string[]]@('RESTORE DATABASE'), [System.StringSplitOptions]::None)).Count -ne 2 -or
238 + $p.Moves.Count -ne 2) { throw 'A02_SELFTEST_SQL_PLAN' }
239 + foreach ($bad in @('relative\file.bak', '\\server\share\a.bak',
240 + 'C:\Private\..\file.bak', 'C:\Private\file.bak:ads', 'C:/Private/file.bak')) {
241 + $rejected = $false
242 + try { $null = Assert-LocalPathShape $bad }
243 + catch { $rejected = $true }
244 + if (-not $rejected) { throw 'A02_SELFTEST_UNSAFE_PATH' }
245 + }
246 + $badType = @(
247 + [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = 1024 },
248 + [pscustomobject]@{ LogicalName = 'Fs'; Type = 'S'; Size = 1024 }
249 + )
250 + $rejected = $false
251 + try { $null = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $badType }
252 + catch { $rejected = $true }
253 + if (-not $rejected) { throw 'A02_SELFTEST_FILE_TYPE' }
254 + [pscustomobject]@{
255 + status = 'selftest-passed'; sqlConnectionOpened = $false
256 + backupOpened = $false; databaseModified = $false; canImport = $false
257 + } | ConvertTo-Json -Compress
258 +}
259 +
260 +if ($Mode -eq 'Test') {
261 + Invoke-SelfTest
262 + return
263 +}
264 +
265 +# A02: explicit consent required before potentially creating a new database.
266 +if ($Mode -eq 'Restore' -and
267 + $ConsentPhrase -cne 'I_AUTHORIZE_A_NEW_ISOLATED_SQL_DATABASE') {
268 + Write-Error 'A02_EXPLICIT_OWNER_CONSENT_REQUIRED'
269 + exit 2
270 +}
271 +$connection = $null
272 +try {
273 + $localBackup = Assert-LocalFilesystemSource $BackupPath
274 + $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
275 + $builder.DataSource = 'lpc:.\FINORAMIG'
276 + $builder.InitialCatalog = 'master'
277 + $builder.IntegratedSecurity = $true
278 + $builder.Encrypt = $true
279 + $builder.TrustServerCertificate = $true
280 + $builder.ConnectTimeout = 10
281 + $builder.Pooling = $false
282 + $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
283 + $connection.Open()
284 + $version = Invoke-SqlRows $connection @"
285 +SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS Major,
286 + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(128)) AS InstanceName,
287 + CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(4000)) AS DataDir,
288 + CAST(SERVERPROPERTY('InstanceDefaultLogPath') AS nvarchar(4000)) AS LogDir;
289 +"@
290 + if ($version.Rows.Count -ne 1 -or
291 + [string]$version.Rows[0]['InstanceName'] -ine 'FINORAMIG') {
292 + throw 'A02_SQL_INSTANCE_NOT_DEDICATED'
293 + }
294 + [int]$serverMajor = $version.Rows[0]['Major']
295 + if ($serverMajor -lt 11) { throw 'A02_SQL_INSTANCE_TOO_OLD' }
296 + $dataPath = [string]$version.Rows[0]['DataDir']
297 + $logPath = [string]$version.Rows[0]['LogDir']
298 + if ($dataPath.EndsWith('\')) { $dataPath = $dataPath.TrimEnd('\') }
299 + if ($logPath.EndsWith('\')) { $logPath = $logPath.TrimEnd('\') }
300 + $null = Assert-LocalPathShape $dataPath
301 + $null = Assert-LocalPathShape $logPath
302 + foreach ($folder in @($dataPath, $logPath)) {
303 + if (-not [System.IO.Directory]::Exists($folder)) {
304 + throw 'A02_SQL_DEFAULT_DIRECTORY_MISSING'
305 + }
306 + }
307 + $sourceLiteral = Sql-Literal $localBackup
308 + $header = Invoke-SqlRows $connection ('RESTORE HEADERONLY FROM DISK = ' + $sourceLiteral)
309 + if ($header.Rows.Count -ne 1 -or
310 + [int]$header.Rows[0]['BackupType'] -ne 1 -or
311 + [int]$header.Rows[0]['Position'] -ne 1) {
312 + throw 'A02_NOT_SINGLE_STANDALONE_FULL_BACKUP'
313 + }
314 + if ($header.Columns.Contains('IsDamaged') -and
315 + $header.Rows[0]['IsDamaged'] -ne [DBNull]::Value -and
316 + [bool]$header.Rows[0]['IsDamaged']) {
317 + throw 'A02_SOURCE_HEADER_DAMAGED'
318 + }
319 + [int]$sourceMajor = $header.Rows[0]['SoftwareVersionMajor']
320 + if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
321 + throw 'A02_SOURCE_SQL_VERSION_INCOMPATIBLE'
322 + }
323 + $files = Invoke-SqlRows $connection ('RESTORE FILELISTONLY FROM DISK = ' + $sourceLiteral)
324 + $plan = New-LocalRestorePlan $localBackup $dataPath $logPath (
325 + New-RandomDatabaseName
326 + ) @($files.Rows)
327 + Assert-DestinationDiskSpace $plan
328 + Assert-PlanCollisionFree $connection $plan
329 + Invoke-SqlCommand $connection $plan.VerifySql 1800
330 + if ($Mode -eq 'Inspect') {
331 + [pscustomobject]@{
332 + status = 'backup-verifyonly-passed'
333 + sourceSqlMajor = $sourceMajor; engineSqlMajor = $serverMajor
334 + fileCount = $plan.Moves.Count; canImport = $false
335 + restoreExecuted = $false; financialReconciled = $false
336 + } | ConvertTo-Json -Compress
337 + return
338 + }
339 + # Recheck to narrow races; SQL itself also refuses existing database
340 + # without WITH REPLACE. This cannot prove true exclusive use of instance.
341 + Assert-PlanCollisionFree $connection $plan
342 + Invoke-SqlCommand $connection $plan.RestoreSql 3600
343 + $schema = Invoke-SqlRows $connection (
344 + 'SELECT (SELECT COUNT(*) FROM [' + $plan.DatabaseName +
345 + '].sys.tables) AS TableCount, (SELECT COUNT(*) FROM [' +
346 + $plan.DatabaseName + '].sys.columns) AS ColumnCount'
347 + )
348 + [pscustomobject]@{
349 + status = 'isolated-restore-completed-needs-mapping-and-reconciliation'
350 + databaseName = $plan.DatabaseName
351 + tableCount = [int]$schema.Rows[0]['TableCount']
352 + columnCount = [int]$schema.Rows[0]['ColumnCount']
353 + canImport = $false; financialReconciled = $false
354 + importPerformed = $false
355 + } | ConvertTo-Json -Compress
356 +} catch {
357 + # Do not leak source paths, company names, SQL logical names, credentials,
358 + # raw SQL errors or source financial data into logs/public CI.
359 + Write-Error 'A02_SQL_ISOLATED_RESTORE_OR_PREFLIGHT_FAILED_CHECK_PRIVATE_LOGS'
360 + exit 3
361 +} finally {
362 + if ($null -ne $connection) { $connection.Dispose() }
363 +}