From b89f3621526a8375e8bc8b26ff4c2dd464f90152 Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Sat, 8 Aug 2026 14:23:38 -0700 Subject: [PATCH 1/7] Add ClickOnce manifest foundation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- Directory.Packages.props | 3 + scripts/VerifyNuGetPackage.ps1 | 4 + src/Sign.Core/Sign.Core.csproj | 2 + .../ClickOnce/ApplicationManifestAdapter.cs | 53 +++++ .../ClickOnce/ClickOnceManifestReader.cs | 54 +++++ .../ClickOnceManifestReaderProvider.cs | 28 +++ .../Tools/ClickOnce/DeployManifestAdapter.cs | 53 +++++ .../Tools/ClickOnce/IApplicationManifest.cs | 15 ++ .../Tools/ClickOnce/IClickOnceManifest.cs | 19 ++ .../ClickOnce/IClickOnceManifestReader.cs | 21 ++ .../Tools/ClickOnce/IDeployManifest.cs | 15 ++ .../ClickOnceManifestReaderProviderTests.cs | 49 +++++ .../ClickOnce/ClickOnceManifestReaderTests.cs | 199 ++++++++++++++++++ 13 files changed, 515 insertions(+) create mode 100644 src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs create mode 100644 src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs create mode 100644 test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs create mode 100644 test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index c5fafeaa..a7cb9fa2 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,6 +13,9 @@ + + diff --git a/scripts/VerifyNuGetPackage.ps1 b/scripts/VerifyNuGetPackage.ps1 index 8ec63073..46e0b763 100644 --- a/scripts/VerifyNuGetPackage.ps1 +++ b/scripts/VerifyNuGetPackage.ps1 @@ -62,6 +62,10 @@ If ($packageFilePaths.Count -ne 1) [string[]] $expectedEntryFullNames = 'tools/net8.0/any/sign.dll', + 'tools/net8.0/any/Microsoft.Build.Framework.dll', + 'tools/net8.0/any/Microsoft.Build.Tasks.Core.dll', + 'tools/net8.0/any/Microsoft.Build.Utilities.Core.dll', + 'tools/net8.0/any/Microsoft.NET.StringTools.dll', 'tools/net8.0/any/tools/SDK/x64/appxpackaging.dll', 'tools/net8.0/any/tools/SDK/x64/appxsip.dll', 'tools/net8.0/any/tools/SDK/x64/makeappx.exe', diff --git a/src/Sign.Core/Sign.Core.csproj b/src/Sign.Core/Sign.Core.csproj index 04afb11b..ab2320b3 100644 --- a/src/Sign.Core/Sign.Core.csproj +++ b/src/Sign.Core/Sign.Core.csproj @@ -7,6 +7,8 @@ + + diff --git a/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs new file mode 100644 index 00000000..d3a702e1 --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal sealed class ApplicationManifestAdapter : IApplicationManifest + { + private readonly ApplicationManifest _manifest; + + internal ApplicationManifestAdapter(ApplicationManifest manifest) + { + ArgumentNullException.ThrowIfNull(manifest, nameof(manifest)); + + _manifest = manifest; + } + + public AssemblyIdentity AssemblyIdentity => _manifest.AssemblyIdentity; + public AssemblyReferenceCollection AssemblyReferences => _manifest.AssemblyReferences; + public AssemblyReference? EntryPoint => _manifest.EntryPoint; + public FileReferenceCollection FileReferences => _manifest.FileReferences; + public OutputMessageCollection OutputMessages => _manifest.OutputMessages; + + public bool ReadOnly + { + get => _manifest.ReadOnly; + set => _manifest.ReadOnly = value; + } + + public void ResolveFiles(string[] searchPaths) + { + ArgumentNullException.ThrowIfNull(searchPaths, nameof(searchPaths)); + + _manifest.ResolveFiles(searchPaths); + } + + public void UpdateFileInfo(string targetFrameworkVersion) + { + ArgumentException.ThrowIfNullOrWhiteSpace(targetFrameworkVersion, nameof(targetFrameworkVersion)); + + _manifest.UpdateFileInfo(targetFrameworkVersion); + } + + public void Write(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream, nameof(stream)); + + ManifestWriter.WriteManifest(_manifest, stream); + } + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs new file mode 100644 index 00000000..218b4e40 --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal sealed class ClickOnceManifestReader : IClickOnceManifestReader + { + public bool TryReadApplicationManifest( + Stream stream, + bool preserveStream, + [NotNullWhen(true)] out IApplicationManifest? manifest) + { + ArgumentNullException.ThrowIfNull(stream, nameof(stream)); + + Manifest? readManifest = ManifestReader.ReadManifest(stream, preserveStream); + + if (readManifest is ApplicationManifest applicationManifest) + { + manifest = new ApplicationManifestAdapter(applicationManifest); + + return true; + } + + manifest = null; + + return false; + } + + public bool TryReadDeployManifest( + Stream stream, + bool preserveStream, + [NotNullWhen(true)] out IDeployManifest? manifest) + { + ArgumentNullException.ThrowIfNull(stream, nameof(stream)); + + Manifest? readManifest = ManifestReader.ReadManifest(stream, preserveStream); + + if (readManifest is DeployManifest deployManifest) + { + manifest = new DeployManifestAdapter(deployManifest); + + return true; + } + + manifest = null; + + return false; + } + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs new file mode 100644 index 00000000..4d37d7fc --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +namespace Sign.Core +{ + internal sealed class ClickOnceManifestReaderProvider + { + private readonly Lazy _reader; + + internal ClickOnceManifestReaderProvider() + : this(static () => new ClickOnceManifestReader()) + { + } + + internal ClickOnceManifestReaderProvider(Func readerFactory) + { + ArgumentNullException.ThrowIfNull(readerFactory, nameof(readerFactory)); + + _reader = new Lazy( + readerFactory, + LazyThreadSafetyMode.ExecutionAndPublication); + } + + internal bool IsValueCreated => _reader.IsValueCreated; + internal IClickOnceManifestReader Reader => _reader.Value; + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs new file mode 100644 index 00000000..e4d07d8d --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal sealed class DeployManifestAdapter : IDeployManifest + { + private readonly DeployManifest _manifest; + + internal DeployManifestAdapter(DeployManifest manifest) + { + ArgumentNullException.ThrowIfNull(manifest, nameof(manifest)); + + _manifest = manifest; + } + + public AssemblyIdentity AssemblyIdentity => _manifest.AssemblyIdentity; + public AssemblyReferenceCollection AssemblyReferences => _manifest.AssemblyReferences; + public AssemblyReference? EntryPoint => _manifest.EntryPoint; + public bool MapFileExtensions => _manifest.MapFileExtensions; + public OutputMessageCollection OutputMessages => _manifest.OutputMessages; + + public bool ReadOnly + { + get => _manifest.ReadOnly; + set => _manifest.ReadOnly = value; + } + + public void ResolveFiles(string[] searchPaths) + { + ArgumentNullException.ThrowIfNull(searchPaths, nameof(searchPaths)); + + _manifest.ResolveFiles(searchPaths); + } + + public void UpdateFileInfo(string targetFrameworkVersion) + { + ArgumentException.ThrowIfNullOrWhiteSpace(targetFrameworkVersion, nameof(targetFrameworkVersion)); + + _manifest.UpdateFileInfo(targetFrameworkVersion); + } + + public void Write(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream, nameof(stream)); + + ManifestWriter.WriteManifest(_manifest, stream); + } + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs b/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs new file mode 100644 index 00000000..b73b6f04 --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal interface IApplicationManifest : IClickOnceManifest + { + AssemblyReferenceCollection AssemblyReferences { get; } + AssemblyReference? EntryPoint { get; } + FileReferenceCollection FileReferences { get; } + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs new file mode 100644 index 00000000..a4b4f6ee --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal interface IClickOnceManifest + { + AssemblyIdentity AssemblyIdentity { get; } + OutputMessageCollection OutputMessages { get; } + bool ReadOnly { get; set; } + + void ResolveFiles(string[] searchPaths); + void UpdateFileInfo(string targetFrameworkVersion); + void Write(Stream stream); + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs new file mode 100644 index 00000000..c4f25565 --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using System.Diagnostics.CodeAnalysis; + +namespace Sign.Core +{ + internal interface IClickOnceManifestReader + { + bool TryReadApplicationManifest( + Stream stream, + bool preserveStream, + [NotNullWhen(true)] out IApplicationManifest? manifest); + + bool TryReadDeployManifest( + Stream stream, + bool preserveStream, + [NotNullWhen(true)] out IDeployManifest? manifest); + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs b/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs new file mode 100644 index 00000000..43fa5713 --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal interface IDeployManifest : IClickOnceManifest + { + AssemblyReferenceCollection AssemblyReferences { get; } + AssemblyReference? EntryPoint { get; } + bool MapFileExtensions { get; } + } +} diff --git a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs new file mode 100644 index 00000000..ad0fa3b8 --- /dev/null +++ b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs @@ -0,0 +1,49 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Moq; + +namespace Sign.Core.Test +{ + public sealed class ClickOnceManifestReaderProviderTests + { + [Fact] + public void Reader_WhenNotAccessed_DoesNotCreateManifestReader() + { + int invocationCount = 0; + ClickOnceManifestReaderProvider provider = new( + () => + { + ++invocationCount; + + return Mock.Of(); + }); + + Assert.False(provider.IsValueCreated); + Assert.Equal(0, invocationCount); + } + + [Fact] + public void Reader_WhenAccessedMultipleTimes_CreatesManifestReaderOnce() + { + int invocationCount = 0; + IClickOnceManifestReader expectedReader = Mock.Of(); + ClickOnceManifestReaderProvider provider = new( + () => + { + ++invocationCount; + + return expectedReader; + }); + + IClickOnceManifestReader firstReader = provider.Reader; + IClickOnceManifestReader secondReader = provider.Reader; + + Assert.Same(expectedReader, firstReader); + Assert.Same(firstReader, secondReader); + Assert.True(provider.IsValueCreated); + Assert.Equal(1, invocationCount); + } + } +} diff --git a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs new file mode 100644 index 00000000..86d05b68 --- /dev/null +++ b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs @@ -0,0 +1,199 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using System.Text; +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core.Test +{ + public sealed class ClickOnceManifestReaderTests + { + [Fact] + public void TryReadApplicationManifest_WhenManifestIsApplication_ReturnsTypedWritableAdapter() + { + ApplicationManifest expectedManifest = CreateApplicationManifest(); + using MemoryStream stream = WriteManifest(expectedManifest); + ClickOnceManifestReader reader = new(); + + bool result = reader.TryReadApplicationManifest( + stream, + preserveStream: true, + out IApplicationManifest? manifest); + + Assert.True(result); + Assert.NotNull(manifest); + Assert.Equal("TestApplication", manifest.AssemblyIdentity.Name); + Assert.NotNull(manifest.OutputMessages); + + manifest.ReadOnly = false; + + Assert.False(manifest.ReadOnly); + } + + [Fact] + public void TryReadDeployManifest_WhenManifestIsDeployment_ReturnsTypedWritableAdapter() + { + DeployManifest expectedManifest = CreateDeployManifest(); + using MemoryStream stream = WriteManifest(expectedManifest); + ClickOnceManifestReader reader = new(); + + bool result = reader.TryReadDeployManifest( + stream, + preserveStream: true, + out IDeployManifest? manifest); + + Assert.True(result); + Assert.NotNull(manifest); + Assert.Equal("TestDeployment", manifest.AssemblyIdentity.Name); + Assert.True(manifest.MapFileExtensions); + + manifest.ReadOnly = false; + + Assert.False(manifest.ReadOnly); + } + + [Fact] + public void TryReadApplicationManifest_WhenManifestIsDeployment_ReturnsFalse() + { + using MemoryStream stream = WriteManifest(CreateDeployManifest()); + ClickOnceManifestReader reader = new(); + + bool result = reader.TryReadApplicationManifest( + stream, + preserveStream: true, + out IApplicationManifest? manifest); + + Assert.False(result); + Assert.Null(manifest); + Assert.Equal(0, stream.Position); + Assert.True( + reader.TryReadDeployManifest( + stream, + preserveStream: true, + out IDeployManifest? deployManifest)); + Assert.NotNull(deployManifest); + } + + [Fact] + public void TryReadDeployManifest_WhenManifestIsApplication_ReturnsFalse() + { + using MemoryStream stream = WriteManifest(CreateApplicationManifest()); + ClickOnceManifestReader reader = new(); + + bool result = reader.TryReadDeployManifest( + stream, + preserveStream: true, + out IDeployManifest? manifest); + + Assert.False(result); + Assert.Null(manifest); + Assert.Equal(0, stream.Position); + Assert.True( + reader.TryReadApplicationManifest( + stream, + preserveStream: true, + out IApplicationManifest? applicationManifest)); + Assert.NotNull(applicationManifest); + } + + [Fact] + public void TryReadApplicationManifest_WhenManifestIsSideBySide_ReturnsFalse() + { + const string Xml = """ + + + + + """; + using MemoryStream stream = new(Encoding.UTF8.GetBytes(Xml)); + ClickOnceManifestReader reader = new(); + + bool result = reader.TryReadApplicationManifest( + stream, + preserveStream: true, + out IApplicationManifest? manifest); + + Assert.False(result); + Assert.Null(manifest); + } + + [Fact] + public void ApplicationManifestAdapter_UpdateFileInfo_UsesRequestedTargetFramework() + { + const int Sha256HashSizeInBytes = 32; + const string TargetFrameworkVersion = "v4.5"; + string temporaryFilePath = Path.GetTempFileName(); + + try + { + File.WriteAllText(temporaryFilePath, "payload"); + ApplicationManifest applicationManifest = CreateApplicationManifest(); + FileReference reference = new(temporaryFilePath); + applicationManifest.FileReferences.Add(reference); + ApplicationManifestAdapter adapter = new(applicationManifest); + + adapter.ResolveFiles(new[] { Path.GetDirectoryName(temporaryFilePath)! }); + adapter.UpdateFileInfo(TargetFrameworkVersion); + + Assert.Equal(Sha256HashSizeInBytes, Convert.FromBase64String(reference.Hash).Length); + Assert.Equal(new FileInfo(temporaryFilePath).Length, reference.Size); + } + finally + { + File.Delete(temporaryFilePath); + } + } + + [Fact] + public void ApplicationManifestAdapter_Write_RoundTripsUpdatedManifest() + { + ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + using MemoryStream stream = new(); + + adapter.Write(stream); + stream.Position = 0; + + ClickOnceManifestReader reader = new(); + Assert.True( + reader.TryReadApplicationManifest( + stream, + preserveStream: true, + out IApplicationManifest? manifest)); + Assert.NotNull(manifest); + Assert.Equal("TestApplication", manifest.AssemblyIdentity.Name); + } + + private static ApplicationManifest CreateApplicationManifest() + { + ApplicationManifest manifest = new(); + manifest.AssemblyIdentity.Name = "TestApplication"; + manifest.AssemblyIdentity.Version = "1.0.0.0"; + manifest.AssemblyIdentity.ProcessorArchitecture = "msil"; + + return manifest; + } + + private static DeployManifest CreateDeployManifest() + { + DeployManifest manifest = new() + { + MapFileExtensions = true + }; + manifest.AssemblyIdentity.Name = "TestDeployment"; + manifest.AssemblyIdentity.Version = "1.0.0.0"; + manifest.AssemblyIdentity.ProcessorArchitecture = "msil"; + + return manifest; + } + + private static MemoryStream WriteManifest(Manifest manifest) + { + MemoryStream stream = new(); + ManifestWriter.WriteManifest(manifest, stream); + stream.Position = 0; + + return stream; + } + } +} From 9d68fdaf7b15b17d828e6263f3347d07e6fbad3a Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Sun, 9 Aug 2026 15:38:36 -0700 Subject: [PATCH 2/7] Remove redundant manifest reader provider Defer manifest-reader construction to conditional version 2 service registration, which already receives lazy singleton behavior from dependency injection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- .../ClickOnceManifestReaderProvider.cs | 28 ----------- .../ClickOnceManifestReaderProviderTests.cs | 49 ------------------- 2 files changed, 77 deletions(-) delete mode 100644 src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs delete mode 100644 test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs deleted file mode 100644 index 4d37d7fc..00000000 --- a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReaderProvider.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE.txt file in the project root for more information. - -namespace Sign.Core -{ - internal sealed class ClickOnceManifestReaderProvider - { - private readonly Lazy _reader; - - internal ClickOnceManifestReaderProvider() - : this(static () => new ClickOnceManifestReader()) - { - } - - internal ClickOnceManifestReaderProvider(Func readerFactory) - { - ArgumentNullException.ThrowIfNull(readerFactory, nameof(readerFactory)); - - _reader = new Lazy( - readerFactory, - LazyThreadSafetyMode.ExecutionAndPublication); - } - - internal bool IsValueCreated => _reader.IsValueCreated; - internal IClickOnceManifestReader Reader => _reader.Value; - } -} diff --git a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs deleted file mode 100644 index ad0fa3b8..00000000 --- a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderProviderTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE.txt file in the project root for more information. - -using Moq; - -namespace Sign.Core.Test -{ - public sealed class ClickOnceManifestReaderProviderTests - { - [Fact] - public void Reader_WhenNotAccessed_DoesNotCreateManifestReader() - { - int invocationCount = 0; - ClickOnceManifestReaderProvider provider = new( - () => - { - ++invocationCount; - - return Mock.Of(); - }); - - Assert.False(provider.IsValueCreated); - Assert.Equal(0, invocationCount); - } - - [Fact] - public void Reader_WhenAccessedMultipleTimes_CreatesManifestReaderOnce() - { - int invocationCount = 0; - IClickOnceManifestReader expectedReader = Mock.Of(); - ClickOnceManifestReaderProvider provider = new( - () => - { - ++invocationCount; - - return expectedReader; - }); - - IClickOnceManifestReader firstReader = provider.Reader; - IClickOnceManifestReader secondReader = provider.Reader; - - Assert.Same(expectedReader, firstReader); - Assert.Same(firstReader, secondReader); - Assert.True(provider.IsValueCreated); - Assert.Equal(1, invocationCount); - } - } -} From 287a62b35adfb66ab209a941283661a9739188e6 Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Mon, 10 Aug 2026 19:01:23 -0700 Subject: [PATCH 3/7] Fix ClickOnce manifest serialization Use the framework-aware ManifestUtilities writer and SHA-256 metadata updates through a shared adapter base. Strengthen the typed filesystem contract and adapter regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- .../ClickOnce/ApplicationManifestAdapter.cs | 43 +-- .../ClickOnce/ClickOnceManifestAdapter.cs | 74 +++++ .../Tools/ClickOnce/DeployManifestAdapter.cs | 43 +-- .../Tools/ClickOnce/IClickOnceManifest.cs | 6 +- .../ClickOnce/ClickOnceManifestReaderTests.cs | 290 +++++++++++++++++- 5 files changed, 367 insertions(+), 89 deletions(-) create mode 100644 src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs diff --git a/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs index d3a702e1..40e2434b 100644 --- a/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs +++ b/src/Sign.Core/Tools/ClickOnce/ApplicationManifestAdapter.cs @@ -6,48 +6,15 @@ namespace Sign.Core { - internal sealed class ApplicationManifestAdapter : IApplicationManifest + internal sealed class ApplicationManifestAdapter : + ClickOnceManifestAdapter, + IApplicationManifest { - private readonly ApplicationManifest _manifest; - internal ApplicationManifestAdapter(ApplicationManifest manifest) + : base(manifest) { - ArgumentNullException.ThrowIfNull(manifest, nameof(manifest)); - - _manifest = manifest; } - public AssemblyIdentity AssemblyIdentity => _manifest.AssemblyIdentity; - public AssemblyReferenceCollection AssemblyReferences => _manifest.AssemblyReferences; - public AssemblyReference? EntryPoint => _manifest.EntryPoint; - public FileReferenceCollection FileReferences => _manifest.FileReferences; - public OutputMessageCollection OutputMessages => _manifest.OutputMessages; - - public bool ReadOnly - { - get => _manifest.ReadOnly; - set => _manifest.ReadOnly = value; - } - - public void ResolveFiles(string[] searchPaths) - { - ArgumentNullException.ThrowIfNull(searchPaths, nameof(searchPaths)); - - _manifest.ResolveFiles(searchPaths); - } - - public void UpdateFileInfo(string targetFrameworkVersion) - { - ArgumentException.ThrowIfNullOrWhiteSpace(targetFrameworkVersion, nameof(targetFrameworkVersion)); - - _manifest.UpdateFileInfo(targetFrameworkVersion); - } - - public void Write(Stream stream) - { - ArgumentNullException.ThrowIfNull(stream, nameof(stream)); - - ManifestWriter.WriteManifest(_manifest, stream); - } + public FileReferenceCollection FileReferences => Manifest.FileReferences; } } diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs new file mode 100644 index 00000000..19b84b2c --- /dev/null +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs @@ -0,0 +1,74 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE.txt file in the project root for more information. + +using Microsoft.Build.Tasks.Deployment.ManifestUtilities; + +namespace Sign.Core +{ + internal abstract class ClickOnceManifestAdapter : IClickOnceManifest + where TManifest : Manifest + { + private const string TargetFrameworkVersion = "v4.5"; + + protected TManifest Manifest { get; } + + protected ClickOnceManifestAdapter(TManifest manifest) + { + ArgumentNullException.ThrowIfNull(manifest, nameof(manifest)); + + Manifest = manifest; + } + + public AssemblyIdentity AssemblyIdentity => Manifest.AssemblyIdentity; + public AssemblyReferenceCollection AssemblyReferences => Manifest.AssemblyReferences; + public AssemblyReference? EntryPoint => Manifest.EntryPoint; + public OutputMessageCollection OutputMessages => Manifest.OutputMessages; + + public bool ReadOnly + { + get => Manifest.ReadOnly; + set => Manifest.ReadOnly = value; + } + + public void ResolveFiles(IReadOnlyList searchDirectories) + { + ArgumentNullException.ThrowIfNull( + searchDirectories, + nameof(searchDirectories)); + + string[] searchPaths = new string[searchDirectories.Count]; + + for (int i = 0; i < searchDirectories.Count; ++i) + { + DirectoryInfo? searchDirectory = searchDirectories[i]; + + if (searchDirectory is null) + { + throw new ArgumentException( + message: null, + nameof(searchDirectories)); + } + + searchPaths[i] = searchDirectory.FullName; + } + + Manifest.ResolveFiles(searchPaths); + } + + public void UpdateFileInfo() + { + Manifest.UpdateFileInfo(TargetFrameworkVersion); + } + + public void Write(FileInfo file) + { + ArgumentNullException.ThrowIfNull(file, nameof(file)); + + ManifestWriter.WriteManifest( + Manifest, + file.FullName, + TargetFrameworkVersion); + } + } +} diff --git a/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs index e4d07d8d..490986c6 100644 --- a/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs +++ b/src/Sign.Core/Tools/ClickOnce/DeployManifestAdapter.cs @@ -6,48 +6,15 @@ namespace Sign.Core { - internal sealed class DeployManifestAdapter : IDeployManifest + internal sealed class DeployManifestAdapter : + ClickOnceManifestAdapter, + IDeployManifest { - private readonly DeployManifest _manifest; - internal DeployManifestAdapter(DeployManifest manifest) + : base(manifest) { - ArgumentNullException.ThrowIfNull(manifest, nameof(manifest)); - - _manifest = manifest; } - public AssemblyIdentity AssemblyIdentity => _manifest.AssemblyIdentity; - public AssemblyReferenceCollection AssemblyReferences => _manifest.AssemblyReferences; - public AssemblyReference? EntryPoint => _manifest.EntryPoint; - public bool MapFileExtensions => _manifest.MapFileExtensions; - public OutputMessageCollection OutputMessages => _manifest.OutputMessages; - - public bool ReadOnly - { - get => _manifest.ReadOnly; - set => _manifest.ReadOnly = value; - } - - public void ResolveFiles(string[] searchPaths) - { - ArgumentNullException.ThrowIfNull(searchPaths, nameof(searchPaths)); - - _manifest.ResolveFiles(searchPaths); - } - - public void UpdateFileInfo(string targetFrameworkVersion) - { - ArgumentException.ThrowIfNullOrWhiteSpace(targetFrameworkVersion, nameof(targetFrameworkVersion)); - - _manifest.UpdateFileInfo(targetFrameworkVersion); - } - - public void Write(Stream stream) - { - ArgumentNullException.ThrowIfNull(stream, nameof(stream)); - - ManifestWriter.WriteManifest(_manifest, stream); - } + public bool MapFileExtensions => Manifest.MapFileExtensions; } } diff --git a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs index a4b4f6ee..e71f5e87 100644 --- a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs +++ b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs @@ -12,8 +12,8 @@ internal interface IClickOnceManifest OutputMessageCollection OutputMessages { get; } bool ReadOnly { get; set; } - void ResolveFiles(string[] searchPaths); - void UpdateFileInfo(string targetFrameworkVersion); - void Write(Stream stream); + void ResolveFiles(IReadOnlyList searchDirectories); + void UpdateFileInfo(); + void Write(FileInfo file); } } diff --git a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs index 86d05b68..045e4f51 100644 --- a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs +++ b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs @@ -2,13 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE.txt file in the project root for more information. +using System.Security.Cryptography; using System.Text; +using System.Xml.Linq; using Microsoft.Build.Tasks.Deployment.ManifestUtilities; +using Sign.TestInfrastructure; namespace Sign.Core.Test { public sealed class ClickOnceManifestReaderTests { + private const string TargetFrameworkVersion = "v4.5"; + [Fact] public void TryReadApplicationManifest_WhenManifestIsApplication_ReturnsTypedWritableAdapter() { @@ -26,6 +31,10 @@ public void TryReadApplicationManifest_WhenManifestIsApplication_ReturnsTypedWri Assert.Equal("TestApplication", manifest.AssemblyIdentity.Name); Assert.NotNull(manifest.OutputMessages); + manifest.ReadOnly = true; + + Assert.True(manifest.ReadOnly); + manifest.ReadOnly = false; Assert.False(manifest.ReadOnly); @@ -48,6 +57,10 @@ public void TryReadDeployManifest_WhenManifestIsDeployment_ReturnsTypedWritableA Assert.Equal("TestDeployment", manifest.AssemblyIdentity.Name); Assert.True(manifest.MapFileExtensions); + manifest.ReadOnly = true; + + Assert.True(manifest.ReadOnly); + manifest.ReadOnly = false; Assert.False(manifest.ReadOnly); @@ -106,6 +119,7 @@ public void TryReadApplicationManifest_WhenManifestIsSideBySide_ReturnsFalse() """; + using MemoryStream stream = new(Encoding.UTF8.GetBytes(Xml)); ClickOnceManifestReader reader = new(); @@ -119,10 +133,8 @@ public void TryReadApplicationManifest_WhenManifestIsSideBySide_ReturnsFalse() } [Fact] - public void ApplicationManifestAdapter_UpdateFileInfo_UsesRequestedTargetFramework() + public void ApplicationManifestAdapter_UpdateFileInfo_UsesSha256() { - const int Sha256HashSizeInBytes = 32; - const string TargetFrameworkVersion = "v4.5"; string temporaryFilePath = Path.GetTempFileName(); try @@ -133,10 +145,13 @@ public void ApplicationManifestAdapter_UpdateFileInfo_UsesRequestedTargetFramewo applicationManifest.FileReferences.Add(reference); ApplicationManifestAdapter adapter = new(applicationManifest); - adapter.ResolveFiles(new[] { Path.GetDirectoryName(temporaryFilePath)! }); - adapter.UpdateFileInfo(TargetFrameworkVersion); + adapter.ResolveFiles( + new[] { new FileInfo(temporaryFilePath).Directory! }); + adapter.UpdateFileInfo(); - Assert.Equal(Sha256HashSizeInBytes, Convert.FromBase64String(reference.Hash).Length); + Assert.Equal( + SHA256.HashData(File.ReadAllBytes(temporaryFilePath)), + Convert.FromBase64String(reference.Hash)); Assert.Equal(new FileInfo(temporaryFilePath).Length, reference.Size); } finally @@ -146,14 +161,189 @@ public void ApplicationManifestAdapter_UpdateFileInfo_UsesRequestedTargetFramewo } [Fact] - public void ApplicationManifestAdapter_Write_RoundTripsUpdatedManifest() + public void ApplicationManifestAdapter_Properties_ForwardToManifest() + { + ApplicationManifest manifest = CreateApplicationManifest(); + AssemblyReference entryPoint = new(); + manifest.AssemblyReferences.Add(entryPoint); + manifest.EntryPoint = entryPoint; + ApplicationManifestAdapter adapter = new(manifest); + + Assert.Same(manifest.AssemblyIdentity, adapter.AssemblyIdentity); + Assert.Same(manifest.AssemblyReferences, adapter.AssemblyReferences); + Assert.Same(manifest.EntryPoint, adapter.EntryPoint); + Assert.Same(manifest.FileReferences, adapter.FileReferences); + Assert.Same(manifest.OutputMessages, adapter.OutputMessages); + } + + [Fact] + public void DeployManifestAdapter_Properties_ForwardToManifest() + { + DeployManifest manifest = CreateDeployManifest(); + AssemblyReference entryPoint = new(); + manifest.AssemblyReferences.Add(entryPoint); + manifest.EntryPoint = entryPoint; + DeployManifestAdapter adapter = new(manifest); + + Assert.Same(manifest.AssemblyIdentity, adapter.AssemblyIdentity); + Assert.Same(manifest.AssemblyReferences, adapter.AssemblyReferences); + Assert.Same(manifest.EntryPoint, adapter.EntryPoint); + Assert.Same(manifest.OutputMessages, adapter.OutputMessages); + Assert.Equal(manifest.MapFileExtensions, adapter.MapFileExtensions); + } + + [Fact] + public void ApplicationManifestAdapter_ResolveFiles_PreservesSearchOrder() + { + const string PayloadFileName = "payload.dll"; + + using DirectoryServiceStub directoryService = new(); + DirectoryInfo firstDirectory = directoryService.CreateTemporaryDirectory(); + DirectoryInfo secondDirectory = directoryService.CreateTemporaryDirectory(); + string firstPayloadPath = Path.Combine( + firstDirectory.FullName, + PayloadFileName); + string secondPayloadPath = Path.Combine( + secondDirectory.FullName, + PayloadFileName); + File.WriteAllText(firstPayloadPath, contents: "first"); + File.WriteAllText(secondPayloadPath, contents: "second"); + ApplicationManifest manifest = CreateApplicationManifest(); + FileReference reference = new(PayloadFileName); + manifest.FileReferences.Add(reference); + ApplicationManifestAdapter adapter = new(manifest); + + adapter.ResolveFiles( + new[] { firstDirectory, firstDirectory, secondDirectory }); + + Assert.Equal(firstPayloadPath, reference.ResolvedPath); + } + + [Fact] + public void ApplicationManifestAdapter_ResolveFiles_AllowsNoSearchDirectories() + { + const string ExpectedMessageName = + "GenerateManifest.ResolveFailedInReadWriteMode"; + + ApplicationManifest manifest = CreateApplicationManifest(); + manifest.FileReferences.Add( + new FileReference(path: "missing.dll")); + ApplicationManifestAdapter adapter = new(manifest); + + adapter.ResolveFiles(Array.Empty()); + + Assert.Equal( + expected: 1, + actual: adapter.OutputMessages.ErrorCount); + OutputMessage message = adapter.OutputMessages[0]; + Assert.Equal(ExpectedMessageName, message.Name); + Assert.Equal(OutputMessageType.Error, message.Type); + Assert.False(string.IsNullOrWhiteSpace(message.Text)); + } + + [Fact] + public void ApplicationManifestAdapter_ResolveFiles_RejectsNullArguments() { ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); - using MemoryStream stream = new(); - adapter.Write(stream); - stream.Position = 0; + ArgumentNullException nullCollectionException = + Assert.Throws( + () => adapter.ResolveFiles(searchDirectories: null!)); + ArgumentException nullElementException = + Assert.Throws( + () => adapter.ResolveFiles(new DirectoryInfo[] { null! })); + + Assert.Equal( + "searchDirectories", + nullCollectionException.ParamName); + Assert.Equal( + expected: "searchDirectories", + actual: nullElementException.ParamName); + } + + [Fact] + public void DeployManifestAdapter_ResolveFiles_RejectsNullArguments() + { + DeployManifestAdapter adapter = new(CreateDeployManifest()); + + ArgumentNullException nullCollectionException = + Assert.Throws( + () => adapter.ResolveFiles(searchDirectories: null!)); + ArgumentException nullElementException = + Assert.Throws( + () => adapter.ResolveFiles( + new DirectoryInfo[] { null! })); + + Assert.Equal( + "searchDirectories", + nullCollectionException.ParamName); + Assert.Equal( + expected: "searchDirectories", + actual: nullElementException.ParamName); + } + + [Fact] + public void ApplicationManifestAdapter_Write_PreservesSha256DigestMethod() + { + using TemporaryFile payload = new(); + using TemporaryFile output = new(); + string payloadPath = payload.File.FullName; + string manifestPath = output.File.FullName; + + File.WriteAllText(payloadPath, contents: "payload"); + ApplicationManifest manifest = CreateApplicationManifest(); + manifest.FileReferences.Add(new FileReference(payloadPath)); + ApplicationManifestAdapter adapter = new(manifest); + + adapter.ResolveFiles(new[] { payload.File.Directory! }); + adapter.UpdateFileInfo(); + adapter.Write(output.File); + + AssertSha256Digest(manifestPath, payloadPath); + } + + [Fact] + public void DeployManifestAdapter_Write_PreservesSha256DigestMethod() + { + using TemporaryFile applicationManifestFile = new(); + using TemporaryFile deployManifestFile = new(); + string applicationManifestPath = applicationManifestFile.File.FullName; + string deployManifestPath = deployManifestFile.File.FullName; + + ApplicationManifest applicationManifest = CreateApplicationManifest(); + ManifestWriter.WriteManifest( + applicationManifest, + applicationManifestPath, + TargetFrameworkVersion); + + DeployManifest deployManifest = CreateDeployManifest(); + AssemblyReference entryPoint = new(applicationManifestPath) + { + AssemblyIdentity = applicationManifest.AssemblyIdentity, + ReferenceType = AssemblyReferenceType.ClickOnceManifest + }; + deployManifest.AssemblyReferences.Add(entryPoint); + deployManifest.EntryPoint = entryPoint; + DeployManifestAdapter adapter = new(deployManifest); + + adapter.ResolveFiles(new[] { applicationManifestFile.File.Directory! }); + adapter.UpdateFileInfo(); + adapter.Write(deployManifestFile.File); + + AssertSha256Digest(deployManifestPath, applicationManifestPath); + } + + [Fact] + public void ApplicationManifestAdapter_Write_OverwritesAndRoundTripsManifest() + { + using TemporaryFile output = new(); + string manifestPath = output.File.FullName; + File.WriteAllText(manifestPath, contents: "junk"); + ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + adapter.Write(output.File); + + using FileStream stream = File.OpenRead(manifestPath); ClickOnceManifestReader reader = new(); Assert.True( reader.TryReadApplicationManifest( @@ -164,6 +354,69 @@ public void ApplicationManifestAdapter_Write_RoundTripsUpdatedManifest() Assert.Equal("TestApplication", manifest.AssemblyIdentity.Name); } + [Fact] + public void ApplicationManifestAdapter_Write_DoesNotCreateParentDirectory() + { + const string ManifestFileName = "app.manifest"; + const string MissingDirectoryName = "missing"; + + using DirectoryServiceStub directoryService = new(); + DirectoryInfo rootDirectory = + directoryService.CreateTemporaryDirectory(); + FileInfo output = new( + Path.Combine( + rootDirectory.FullName, + MissingDirectoryName, + ManifestFileName)); + ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + + Assert.Throws( + () => adapter.Write(output)); + Assert.False(Directory.Exists(output.DirectoryName)); + } + + [Fact] + public void ApplicationManifestAdapter_Write_WhenFileIsNull_Throws() + { + ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + + Assert.Throws( + () => adapter.Write(file: null!)); + } + + [Fact] + public void DeployManifestAdapter_Write_WhenFileIsNull_Throws() + { + DeployManifestAdapter adapter = new(CreateDeployManifest()); + + Assert.Throws( + () => adapter.Write(file: null!)); + } + + [Fact] + public void ApplicationManifestAdapter_Constructor_WhenManifestIsNull_Throws() + { + ArgumentNullException exception = + Assert.Throws( + () => new ApplicationManifestAdapter(manifest: null!)); + + Assert.Equal( + expected: "manifest", + actual: exception.ParamName); + } + + [Fact] + public void DeployManifestAdapter_Constructor_WhenManifestIsNull_Throws() + { + ArgumentNullException exception = + Assert.Throws( + () => new DeployManifestAdapter(manifest: null!)); + + Assert.Equal( + expected: "manifest", + actual: exception.ParamName); + } + private static ApplicationManifest CreateApplicationManifest() { ApplicationManifest manifest = new(); @@ -195,5 +448,22 @@ private static MemoryStream WriteManifest(Manifest manifest) return stream; } + + private static void AssertSha256Digest(string manifestPath, string referencedFilePath) + { + const string Sha256Algorithm = "http://www.w3.org/2000/09/xmldsig#sha256"; + + XNamespace dsig = "http://www.w3.org/2000/09/xmldsig#"; + XDocument document = XDocument.Load(manifestPath); + XElement digestMethod = Assert.Single(document.Descendants(dsig + "DigestMethod")); + XElement digestValue = Assert.Single(document.Descendants(dsig + "DigestValue")); + + Assert.Equal( + Sha256Algorithm, + digestMethod.Attribute(name: "Algorithm")?.Value); + Assert.Equal( + SHA256.HashData(File.ReadAllBytes(referencedFilePath)), + Convert.FromBase64String(digestValue.Value)); + } } } From 80e39e1b4c5eda7c41aeb8d947160810c7346d8d Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Tue, 11 Aug 2026 17:45:16 -0700 Subject: [PATCH 4/7] Preserve unmodeled ClickOnce manifest XML Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- .../ClickOnce/ClickOnceManifestAdapter.cs | 5 + .../ClickOnce/ClickOnceManifestReader.cs | 193 ++++++- .../ClickOnce/IClickOnceManifestReader.cs | 2 - .../ClickOnce/VstoApplication.manifest | 93 +++ .../ClickOnce/ClickOnceManifestReaderTests.cs | 534 +++++++++++++++++- 5 files changed, 796 insertions(+), 31 deletions(-) create mode 100644 test/Sign.Core.Test/TestAssets/ClickOnce/VstoApplication.manifest diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs index 19b84b2c..1b1f0c28 100644 --- a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestAdapter.cs @@ -65,6 +65,11 @@ public void Write(FileInfo file) { ArgumentNullException.ThrowIfNull(file, nameof(file)); + if (Manifest.InputStream is { CanSeek: true } inputStream) + { + inputStream.Position = 0; + } + ManifestWriter.WriteManifest( Manifest, file.FullName, diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs index 218b4e40..1283f7ca 100644 --- a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs @@ -3,52 +3,213 @@ // See the LICENSE.txt file in the project root for more information. using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Xml; using Microsoft.Build.Tasks.Deployment.ManifestUtilities; namespace Sign.Core { internal sealed class ClickOnceManifestReader : IClickOnceManifestReader { + private const string AssemblyV2Namespace = + "urn:schemas-microsoft-com:asm.v2"; + private const string SignatureNamespace = + "http://www.w3.org/2000/09/xmldsig#"; public bool TryReadApplicationManifest( Stream stream, - bool preserveStream, [NotNullWhen(true)] out IApplicationManifest? manifest) { - ArgumentNullException.ThrowIfNull(stream, nameof(stream)); - - Manifest? readManifest = ManifestReader.ReadManifest(stream, preserveStream); + Manifest readManifest = ReadManifest(stream); - if (readManifest is ApplicationManifest applicationManifest) + if (readManifest is not ApplicationManifest applicationManifest) { - manifest = new ApplicationManifestAdapter(applicationManifest); + readManifest.InputStream.Dispose(); + stream.Position = 0; + manifest = null; - return true; + return false; } - manifest = null; + applicationManifest.InputStream = SanitizePreservedInput( + applicationManifest.InputStream); + manifest = new ApplicationManifestAdapter(applicationManifest); - return false; + return true; } public bool TryReadDeployManifest( Stream stream, - bool preserveStream, [NotNullWhen(true)] out IDeployManifest? manifest) + { + Manifest readManifest = ReadManifest(stream); + + if (readManifest is not DeployManifest deployManifest) + { + readManifest.InputStream.Dispose(); + stream.Position = 0; + manifest = null; + + return false; + } + + deployManifest.InputStream = SanitizePreservedInput( + deployManifest.InputStream); + manifest = new DeployManifestAdapter(deployManifest); + + return true; + } + + private static Manifest ReadManifest(Stream stream) { ArgumentNullException.ThrowIfNull(stream, nameof(stream)); - Manifest? readManifest = ManifestReader.ReadManifest(stream, preserveStream); + if (!stream.CanRead) + { + throw new ArgumentException( + "The manifest stream must be readable.", + nameof(stream)); + } - if (readManifest is DeployManifest deployManifest) + if (!stream.CanSeek) { - manifest = new DeployManifestAdapter(deployManifest); + throw new ArgumentException( + "The manifest stream must be seekable.", + nameof(stream)); + } - return true; + if (stream.Position != 0) + { + throw new ArgumentException( + "The manifest stream must be positioned at the beginning.", + nameof(stream)); } - manifest = null; + return ManifestReader.ReadManifest(stream, preserveStream: true); + } + + private static Stream SanitizePreservedInput(Stream input) + { + input.Position = 0; + MemoryStream output = new(); + XmlReaderSettings readerSettings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null + }; + XmlWriterSettings writerSettings = new() + { + CloseOutput = false, + Encoding = new UTF8Encoding( + encoderShouldEmitUTF8Identifier: false), + Indent = false + }; + + try + { + using XmlReader reader = + XmlReader.Create(input, readerSettings); + using XmlWriter writer = + XmlWriter.Create(output, writerSettings); + + bool advanceReader = true; + + while (!reader.EOF) + { + if (advanceReader && !reader.Read()) + { + break; + } - return false; + advanceReader = true; + + if (reader.NodeType == XmlNodeType.Element) + { + if (reader.Depth == 1 && + IsStaleSigningElement(reader)) + { + reader.Skip(); + advanceReader = false; + continue; + } + + writer.WriteStartElement( + reader.Prefix, + reader.LocalName, + reader.NamespaceURI); + + if (reader.HasAttributes) + { + writer.WriteAttributes(reader, defattr: true); + } + + if (reader.IsEmptyElement) + { + writer.WriteEndElement(); + } + } + else + { + WriteNode(reader, writer); + } + } + + writer.Flush(); + output.Position = 0; + input.Dispose(); + + return output; + } + catch + { + input.Dispose(); + output.Dispose(); + throw; + } + } + + private static bool IsStaleSigningElement(XmlReader reader) + { + bool isPublisherIdentity = + reader.LocalName == "publisherIdentity" && + reader.NamespaceURI == AssemblyV2Namespace; + bool isSignature = + reader.LocalName == "Signature" && + reader.NamespaceURI == SignatureNamespace; + + return isPublisherIdentity || isSignature; + } + + private static void WriteNode(XmlReader reader, XmlWriter writer) + { + switch (reader.NodeType) + { + case XmlNodeType.EndElement: + writer.WriteFullEndElement(); + break; + + case XmlNodeType.Text: + writer.WriteString(reader.Value); + break; + + case XmlNodeType.CDATA: + writer.WriteCData(reader.Value); + break; + + case XmlNodeType.Comment: + writer.WriteComment(reader.Value); + break; + + case XmlNodeType.Whitespace: + case XmlNodeType.SignificantWhitespace: + writer.WriteWhitespace(reader.Value); + break; + + case XmlNodeType.ProcessingInstruction: + writer.WriteProcessingInstruction( + reader.Name, + reader.Value); + break; + } } } } diff --git a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs index c4f25565..ceaf0d76 100644 --- a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs +++ b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifestReader.cs @@ -10,12 +10,10 @@ internal interface IClickOnceManifestReader { bool TryReadApplicationManifest( Stream stream, - bool preserveStream, [NotNullWhen(true)] out IApplicationManifest? manifest); bool TryReadDeployManifest( Stream stream, - bool preserveStream, [NotNullWhen(true)] out IDeployManifest? manifest); } } diff --git a/test/Sign.Core.Test/TestAssets/ClickOnce/VstoApplication.manifest b/test/Sign.Core.Test/TestAssets/ClickOnce/VstoApplication.manifest new file mode 100644 index 00000000..df626512 --- /dev/null +++ b/test/Sign.Core.Test/TestAssets/ClickOnce/VstoApplication.manifest @@ -0,0 +1,93 @@ + + + + Old Description + + + + + + + + + + + + + + + + + + + + + + + + AAAA + + + + + + + + + + + + + + + + + VSTO test add-in + Repository-owned test manifest + + + + + + + + + + AA== + + diff --git a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs index 045e4f51..6cef8f18 100644 --- a/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs +++ b/test/Sign.Core.Test/Tools/ClickOnce/ClickOnceManifestReaderTests.cs @@ -4,6 +4,7 @@ using System.Security.Cryptography; using System.Text; +using System.Xml; using System.Xml.Linq; using Microsoft.Build.Tasks.Deployment.ManifestUtilities; using Sign.TestInfrastructure; @@ -12,7 +13,17 @@ namespace Sign.Core.Test { public sealed class ClickOnceManifestReaderTests { + private const string AssemblyV1Namespace = + "urn:schemas-microsoft-com:asm.v1"; + private const string AssemblyV2Namespace = + "urn:schemas-microsoft-com:asm.v2"; + private const string SignatureNamespace = + "http://www.w3.org/2000/09/xmldsig#"; private const string TargetFrameworkVersion = "v4.5"; + private const string VstaV3Namespace = + "urn:schemas-microsoft-com:vsta.v3"; + private const string VstoV4Namespace = + "urn:schemas-microsoft-com:vsto.v4"; [Fact] public void TryReadApplicationManifest_WhenManifestIsApplication_ReturnsTypedWritableAdapter() @@ -23,7 +34,6 @@ public void TryReadApplicationManifest_WhenManifestIsApplication_ReturnsTypedWri bool result = reader.TryReadApplicationManifest( stream, - preserveStream: true, out IApplicationManifest? manifest); Assert.True(result); @@ -49,7 +59,6 @@ public void TryReadDeployManifest_WhenManifestIsDeployment_ReturnsTypedWritableA bool result = reader.TryReadDeployManifest( stream, - preserveStream: true, out IDeployManifest? manifest); Assert.True(result); @@ -74,7 +83,6 @@ public void TryReadApplicationManifest_WhenManifestIsDeployment_ReturnsFalse() bool result = reader.TryReadApplicationManifest( stream, - preserveStream: true, out IApplicationManifest? manifest); Assert.False(result); @@ -83,7 +91,6 @@ public void TryReadApplicationManifest_WhenManifestIsDeployment_ReturnsFalse() Assert.True( reader.TryReadDeployManifest( stream, - preserveStream: true, out IDeployManifest? deployManifest)); Assert.NotNull(deployManifest); } @@ -96,7 +103,6 @@ public void TryReadDeployManifest_WhenManifestIsApplication_ReturnsFalse() bool result = reader.TryReadDeployManifest( stream, - preserveStream: true, out IDeployManifest? manifest); Assert.False(result); @@ -105,7 +111,6 @@ public void TryReadDeployManifest_WhenManifestIsApplication_ReturnsFalse() Assert.True( reader.TryReadApplicationManifest( stream, - preserveStream: true, out IApplicationManifest? applicationManifest)); Assert.NotNull(applicationManifest); } @@ -125,13 +130,383 @@ public void TryReadApplicationManifest_WhenManifestIsSideBySide_ReturnsFalse() bool result = reader.TryReadApplicationManifest( stream, - preserveStream: true, out IApplicationManifest? manifest); Assert.False(result); Assert.Null(manifest); } + [Fact] + public void TryReadApplicationManifest_WhenManifestIsVsto_PreservesVstoXml() + { + using DirectoryServiceStub directoryService = new(); + DirectoryInfo directory = + directoryService.CreateTemporaryDirectory(); + string payloadPath = + Path.Combine(directory.FullName, "payload.dll"); + File.WriteAllText(payloadPath, contents: "updated payload"); + using FileStream stream = File.OpenRead(GetVstoManifestPath()); + ClickOnceManifestReader reader = new(); + + Assert.True( + reader.TryReadApplicationManifest( + stream, + out IApplicationManifest? manifest)); + Assert.NotNull(manifest); + + XElement expectedVstoExtension = Assert.Single( + XDocument.Load(GetVstoManifestPath()) + .Descendants(XName.Get("addIn", VstaV3Namespace))); + FileInfo output = new( + Path.Combine(directory.FullName, "output.manifest")); + + manifest.ResolveFiles(new[] { directory }); + manifest.UpdateFileInfo(); + manifest.Write(output); + + XDocument document = XDocument.Load(output.FullName); + XElement actualVstoExtension = Assert.Single( + document.Descendants(XName.Get("addIn", VstaV3Namespace))); + XElement appAddIn = Assert.Single( + actualVstoExtension.Descendants( + XName.Get("appAddIn", VstoV4Namespace))); + + Assert.True( + XNode.DeepEquals( + NormalizeElement(expectedVstoExtension), + NormalizeElement(actualVstoExtension))); + Assert.Equal("VstoTestAddIn", appAddIn.Attribute("keyName")?.Value); + Assert.Empty( + document.Descendants( + XName.Get("publisherIdentity", AssemblyV2Namespace))); + Assert.Empty( + document.Descendants( + XName.Get("Signature", SignatureNamespace))); + AssertSha256Digest(output.FullName, payloadPath); + } + + [Fact] + public void ApplicationManifestAdapter_WhenWrittenTwice_PreservesVstoXml() + { + XDocument original = XDocument.Load(GetVstoManifestPath()); + using FileStream stream = File.OpenRead(GetVstoManifestPath()); + ClickOnceManifestReader reader = new(); + Assert.True( + reader.TryReadApplicationManifest( + stream, + out IApplicationManifest? manifest)); + Assert.NotNull(manifest); + using TemporaryFile firstOutput = new(); + using TemporaryFile secondOutput = new(); + + manifest.Write(firstOutput.File); + manifest.Write(secondOutput.File); + + AssertVstoXmlPreserved( + original, + XDocument.Load(firstOutput.File.FullName)); + AssertVstoXmlPreserved( + original, + XDocument.Load(secondOutput.File.FullName)); + } + + [Fact] + public void TryReadDeployManifest_PreservesUnknownXml() + { + const string Xml = """ + + + + + + + + + """; + + using MemoryStream stream = CreateStream(Xml); + ClickOnceManifestReader reader = new(); + using TemporaryFile output = new(); + + Assert.True( + reader.TryReadDeployManifest( + stream, + out IDeployManifest? manifest)); + Assert.NotNull(manifest); + + manifest.Write(output.File); + + XNamespace testNamespace = "urn:test"; + XElement extension = Assert.Single( + XDocument.Load(output.File.FullName) + .Descendants(testNamespace + "extension")); + + Assert.Equal( + "preserved", + extension.Attribute(testNamespace + "attribute")?.Value); + Assert.Empty( + XDocument.Load(output.File.FullName) + .Descendants( + XName.Get( + "publisherIdentity", + AssemblyV2Namespace))); + } + + [Fact] + public void TryReadApplicationManifest_WhenStreamPositionIsNotZero_Throws() + { + using MemoryStream stream = + WriteManifest(CreateApplicationManifest()); + stream.Position = 1; + ClickOnceManifestReader reader = new(); + + ArgumentException exception = Assert.Throws( + () => reader.TryReadApplicationManifest(stream, out _)); + + Assert.Equal("stream", exception.ParamName); + } + + [Fact] + public void TryReadApplicationManifest_WhenStreamIsNotSeekable_Throws() + { + using MemoryStream innerStream = + WriteManifest(CreateApplicationManifest()); + using NonSeekableReadStream stream = new(innerStream); + ClickOnceManifestReader reader = new(); + + ArgumentException exception = Assert.Throws( + () => reader.TryReadApplicationManifest(stream, out _)); + + Assert.Equal("stream", exception.ParamName); + } + + [Fact] + public void TryReadApplicationManifest_WhenStreamIsNotReadable_Throws() + { + using MemoryStream stream = new( + buffer: new byte[1], + index: 0, + count: 1, + writable: true, + publiclyVisible: true); + stream.Close(); + ClickOnceManifestReader reader = new(); + + ArgumentException exception = Assert.Throws( + () => reader.TryReadApplicationManifest(stream, out _)); + + Assert.Equal("stream", exception.ParamName); + } + + [Fact] + public void TryReadApplicationManifest_WhenStreamIsNull_Throws() + { + ClickOnceManifestReader reader = new(); + + ArgumentNullException exception = + Assert.Throws( + () => reader.TryReadApplicationManifest( + stream: null!, + out _)); + + Assert.Equal("stream", exception.ParamName); + } + + [Theory] + [InlineData( + "]>", + "&identityName;")] + [InlineData( + "", + "ExternalName")] + public void TryReadApplicationManifest_DtdBehaviorMatchesManifestUtilities( + string documentType, + string identityName) + { + string xml = CreateApplicationManifestXml( + documentType, + identityName); + Manifest? expectedManifest = null; + Exception? expectedException; + + using (MemoryStream stream = CreateStream(xml)) + { + expectedException = Record.Exception( + () => expectedManifest = ManifestReader.ReadManifest( + stream, + preserveStream: true)); + } + + IApplicationManifest? actualManifest = null; + Exception? actualException; + + using (MemoryStream stream = CreateStream(xml)) + { + ClickOnceManifestReader reader = new(); + actualException = Record.Exception( + () => reader.TryReadApplicationManifest( + stream, + out actualManifest)); + } + + Assert.Equal( + expectedException?.GetType(), + actualException?.GetType()); + + if (expectedException is null) + { + Assert.NotNull(expectedManifest); + Assert.NotNull(actualManifest); + Assert.Equal( + expectedManifest.AssemblyIdentity.Name, + actualManifest.AssemblyIdentity.Name); + using TemporaryFile output = new(); + + actualManifest.Write(output.File); + + using FileStream outputStream = + File.OpenRead(output.File.FullName); + Assert.True( + new ClickOnceManifestReader() + .TryReadApplicationManifest(outputStream, out _)); + } + } + + [Fact] + public void TryReadApplicationManifest_WhenXmlIsMalformed_Throws() + { + using MemoryStream stream = CreateStream(""); + ClickOnceManifestReader reader = new(); + + Assert.ThrowsAny( + () => reader.TryReadApplicationManifest(stream, out _)); + } + + [Fact] + public void ManifestUtilities_WhenPreservingStream_RetainsPublisherIdentity() + { + using FileStream stream = File.OpenRead(GetVstoManifestPath()); + ApplicationManifest manifest = Assert.IsType( + ManifestReader.ReadManifest(stream, preserveStream: true)); + using TemporaryFile output = new(); + + ManifestWriter.WriteManifest( + manifest, + output.File.FullName, + TargetFrameworkVersion); + + Assert.Single( + XDocument.Load(output.File.FullName) + .Descendants( + XName.Get("publisherIdentity", AssemblyV2Namespace))); + } + + [Fact] + public void ManifestUtilities_WhenModeledValuesAreCleared_DoesNotRestoreThemFromBase() + { + using FileStream stream = File.OpenRead(GetVstoManifestPath()); + ApplicationManifest manifest = Assert.IsType( + ManifestReader.ReadManifest(stream, preserveStream: true)); + using TemporaryFile output = new(); + + manifest.AssemblyIdentity.PublicKeyToken = null; + manifest.Description = null; + manifest.Publisher = null; + manifest.Product = null; + manifest.TrustInfo = new TrustInfo + { + SameSiteAccess = "none" + }; + ManifestWriter.WriteManifest( + manifest, + output.File.FullName, + TargetFrameworkVersion); + + XDocument document = XDocument.Load(output.File.FullName); + XElement identity = Assert.Single( + document.Descendants( + XName.Get("assemblyIdentity", AssemblyV1Namespace))); + + Assert.NotEqual( + "0011223344556677", + identity.Attribute("publicKeyToken")?.Value); + Assert.Empty( + document.Descendants( + XName.Get("description", AssemblyV1Namespace))); + Assert.DoesNotContain( + "Old Product", + document.ToString(), + StringComparison.Ordinal); + Assert.DoesNotContain( + "SameSite=\"site\"", + document.ToString(), + StringComparison.Ordinal); + } + + [Fact] + public void ManifestUtilities_WhenDeploymentValuesChange_UsesUpdatedValues() + { + const string Xml = """ + + + + + + + """; + + using MemoryStream stream = CreateStream(Xml); + DeployManifest manifest = Assert.IsType( + ManifestReader.ReadManifest( + stream, + preserveStream: true)); + using TemporaryFile output = new(); + + manifest.Install = false; + manifest.MapFileExtensions = false; + manifest.MinimumRequiredVersion = null; + manifest.TrustUrlParameters = false; + ManifestWriter.WriteManifest( + manifest, + output.File.FullName, + TargetFrameworkVersion); + + XElement deployment = Assert.Single( + XDocument.Load(output.File.FullName) + .Descendants( + XName.Get("deployment", AssemblyV2Namespace))); + + Assert.NotEqual("true", deployment.Attribute("install")?.Value); + Assert.NotEqual( + "true", + deployment.Attribute("mapFileExtensions")?.Value); + Assert.Null(deployment.Attribute("minimumRequiredVersion")); + Assert.NotEqual( + "true", + deployment.Attribute("trustURLParameters")?.Value); + } + [Fact] public void ApplicationManifestAdapter_UpdateFileInfo_UsesSha256() { @@ -139,7 +514,7 @@ public void ApplicationManifestAdapter_UpdateFileInfo_UsesSha256() try { - File.WriteAllText(temporaryFilePath, "payload"); + File.WriteAllText(temporaryFilePath, contents: "payload"); ApplicationManifest applicationManifest = CreateApplicationManifest(); FileReference reference = new(temporaryFilePath); applicationManifest.FileReferences.Add(reference); @@ -244,7 +619,8 @@ public void ApplicationManifestAdapter_ResolveFiles_AllowsNoSearchDirectories() [Fact] public void ApplicationManifestAdapter_ResolveFiles_RejectsNullArguments() { - ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + ApplicationManifestAdapter adapter = new( + CreateApplicationManifest()); ArgumentNullException nullCollectionException = Assert.Throws( @@ -340,7 +716,8 @@ public void ApplicationManifestAdapter_Write_OverwritesAndRoundTripsManifest() string manifestPath = output.File.FullName; File.WriteAllText(manifestPath, contents: "junk"); - ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + ApplicationManifestAdapter adapter = new( + CreateApplicationManifest()); adapter.Write(output.File); using FileStream stream = File.OpenRead(manifestPath); @@ -348,7 +725,6 @@ public void ApplicationManifestAdapter_Write_OverwritesAndRoundTripsManifest() Assert.True( reader.TryReadApplicationManifest( stream, - preserveStream: true, out IApplicationManifest? manifest)); Assert.NotNull(manifest); Assert.Equal("TestApplication", manifest.AssemblyIdentity.Name); @@ -368,7 +744,8 @@ public void ApplicationManifestAdapter_Write_DoesNotCreateParentDirectory() rootDirectory.FullName, MissingDirectoryName, ManifestFileName)); - ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + ApplicationManifestAdapter adapter = new( + CreateApplicationManifest()); Assert.Throws( () => adapter.Write(output)); @@ -378,7 +755,8 @@ public void ApplicationManifestAdapter_Write_DoesNotCreateParentDirectory() [Fact] public void ApplicationManifestAdapter_Write_WhenFileIsNull_Throws() { - ApplicationManifestAdapter adapter = new(CreateApplicationManifest()); + ApplicationManifestAdapter adapter = new( + CreateApplicationManifest()); Assert.Throws( () => adapter.Write(file: null!)); @@ -449,6 +827,85 @@ private static MemoryStream WriteManifest(Manifest manifest) return stream; } + private static string CreateApplicationManifestXml( + string documentType, + string identityName) + { + return $$""" + + {{documentType}} + + + + + + + + """; + } + + private static void AssertVstoXmlPreserved( + XDocument expected, + XDocument actual) + { + XElement expectedExtension = Assert.Single( + expected.Descendants( + XName.Get("addIn", VstaV3Namespace))); + XElement actualExtension = Assert.Single( + actual.Descendants( + XName.Get("addIn", VstaV3Namespace))); + + Assert.True( + XNode.DeepEquals( + NormalizeElement(expectedExtension), + NormalizeElement(actualExtension))); + Assert.Empty( + actual.Descendants( + XName.Get( + "publisherIdentity", + AssemblyV2Namespace))); + Assert.Empty( + actual.Descendants( + XName.Get("Signature", SignatureNamespace))); + } + + private static MemoryStream CreateStream(string xml) + { + return new MemoryStream(Encoding.UTF8.GetBytes(xml)); + } + + private static string GetVstoManifestPath() + { + return Path.Combine( + AppContext.BaseDirectory, + "TestAssets", + "ClickOnce", + "VstoApplication.manifest"); + } + + private static XElement NormalizeElement(XElement element) + { + return new XElement( + element.Name, + element.Attributes() + .Where(attribute => !attribute.IsNamespaceDeclaration) + .OrderBy(attribute => attribute.Name.NamespaceName) + .ThenBy(attribute => attribute.Name.LocalName), + element.Nodes() + .Where(node => node is not XText text || + !string.IsNullOrWhiteSpace(text.Value)) + .Select(node => node is XElement child + ? NormalizeElement(child) + : node)); + } + private static void AssertSha256Digest(string manifestPath, string referencedFilePath) { const string Sha256Algorithm = "http://www.w3.org/2000/09/xmldsig#sha256"; @@ -465,5 +922,56 @@ private static void AssertSha256Digest(string manifestPath, string referencedFil SHA256.HashData(File.ReadAllBytes(referencedFilePath)), Convert.FromBase64String(digestValue.Value)); } + + private sealed class NonSeekableReadStream : Stream + { + private readonly Stream _innerStream; + + internal NonSeekableReadStream(Stream innerStream) + { + _innerStream = innerStream; + } + + public override bool CanRead => _innerStream.CanRead; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => _innerStream.Length; + + public override long Position + { + get => _innerStream.Position; + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read( + byte[] buffer, + int offset, + int count) + { + return _innerStream.Read(buffer, offset, count); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write( + byte[] buffer, + int offset, + int count) + { + throw new NotSupportedException(); + } + } } } From 241f724096f40e2c53c6687b4aa2a86d406a2ded Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Wed, 12 Aug 2026 12:12:03 -0700 Subject: [PATCH 5/7] Address manifest reader formatting feedback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs index 1283f7ca..c66e6e99 100644 --- a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs @@ -15,6 +15,7 @@ internal sealed class ClickOnceManifestReader : IClickOnceManifestReader "urn:schemas-microsoft-com:asm.v2"; private const string SignatureNamespace = "http://www.w3.org/2000/09/xmldsig#"; + public bool TryReadApplicationManifest( Stream stream, [NotNullWhen(true)] out IApplicationManifest? manifest) From f57c26a85541e254ed0dea17975f39de264c979c Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Wed, 12 Aug 2026 14:33:56 -0700 Subject: [PATCH 6/7] Consolidate ClickOnce manifest interfaces Move shared assembly references and entry-point properties to the common manifest contract. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs | 2 -- src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs | 2 ++ src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs | 4 ---- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs b/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs index b73b6f04..c32cb4d9 100644 --- a/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs +++ b/src/Sign.Core/Tools/ClickOnce/IApplicationManifest.cs @@ -8,8 +8,6 @@ namespace Sign.Core { internal interface IApplicationManifest : IClickOnceManifest { - AssemblyReferenceCollection AssemblyReferences { get; } - AssemblyReference? EntryPoint { get; } FileReferenceCollection FileReferences { get; } } } diff --git a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs index e71f5e87..ab0d9a14 100644 --- a/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs +++ b/src/Sign.Core/Tools/ClickOnce/IClickOnceManifest.cs @@ -9,6 +9,8 @@ namespace Sign.Core internal interface IClickOnceManifest { AssemblyIdentity AssemblyIdentity { get; } + AssemblyReferenceCollection AssemblyReferences { get; } + AssemblyReference? EntryPoint { get; } OutputMessageCollection OutputMessages { get; } bool ReadOnly { get; set; } diff --git a/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs b/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs index 43fa5713..ee8fa2fc 100644 --- a/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs +++ b/src/Sign.Core/Tools/ClickOnce/IDeployManifest.cs @@ -2,14 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE.txt file in the project root for more information. -using Microsoft.Build.Tasks.Deployment.ManifestUtilities; - namespace Sign.Core { internal interface IDeployManifest : IClickOnceManifest { - AssemblyReferenceCollection AssemblyReferences { get; } - AssemblyReference? EntryPoint { get; } bool MapFileExtensions { get; } } } From 4caf17486d419bbed8dbe241c368885c5bbe7e64 Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Wed, 12 Aug 2026 15:30:48 -0700 Subject: [PATCH 7/7] Simplify preserved manifest sanitization Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: be91288d-5106-4c59-a1fa-c5353dccb828 --- .../ClickOnce/ClickOnceManifestReader.cs | 130 +++++++----------- 1 file changed, 48 insertions(+), 82 deletions(-) diff --git a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs index c66e6e99..a9b06221 100644 --- a/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs +++ b/src/Sign.Core/Tools/ClickOnce/ClickOnceManifestReader.cs @@ -31,8 +31,7 @@ public bool TryReadApplicationManifest( return false; } - applicationManifest.InputStream = SanitizePreservedInput( - applicationManifest.InputStream); + ReplaceManifestInputStream(applicationManifest); manifest = new ApplicationManifestAdapter(applicationManifest); return true; @@ -53,8 +52,7 @@ public bool TryReadDeployManifest( return false; } - deployManifest.InputStream = SanitizePreservedInput( - deployManifest.InputStream); + ReplaceManifestInputStream(deployManifest); manifest = new DeployManifestAdapter(deployManifest); return true; @@ -88,7 +86,25 @@ private static Manifest ReadManifest(Stream stream) return ManifestReader.ReadManifest(stream, preserveStream: true); } - private static Stream SanitizePreservedInput(Stream input) + private static void ReplaceManifestInputStream(Manifest manifest) + { + Stream input = manifest.InputStream; + Stream? output = null; + + try + { + output = CreateSanitizedManifestInputStream(input); + manifest.InputStream = output; + output = null; + } + finally + { + output?.Dispose(); + input.Dispose(); + } + } + + private static Stream CreateSanitizedManifestInputStream(Stream input) { input.Position = 0; MemoryStream output = new(); @@ -109,108 +125,58 @@ private static Stream SanitizePreservedInput(Stream input) { using XmlReader reader = XmlReader.Create(input, readerSettings); - using XmlWriter writer = - XmlWriter.Create(output, writerSettings); + XmlDocument document = new() + { + PreserveWhitespace = true, + XmlResolver = null + }; + document.Load(reader); - bool advanceReader = true; + XmlElement root = document.DocumentElement ?? + throw new XmlException( + "The manifest XML does not have a document element."); - while (!reader.EOF) + for (XmlNode? node = root.FirstChild; + node is not null;) { - if (advanceReader && !reader.Read()) + XmlNode? nextNode = node.NextSibling; + + if (node is XmlElement element && + IsStaleSigningElement(element)) { - break; + root.RemoveChild(node); } - advanceReader = true; + node = nextNode; + } - if (reader.NodeType == XmlNodeType.Element) - { - if (reader.Depth == 1 && - IsStaleSigningElement(reader)) - { - reader.Skip(); - advanceReader = false; - continue; - } - - writer.WriteStartElement( - reader.Prefix, - reader.LocalName, - reader.NamespaceURI); - - if (reader.HasAttributes) - { - writer.WriteAttributes(reader, defattr: true); - } - - if (reader.IsEmptyElement) - { - writer.WriteEndElement(); - } - } - else - { - WriteNode(reader, writer); - } + using (XmlWriter writer = + XmlWriter.Create(output, writerSettings)) + { + document.Save(writer); } - writer.Flush(); output.Position = 0; - input.Dispose(); return output; } catch { - input.Dispose(); output.Dispose(); throw; } } - private static bool IsStaleSigningElement(XmlReader reader) + private static bool IsStaleSigningElement(XmlElement element) { bool isPublisherIdentity = - reader.LocalName == "publisherIdentity" && - reader.NamespaceURI == AssemblyV2Namespace; + element.LocalName == "publisherIdentity" && + element.NamespaceURI == AssemblyV2Namespace; bool isSignature = - reader.LocalName == "Signature" && - reader.NamespaceURI == SignatureNamespace; + element.LocalName == "Signature" && + element.NamespaceURI == SignatureNamespace; return isPublisherIdentity || isSignature; } - - private static void WriteNode(XmlReader reader, XmlWriter writer) - { - switch (reader.NodeType) - { - case XmlNodeType.EndElement: - writer.WriteFullEndElement(); - break; - - case XmlNodeType.Text: - writer.WriteString(reader.Value); - break; - - case XmlNodeType.CDATA: - writer.WriteCData(reader.Value); - break; - - case XmlNodeType.Comment: - writer.WriteComment(reader.Value); - break; - - case XmlNodeType.Whitespace: - case XmlNodeType.SignificantWhitespace: - writer.WriteWhitespace(reader.Value); - break; - - case XmlNodeType.ProcessingInstruction: - writer.WriteProcessingInstruction( - reader.Name, - reader.Value); - break; - } - } } }