فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix(a02): validate decrypted schema fingerprint and include foreign-key actions with SQL 2012-compatible catalogs
davoodmehraban89 committed
Oct 30, 2026 at 20:33 UTC
ed10842fb5021965ea2635e6d41578cf972d3fb3
1 file changed
+115
-8
scripts/a02-isolated-schema-inventory.ps1
+115
-8
@@ -165,7 +165,10 @@ SELECT fk.object_id AS ForeignKeyId,fk.name AS ForeignKeyName,
165
pc.name AS ParentColumn,rs.name AS ReferencedSchema,
166
rt.name AS ReferencedTable,rc.name AS ReferencedColumn,
167
fkc.constraint_column_id AS Ordinal,
168
- fk.is_disabled AS IsDisabled,fk.is_not_trusted AS IsNotTrusted
168
+ fk.is_disabled AS IsDisabled,fk.is_not_trusted AS IsNotTrusted,
169
+ fk.delete_referential_action_desc AS DeleteAction,
170
+ fk.update_referential_action_desc AS UpdateAction,
171
+ fk.is_not_for_replication AS IsNotForReplication
172
FROM sys.foreign_keys AS fk
173
JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id=fk.object_id
174
JOIN sys.tables AS pt ON pt.object_id=fk.parent_object_id
@@ -195,7 +198,7 @@ FROM sys.databases AS d WHERE d.name=DB_NAME();
198
try{[void]$adapter.Fill($result)}finally{$adapter.Dispose();$cmd.Dispose()}
199
Set-Variable -Name $spec.Name -Value $result -Scope Local
200
}
198
- if($columnTable.Rows.Count -lt 2 -or $columnTable.Rows.Count -gt 200000 -or
201
+ if($columnTable.Rows.Count -lt 1 -or $columnTable.Rows.Count -gt 200000 -or
202
$metaTable.Rows.Count -ne 1){throw 'A02_SCHEMA_SIZE_OR_METADATA_INVALID'}
203
$tableMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal);$tableOrder=[Collections.Generic.List[string]]::new()
204
foreach($r in $columnTable.Rows){
@@ -221,7 +224,7 @@ FROM sys.databases AS d WHERE d.name=DB_NAME();
224
fileStream=([int]$r['IsFileStream'] -eq 1)
225
})
226
}
224
- $indexMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal);$indexOrder=[Collections.Generic.List[string]]::new()
227
+ $indexMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal)
228
foreach($r in $indexTable.Rows){
229
$tableKey=(Frame ([string]$r['SchemaName']))+(Frame ([string]$r['TableName']))
230
$idxKey=$tableKey+(Frame ([string]$r['IndexId']))
@@ -235,7 +238,6 @@ FROM sys.databases AS d WHERE d.name=DB_NAME();
238
keyColumns=[Collections.Generic.List[object]]::new()
239
includedColumns=[Collections.Generic.List[string]]::new()
240
}
238
- $indexOrder.Add($idxKey)
241
$tableMap[$tableKey].indexes.Add($indexMap[$idxKey])
242
}
243
if([int]$r['IsIncludedColumn'] -eq 1){
@@ -247,7 +249,7 @@ FROM sys.databases AS d WHERE d.name=DB_NAME();
249
})
250
}
251
}
250
- $foreignMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal);$foreignOrder=[Collections.Generic.List[string]]::new()
252
+ $foreignMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal)
253
foreach($r in $foreignTable.Rows){
254
$parentKey=(Frame ([string]$r['ParentSchema']))+(Frame ([string]$r['ParentTable']))
255
$fkKey=$parentKey+(Frame ([string]$r['ForeignKeyId']))
@@ -259,9 +261,10 @@ FROM sys.databases AS d WHERE d.name=DB_NAME();
261
referencedTable=[string]$r['ReferencedTable']
262
disabled=([int]$r['IsDisabled'] -eq 1)
263
notTrusted=([int]$r['IsNotTrusted'] -eq 1)
264
+ deleteAction=[string]$r['DeleteAction'];updateAction=[string]$r['UpdateAction']
265
+ notForReplication=([int]$r['IsNotForReplication'] -eq 1)
266
columns=[Collections.Generic.List[object]]::new()
267
}
264
- $foreignOrder.Add($fkKey)
268
$tableMap[$parentKey].foreignKeys.Add($foreignMap[$fkKey])
269
}
270
$foreignMap[$fkKey].columns.Add([pscustomobject]@{
@@ -323,11 +326,115 @@ function Read-EncryptedManifest([string]$path){
326
$cipher,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser)
327
$json=[Text.Encoding]::UTF8.GetString($plain)
328
$manifest=$json | ConvertFrom-Json
329
+ if($null -eq $manifest.tables){throw 'A02_PRIVATE_MANIFEST_TABLES_MISSING'}
330
+ $schemaObject=[ordered]@{tables=$manifest.tables}
331
+ $canonical=ConvertTo-Json -InputObject $schemaObject -Depth 20 -Compress
332
+ $sha=[Security.Cryptography.SHA256]::Create()
333
+ try{
334
+ $actualFingerprint=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($canonical))).Replace('-','').ToLowerInvariant()
335
+ }finally{$sha.Dispose()}
336
+ if($actualFingerprint -cne [string]$manifest.schemaFingerprintSha256){
337
+ throw 'A02_PRIVATE_MANIFEST_FINGERPRINT_MISMATCH'
338
+ }
339
if($manifest.format -cne 'factor-easypro-a02-schema-manifest' -or
340
[int]$manifest.formatVersion -ne 1 -or
328
- [string]$manifest.schemaFingerprintSha256 -cnotmatch '^[0-9a-f]{64}$' -or
341
+ [string]$manifest.schemaFingerprintSha256 -cnotmatch '^[0-9a-f]{64}
342
+ $manifest.userRowsRead -ne $false -or
343
+ $manifest.databaseModified -ne $false -or
344
+ $manifest.canImport -ne $false){
345
+ throw 'A02_PRIVATE_MANIFEST_CONTRACT_INVALID'
346
+ }
347
+ return ,$plain
348
+}
349
+
350
+if($Mode -eq 'Test'){
351
+ Assert-Target 'FINORAMIG' 'FinoraHoloo_0123456789abcdef0123456789abcdef'
352
+ Assert-Target 'FinoraA02_0123456789ab' 'A02Restore_0123456789ab'
353
+ foreach($pair in @(@('FINORAMIG','master'),@('FINORAMIG','Holoo1'),
354
+ @('master','FinoraHoloo_0123456789abcdef0123456789abcdef'),
355
+ @('FinoraA02_0123456789ab','A02Restore_aaaaaaaaaaaa'))){
356
+ $blocked=$false
357
+ try{Assert-Target $pair[0] $pair[1]}catch{$blocked=$true}
358
+ if(-not $blocked){throw 'A02_UNSAFE_TARGET_ACCEPTED'}
359
+ }
360
+ $rows=@(
361
+ [pscustomobject]@{SchemaName='dbo';TableName='Synthetic';ColumnName='id';DataType='int';Ordinal=1;MaxLength=4;Precision=10;Scale=0;IsNullable=0;IsIdentity=0;IsComputed=0},
362
+ [pscustomobject]@{SchemaName='dbo';TableName='Synthetic';ColumnName='amount';DataType='bigint';Ordinal=2;MaxLength=8;Precision=19;Scale=0;IsNullable=0;IsIdentity=0;IsComputed=0}
363
+ )
364
+ $h=Fingerprint $rows;[array]::Reverse($rows)
365
+ if((Fingerprint $rows) -cne $h){throw 'A02_FINGERPRINT_NOT_ORDER_INDEPENDENT'}
366
+ $rows[0].ColumnName='changed'
367
+ if((Fingerprint $rows) -ceq $h){throw 'A02_FINGERPRINT_NOT_CHANGE_SENSITIVE'}
368
+ [pscustomobject]@{
369
+ status='schema-fingerprint-selftest-passed';sqlOpened=$false
370
+ userRowsRead=$false;databaseModified=$false;canImport=$false
371
+ }|ConvertTo-Json -Compress
372
+ return
373
+}
374
+
375
+if($Mode -eq 'DecryptManifest'){
376
+ try{
377
+ if([string]::IsNullOrWhiteSpace($InputPath) -or [string]::IsNullOrWhiteSpace($OutputPath)){
378
+ throw 'A02_PRIVATE_MANIFEST_PATHS_REQUIRED'
379
+ }
380
+ $plain=Read-EncryptedManifest $InputPath
381
+ Write-RestrictedFile $OutputPath $plain
382
+ [pscustomobject]@{status='private-schema-manifest-decrypted';plaintextFileAclRestricted=$true;userRowsRead=$false;databaseModified=$false;canImport=$false}|ConvertTo-Json -Compress
383
+ }catch{Write-Error 'A02_PRIVATE_MANIFEST_DECRYPT_FAILED';exit 2}
384
+ return
385
+}
386
+
387
+$conn=$null
388
+try{
389
+ Assert-Target $InstanceName $DatabaseName
390
+ $source=if($InstanceName -ceq 'FINORAMIG'){'lpc:.\FINORAMIG'}else{'(localdb)\'+$InstanceName}
391
+ $connectionString='Data Source='+$source+';Initial Catalog=master;Integrated Security=True;Connect Timeout=15;Encrypt=False;Pooling=False;'
392
+ $conn=[Data.SqlClient.SqlConnection]::new($connectionString);$conn.Open()
393
+ $check=$conn.CreateCommand()
394
+ $check.CommandText='SELECT state_desc FROM sys.databases WHERE name=@db;'
395
+ [void]$check.Parameters.Add('@db',[Data.SqlDbType]::NVarChar,128)
396
+ $check.Parameters['@db'].Value=$DatabaseName
397
+ $status=$check.ExecuteScalar();$check.Dispose()
398
+ if($null -eq $status -or [string]$status -cne 'ONLINE'){throw 'A02_RESTORE_NOT_ONLINE'}
399
+ $conn.ChangeDatabase($DatabaseName)
400
+ $manifest=Get-SchemaData $conn
401
+ if($Mode -eq 'Inspect'){
402
+ [pscustomobject]@{
403
+ status='isolated-schema-inventoried'
404
+ fingerprintSha256=$manifest.schemaFingerprintSha256
405
+ tableCount=$manifest.tableCount;columnCount=$manifest.columnCount
406
+ primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount
407
+ userRowsRead=$false;databaseModified=$false;canImport=$false
408
+ }|ConvertTo-Json -Compress
409
+ }else{
410
+ if([string]::IsNullOrWhiteSpace($OutputPath)){throw 'A02_PRIVATE_OUTPUT_PATH_REQUIRED'}
411
+ $json=ConvertTo-Json -InputObject $manifest -Depth 20
412
+ $plain=[Text.Encoding]::UTF8.GetBytes($json)
413
+ if($plain.Length -gt 33554432){throw 'A02_PRIVATE_MANIFEST_TOO_LARGE'}
414
+ Add-Type -AssemblyName System.Security -ErrorAction Stop
415
+ $cipher=[Security.Cryptography.ProtectedData]::Protect(
416
+ $plain,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser)
417
+ $header=[Text.Encoding]::ASCII.GetBytes($script:ManifestHeader)
418
+ $payload=New-Object byte[] ($header.Length+1+$cipher.Length)
419
+ [Buffer]::BlockCopy($header,0,$payload,0,$header.Length)
420
+ $payload[$header.Length]=10
421
+ [Buffer]::BlockCopy($cipher,0,$payload,$header.Length+1,$cipher.Length)
422
+ Write-RestrictedFile $OutputPath $payload
423
+ [pscustomobject]@{
424
+ status='private-schema-manifest-encrypted'
425
+ tableCount=$manifest.tableCount;columnCount=$manifest.columnCount
426
+ primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount
427
+ dpapiScope='CurrentUser';fileAclRestricted=$true
428
+ userRowsRead=$false;databaseModified=$false;canImport=$false
429
+ }|ConvertTo-Json -Compress
430
+ }
431
+}catch{
432
+ Write-Error 'A02_SCHEMA_INVENTORY_OR_PRIVATE_EXPORT_FAILED'
433
+ exit 2
434
+}finally{if($null -ne $conn){$conn.Dispose()}}
435
+ -or
436
[int]$manifest.tableCount -lt 1 -or
330
- [int]$manifest.columnCount -lt 2 -or
437
+ [int]$manifest.columnCount -lt 1 -or
438
$manifest.userRowsRead -ne $false -or
439
$manifest.databaseModified -ne $false -or
440
$manifest.canImport -ne $false){