فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
integrate(a02): carry reviewed scripts/a02-sql-backup-readonly-preflight.ps1 into combined candidate
davoodmehraban89 committed
Oct 30, 2026 at 19:43 UTC
360f6b08964eabd3d9c1ac0b712c0dc673875c6d
1 file changed
+219
scripts/a02-sql-backup-readonly-preflight.ps1
new
+219
@@ -0,0 +1,219 @@
1
+#requires -Version 5.1
2
+<#
3
+A02: optional read-only SQL Server BACKUP metadata preflight.
4
+- Existing *local named* SQL Server instance only. No network/remote credentials.
5
+- No CREATE DATABASE, RESTORE DATABASE, service controls, setup or import.
6
+- Owner's source backup stays on their device. No source metadata is logged.
7
+- This is a developer/diagnostic bridge, not the final user-facing wizard.
8
+#>
9
+[CmdletBinding()]
10
+param(
11
+ [string]$BackupPath = '',
12
+ [ValidatePattern('^[A-Za-z][A-Za-z0-9_]{0,31}$')]
13
+ [string]$InstanceName = 'FINORAMIG',
14
+ [switch]$SelfTest
15
+)
16
+Set-StrictMode -Version Latest
17
+$ErrorActionPreference = 'Stop'
18
+
19
+function ConvertTo-SqlUnicodeLiteral([string]$Value) {
20
+ # T-SQL RESTORE FROM DISK cannot bind a normal SQL parameter.
21
+ # Quote the complete absolute filename as one unicode string literal.
22
+ return "N'" + $Value.Replace("'", "''") + "'"
23
+}
24
+
25
+function New-SafeBackupCommands([string]$AbsolutePath) {
26
+ $literal = ConvertTo-SqlUnicodeLiteral $AbsolutePath
27
+ return @{
28
+ Header = 'RESTORE HEADERONLY FROM DISK = ' + $literal
29
+ FileList = 'RESTORE FILELISTONLY FROM DISK = ' + $literal
30
+ Verify = 'RESTORE VERIFYONLY FROM DISK = ' + $literal
31
+ }
32
+}
33
+
34
+function Assert-LocalDrivePathShape([string]$PathValue) {
35
+ # IsPathRooted alone accepts '\relative-to-current-drive', which is
36
+ # ambiguous. Require a fully qualified local DOS drive and safe segments.
37
+ if ([string]::IsNullOrWhiteSpace($PathValue) -or
38
+ $PathValue -notmatch '^[A-Za-z]:\\' -or
39
+ $PathValue -match '[/\x00-\x1f]' -or
40
+ $PathValue.Substring(2).Contains(':')) {
41
+ throw 'BACKUP_LOCAL_DRIVE_PATH_REQUIRED'
42
+ }
43
+ foreach ($segment in $PathValue.Substring(3).Split('\')) {
44
+ if ([string]::IsNullOrWhiteSpace($segment) -or
45
+ $segment -eq '.' -or $segment -eq '..' -or
46
+ $segment.EndsWith(' ') -or $segment.EndsWith('.')) {
47
+ throw 'BACKUP_AMBIGUOUS_PATH_BLOCKED'
48
+ }
49
+ }
50
+}
51
+
52
+function Assert-PrivateLocalBackupFile([string]$PathValue) {
53
+ Assert-LocalDrivePathShape $PathValue
54
+ $fullPath = [System.IO.Path]::GetFullPath($PathValue)
55
+ # Reject drive letters mapped to a network share. Local USB media is
56
+ # allowed, but the SQL Server service must still be able to read it.
57
+ $drive = New-Object System.IO.DriveInfo($fullPath.Substring(0, 1))
58
+ if ($drive.DriveType -ne [System.IO.DriveType]::Fixed -and
59
+ $drive.DriveType -ne [System.IO.DriveType]::Removable) {
60
+ throw 'BACKUP_NETWORK_DRIVE_BLOCKED'
61
+ }
62
+ $info = New-Object System.IO.FileInfo($fullPath)
63
+ if (-not $info.Exists) {
64
+ throw 'BACKUP_FILE_NOT_FOUND'
65
+ }
66
+ # Reject a reparse-point file OR any parent directory junction/symlink.
67
+ # Prevents source redirection from a trusted path to an arbitrary target.
68
+ if (($info.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
69
+ throw 'BACKUP_REPARSE_POINT_BLOCKED'
70
+ }
71
+ $parent = $info.Directory
72
+ while ($null -ne $parent) {
73
+ if (($parent.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
74
+ throw 'BACKUP_PARENT_REPARSE_POINT_BLOCKED'
75
+ }
76
+ $parent = $parent.Parent
77
+ }
78
+ if ($info.Length -le 0 -or $info.Length -gt 4GB) {
79
+ throw 'BACKUP_SIZE_OUTSIDE_PREFLIGHT_LIMIT'
80
+ }
81
+ return $fullPath
82
+}
83
+
84
+function Invoke-SqlTable($Connection, [string]$Query) {
85
+ $command = $Connection.CreateCommand()
86
+ $command.CommandText = $Query
87
+ $command.CommandTimeout = 300
88
+ $table = New-Object System.Data.DataTable
89
+ $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
90
+ try {
91
+ [void]$adapter.Fill($table)
92
+ return ,$table
93
+ } finally {
94
+ $adapter.Dispose()
95
+ $command.Dispose()
96
+ }
97
+}
98
+
99
+if ($SelfTest) {
100
+ # Pure parser/quoting contract; no SQL connection or disk access.
101
+ $testPath = "C:\Sample\copy'; DROP DATABASE master;--.bak"
102
+ $commands = New-SafeBackupCommands $testPath
103
+ if ($commands.Header -notlike "*copy''; DROP DATABASE master;--.bak'*") {
104
+ throw 'SELFTEST_LITERAL_ESCAPE_FAILED'
105
+ }
106
+ if ($commands.Header -notlike 'RESTORE HEADERONLY FROM DISK = N*' -or
107
+ $commands.FileList -notlike 'RESTORE FILELISTONLY FROM DISK = N*' -or
108
+ $commands.Verify -notlike 'RESTORE VERIFYONLY FROM DISK = N*') {
109
+ throw 'SELFTEST_COMMAND_SCOPE_FAILED'
110
+ }
111
+ # The synthetic SQL-like text is deliberately part of the quoted
112
+ # filename; its embedded single quote has been escaped to two quotes.
113
+ if ($commands.Header -ne ('RESTORE HEADERONLY FROM DISK = N' +
114
+ "'" + $testPath.Replace("'", "''") + "'")) {
115
+ throw 'SELFTEST_SQL_LITERAL_MISMATCH'
116
+ }
117
+ foreach ($badPath in @(
118
+ 'relative\copy.bak', '\rooted\copy.bak',
119
+ '\\server\share\copy.bak', 'C:\safe\..\copy.bak',
120
+ 'C:\safe\.\copy.bak', 'C:\safe\copy.bak:ADS',
121
+ 'C:/safe/copy.bak', 'C:\safe\name.\copy.bak'
122
+ )) {
123
+ $rejected = $false
124
+ try { Assert-LocalDrivePathShape $badPath }
125
+ catch { $rejected = $true }
126
+ if (-not $rejected) { throw 'SELFTEST_UNSAFE_PATH_ACCEPTED' }
127
+ }
128
+ Assert-LocalDrivePathShape 'C:\Private\copy.bak'
129
+ @{ status = 'selftest-passed'; sourceRead = $false; connectionOpened = $false;
130
+ databaseModified = $false; canImport = $false } |
131
+ ConvertTo-Json -Compress
132
+ return
133
+}
134
+
135
+try {
136
+ $localFile = Assert-PrivateLocalBackupFile $BackupPath
137
+} catch {
138
+ # No path or other personal/source metadata in diagnostic output.
139
+ Write-Error 'HOLOO_BACKUP_PREFLIGHT_INVALID_LOCAL_SOURCE'
140
+ exit 2
141
+}
142
+
143
+$connection = $null
144
+try {
145
+ # Local shared-memory endpoint only, Windows authentication only.
146
+ # Server version, actual backup format and permissions are checked live.
147
+ $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
148
+ $builder.DataSource = 'lpc:.\' + $InstanceName
149
+ $builder.IntegratedSecurity = $true
150
+ $builder.Encrypt = $true
151
+ $builder.TrustServerCertificate = $true
152
+ $builder.Pooling = $false
153
+ $builder.ConnectTimeout = 10
154
+ $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
155
+ $connection.Open()
156
+ $versionQuery = $connection.CreateCommand()
157
+ $versionQuery.CommandText = "SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int)"
158
+ $versionQuery.CommandTimeout = 10
159
+ $serverMajor = [int]$versionQuery.ExecuteScalar()
160
+ $versionQuery.Dispose()
161
+ if ($serverMajor -lt 10) {
162
+ throw 'SQL_VERSION_UNDETERMINED'
163
+ }
164
+
165
+ $sql = New-SafeBackupCommands $localFile
166
+ $header = Invoke-SqlTable $connection $sql.Header
167
+ if ($header.Rows.Count -ne 1) {
168
+ # Multiple backup sets need explicit FILE number/version handling.
169
+ throw 'BACKUP_SET_COUNT_UNSUPPORTED'
170
+ }
171
+ # A02 only supports a single full-database backup set at position 1.
172
+ # Do not mistake a log, differential or partial backup for a restorable
173
+ # standalone database image.
174
+ if ([int]$header.Rows[0]['BackupType'] -ne 1 -or
175
+ [int]$header.Rows[0]['Position'] -ne 1) {
176
+ throw 'BACKUP_NOT_STANDALONE_FULL_DATABASE'
177
+ }
178
+ if ($header.Columns.Contains('IsDamaged') -and
179
+ $header.Rows[0]['IsDamaged'] -ne [System.DBNull]::Value -and
180
+ [bool]$header.Rows[0]['IsDamaged']) {
181
+ throw 'BACKUP_HEADER_REPORTS_DAMAGED'
182
+ }
183
+ $sourceMajor = [int]$header.Rows[0]['SoftwareVersionMajor']
184
+ if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
185
+ throw 'SQL_BACKUP_VERSION_INCOMPATIBLE'
186
+ }
187
+ $fileList = Invoke-SqlTable $connection $sql.FileList
188
+ if ($fileList.Rows.Count -lt 1) {
189
+ throw 'SQL_BACKUP_EMPTY_FILE_LIST'
190
+ }
191
+ $verify = $connection.CreateCommand()
192
+ $verify.CommandText = $sql.Verify
193
+ $verify.CommandTimeout = 1800
194
+ [void]$verify.ExecuteNonQuery()
195
+ $verify.Dispose()
196
+
197
+ # Deliberately no database name, file path, logical file name,
198
+ # instance name, account data, raw SQL errors or source hash in output.
199
+ @{
200
+ status = 'sql-backup-verifyonly-passed'
201
+ backupSetCount = $header.Rows.Count
202
+ fileCount = $fileList.Rows.Count
203
+ sourceSqlMajor = $sourceMajor
204
+ installedSqlMajor = $serverMajor
205
+ verifyOnlyPassed = $true
206
+ restoreAttempted = $false
207
+ schemaVerified = $false
208
+ financialReconciled = $false
209
+ importPerformed = $false
210
+ canImport = $false
211
+ } | ConvertTo-Json -Compress
212
+} catch {
213
+ Write-Error 'HOLOO_SQL_BACKUP_METADATA_OR_VERIFY_FAILED'
214
+ exit 3
215
+} finally {
216
+ if ($null -ne $connection) {
217
+ $connection.Dispose()
218
+ }
219
+}