From 6f75d1a6e21f052f99cd398eb068d0cb8b8d9007 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 04:41:38 +0300 Subject: [PATCH 1/4] Write non-finite geometry as JSON null and make file export atomic DwgJsonExporter now checks each geometry value with double.IsFinite: finite values keep the existing six-decimal rounding, non-finite values are written as JSON null and reported through DwgDocument.Diagnostics. WriteFile writes to a temporary file next to the target and moves it into place, so a failed export leaves neither a partial target file nor a temporary file. The CLI prints unexpected failures as a single line instead of a stack trace. --- src/DwgIO.Cli/Program.cs | 2 +- src/DwgIO/DwgDocument.cs | 15 ++++ src/DwgIO/Json/DwgJsonExporter.cs | 51 ++++++++++- tests/DwgIO.Tests/JsonExporterTests.cs | 119 +++++++++++++++++++++++++ 4 files changed, 183 insertions(+), 4 deletions(-) create mode 100644 tests/DwgIO.Tests/JsonExporterTests.cs diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 9d65583..f2e48aa 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -47,7 +47,7 @@ private static int Main(string[] args) } catch (Exception ex) { - Console.Error.WriteLine($"unexpected error: {ex}"); + Console.Error.WriteLine($"unexpected error: {ex.Message}"); return ExitParseError; } } diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 3c3c448..87fa187 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -92,6 +92,21 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Best-effort parse failures collected while opening (section name → message). public IReadOnlyList Diagnostics { get; } = []; + /// Creates an in-memory document over a file header and a fixed entity list (tests). + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities) + { + Path = path; + _fileBytes = []; + FileHeader = fileHeader; + Version = fileHeader.Version; + Sections = []; + Diagnostics = _diagnostics; + Entities = entities; + } + + /// Records a non-fatal problem found after the document was opened (e.g. by an exporter). + internal void ReportDiagnostic(string message) => _diagnostics.Add(message); + /// Opens and parses a DWG file. /// The file does not exist. /// The file's container is not implemented yet diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index ae2e3fd..1ef22d8 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -143,12 +143,26 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio if (entity.Geometry is { } geometry) { writer.WriteStartArray("geometry"); + int nonFiniteValues = 0; foreach (var value in geometry) { - writer.WriteNumberValue(Math.Round(value, 6)); + if (double.IsFinite(value)) + { + writer.WriteNumberValue(Math.Round(value, 6)); + } + else + { + writer.WriteNullValue(); + nonFiniteValues++; + } } writer.WriteEndArray(); + if (nonFiniteValues > 0) + { + document.ReportDiagnostic( + $"entity {entity.Handle:X}: {nonFiniteValues} non-finite geometry value(s) written as null"); + } } if (entity.ColorIndex != 0) @@ -196,8 +210,39 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio /// Writes as JSON to a new file at . public static void WriteFile(DwgDocument document, string path, DwgJsonExportOptions options) { - using var stream = File.Create(path); - Write(document, stream, options); + var fullPath = Path.GetFullPath(path); + var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + Write(document, stream, options); + } + + File.Move(tempPath, fullPath, overwrite: true); + } + catch + { + TryDelete(tempPath); + throw; + } + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } } private static bool IsIncluded(DwgDocument document, string name, DwgJsonExportOptions options) => diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs new file mode 100644 index 0000000..80ae00f --- /dev/null +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -0,0 +1,119 @@ +using System.Text.Json; +using DwgIO.Json; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class JsonExporterTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity CreateEntity(double[] geometry) => + new() + { + Handle = 0x2A, + TypeCode = 0x04, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = geometry, + }; + + [Fact] + public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() + { + var document = CreateDocument(CreateEntity( + [double.NaN, double.PositiveInfinity, 1.5, double.NegativeInfinity, -2.25, 0.0])); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var geometry = json.RootElement.GetProperty("entities")[0].GetProperty("geometry"); + Assert.Equal(JsonValueKind.Null, geometry[0].ValueKind); + Assert.Equal(JsonValueKind.Null, geometry[1].ValueKind); + Assert.Equal(1.5, geometry[2].GetDouble()); + Assert.Equal(JsonValueKind.Null, geometry[3].ValueKind); + Assert.Equal(-2.25, geometry[4].GetDouble()); + Assert.Equal(0.0, geometry[5].GetDouble()); + Assert.Contains(document.Diagnostics, d => d.StartsWith("entity 2A:", StringComparison.Ordinal)); + } + + [Fact] + public void Write_FiniteGeometry_RoundsWithoutDiagnostics() + { + var document = CreateDocument(CreateEntity([1.12345678, 2.0, 3.0, 4.0, 5.0, 6.0])); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var geometry = json.RootElement.GetProperty("entities")[0].GetProperty("geometry"); + Assert.Equal(1.123457, geometry[0].GetDouble()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void WriteFile_WritesFileAndLeavesNoTemporaryFile() + { + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + Assert.True(File.Exists(target)); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + using var json = JsonDocument.Parse(File.ReadAllBytes(target)); + Assert.Equal(1, json.RootElement.GetProperty("entityCount").GetInt32()); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void WriteFile_FailedMove_LeavesNoTargetFileOrTemporaryFile() + { + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + // A directory at the target path makes the final move fail after the temporary file was written. + Directory.CreateDirectory(target); + + var exception = Record.Exception(() => DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default)); + + Assert.NotNull(exception); + Assert.True(exception is IOException or UnauthorizedAccessException, exception.ToString()); + Assert.False(File.Exists(target)); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} From 5b22d3a3cc4bda21e47d024bb775300f3dbb720e Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 12:09:58 +0300 Subject: [PATCH 2/4] Preserve destination access rights on JSON overwrite Copy the existing file's DACL (Windows) or mode (Unix) onto the temporary export before writing, and re-apply after the atomic replace, so overwriting a protected JSON file keeps its rights. --- src/DwgIO/Json/DwgJsonExporter.cs | 104 ++++++++++++++++++++++++- tests/DwgIO.Tests/JsonExporterTests.cs | 38 +++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 1ef22d8..d566703 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,3 +1,4 @@ +using System.Security.AccessControl; using System.Text.Json; namespace DwgIO.Json; @@ -213,14 +214,69 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt var fullPath = Path.GetFullPath(path); var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + + // Preserve the destination's access rights across the atomic replace: a fresh + // temporary file inherits the directory ACL, which may be more permissive than + // the file being overwritten. Copy the existing rights onto the temporary file + // before any JSON bytes are written, then re-apply them after the move. + FileSecurity? savedWindowsAcl = null; + UnixFileMode? savedUnixMode = null; + bool haveExistingFile = false; + try + { + haveExistingFile = File.Exists(fullPath); + if (haveExistingFile) + { + if (OperatingSystem.IsWindows()) + { + try + { + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException or InvalidOperationException) + { + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) + { + savedUnixMode = null; + } + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + haveExistingFile = false; + } + try { - using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + // Create the temporary file empty first so its rights can be tightened + // before any document content hits the disk. + using (var _ = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + } + + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode); + + using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) { Write(document, stream, options); } File.Move(tempPath, fullPath, overwrite: true); + + // File.Move within a directory keeps the source (temporary) file's rights, + // which already mirror the destination. Re-apply best-effort in case the + // platform re-inherited rights on replace. + ApplyTempSecurity(fullPath, savedWindowsAcl, savedUnixMode); } catch { @@ -229,6 +285,52 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt } } + private static void ApplyTempSecurity( + string filePath, + FileSecurity? windowsAcl, + UnixFileMode? unixMode) + { + if (windowsAcl is not null && OperatingSystem.IsWindows()) + { + try + { + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException or InvalidOperationException or System.Security.AccessControl.PrivilegeNotHeldException) + { + } + } + + if (unixMode.HasValue && (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())) + { + try + { + File.SetUnixFileMode(filePath, unixMode.Value); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) + { + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static FileSecurity CloneDacl(FileSecurity source) + { + var clone = new FileSecurity(); + clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); + foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) + { + clone.AddAccessRule(rule); + } + + return clone; + } + private static void TryDelete(string path) { try diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 80ae00f..05f66d6 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -92,6 +92,44 @@ public void WriteFile_WritesFileAndLeavesNoTemporaryFile() } } + [Fact] + public void WriteFile_Overwrite_PreservesExistingAccessRules() + { + if (!OperatingSystem.IsWindows()) + { + return; + } + + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + var acl = new FileInfo(target).GetAccessControl(); + acl.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + new FileInfo(target).SetAccessControl(acl); + Assert.True(new FileInfo(target).GetAccessControl().AreAccessRulesProtected); + + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + Assert.True(new FileInfo(target).GetAccessControl().AreAccessRulesProtected); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + using var json = JsonDocument.Parse(File.ReadAllBytes(target)); + Assert.Equal(1, json.RootElement.GetProperty("entityCount").GetInt32()); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + [Fact] public void WriteFile_FailedMove_LeavesNoTargetFileOrTemporaryFile() { From f511f7ec52a49162dd567ef2bd3b81e8246bcdcd Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 12:37:01 +0300 Subject: [PATCH 3/4] Fail JSON export when destination rights cannot be preserved Reading or applying the existing DACL (Windows) or mode (Unix) is mandatory when overwriting: propagate failures instead of falling back to directory-inherited rights, so a protected file is never silently replaced. Add a regression test that denies READ_CONTROL and asserts the original is kept with no temp left. --- src/DwgIO/Json/DwgJsonExporter.cs | 88 ++++++++++++-------------- tests/DwgIO.Tests/JsonExporterTests.cs | 73 +++++++++++++++++++++ 2 files changed, 115 insertions(+), 46 deletions(-) diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index d566703..55c9f09 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -219,41 +219,35 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt // temporary file inherits the directory ACL, which may be more permissive than // the file being overwritten. Copy the existing rights onto the temporary file // before any JSON bytes are written, then re-apply them after the move. + // Reading or applying the rights is mandatory: failures abort the export + // before the destination is touched, instead of silently widening access. FileSecurity? savedWindowsAcl = null; UnixFileMode? savedUnixMode = null; - bool haveExistingFile = false; - try + bool destinationExists = File.Exists(fullPath); + if (destinationExists) { - haveExistingFile = File.Exists(fullPath); - if (haveExistingFile) + if (OperatingSystem.IsWindows()) { - if (OperatingSystem.IsWindows()) + try { - try - { - savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException or InvalidOperationException) - { - savedWindowsAcl = null; - } + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); } - else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + catch (PlatformNotSupportedException) { - try - { - savedUnixMode = File.GetUnixFileMode(fullPath); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) - { - savedUnixMode = null; - } + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (PlatformNotSupportedException) + { + savedUnixMode = null; } } - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - haveExistingFile = false; } try @@ -264,7 +258,7 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt { } - ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode); + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) { @@ -274,9 +268,9 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt File.Move(tempPath, fullPath, overwrite: true); // File.Move within a directory keeps the source (temporary) file's rights, - // which already mirror the destination. Re-apply best-effort in case the - // platform re-inherited rights on replace. - ApplyTempSecurity(fullPath, savedWindowsAcl, savedUnixMode); + // which already mirror the destination. Re-apply in case the platform + // re-inherited rights on replace; a failure here is reported, not hidden. + ApplyTempSecurity(fullPath, savedWindowsAcl, savedUnixMode, destinationExists); } catch { @@ -288,33 +282,35 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt private static void ApplyTempSecurity( string filePath, FileSecurity? windowsAcl, - UnixFileMode? unixMode) + UnixFileMode? unixMode, + bool destinationExists) { - if (windowsAcl is not null && OperatingSystem.IsWindows()) + if (!destinationExists) { - try + return; + } + + if (OperatingSystem.IsWindows()) + { + if (windowsAcl is null) { - // Copy only the DACL and its protection flag. Persisting the whole - // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, - // when unmodified, persists nothing — the temporary file would keep - // the directory's inherited rules. - new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); return; } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException or InvalidOperationException or System.Security.AccessControl.PrivilegeNotHeldException) - { - } + + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; } - if (unixMode.HasValue && (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())) + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { - try + if (unixMode.HasValue) { File.SetUnixFileMode(filePath, unixMode.Value); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) - { - } } } diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 05f66d6..770c48d 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -130,6 +130,79 @@ public void WriteFile_Overwrite_PreservesExistingAccessRules() } } + [Fact] + public void WriteFile_UnreadableAcl_AbortsWithoutReplacing() + { + if (!OperatingSystem.IsWindows()) + { + return; + } + + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + var target = Path.Combine(directory, "out.json"); + File.WriteAllText(target, "KEEP ORIGINAL"); + var fileInfo = new FileInfo(target); + + var deny = new System.Security.AccessControl.FileSecurity(); + deny.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + user, + System.Security.AccessControl.FileSystemRights.ReadPermissions, + System.Security.AccessControl.AccessControlType.Deny)); + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + new System.Security.Principal.SecurityIdentifier("S-1-3-4"), + System.Security.AccessControl.FileSystemRights.ChangePermissions, + System.Security.AccessControl.AccessControlType.Allow)); + fileInfo.SetAccessControl(deny); + + try + { + bool readDenied; + try + { + fileInfo.GetAccessControl(); + readDenied = false; + } + catch (UnauthorizedAccessException) + { + readDenied = true; + } + + Assert.True(readDenied, "probe invalid: reading the ACL was not denied"); + + var exception = Record.Exception(() => DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default)); + + Assert.NotNull(exception); + Assert.True(exception is UnauthorizedAccessException or IOException, exception.ToString()); + // READ_CONTROL is denied, so contents cannot be opened for reading + // (GENERIC_READ includes READ_CONTROL); the directory-reported length + // still proves the original 13-byte file was not replaced. + Assert.Equal(13, new FileInfo(target).Length); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + } + finally + { + // The deny ACL blocks READ_CONTROL, so it cannot be restored in-process; + // deleting only needs DELETE, which FullControl still allows. + try + { + File.Delete(target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + + Directory.Delete(directory, recursive: true); + } + } + [Fact] public void WriteFile_FailedMove_LeavesNoTargetFileOrTemporaryFile() { From f0f21467b61e4651f64b3a88149f00c177a7c64a Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 12:44:07 +0300 Subject: [PATCH 4/4] Preserve copied access rights without reapplying them after replace --- src/DwgIO/Json/DwgJsonExporter.cs | 7 +------ tests/DwgIO.Tests/JsonExporterTests.cs | 25 +++++++++++++++++++++---- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 55c9f09..ca2ab32 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -218,7 +218,7 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt // Preserve the destination's access rights across the atomic replace: a fresh // temporary file inherits the directory ACL, which may be more permissive than // the file being overwritten. Copy the existing rights onto the temporary file - // before any JSON bytes are written, then re-apply them after the move. + // before any JSON bytes are written; the same-directory move preserves them. // Reading or applying the rights is mandatory: failures abort the export // before the destination is touched, instead of silently widening access. FileSecurity? savedWindowsAcl = null; @@ -266,11 +266,6 @@ public static void WriteFile(DwgDocument document, string path, DwgJsonExportOpt } File.Move(tempPath, fullPath, overwrite: true); - - // File.Move within a directory keeps the source (temporary) file's rights, - // which already mirror the destination. Re-apply in case the platform - // re-inherited rights on replace; a failure here is reported, not hidden. - ApplyTempSecurity(fullPath, savedWindowsAcl, savedUnixMode, destinationExists); } catch { diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 770c48d..7ab59d9 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -92,8 +92,10 @@ public void WriteFile_WritesFileAndLeavesNoTemporaryFile() } } - [Fact] - public void WriteFile_Overwrite_PreservesExistingAccessRules() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WriteFile_Overwrite_PreservesExistingAccessRules(bool denyAclChanges) { if (!OperatingSystem.IsWindows()) { @@ -114,12 +116,27 @@ public void WriteFile_Overwrite_PreservesExistingAccessRules() System.Security.Principal.WindowsIdentity.GetCurrent().User!, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); + if (denyAclChanges) + { + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.ChangePermissions, + System.Security.AccessControl.AccessControlType.Deny)); + // OWNER RIGHTS suppresses the owner's implicit permission to change the ACL. + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + new System.Security.Principal.SecurityIdentifier("S-1-3-4"), + System.Security.AccessControl.FileSystemRights.ReadPermissions, + System.Security.AccessControl.AccessControlType.Allow)); + } + new FileInfo(target).SetAccessControl(acl); - Assert.True(new FileInfo(target).GetAccessControl().AreAccessRulesProtected); + var expectedAcl = new FileInfo(target).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access); DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); - Assert.True(new FileInfo(target).GetAccessControl().AreAccessRulesProtected); + Assert.Equal(expectedAcl, new FileInfo(target).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access)); Assert.Empty(Directory.GetFiles(directory, "*.tmp")); using var json = JsonDocument.Parse(File.ReadAllBytes(target)); Assert.Equal(1, json.RootElement.GetProperty("entityCount").GetInt32());