// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Aspire.Cli.DotNet;
using Aspire.Cli.Resources;
using Aspire.Shared;
using Microsoft.AspNetCore.Certificates.Generation;
using Microsoft.Extensions.Logging;
namespace Aspire.Cli.Utils.EnvironmentChecker;
internal interface IDcpConnectionChecker
{
Task<EnvironmentCheckResult> TestConnectionAsync(string dcpDirectory, bool useDeveloperCertificate, CancellationToken cancellationToken);
}
internal sealed class DcpConnectionChecker(
CertificateManager certificateManager,
IProcessExecutionFactory processExecutionFactory,
CliExecutionContext executionContext,
IEnvironment environment,
ITemporaryStorage temporaryStorage,
ILogger<DcpConnectionChecker> logger) : IDcpConnectionChecker
{
private static readonly TimeSpan s_connectionTimeout = TimeSpan.FromSeconds(20);
private static readonly TimeSpan s_stopRequestTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan s_processExitTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan s_processExitPollInterval = TimeSpan.FromMilliseconds(50);
private const string DcpStopRequestMediaType = "application/merge-patch+json";
public async Task<EnvironmentCheckResult> TestConnectionAsync(string dcpDirectory, bool useDeveloperCertificate, CancellationToken cancellationToken)
{
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(s_connectionTimeout);
try
{
try
{
await using var session = await DcpConnectionTestSession.StartAsync(
dcpDirectory,
useDeveloperCertificate,
certificateManager,
processExecutionFactory,
executionContext,
environment,
temporaryStorage,
logger,
timeoutCts.Token).ConfigureAwait(false);
return await ProbeAsync(session, useDeveloperCertificate, timeoutCts.Token).ConfigureAwait(false);
}
finally
{
// Teardown ignores the caller's token so cancellation cannot interrupt cleanup.
// Honor cancellation even when the probe throws, after disposal has finished.
cancellationToken.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (OperationCanceledException)
{
return Failed(
useDeveloperCertificate,
details: string.Format(
CultureInfo.CurrentCulture,
DoctorCommandStrings.DcpConnectionTimedOutMessageFormat,
s_connectionTimeout.TotalSeconds));
}
catch (DcpDeveloperCertificateUnavailableException ex)
{
return CreateResult(
useDeveloperCertificate,
EnvironmentCheckStatus.Warning,
DoctorCommandStrings.DcpDeveloperCertificateUnavailableMessage,
details: ex.Message,
fix: DoctorCommandStrings.DcpDeveloperCertificateTrustFix);
}
catch (AuthenticationException ex)
{
return Failed(
useDeveloperCertificate,
details: string.Format(CultureInfo.CurrentCulture, DoctorCommandStrings.DcpTlsAuthenticationFailedDetailsFormat, ex.Message),
useDeveloperCertificate ? DoctorCommandStrings.DcpDeveloperCertificateRepairTrustFix : null);
}
catch (HttpRequestException ex)
{
return Failed(useDeveloperCertificate, details: ex.Message);
}
catch (Exception ex)
{
return Failed(useDeveloperCertificate, details: ex.Message);
}
}
private static async Task<EnvironmentCheckResult> ProbeAsync(DcpConnectionTestSession session, bool useDeveloperCertificate, CancellationToken cancellationToken)
{
var kubeconfig = await session.ReadKubeconfigAsync(cancellationToken).ConfigureAwait(false);
using var handler = CreateHttpClientHandler(kubeconfig);
using var client = new HttpClient(handler)
{
BaseAddress = kubeconfig.Server,
Timeout = s_connectionTimeout
};
if (!string.IsNullOrWhiteSpace(kubeconfig.Token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", kubeconfig.Token);
}
using var response = await client.GetAsync(new Uri(kubeconfig.Server, "/version"), cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
return Failed(
useDeveloperCertificate,
details: string.Format(
CultureInfo.CurrentCulture,
DoctorCommandStrings.DcpApiServerReturnedHttpStatusMessageFormat,
(int)response.StatusCode,
response.StatusCode));
}
return useDeveloperCertificate
? Passed(useDeveloperCertificate, DoctorCommandStrings.DcpDeveloperCertificateConnectionSucceededMessage)
: Passed(useDeveloperCertificate, DoctorCommandStrings.DcpEphemeralCertificateConnectionSucceededMessage);
}
private static HttpClientHandler CreateHttpClientHandler(DcpKubeconfig kubeconfig)
{
var handler = new HttpClientHandler();
if (kubeconfig.ClientCertificate is not null)
{
// DCP writes client certificate material into the generated kubeconfig. Supplying it
// here validates that the kubeconfig is sufficient for client authentication without
// relying on AppHost-specific process setup.
handler.ClientCertificates.Add(kubeconfig.ClientCertificate);
}
if (kubeconfig.CertificateAuthorityCertificates.Count > 0)
{
// DCP's generated kubeconfig includes the CA that should authenticate the API server.
// Trust that CA explicitly so this probe validates the DCP-issued connection material
// instead of relying on the OS/user certificate stores. Other TLS policy failures still
// fail the request because the goal is only to replace chain trust, not hostname or
// certificate validity checks.
handler.ServerCertificateCustomValidationCallback = (request, certificate, _, sslPolicyErrors) =>
{
if (certificate is null)
{
return false;
}
if ((sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateChainErrors) != SslPolicyErrors.None)
{
return false;
}
using var serverCertificate = X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
foreach (var authorityCertificate in kubeconfig.CertificateAuthorityCertificates)
{
chain.ChainPolicy.CustomTrustStore.Add(authorityCertificate);
}
return chain.Build(serverCertificate);
};
}
return handler;
}
private static EnvironmentCheckResult Passed(bool useDeveloperCertificate, string message) =>
CreateResult(useDeveloperCertificate, EnvironmentCheckStatus.Pass, message);
private static EnvironmentCheckResult Failed(bool useDeveloperCertificate, string? details = null, string? fix = null) =>
CreateResult(
useDeveloperCertificate,
EnvironmentCheckStatus.Fail,
useDeveloperCertificate
? DoctorCommandStrings.DcpDeveloperCertificateConnectionFailedMessage
: DoctorCommandStrings.DcpEphemeralCertificateConnectionFailedMessage,
details,
fix);
private static EnvironmentCheckResult CreateResult(bool useDeveloperCertificate, EnvironmentCheckStatus status, string message, string? details = null, string? fix = null)
{
return new EnvironmentCheckResult
{
Category = EnvironmentCheckCategories.Aspire,
Name = CheckName(useDeveloperCertificate),
Status = status,
Message = message,
Details = details,
Fix = fix
};
}
private static string CheckName(bool useDeveloperCertificate)
{
return useDeveloperCertificate
? DcpConnectionHealthCheck.DeveloperCertificateCheckName
: DcpConnectionHealthCheck.EphemeralCertificateCheckName;
}
internal sealed class DcpConnectionTestSession : IAsyncDisposable
{
private readonly IProcessExecution _process;
private readonly string _sessionDirectory;
private readonly string _kubeconfigPath;
private readonly OutputCollector _output;
private readonly ILogger _logger;
private DcpKubeconfig? _kubeconfig;
private DcpConnectionTestSession(IProcessExecution process, string sessionDirectory, string kubeconfigPath, OutputCollector output, ILogger logger)
{
_process = process;
_sessionDirectory = sessionDirectory;
_kubeconfigPath = kubeconfigPath;
_output = output;
_logger = logger;
}
public static async Task<DcpConnectionTestSession> StartAsync(
string dcpDirectory,
bool useDeveloperCertificate,
CertificateManager certificateManager,
IProcessExecutionFactory processExecutionFactory,
CliExecutionContext executionContext,
IEnvironment environment,
ITemporaryStorage temporaryStorage,
ILogger logger,
CancellationToken cancellationToken)
{
var sessionDirectory = temporaryStorage.CreateTempSubdirectory("dcp-").FullName;
var kubeconfigPath = Path.Combine(sessionDirectory, "kubeconfig");
var dcpExecutablePath = BundleDiscovery.GetDcpExecutablePath(dcpDirectory);
var output = new OutputCollector();
IProcessExecution? process = null;
var processStarted = false;
try
{
// Abrupt CLI exit can bypass disposal. Let DCP capture the native parent identity;
// its Linux identity time is boot-relative, not a .NET wall-clock start time.
// https://github.com/microsoft/dcp/blob/02587e8f87bc76cb01d6baf60314c693b7a88976/pkg/process/process_handle.go#L18-L55
var arguments = new List<string>
{
"start-apiserver",
// Doctor only probes /version, so controller startup and container-runtime discovery are unnecessary.
"--server-only",
"--monitor",
Environment.ProcessId.ToString(CultureInfo.InvariantCulture),
"--kubeconfig",
kubeconfigPath
};
if (useDeveloperCertificate)
{
AddDeveloperCertificateArguments(arguments, certificateManager, environment);
}
var environmentVariables = new Dictionary<string, string>();
var extensionsPath = Path.Combine(dcpDirectory, "ext");
if (Directory.Exists(extensionsPath))
{
environmentVariables["DCP_EXTENSIONS_PATH"] = extensionsPath;
}
// DCP uses this folder for process-scoped state such as the generated kubeconfig.
// Keeping it under the doctor-owned temp directory prevents overlap with AppHost sessions.
// This probe creates no workloads or logging socket. DCP's notification socket uses
// the user cache directory, not this folder, so its Unix socket path limit is independent.
// https://github.com/microsoft/dcp/blob/v0.27.5/internal/dcp/bootstrap/dcp_run.go#L243-L253
environmentVariables["DCP_SESSION_FOLDER"] = sessionDirectory;
var options = new ProcessInvocationOptions
{
StandardOutputCallback = output.AppendOutput,
StandardErrorCallback = output.AppendError
};
process = processExecutionFactory.CreateExecution(
dcpExecutablePath,
arguments.ToArray(),
environmentVariables,
executionContext.WorkingDirectory,
options);
if (!await process.StartAsync(cancellationToken).ConfigureAwait(false))
{
throw new InvalidOperationException(DoctorCommandStrings.DcpStartFailedMessage);
}
processStarted = true;
var session = new DcpConnectionTestSession(process, sessionDirectory, kubeconfigPath, output, logger);
await session.WaitForKubeconfigFileAsync(cancellationToken).ConfigureAwait(false);
return session;
}
catch
{
if (processStarted && !process!.HasExited)
{
await new DcpConnectionTestSession(process, sessionDirectory, kubeconfigPath, output, logger).DisposeAsync().ConfigureAwait(false);
}
else
{
if (process is not null)
{
await process.DisposeAsync().ConfigureAwait(false);
}
TryDeleteSessionDirectory(sessionDirectory, logger);
}
throw;
}
}
public async Task<DcpKubeconfig> ReadKubeconfigAsync(CancellationToken cancellationToken)
{
if (_kubeconfig is not null)
{
return _kubeconfig;
}
await WaitForKubeconfigFileAsync(cancellationToken).ConfigureAwait(false);
_kubeconfig = await DcpKubeconfig.ReadFileWithRetryAsync(_kubeconfigPath, cancellationToken: cancellationToken).ConfigureAwait(false);
return _kubeconfig;
}
public async ValueTask DisposeAsync()
{
try
{
var exited = _process.HasExited;
if (!exited && await RequestStopAsync().ConfigureAwait(false))
{
exited = await WaitForExitAsync().ConfigureAwait(false);
}
if (!exited)
{
exited = await ForceStopAsync().ConfigureAwait(false);
}
if (exited)
{
await _process.DisposeAsync().ConfigureAwait(false);
TryDeleteSessionDirectory(_sessionDirectory, _logger);
}
else
{
// Even a tree kill did not end DCP. Disposing a running process would block on
// another kill attempt, so abandon the handle; --monitor makes DCP shut down
// when this CLI process exits, and DCP owns its session folder until then.
_logger.LogDebug(
"DCP doctor process {ProcessId} could not be stopped; leaving it to exit with its monitored parent.",
_process.ProcessId);
}
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failed to stop DCP doctor process.");
}
finally
{
_kubeconfig?.Dispose();
}
}
/// <returns><see langword="true"/> if DCP accepted the stop request.</returns>
private async Task<bool> RequestStopAsync()
{
// Teardown must not depend on the caller's (possibly already cancelled) probe token.
using var timeoutCts = new CancellationTokenSource(s_stopRequestTimeout);
try
{
if (_kubeconfig is null && !File.Exists(_kubeconfigPath))
{
_logger.LogDebug("DCP doctor kubeconfig '{KubeconfigPath}' does not exist; cannot request DCP shutdown.", _kubeconfigPath);
return false;
}
var kubeconfig = await ReadKubeconfigAsync(timeoutCts.Token).ConfigureAwait(false);
using var handler = CreateHttpClientHandler(kubeconfig);
using var client = new HttpClient(handler)
{
BaseAddress = kubeconfig.Server,
Timeout = s_stopRequestTimeout
};
if (!string.IsNullOrWhiteSpace(kubeconfig.Token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", kubeconfig.Token);
}
// The doctor DCP instance never creates workloads, so it can skip resource cleanup.
var content = new StringContent("""{"status":"Stopping","shutdownResourceCleanup":"None"}""", Encoding.UTF8);
// DCP matches the media type exactly and answers 415 when StringContent appends
// "; charset=utf-8", which would leave the process to be killed instead of stopped.
// This mirrors the header DcpKubernetesClient sends for the same PATCH.
content.Headers.ContentType = new MediaTypeHeaderValue(DcpStopRequestMediaType);
using var request = new HttpRequestMessage(HttpMethod.Patch, new Uri(kubeconfig.Server, "/admin/execution"))
{
Content = content
};
using var response = await client.SendAsync(request, timeoutCts.Token).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
_logger.LogDebug("DCP doctor stop request returned HTTP {StatusCode}.", response.StatusCode);
return false;
}
return true;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failed to request DCP shutdown for doctor connection check.");
return false;
}
}
/// <summary>
/// Kills the doctor-only DCP process tree when it could not be stopped gracefully.
/// </summary>
/// <returns><see langword="true"/> if DCP exited after being killed.</returns>
private async Task<bool> ForceStopAsync()
{
// IMPORTANT: Killing DCP is acceptable ONLY because this DCP instance exists solely for the
// `aspire doctor` connectivity health check. It runs only the API server in a private session
// folder. The probe calls GET /version and creates no API objects, so there are no workloads
// or networks that a forced kill could orphan. A DCP instance that runs an AppHost must NOT be
// stopped this way: it has to be shut down gracefully so it can clean up the resources it owns.
//
// The graceful stop request fails exactly when the probe found DCP unhealthy (no kubeconfig,
// TLS or authentication failures, or an unresponsive API server). Leaving DCP for --monitor would
// keep it alive until the CLI exits, which in a long-lived `aspire agent mcp` server could be
// indefinitely and would leave another API server running after each failed doctor run.
_logger.LogDebug("DCP doctor process {ProcessId} did not stop gracefully; killing its process tree.", _process.ProcessId);
try
{
_process.Kill(entireProcessTree: true);
}
catch (InvalidOperationException) when (_process.HasExited)
{
return true;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failed to kill DCP doctor process {ProcessId}.", _process.ProcessId);
}
return await WaitForExitAsync().ConfigureAwait(false);
}
private async Task<bool> WaitForExitAsync()
{
// Poll instead of calling IProcessExecution.WaitForExitAsync with a timeout token: a cancelled
// wait terminates the child itself, whereas this teardown must first give DCP a chance to stop
// gracefully and only then decide explicitly (in ForceStopAsync) whether to kill it.
var stopwatch = Stopwatch.StartNew();
while (!_process.HasExited)
{
if (stopwatch.Elapsed >= s_processExitTimeout)
{
return false;
}
await Task.Delay(s_processExitPollInterval).ConfigureAwait(false);
}
return true;
}
private static void TryDeleteSessionDirectory(string sessionDirectory, ILogger logger)
{
try
{
Directory.Delete(sessionDirectory, recursive: true);
}
catch (DirectoryNotFoundException)
{
}
catch (Exception ex)
{
logger.LogDebug(ex, "Failed to delete DCP doctor session directory '{SessionDirectory}'.", sessionDirectory);
}
}
private async Task WaitForKubeconfigFileAsync(CancellationToken cancellationToken)
{
while (!File.Exists(_kubeconfigPath))
{
if (_process.HasExited)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
DoctorCommandStrings.DcpExitedBeforeKubeconfigDetailsFormat,
_process.ExitCode,
Environment.NewLine,
GetRecentOutput(_output)));
}
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
}
}
private static string GetRecentOutput(OutputCollector output)
{
var lines = output.GetLines()
.TakeLast(40)
.Select(line => $"{line.Stream}: {line.Line}")
.ToArray();
return lines.Length == 0 ? DoctorCommandStrings.DcpNoOutputDetails : string.Join(Environment.NewLine, lines);
}
private static void AddDeveloperCertificateArguments(List<string> arguments, CertificateManager certificateManager, IEnvironment environment)
{
var certificates = certificateManager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true);
try
{
var certificate = certificates.FirstOrDefault(c =>
c.HasPrivateKey &&
certificateManager.GetTrustLevel(c) == CertificateManager.TrustLevel.Full);
if (certificate is null)
{
throw new DcpDeveloperCertificateUnavailableException(DoctorCommandStrings.DcpDeveloperCertificateNoTrustedExportableDetails);
}
if (string.IsNullOrWhiteSpace(certificate.Thumbprint))
{
throw new DcpDeveloperCertificateUnavailableException(DoctorCommandStrings.DcpDeveloperCertificateMissingThumbprintDetails);
}
arguments.Add("--tls-cert-thumbprint");
arguments.Add(certificate.Thumbprint);
if (environment.IsWindows())
{
return;
}
var certificatePath = DcpDeveloperCertificateCache.EnsureDeveloperCertificateCache(certificateManager, certificate);
var keyPath = Path.ChangeExtension(certificatePath, ".key");
arguments.Add("--tls-cert-file");
arguments.Add(certificatePath);
arguments.Add("--tls-key-file");
arguments.Add(keyPath);
}
finally
{
CertificateManager.DisposeCertificates(certificates);
}
}
}
}
internal sealed class DcpDeveloperCertificateUnavailableException(string message) : Exception(message);