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

fix/phase-a-pack5-integrated-evidence-20261101
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
ps1 447 lines 18.6 KB
Raw
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 = [System.IO.DriveInfo]::new($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 = [System.Collections.Generic.HashSet[string]]::new(
91 [System.StringComparer]::OrdinalIgnoreCase
92 )
93 $moves = @()
94 $data = 0
95 $logs = 0
96 $totalBytes = [long]0
97 $dataBytes = [long]0
98 $logBytes = [long]0
99 foreach ($file in $Files) {
100 $logical = [string]$file.LogicalName
101 $type = [string]$file.Type
102 [long]$size = $file.Size
103 if ([string]::IsNullOrWhiteSpace($logical) -or $logical.Length -gt 128 -or
104 $logical -match '[\x00-\x1f]' -or
105 -not $seen.Add($logical) -or
106 $size -le 0 -or $size -gt 2TB) {
107 throw 'A02_FILELIST_UNSAFE_ENTRY'
108 }
109 if ($type -eq 'D') {
110 $data++
111 $ext = if ($data -eq 1) { '.mdf' } else { '.ndf' }
112 $directory = $DataDirectory
113 } elseif ($type -eq 'L') {
114 $logs++
115 $ext = '.ldf'
116 $directory = $LogDirectory
117 } else { throw 'A02_UNSUPPORTED_SQL_FILE_TYPE' }
118 if ($totalBytes -gt [long]::MaxValue - $size) {
119 throw 'A02_FILELIST_SIZE_OVERFLOW'
120 }
121 $totalBytes += $size
122 if ($type -eq 'D') { $dataBytes += $size } else { $logBytes += $size }
123 $filename = $DatabaseName + '_file' + ($moves.Count + 1).ToString('00') + $ext
124 $target = [System.IO.Path]::Combine($directory, $filename)
125 $null = Assert-LocalPathShape $target
126 $moves += [pscustomobject]@{
127 Logical = $logical; Target = $target; Type = $type; Bytes = $size
128 }
129 }
130 if ($data -eq 0 -or $logs -eq 0) {
131 throw 'A02_DATA_AND_LOG_FILES_REQUIRED'
132 }
133 $clauses = @($moves | ForEach-Object {
134 'MOVE ' + (Sql-Literal $_.Logical) + ' TO ' + (Sql-Literal $_.Target)
135 })
136 $sourceSql = 'FROM DISK = ' + (Sql-Literal $BackupFile) +
137 ' WITH FILE = 1, ' + ($clauses -join ', ')
138 $guard = 'IF DB_ID(' + (Sql-Literal $DatabaseName) +
139 ") IS NOT NULL THROW 51001, 'A02_DATABASE_COLLISION', 1;"
140 $verify = 'RESTORE VERIFYONLY ' + $sourceSql + ';'
141 $restore = $guard + [Environment]::NewLine +
142 'RESTORE DATABASE [' + $DatabaseName + '] ' +
143 $sourceSql + ', RECOVERY, STATS = 10;'
144 return [pscustomobject]@{
145 DatabaseName = $DatabaseName
146 Moves = @($moves)
147 TotalBytes = $totalBytes
148 DataBytes = $dataBytes
149 LogBytes = $logBytes
150 VerifySql = $verify
151 RestoreSql = $restore
152 RestoreExecuted = $false
153 CanImport = $false
154 }
155 }
156
157 function Invoke-SqlRows($Connection, [string]$Sql) {
158 $cmd = $Connection.CreateCommand()
159 $cmd.CommandText = $Sql
160 $cmd.CommandTimeout = 300
161 $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
162 $rows = New-Object System.Data.DataTable
163 try {
164 [void]$adapter.Fill($rows)
165 return ,$rows
166 } finally {
167 $adapter.Dispose()
168 $cmd.Dispose()
169 }
170 }
171
172 function Invoke-SqlCommand($Connection, [string]$Sql, [int]$Timeout = 1800) {
173 $cmd = $Connection.CreateCommand()
174 $cmd.CommandText = $Sql
175 $cmd.CommandTimeout = $Timeout
176 try { [void]$cmd.ExecuteNonQuery() }
177 finally { $cmd.Dispose() }
178 }
179
180 function Assert-PlanCollisionFree($Connection, $Plan) {
181 # Only read system catalogs; no CREATE/DROP/ALTER.
182 $catalog = Invoke-SqlRows $Connection 'SELECT physical_name FROM sys.master_files'
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 = [System.IO.DriveInfo]::new($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 Get-ExpressDataLimitBytes([int]$Major,[int]$EngineEdition) {
228 if ($EngineEdition -ne 4) { return [long]0 }
229 if ($Major -ge 11 -and $Major -le 16) { return [long]10GB }
230 if ($Major -eq 17) { return [long]50GB }
231 throw 'A02_EXPRESS_LIMIT_VERSION_UNSUPPORTED'
232 }
233
234 function Assert-ExpressDatabaseSizeLimit($Plan,[int]$Major,[int]$EngineEdition) {
235 $limit = Get-ExpressDataLimitBytes $Major $EngineEdition
236 if ($limit -gt 0 -and [long]$Plan.DataBytes -gt $limit) {
237 throw 'A02_EXPRESS_DATABASE_SIZE_LIMIT_EXCEEDED'
238 }
239 return [long]$limit
240 }
241
242 function Invoke-SelfTest {
243 $name = 'FinoraHoloo_0123456789abcdef0123456789abcdef'
244 $files = @(
245 [pscustomobject]@{ LogicalName = "Data';DROP DATABASE master;--"; Type = 'D'; Size = 1024 },
246 [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
247 )
248 $p = New-LocalRestorePlan "D:\Private\O'Connor.bak" 'C:\SqlData' 'C:\SqlLog' $name $files
249 if (-not $p.VerifySql.Contains("O''Connor.bak") -or
250 -not $p.RestoreSql.Contains("Data'';DROP DATABASE master;--") -or
251 $p.RestoreSql -match '(?i)\bWITH\s+REPLACE\b' -or
252 ($p.RestoreSql.Split([string[]]@('RESTORE DATABASE'), [System.StringSplitOptions]::None)).Count -ne 2 -or
253 $p.Moves.Count -ne 2 -or $p.DataBytes -ne 1024 -or $p.LogBytes -ne 2048) {
254 throw 'A02_SELFTEST_SQL_PLAN'
255 }
256 if ((Get-ExpressDataLimitBytes 16 4) -ne 10GB -or
257 (Get-ExpressDataLimitBytes 17 4) -ne 50GB -or
258 (Get-ExpressDataLimitBytes 16 2) -ne 0) {
259 throw 'A02_SELFTEST_EXPRESS_LIMIT_MAPPING'
260 }
261 $null = Assert-ExpressDatabaseSizeLimit $p 16 4
262 $limitFiles = @(
263 [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = 10GB },
264 [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
265 )
266 $atLimit = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $limitFiles
267 $null = Assert-ExpressDatabaseSizeLimit $atLimit 16 4
268 $tooLargeFiles = @(
269 [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = (10GB + 1) },
270 [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
271 )
272 $tooLarge = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $tooLargeFiles
273 $rejected = $false
274 try { $null = Assert-ExpressDatabaseSizeLimit $tooLarge 16 4 }
275 catch { $rejected = $true }
276 if (-not $rejected) { throw 'A02_SELFTEST_EXPRESS_10GB_LIMIT' }
277 $tooLarge2025Files = @(
278 [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = (50GB + 1) },
279 [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
280 )
281 $tooLarge2025 = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $tooLarge2025Files
282 $rejected = $false
283 try { $null = Assert-ExpressDatabaseSizeLimit $tooLarge2025 17 4 }
284 catch { $rejected = $true }
285 if (-not $rejected) { throw 'A02_SELFTEST_EXPRESS_50GB_LIMIT' }
286 $unknownVersionRejected = $false
287 try { $null = Get-ExpressDataLimitBytes 18 4 }
288 catch { $unknownVersionRejected = $true }
289 if (-not $unknownVersionRejected) { throw 'A02_SELFTEST_UNKNOWN_EXPRESS_VERSION' }
290 foreach ($bad in @('relative\file.bak', '\\server\share\a.bak',
291 'C:\Private\..\file.bak', 'C:\Private\file.bak:ads', 'C:/Private/file.bak')) {
292 $rejected = $false
293 try { $null = Assert-LocalPathShape $bad }
294 catch { $rejected = $true }
295 if (-not $rejected) { throw 'A02_SELFTEST_UNSAFE_PATH' }
296 }
297 $badType = @(
298 [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = 1024 },
299 [pscustomobject]@{ LogicalName = 'Fs'; Type = 'S'; Size = 1024 }
300 )
301 $rejected = $false
302 try { $null = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $badType }
303 catch { $rejected = $true }
304 if (-not $rejected) { throw 'A02_SELFTEST_FILE_TYPE' }
305 [pscustomobject]@{
306 status = 'selftest-passed'; sqlConnectionOpened = $false
307 backupOpened = $false; databaseModified = $false; canImport = $false
308 } | ConvertTo-Json -Compress
309 }
310
311 if ($Mode -eq 'Test') {
312 Invoke-SelfTest
313 return
314 }
315
316 # A02: explicit consent required before potentially creating a new database.
317 if ($Mode -eq 'Restore' -and
318 $ConsentPhrase -cne 'I_AUTHORIZE_A_NEW_ISOLATED_SQL_DATABASE') {
319 Write-Error 'A02_EXPLICIT_OWNER_CONSENT_REQUIRED'
320 exit 2
321 }
322 $connection = $null
323 try {
324 $localBackup = Assert-LocalFilesystemSource $BackupPath
325 # Bind metadata/VERIFYONLY and eventual restore to unchanged file bytes.
326 # Never output this private source fingerprint to console or CI.
327 $sourceHash = (Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash
328 $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
329 $builder.DataSource = 'lpc:.\FINORAMIG'
330 $builder.InitialCatalog = 'master'
331 $builder.IntegratedSecurity = $true
332 $builder.Encrypt = $true
333 $builder.TrustServerCertificate = $true
334 $builder.ConnectTimeout = 10
335 $builder.Pooling = $false
336 $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
337 $connection.Open()
338 $version = Invoke-SqlRows $connection @"
339 SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS Major,
340 CAST(SERVERPROPERTY('EngineEdition') AS int) AS EngineEdition,
341 CAST(SERVERPROPERTY('Edition') AS nvarchar(128)) AS Edition,
342 CAST(SERVERPROPERTY('InstanceName') AS nvarchar(128)) AS InstanceName,
343 CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(4000)) AS DataDir,
344 CAST(SERVERPROPERTY('InstanceDefaultLogPath') AS nvarchar(4000)) AS LogDir;
345 "@
346 if ($version.Rows.Count -ne 1 -or
347 [string]$version.Rows[0]['InstanceName'] -ine 'FINORAMIG') {
348 throw 'A02_SQL_INSTANCE_NOT_DEDICATED'
349 }
350 [int]$serverMajor = $version.Rows[0]['Major']
351 [int]$engineEdition = $version.Rows[0]['EngineEdition']
352 [string]$engineEditionName = [string]$version.Rows[0]['Edition']
353 if ($serverMajor -lt 11) { throw 'A02_SQL_INSTANCE_TOO_OLD' }
354 if ($engineEdition -le 0 -or [string]::IsNullOrWhiteSpace($engineEditionName)) { throw 'A02_SQL_ENGINE_EDITION_UNKNOWN' }
355 $dataPath = [string]$version.Rows[0]['DataDir']
356 $logPath = [string]$version.Rows[0]['LogDir']
357 if ($dataPath.EndsWith('\')) { $dataPath = $dataPath.TrimEnd('\') }
358 if ($logPath.EndsWith('\')) { $logPath = $logPath.TrimEnd('\') }
359 $null = Assert-LocalPathShape $dataPath
360 $null = Assert-LocalPathShape $logPath
361 foreach ($folder in @($dataPath, $logPath)) {
362 if (-not [System.IO.Directory]::Exists($folder)) {
363 throw 'A02_SQL_DEFAULT_DIRECTORY_MISSING'
364 }
365 }
366 $sourceLiteral = Sql-Literal $localBackup
367 $header = Invoke-SqlRows $connection ('RESTORE HEADERONLY FROM DISK = ' + $sourceLiteral)
368 if ($header.Rows.Count -ne 1 -or
369 [int]$header.Rows[0]['BackupType'] -ne 1 -or
370 [int]$header.Rows[0]['Position'] -ne 1) {
371 throw 'A02_NOT_SINGLE_STANDALONE_FULL_BACKUP'
372 }
373 if ($header.Columns.Contains('IsDamaged') -and
374 $header.Rows[0]['IsDamaged'] -ne [DBNull]::Value -and
375 [bool]$header.Rows[0]['IsDamaged']) {
376 throw 'A02_SOURCE_HEADER_DAMAGED'
377 }
378 [int]$sourceMajor = $header.Rows[0]['SoftwareVersionMajor']
379 if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
380 throw 'A02_SOURCE_SQL_VERSION_INCOMPATIBLE'
381 }
382 $files = Invoke-SqlRows $connection ('RESTORE FILELISTONLY FROM DISK = ' + $sourceLiteral)
383 $plan = New-LocalRestorePlan $localBackup $dataPath $logPath (
384 New-RandomDatabaseName
385 ) @($files.Rows)
386 $expressLimitBytes = Assert-ExpressDatabaseSizeLimit $plan $serverMajor $engineEdition
387 Assert-DestinationDiskSpace $plan
388 Assert-PlanCollisionFree $connection $plan
389 Invoke-SqlCommand $connection $plan.VerifySql 1800
390 if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
391 throw 'A02_SOURCE_BACKUP_CHANGED_AFTER_VERIFY'
392 }
393 if ($Mode -eq 'Inspect') {
394 [pscustomobject]@{
395 status = 'backup-verifyonly-passed'
396 sourceSqlMajor = $sourceMajor; engineSqlMajor = $serverMajor
397 engineEdition = $engineEditionName; engineEditionCode = $engineEdition
398 dataFileBytes = $plan.DataBytes; logFileBytes = $plan.LogBytes
399 expressDataLimitBytes = if ($expressLimitBytes -gt 0) { $expressLimitBytes } else { $null }
400 expressSizeLimitCheck = if ($expressLimitBytes -gt 0) { 'passed' } else { 'not-applicable' }
401 fileCount = $plan.Moves.Count; canImport = $false
402 restoreExecuted = $false; financialReconciled = $false
403 } | ConvertTo-Json -Compress
404 return
405 }
406 # Recheck to narrow races; SQL itself also refuses existing database
407 # without WITH REPLACE. This cannot prove true exclusive use of instance.
408 Assert-PlanCollisionFree $connection $plan
409 if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
410 throw 'A02_SOURCE_BACKUP_CHANGED_BEFORE_RESTORE'
411 }
412 Invoke-SqlCommand $connection $plan.RestoreSql 3600
413 $online = Invoke-SqlRows $connection (
414 'SELECT state_desc FROM sys.databases WHERE name = ' +
415 (Sql-Literal $plan.DatabaseName)
416 )
417 if ($online.Rows.Count -ne 1 -or [string]$online.Rows[0]['state_desc'] -ne 'ONLINE') {
418 throw 'A02_ISOLATED_DATABASE_NOT_ONLINE'
419 }
420 # Restore success and ONLINE alone do not prove database page integrity.
421 # CHECKDB is run only on the new, randomly named isolated database.
422 Invoke-SqlCommand $connection ('DBCC CHECKDB([' + $plan.DatabaseName +
423 ']) WITH NO_INFOMSGS;') 3600
424 $schema = Invoke-SqlRows $connection (
425 'SELECT (SELECT COUNT(*) FROM [' + $plan.DatabaseName +
426 '].sys.tables) AS TableCount, (SELECT COUNT(*) FROM [' +
427 $plan.DatabaseName + '].sys.columns) AS ColumnCount'
428 )
429 [pscustomobject]@{
430 status = 'isolated-restore-completed-needs-mapping-and-reconciliation'
431 databaseName = $plan.DatabaseName
432 engineEdition = $engineEditionName
433 expressDataLimitBytes = if ($expressLimitBytes -gt 0) { $expressLimitBytes } else { $null }
434 tableCount = [int]$schema.Rows[0]['TableCount']
435 columnCount = [int]$schema.Rows[0]['ColumnCount']
436 dbccCheckDbPassed = $true
437 canImport = $false; financialReconciled = $false
438 importPerformed = $false
439 } | ConvertTo-Json -Compress
440 } catch {
441 # Do not leak source paths, company names, SQL logical names, credentials,
442 # raw SQL errors or source financial data into logs/public CI.
443 Write-Error 'A02_SQL_ISOLATED_RESTORE_OR_PREFLIGHT_FAILED_CHECK_PRIVATE_LOGS'
444 exit 3
445 } finally {
446 if ($null -ne $connection) { $connection.Dispose() }
447 }