Skip to content
Next Next commit
Consolidate approach for conditional tests that check for privileged …
…processes
  • Loading branch information
jeffhandley committed Nov 24, 2022
commit fdc14277e6cc4e81aafde0ae380c2571d42334d5
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,8 @@ namespace System.IO
/// <summary>Base class for test classes the use temporary files that need to be cleaned up.</summary>
public abstract partial class FileCleanupTestBase : IDisposable
{
private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());

private string fallbackGuid = Guid.NewGuid().ToString("N").Substring(0, 10);

protected static bool IsProcessElevated => s_isElevated.Value;

/// <summary>Initialize the test class base. This creates the associated test directory.</summary>
protected FileCleanupTestBase(string tempDirectory = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,25 @@ public static partial class PlatformDetection
public static bool IsNotFedoraOrRedHatFamily => !IsFedora && !IsRedHatFamily;
public static bool IsNotDebian10 => !IsDebian10;

public static bool IsSuperUser => IsBrowser || IsWindows ? false : libc.geteuid() == 0;
private static int s_isSuperUser = -1;
public static bool IsSuperUser
{
get
{
if (s_isSuperUser != -1)
return s_isSuperUser == 1;

if (IsBrowser || IsWindows)
{
s_isSuperUser = 0;
return false;
}

s_isSuperUser = AdminHelpers.IsProcessElevated() ? 1 : 0;

return s_isSuperUser == 1;
}
}

public static bool IsUnixAndSuperUser => !IsWindows && IsSuperUser;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ public static partial class PlatformDetection
public static bool Is64BitProcess => IntPtr.Size == 8;
public static bool IsNotWindows => !IsWindows;

public static bool IsPrivilegedProcess => IsUnixAndSuperUser || IsWindowsAndElevated;

public static bool IsMarshalGetExceptionPointersSupported => !IsMonoRuntime && !IsNativeAot;

private static readonly Lazy<bool> s_isCheckedRuntime = new Lazy<bool>(() => AssemblyConfigurationEquals("Checked"));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
Expand All @@ -14,7 +15,7 @@ public partial class FuzzyTests
{
static partial void Test_Write_Fuzzy_TestEtw(List<SubTest> tests, EventSource logger)
{
if (TestUtilities.IsProcessElevated)
if (PlatformDetection.IsPrivilegedProcess)
{
using (var listener = new EtwListener())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ namespace BasicEventSourceTests
{
public partial class TestEventCounter
{
// Specifies whether the process is elevated or not.
private static bool IsProcessElevated => Environment.IsPrivilegedProcess;

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/25035")]
public void Test_Write_Metric_ETW()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ namespace BasicEventSourceTests
{
internal class TestUtilities
{
// Specifies whether the process is elevated or not.
internal static bool IsProcessElevated => Environment.IsPrivilegedProcess;

/// <summary>
/// Confirms that there are no EventSources running.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ namespace BasicEventSourceTests
public partial class TestsManifestGeneration
{
// Specifies whether the process is elevated or not.
private static bool IsProcessElevated => Environment.IsPrivilegedProcess;
private static bool IsProcessElevatedAndNotWindowsNanoServerAndRemoteExecutorSupported =>
IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer && RemoteExecutor.IsSupported;
PlatformDetection.IsPrivilegedProcess && PlatformDetection.IsNotWindowsNanoServer && RemoteExecutor.IsSupported;

/// ETW only works with elevated process
[ConditionalFact(nameof(IsProcessElevatedAndNotWindowsNanoServerAndRemoteExecutorSupported))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public void Test_BadEventSource_MismatchedIds_WithEtwListener()
{
// We expect only one session to be on when running the test but if a ETW session was left
// hanging, it will confuse the EventListener tests.
if (TestUtilities.IsProcessElevated)
if (PlatformDetection.IsPrivilegedProcess)
{
EtwListener.EnsureStopped();
}
Expand All @@ -31,7 +31,7 @@ public void Test_BadEventSource_MismatchedIds_WithEtwListener()

var listenerGenerators = new List<Func<Listener>> { () => new EventListenerListener() };

if (TestUtilities.IsProcessElevated)
if (PlatformDetection.IsPrivilegedProcess)
{
listenerGenerators.Add(() => new EtwListener());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ namespace BasicEventSourceTests
public partial class TestsWrite
{
// Specifies whether the process is elevated or not.
private static bool IsProcessElevated => Environment.IsPrivilegedProcess;
private static bool IsProcessElevatedAndNotWindowsNanoServer =>
IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer; // ActiveIssue: https://github.com/dotnet/runtime/issues/26197
PlatformDetection.IsPrivilegedProcess && PlatformDetection.IsNotWindowsNanoServer; // ActiveIssue: https://github.com/dotnet/runtime/issues/26197

/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
Expand All @@ -30,7 +29,7 @@ public void Test_Write_T_ETW()

[ActiveIssue("https://github.com/dotnet/runtime/issues/21295", TargetFrameworkMonikers.NetFramework)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/25035")]
[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Test_Write_T_In_Manifest_Serialization_WithEtwListener()
{
using (var eventListener = new EventListenerListener())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ namespace BasicEventSourceTests
partial class TestsWriteEvent
{
// Specifies whether the process is elevated or not.
private static bool IsProcessElevated => Environment.IsPrivilegedProcess;
private static bool IsProcessElevatedAndNotWindowsNanoServer =>
IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer; // ActiveIssue: https://github.com/dotnet/runtime/issues/26197
PlatformDetection.IsPrivilegedProcess && PlatformDetection.IsNotWindowsNanoServer; // ActiveIssue: https://github.com/dotnet/runtime/issues/26197

/// <summary>
/// Tests WriteEvent using the manifest based mechanism.
Expand Down Expand Up @@ -84,7 +83,7 @@ public void Test_WriteEvent_ByteArray_SelfDescribing_ETW()

static partial void Test_WriteEvent_AddEtwTests(List<SubTest> tests, EventSourceTest logger)
{
if (!IsProcessElevated)
if (!PlatformDetection.IsPrivilegedProcess)
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ namespace BasicEventSourceTests
{
public partial class TestsWriteEventToListener
{
// Specifies whether the process is elevated or not.
private static bool IsProcessElevated => Environment.IsPrivilegedProcess;

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Test_WriteEvent_TransferEvents()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ public class ServiceBaseTests : IDisposable
private const int connectionTimeout = 30000;
private readonly TestServiceProvider _testService;

private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
protected static bool IsProcessElevated => s_isElevated.Value;
protected static bool IsElevatedAndSupportsEventLogs => IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer;
protected static bool IsElevatedAndWindows10OrLater => IsProcessElevated && PlatformDetection.IsWindows10OrLater;
protected static bool IsElevatedAndSupportsEventLogs => PlatformDetection.IsPrivilegedProcess && PlatformDetection.IsNotWindowsNanoServer;
protected static bool IsElevatedAndWindows10OrLater => PlatformDetection.IsPrivilegedProcess && PlatformDetection.IsWindows10OrLater;

private bool _disposed;

Expand Down Expand Up @@ -73,7 +71,7 @@ private void Cleanup()
}

#if NETCOREAPP
[ConditionalTheory(nameof(IsProcessElevated))]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
[InlineData(-2)]
[InlineData((long)int.MaxValue + 1)]
public void RequestAdditionalTime_Throws_ArgumentOutOfRangeException(long milliseconds)
Expand All @@ -84,7 +82,7 @@ public void RequestAdditionalTime_Throws_ArgumentOutOfRangeException(long millis
}
#endif

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void TestOnStartThenStop()
{
ServiceController controller = ConnectToServer();
Expand Down Expand Up @@ -120,7 +118,7 @@ public void TestOnStartWithArgsThenStop()
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void TestOnPauseThenStop()
{
ServiceController controller = ConnectToServer();
Expand All @@ -134,7 +132,7 @@ public void TestOnPauseThenStop()
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void TestOnPauseAndContinueThenStop()
{
ServiceController controller = ConnectToServer();
Expand All @@ -152,7 +150,7 @@ public void TestOnPauseAndContinueThenStop()
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void TestOnExecuteCustomCommand()
{
if (PlatformDetection.IsWindowsServerCore)
Expand All @@ -179,7 +177,7 @@ public void TestOnExecuteCustomCommand()
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void TestOnContinueBeforePause()
{
ServiceController controller = ConnectToServer();
Expand Down Expand Up @@ -211,7 +209,7 @@ public void LogWritten_AutoLog_False()
testService.DeleteTestServices();
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework receives the Connected Byte Code after the Exception Thrown Byte Code")]
public void PropagateExceptionFromOnStart()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ public partial class ServiceControllerTests : IDisposable
private const int connectionTimeout = 30000;
private readonly TestServiceProvider _testService;

private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
protected static bool IsProcessElevated => s_isElevated.Value;

private bool _disposed;

public ServiceControllerTests()
Expand All @@ -30,28 +27,28 @@ private void AssertExpectedProperties(ServiceController testServiceController)
Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
AssertExpectedProperties(controller);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ConstructWithServiceName_ToUpper()
{
var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant());
AssertExpectedProperties(controller);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
AssertExpectedProperties(controller);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
Expand All @@ -60,7 +57,7 @@ public void ConstructWithMachineName()
AssertExtensions.Throws<ArgumentException>(null, () => { new ServiceController(_testService.TestServiceName, ""); });
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand All @@ -71,14 +68,14 @@ public void ControlCapabilities()
Assert.True(controller.CanShutdown);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Start_NullArg_ThrowsArgumentNullException()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<ArgumentNullException>(() => controller.Start(new string[] { null } ));
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand All @@ -97,7 +94,7 @@ public void StopAndStart()
}
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void PauseAndContinue()
{
string serviceName = _testService.TestServiceName;
Expand Down Expand Up @@ -128,7 +125,7 @@ public void PauseAndContinue()
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void GetServices_FindSelf()
{
bool foundTestService = false;
Expand All @@ -145,7 +142,7 @@ public void GetServices_FindSelf()
Assert.True(foundTestService, "Test service was not enumerated with all services");
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Dependencies()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand All @@ -160,7 +157,7 @@ public void Dependencies()
Assert.Equal(prerequisiteServiceController.DependentServices[0].ServiceName, controller.ServiceName);
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace System.ServiceProcess.Tests
[OuterLoop(/* Modifies machine state */)]
public partial class ServiceControllerTests : IDisposable
{
[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Stop_FalseArg_WithDependentServices_ThrowsInvalidOperationException()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand All @@ -23,7 +23,7 @@ public void Stop_FalseArg_WithDependentServices_ThrowsInvalidOperationException(
Assert.Throws<InvalidOperationException>(() => prerequisiteServiceController.Stop(stopDependentServices: false));
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void Stop_TrueArg_WithDependentServices_StopsTheServiceAndItsDependents()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand All @@ -36,7 +36,7 @@ public void Stop_TrueArg_WithDependentServices_StopsTheServiceAndItsDependents()
Assert.All(controller.DependentServices, service => Assert.Equal(ServiceControllerStatus.Stopped, service.Status));
}

[ConditionalFact(nameof(IsProcessElevated))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPrivilegedProcess))]
public void StopTheServiceAndItsDependentsManually()
{
var controller = new ServiceController(_testService.TestServiceName);
Expand Down