diff --git a/doc/release-notes/1.31/dsc-direct-package-path.md b/doc/release-notes/1.31/dsc-direct-package-path.md
new file mode 100644
index 0000000000..a5c16b0750
--- /dev/null
+++ b/doc/release-notes/1.31/dsc-direct-package-path.md
@@ -0,0 +1,5 @@
+## Bug Fixes
+
+### Minor Bug Fixes
+
+* Configuration now launches DSC directly from its installed package location and attempts to re-register unhealthy DSC packages before use.
diff --git a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/FindDscPackageStateMachine.cs b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/FindDscPackageStateMachine.cs
index 67af276bb5..20d11d0bc6 100644
--- a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/FindDscPackageStateMachine.cs
+++ b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/FindDscPackageStateMachine.cs
@@ -7,15 +7,13 @@
namespace Microsoft.Management.Configuration.Processor.DSCv3.Helpers
{
using System;
+ using static Microsoft.Management.Configuration.Processor.DSCv3.Helpers.PackageInformation;
///
/// Provides the state machine that decides which DSC package to use.
///
internal class FindDscPackageStateMachine
{
- private const string StableDscPackageFamilyName = "Microsoft.DesiredStateConfiguration_8wekyb3d8bbwe";
- private const string PreviewDscPackageFamilyName = "Microsoft.DesiredStateConfiguration-Preview_8wekyb3d8bbwe";
-
private readonly Version minimumStableVersion = new Version(3, 1);
private readonly Version minimumPreviewVersion = new Version(3, 1, 7);
@@ -74,6 +72,11 @@ public enum Transition
NotFound,
}
+ ///
+ /// Gets or sets the diagnostics sink.
+ ///
+ public IDiagnosticsSink? DiagnosticsSink { get; set; }
+
///
/// Gets the file path of the DSC (Desired State Configuration) executable.
///
@@ -90,14 +93,14 @@ public string? DscExecutablePath
PackageInformation stableInformation = new PackageInformation(StableDscPackageFamilyName);
if (stableInformation.IsInstalled && stableInformation.Version >= this.minimumStableVersion)
{
- return stableInformation.AliasPath;
+ return stableInformation.GetExecutablePath(this.DiagnosticsSink);
}
else
{
PackageInformation previewInformation = new PackageInformation(PreviewDscPackageFamilyName);
if (previewInformation.IsInstalled && previewInformation.Version >= this.minimumPreviewVersion)
{
- return previewInformation.AliasPath;
+ return previewInformation.GetExecutablePath(this.DiagnosticsSink);
}
else
{
@@ -178,7 +181,7 @@ public Transition DetermineNextTransition()
private Transition Found(PackageInformation packageInformation)
{
- this.dscExecutablePath = packageInformation.AliasPath;
+ this.dscExecutablePath = packageInformation.GetExecutablePath(this.DiagnosticsSink);
this.currentState = State.Terminated;
return Transition.Found;
}
diff --git a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/PackageInformation.cs b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/PackageInformation.cs
index 1810eb50bc..84e913b86d 100644
--- a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/PackageInformation.cs
+++ b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/PackageInformation.cs
@@ -8,6 +8,7 @@ namespace Microsoft.Management.Configuration.Processor.DSCv3.Helpers
{
using System;
using System.IO;
+ using Windows.ApplicationModel;
using Windows.Management.Deployment;
///
@@ -15,7 +16,18 @@ namespace Microsoft.Management.Configuration.Processor.DSCv3.Helpers
///
internal class PackageInformation
{
+ ///
+ /// The stable DSC package family name.
+ ///
+ public const string StableDscPackageFamilyName = "Microsoft.DesiredStateConfiguration_8wekyb3d8bbwe";
+
+ ///
+ /// The preview DSC package family name.
+ ///
+ public const string PreviewDscPackageFamilyName = "Microsoft.DesiredStateConfiguration-Preview_8wekyb3d8bbwe";
+
private const string DscExecutableFileName = "dsc.exe";
+ private Package? package;
///
/// Initializes a new instance of the class.
@@ -37,37 +49,121 @@ public PackageInformation(string familyName)
if (this.Version == null || version > this.Version)
{
this.Version = version;
+ this.package = package;
}
}
}
+ }
- string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- string aliasPath = Path.Combine(localAppData, "Microsoft\\WindowsApps", familyName, DscExecutableFileName);
+ ///
+ /// Gets a value indicating whether the package is installed or not.
+ ///
+ public bool IsInstalled => this.package != null;
+
+ ///
+ /// Gets the version of the package.
+ ///
+ public Version? Version { get; private set; }
- if (Path.Exists(aliasPath))
+ ///
+ /// Gets the packaged DSC executable path, repairing an unhealthy registration first.
+ ///
+ /// The diagnostics sink.
+ /// The executable path, or null if the package is not installed.
+ public string? GetExecutablePath(IDiagnosticsSink? diagnosticsSink)
+ {
+ if (this.package == null)
{
- this.AliasPath = aliasPath;
+ return null;
}
- if (this.AliasPath != null && this.Version != null)
+ Package selectedPackage = this.package;
+ string packageFullName = selectedPackage.Id.FullName;
+ EnsureHealthy(
+ packageFullName,
+ () => selectedPackage.Status.VerifyIsOK(),
+ () =>
+ {
+ PackageManager packageManager = new PackageManager();
+ DeploymentResult result = packageManager.RegisterPackageByFullNameAsync(
+ packageFullName, null, DeploymentOptions.None).AsTask().GetAwaiter().GetResult();
+
+ if (result.ExtendedErrorCode != null)
+ {
+ throw new InvalidOperationException($"Failed to re-register DSC package '{packageFullName}': {result.ErrorText}", result.ExtendedErrorCode);
+ }
+
+ selectedPackage = packageManager.FindPackageForUser(string.Empty, packageFullName)
+ ?? throw new InvalidOperationException($"DSC package '{packageFullName}' was not found after re-registration.");
+ },
+ diagnosticsSink);
+
+ this.package = selectedPackage;
+ string executablePath = Path.Combine(selectedPackage.InstalledLocation.Path, DscExecutableFileName);
+ if (!File.Exists(executablePath))
{
- this.IsInstalled = true;
+ throw new FileNotFoundException($"The DSC executable was not found in package '{packageFullName}'.", executablePath);
}
+
+ return executablePath;
}
///
- /// Gets a value indicating whether the package is installed or not.
+ /// Finds the immutable package directory containing a registered Store DSC executable.
///
- public bool IsInstalled { get; private set; }
+ /// The normalized executable path.
+ /// The package directory, or null if the path is not a trusted packaged executable.
+ internal static string? FindTrustedPackageRoot(string executablePath)
+ {
+ if (!string.Equals(Path.GetFileName(executablePath), DscExecutableFileName, StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
- ///
- /// Gets the path to the dsc.exe alias.
- ///
- public string? AliasPath { get; private set; }
+ foreach (string familyName in new[] { StableDscPackageFamilyName, PreviewDscPackageFamilyName })
+ {
+ var information = new PackageInformation(familyName);
+ Package? package = information.package;
+ if (package == null || package.IsDevelopmentMode || package.SignatureKind != PackageSignatureKind.Store || !package.Status.VerifyIsOK())
+ {
+ continue;
+ }
+
+ string packageRoot = package.InstalledLocation.Path;
+ if (!string.Equals(executablePath, Path.Combine(packageRoot, DscExecutableFileName), StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ return packageRoot;
+ }
+
+ return null;
+ }
///
- /// Gets the version of the package.
+ /// Re-registers an unhealthy package once and verifies that the repair succeeded.
///
- public Version? Version { get; private set; }
+ /// The package full name.
+ /// Checks the current package status.
+ /// Re-registers the package and refreshes its information.
+ /// The diagnostics sink.
+ internal static void EnsureHealthy(string packageFullName, Func verifyIsOK, Action register, IDiagnosticsSink? diagnosticsSink)
+ {
+ if (verifyIsOK())
+ {
+ return;
+ }
+
+ diagnosticsSink?.OnDiagnostics(DiagnosticLevel.Warning, $"DSC package '{packageFullName}' is unhealthy; attempting re-registration.");
+ register();
+
+ if (!verifyIsOK())
+ {
+ throw new InvalidOperationException($"DSC package '{packageFullName}' is still unhealthy after re-registration.");
+ }
+
+ diagnosticsSink?.OnDiagnostics(DiagnosticLevel.Informational, $"DSC package '{packageFullName}' was successfully re-registered.");
+ }
}
}
diff --git a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorPathBinding.cs b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorPathBinding.cs
index 9a4d76bbb8..a1e71f6f00 100644
--- a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorPathBinding.cs
+++ b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorPathBinding.cs
@@ -42,6 +42,10 @@ namespace Microsoft.Management.Configuration.Processor.DSCv3.Helpers
/// also opened without following reparse points and rejected if it is one, so a component that is
/// swapped for a link while the path is being pinned is detected rather than followed.
///
+ ///
+ /// For registered Store DSC packages, pinning stops at the immutable installation directory
+ /// reported by the package APIs. Its ancestors need not be accessible to the caller.
+ ///
///
internal sealed class ProcessorPathBinding : IDisposable
{
@@ -122,6 +126,7 @@ private void Pin(string path, string expectedHash, bool isAlias)
try
{
string finalPath = ProcessorPathIntegrity.GetFinalPath(file.ContentHandle);
+ string? packageRoot = isAlias ? null : PackageInformation.FindTrustedPackageRoot(finalPath);
// Pinning the ancestors is itself done by path, so a rename that happens while the
// ancestors are being pinned could leave a directory pinned that is no longer part of
@@ -132,7 +137,7 @@ private void Pin(string path, string expectedHash, bool isAlias)
{
try
{
- this.PinAncestors(finalPath);
+ this.PinAncestors(finalPath, packageRoot);
string currentPath = ProcessorPathIntegrity.GetFinalPath(file.ContentHandle);
if (string.Equals(currentPath, finalPath, StringComparison.OrdinalIgnoreCase))
@@ -170,7 +175,7 @@ private void Pin(string path, string expectedHash, bool isAlias)
}
}
- private void PinAncestors(string finalPath)
+ private void PinAncestors(string finalPath, string? packageRoot)
{
// Stop below the root; a volume root cannot be renamed or deleted, and holding a handle
// to it would interfere with operations such as dismounting the volume.
@@ -179,6 +184,11 @@ private void PinAncestors(string finalPath)
directory = Path.GetDirectoryName(directory))
{
this.directoryHandles.Add(ProcessorPathIntegrity.PinDirectory(directory));
+
+ if (string.Equals(directory, packageRoot, StringComparison.OrdinalIgnoreCase))
+ {
+ break;
+ }
}
}
diff --git a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorSettings.cs b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorSettings.cs
index 84dcee2ca7..60c18d0ec2 100644
--- a/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorSettings.cs
+++ b/src/Microsoft.Management.Configuration.Processor/DSCv3/Helpers/ProcessorSettings.cs
@@ -125,7 +125,11 @@ public IDSCv3 DSCv3
///
/// Gets or sets the diagnostics sink to use.
///
- public IDiagnosticsSink? DiagnosticsSink { get; set; } = null;
+ public IDiagnosticsSink? DiagnosticsSink
+ {
+ get => this.dscPackageStateMachine.DiagnosticsSink;
+ set => this.dscPackageStateMachine.DiagnosticsSink = value;
+ }
///
/// Gets or sets a value indicating whether the processor should produce more verbose output.
diff --git a/src/Microsoft.Management.Configuration.UnitTests/Tests/DSCv3PackageInformationTests.cs b/src/Microsoft.Management.Configuration.UnitTests/Tests/DSCv3PackageInformationTests.cs
new file mode 100644
index 0000000000..bae80ade85
--- /dev/null
+++ b/src/Microsoft.Management.Configuration.UnitTests/Tests/DSCv3PackageInformationTests.cs
@@ -0,0 +1,168 @@
+// -----------------------------------------------------------------------------
+//
+// Copyright (c) Microsoft Corporation. Licensed under the MIT License.
+//
+// -----------------------------------------------------------------------------
+
+namespace Microsoft.Management.Configuration.UnitTests.Tests
+{
+ using System;
+ using System.Diagnostics;
+ using System.IO;
+ using System.Linq;
+ using Microsoft.Management.Configuration.Processor.DSCv3.Helpers;
+ using Microsoft.Management.Configuration.UnitTests.Helpers;
+ using Windows.Management.Deployment;
+ using Xunit;
+
+ ///
+ /// Tests for DSC package discovery and registration repair.
+ ///
+ [Collection("UnitTestCollection")]
+ [InProc]
+ public class DSCv3PackageInformationTests
+ {
+ ///
+ /// Healthy packages are not re-registered.
+ ///
+ [Fact]
+ public void EnsureHealthy_HealthyPackage_DoesNotRegister()
+ {
+ PackageInformation.EnsureHealthy(
+ "TestPackage",
+ () => true,
+ () => throw new InvalidOperationException("A healthy package must not be re-registered."),
+ null);
+ }
+
+ ///
+ /// An unhealthy package is re-registered and its refreshed status is checked.
+ ///
+ [Fact]
+ public void EnsureHealthy_UnhealthyPackage_RegistersAndRechecks()
+ {
+ bool healthy = false;
+ int statusChecks = 0;
+ int registrations = 0;
+
+ PackageInformation.EnsureHealthy(
+ "TestPackage",
+ () =>
+ {
+ ++statusChecks;
+ return healthy;
+ },
+ () =>
+ {
+ ++registrations;
+ healthy = true;
+ },
+ null);
+
+ Assert.Equal(1, registrations);
+ Assert.Equal(2, statusChecks);
+ }
+
+ ///
+ /// A registration that leaves the package unhealthy fails without retrying indefinitely.
+ ///
+ [Fact]
+ public void EnsureHealthy_RepairDoesNotRestoreHealth_Throws()
+ {
+ int registrations = 0;
+
+ var exception = Assert.Throws(() => PackageInformation.EnsureHealthy(
+ "TestPackage",
+ () => false,
+ () => ++registrations,
+ null));
+
+ Assert.Contains("TestPackage", exception.Message);
+ Assert.Equal(1, registrations);
+ }
+
+ ///
+ /// Registration failures propagate to the caller without further attempts.
+ ///
+ [Fact]
+ public void EnsureHealthy_RegistrationFails_PropagatesError()
+ {
+ var expected = new UnauthorizedAccessException("Registration denied.");
+ int statusChecks = 0;
+
+ var exception = Assert.Throws(() => PackageInformation.EnsureHealthy(
+ "TestPackage",
+ () =>
+ {
+ ++statusChecks;
+ return false;
+ },
+ () => throw expected,
+ null));
+
+ Assert.Same(expected, exception);
+ Assert.Equal(1, statusChecks);
+ }
+
+ ///
+ /// An arbitrary executable cannot opt out of ancestor pinning by using the DSC file name.
+ ///
+ [Fact]
+ public void FindTrustedPackageRoot_CustomPath_IsNotTrusted()
+ {
+ using var directory = new TempDirectory();
+ string path = Path.Combine(directory.FullDirectoryPath, "dsc.exe");
+ File.WriteAllText(path, "not a packaged executable");
+
+ Assert.Null(PackageInformation.FindTrustedPackageRoot(path));
+ }
+
+ ///
+ /// Discovery returns the executable in the selected package, not its app execution alias.
+ ///
+ /// The DSC package family to discover.
+ [SkippableTheory]
+ [InlineData("Microsoft.DesiredStateConfiguration_8wekyb3d8bbwe")]
+ [InlineData("Microsoft.DesiredStateConfiguration-Preview_8wekyb3d8bbwe")]
+ public void GetExecutablePath_InstalledPackage_ReturnsPackagePath(string familyName)
+ {
+ PackageManager packageManager = new PackageManager();
+ var package = packageManager.FindPackagesForUserWithPackageTypes(null, familyName, PackageTypes.Main)
+ .OrderByDescending(package => new Version(package.Id.Version.Major, package.Id.Version.Minor, package.Id.Version.Build, package.Id.Version.Revision))
+ .FirstOrDefault() ?? throw new SkipException("The DSC package is not installed.");
+
+ Skip.IfNot(package.Status.VerifyIsOK(), "This test must not repair an installed package.");
+
+ var information = new PackageInformation(familyName);
+ string? executablePath = information.GetExecutablePath(null);
+
+ Assert.True(information.IsInstalled);
+ Assert.Equal(Path.Combine(package.InstalledLocation.Path, "dsc.exe"), executablePath);
+ Assert.True(File.Exists(executablePath));
+ string hash = ProcessorPathIntegrity.ComputeHash(executablePath!, out bool isAlias);
+ Assert.False(isAlias);
+
+ using var binding = new ProcessorPathBinding();
+ string launchPath = binding.EnsurePinned(executablePath!, hash, isAlias);
+ using var process = new Process()
+ {
+ StartInfo = new ProcessStartInfo(launchPath, "--version")
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ },
+ };
+
+ process.Start();
+ bool exited = process.WaitForExit(30000);
+ if (!exited)
+ {
+ process.Kill();
+ process.WaitForExit();
+ }
+
+ Assert.True(exited, "The packaged DSC executable did not exit within 30 seconds.");
+ Assert.Equal(0, process.ExitCode);
+ }
+ }
+}