Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -443,10 +443,13 @@ private static void AddPackageInstaller<TResource>(
.AddResource(installer)
.WithParentRelationship(resource.Resource)
.WithIconName("ArrowDownload")
.WithCertificateTrustConfiguration(ConfigurePerlCertificateTrust)
.ExcludeFromManifest();

resource.ApplicationBuilder.Eventing.Subscribe<BeforeStartEvent>(async (evt, ct) =>
{
ApplyInstallerCertificateTrust(installerBuilder, resource.Resource);

var logger = evt.Services.GetRequiredService<ResourceLoggerService>().GetLogger(resource.Resource);

if (!resource.Resource.TryGetLastAnnotation<PerlPackageManagerAnnotation>(out var packageManager))
Expand Down Expand Up @@ -489,9 +492,6 @@ private static void AddPackageInstaller<TResource>(

// Eagerly propagate local::lib env vars if the annotation already exists
TryAttachLocalLibToInstallerResource(installer, resource.Resource);

// Eagerly propagate certificate trust env vars if configured
TryAttachCertificateTrustToInstallerResource(installer, resource);
}

/// <summary>
Expand Down Expand Up @@ -526,10 +526,13 @@ private static void AddProjectDependencyInstaller<TResource>(
.AddResource(installer)
.WithParentRelationship(resource.Resource)
.WithIconName("ArrowDownload")
.WithCertificateTrustConfiguration(ConfigurePerlCertificateTrust)
.ExcludeFromManifest();

resource.ApplicationBuilder.Eventing.Subscribe<BeforeStartEvent>(async (evt, ct) =>
{
ApplyInstallerCertificateTrust(installerBuilder, resource.Resource);

var logger = evt.Services.GetRequiredService<ResourceLoggerService>().GetLogger(resource.Resource);

if (!resource.Resource.TryGetLastAnnotation<PerlPackageManagerAnnotation>(out var packageManager))
Expand Down Expand Up @@ -570,9 +573,6 @@ private static void AddProjectDependencyInstaller<TResource>(
resource.WithAnnotation(new PerlProjectInstallerAnnotation(installer));

TryAttachLocalLibEnvironmentToProjectInstaller(resource);

// Eagerly propagate certificate trust env vars if configured
TryAttachCertificateTrustToInstallerResource(installer, resource);
}

/// <summary>
Expand Down Expand Up @@ -654,52 +654,28 @@ private static void TryAttachLocalLibToExistingInstallers<TResource>(
}

/// <summary>
/// Applies SSL/TLS certificate trust environment variables to a single installer resource.
/// Uses <see cref="PerlCertificateTrustAnnotation"/> on the parent as a guard —
/// only propagates when cert trust is enabled. Skips if already attached.
/// Copies the parent's final trust policy at startup so installer creation order does not affect trust.
/// </summary>
/// <typeparam name="TResource">The type of the parent Perl application resource.</typeparam>
/// <param name="installerResource">The installer resource that receives certificate variables.</param>
/// <param name="resource">The parent Perl resource builder with certificate trust configuration.</param>
private static void TryAttachCertificateTrustToInstallerResource<TResource>(
ExecutableResource installerResource,
IResourceBuilder<TResource> resource) where TResource : PerlAppResource
private static void ApplyInstallerCertificateTrust(
IResourceBuilder<PerlModuleInstallerResource> installer,
PerlAppResource parent)
{
if (!resource.Resource.Annotations.OfType<PerlCertificateTrustAnnotation>().Any())
if (parent.TryGetLastAnnotation<CertificateAuthorityCollectionAnnotation>(out var parentTrust))
{
return;
}
var installerTrust = new CertificateAuthorityCollectionAnnotation();
installerTrust.CertificateAuthorityCollections.AddRange(parentTrust.CertificateAuthorityCollections);

if (installerResource.Annotations.OfType<PerlCertificateTrustAnnotation>().Any())
{
return;
}

installerResource.Annotations.Add(new PerlCertificateTrustAnnotation());
installer.WithAnnotation(installerTrust, ResourceAnnotationMutationBehavior.Replace);

// Unlike Python installers, Perl installers retain certificate trust for CPAN HTTPS requests.
resource.ApplicationBuilder.CreateResourceBuilder(installerResource)
.WithCertificateTrustConfiguration(ConfigurePerlCertificateTrust);
}

/// <summary>
/// Propagates certificate trust to all existing installer child resources.
/// Called from <see cref="WithPerlCertificateTrust{TResource}"/> to handle the case
/// where installers were created before <c>WithPerlCertificateTrust</c> in the fluent chain.
/// </summary>
/// <typeparam name="TResource">The resource type.</typeparam>
/// <param name="resource">The parent Perl resource builder.</param>
private static void TryAttachCertificateTrustToExistingInstallers<TResource>(
IResourceBuilder<TResource> resource) where TResource : PerlAppResource
{
foreach (var moduleAnnotation in resource.Resource.Annotations.OfType<PerlModuleInstallerAnnotation>())
{
TryAttachCertificateTrustToInstallerResource(moduleAnnotation.Resource, resource);
}
if (parentTrust.Scope is { } scope)
{
installer.WithCertificateTrustScope(scope);
}

if (resource.Resource.TryGetLastAnnotation<PerlProjectInstallerAnnotation>(out var projectAnnotation))
{
TryAttachCertificateTrustToInstallerResource(projectAnnotation.Resource, resource);
if (parentTrust.TrustDeveloperCertificates is { } trustDeveloperCertificates)
{
installer.WithDeveloperCertificateTrust(trustDeveloperCertificates);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ private static IResourceBuilder<PerlAppResource> AddPerlAppCore(

resourceBuilder.WithOtlpExporterIfEndpointAvailable(OtlpProtocol.HttpJson);
resourceBuilder.WithRequiredCommand("perl", "https://www.perl.org/get.html");
resourceBuilder
.WithCertificateTrustScope(CertificateTrustScope.System)
.WithCertificateTrustConfiguration(ConfigurePerlCertificateTrust);

// OpenTelemetry::Exporter::OTLP supports HTTP/JSON and HTTP/protobuf, not gRPC.
// HTTP/JSON avoids requiring Google::ProtocolBuffers::Dynamic for protobuf encoding, which can be difficult (though not impossible)to get on windows, specifically.
Expand Down Expand Up @@ -502,34 +505,20 @@ public static IResourceBuilder<TResource> WithLocalLib<TResource>(
}

/// <summary>
/// Configures certificate trust for the Perl application by setting SSL/TLS environment
/// variables that common Perl HTTP libraries respect.
/// Sets <c>SSL_CERT_FILE</c> (IO::Socket::SSL / LWP), <c>PERL_LWP_SSL_CA_FILE</c> (LWP::UserAgent),
/// and <c>MOJO_CA_FILE</c> (Mojolicious) to the certificate bundle path provided by Aspire.
/// Also configures package and project dependency installers using each resource's own certificate trust context.
/// Retained for compatibility. Certificate trust is configured by default for Perl resources.
/// </summary>
/// <typeparam name="TResource">The type of the Perl application resource.</typeparam>
/// <param name="builder">The resource builder.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{TResource}"/>.</returns>
/// <remarks>Use <c>WithCertificateTrustScope</c> to change or disable certificate trust.</remarks>
[Obsolete("Certificate trust is configured by default for Perl resources. Use WithCertificateTrustScope to change or disable it.")]
[Experimental("CTASPIREPERL001")]
[AspireExport]
public static IResourceBuilder<TResource> WithPerlCertificateTrust<TResource>(
this IResourceBuilder<TResource> builder) where TResource : PerlAppResource
{
ArgumentNullException.ThrowIfNull(builder);

if (builder.Resource.Annotations.OfType<PerlCertificateTrustAnnotation>().Any())
{
return builder;
}

builder.Resource.Annotations.Add(new PerlCertificateTrustAnnotation());

builder.WithCertificateTrustConfiguration(ConfigurePerlCertificateTrust);

// Propagate cert trust env vars to any existing installer child resources
TryAttachCertificateTrustToExistingInstallers(builder);

return builder;
}

Expand All @@ -540,9 +529,27 @@ private static Task ConfigurePerlCertificateTrust(CertificateTrustConfigurationC
{
if (context.CertificateBundlePath is { } bundlePath)
{
context.EnvironmentVariables["SSL_CERT_FILE"] = bundlePath;
context.EnvironmentVariables["PERL_LWP_SSL_CA_FILE"] = bundlePath;
context.EnvironmentVariables["MOJO_CA_FILE"] = bundlePath;
if (context.Scope == CertificateTrustScope.Append)
{
var logger = context.ExecutionContext.Services.GetRequiredService<ResourceLoggerService>()
.GetLogger(context.Resource);
logger.LogInformation("Certificate trust scope is set to 'Append', but Perl resources do not support appending to the default certificate authorities; only OTLP certificate trust will be applied.");
}
else
{
context.EnvironmentVariables["SSL_CERT_FILE"] = bundlePath;
context.EnvironmentVariables["PERL_LWP_SSL_CA_FILE"] = bundlePath;
context.EnvironmentVariables["MOJO_CA_FILE"] = bundlePath;
}

context.EnvironmentVariables["OTEL_EXPORTER_OTLP_CERTIFICATE"] = bundlePath;

if (context.EnvironmentVariables.ContainsKey("OTEL_EXPORTER_OTLP_ENDPOINT"))
{
// Environment callbacks use a copy; bind here to observe final certificate-trust writes.
context.EnvironmentVariables.TryAdd("OTEL_PERL_EXPORTER_OTLP_CERTIFICATE",
new PerlOtelEnvironmentVariableMirror(context.EnvironmentVariables, "OTEL_EXPORTER_OTLP_CERTIFICATE"));
}
}

return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace CommunityToolkit.Aspire.Hosting.Perl;
/// <summary>
/// Resolves a Perl-specific OpenTelemetry variable from the final value of its standard variable.
/// </summary>
/// <param name="environmentVariables">The environment variables shared by the resource's environment callbacks.</param>
/// <param name="environmentVariables">The shared environment variables for the current configuration stage.</param>
/// <param name="sourceName">The standard OpenTelemetry variable to read.</param>
internal sealed class PerlOtelEnvironmentVariableMirror(
IReadOnlyDictionary<string, object> environmentVariables,
Expand Down
35 changes: 27 additions & 8 deletions src/CommunityToolkit.Aspire.Hosting.Perl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,33 @@ to install them. Individual module installation is supported with cpan or cpanm

## Certificate trust

The experimental `WithPerlCertificateTrust()` API (`CTASPIREPERL001`) configures
`SSL_CERT_FILE`, `PERL_LWP_SSL_CA_FILE`, and `MOJO_CA_FILE` for the Perl app and its
package and project dependency installers. Each resource uses the certificate bundle
provided by its own Aspire certificate trust context, not the AppHost process's
`SSL_CERT_FILE` environment variable.

Call it before or after `WithPackage()` or `WithProjectDependencies()`; both orders
are supported. Certificate trust remains opt-in.
In run mode, all `AddPerl*` methods configure certificate trust with `System` scope by default.
Aspire's bundle includes system root CAs plus configured custom and developer certificates.
`SSL_CERT_FILE`, `PERL_LWP_SSL_CA_FILE`, and `MOJO_CA_FILE` point to that bundle, replacing
any values configured earlier in environment callbacks. `Override` scope uses only the configured
custom and developer certificates, without system roots.

`OTEL_EXPORTER_OTLP_CERTIFICATE` also points to the resource's bundle. When an OTLP endpoint is
configured, `OTEL_PERL_EXPORTER_OTLP_CERTIFICATE` resolves from the final standard certificate
variable unless a Perl-specific value was explicitly set.

Package and project dependency installers inherit the parent's final trust scope, custom CAs,
and developer-certificate trust setting, regardless of fluent-call order. Each installer uses
its own certificate bundle, not the AppHost process's `SSL_CERT_FILE` environment variable.

Perl TLS libraries cannot append to their default CA stores. With `Append` scope, the integration
logs this limitation and configures only OTLP certificate trust; it leaves the Perl TLS variables
untouched so public HTTPS and CPAN downloads retain their default trust.

To disable Aspire-managed certificate trust for the app and its installers:

```csharp
builder.AddPerlScript("worker", "../scripts", "Worker.pl")
.WithCertificateTrustScope(CertificateTrustScope.None);
```

Publish mode retains the deployment target's default certificate trust behavior.
`WithPerlCertificateTrust()` (`CTASPIREPERL001`) is now an obsolete no-op retained for compatibility.

---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public static ApplicationModel.IResourceBuilder<T> WithPerlbrew<T>(this Applicat
public static ApplicationModel.IResourceBuilder<T> WithPerlbrewEnvironment<T>(this ApplicationModel.IResourceBuilder<T> builder, string version, string? perlbrewRoot = null)
where T : ApplicationModel.PerlAppResource { throw null; }

[System.Obsolete("Certificate trust is configured by default for Perl resources. Use WithCertificateTrustScope to change or disable it.")]
[System.Diagnostics.CodeAnalysis.Experimental("CTASPIREPERL001")]
[AspireExport]
public static ApplicationModel.IResourceBuilder<TResource> WithPerlCertificateTrust<TResource>(this ApplicationModel.IResourceBuilder<TResource> builder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ internal static async Task<List<string>> PublishBeforeStartAndCollectLogsAsync(
DistributedApplication app,
string resourceName,
TimeSpan? timeout = null)
{
await PublishBeforeStartAsync(builder, app);
return await CollectLogsAsync(app, resourceName, timeout);
}

internal static async Task PublishBeforeStartAsync(
IDistributedApplicationBuilder builder,
DistributedApplication app)
{
var appModel = app.Services.GetRequiredService<DistributedApplicationModel>();
var eventing = (DistributedApplicationEventing)builder.Eventing;
Expand All @@ -41,7 +49,13 @@ await eventing.PublishAsync(
{
// Expected: DCP CLI / dashboard paths not configured in unit tests.
}
}

internal static async Task<List<string>> CollectLogsAsync(
DistributedApplication app,
string resourceName,
TimeSpan? timeout = null)
{
var loggerService = app.Services.GetRequiredService<ResourceLoggerService>();
List<string> logs = [];
using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(3));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.ApplicationModel.Docker;
using CommunityToolkit.Aspire.Hosting.Perl.Annotations;
using CommunityToolkit.Aspire.Testing;
using Microsoft.Extensions.DependencyInjection;

namespace CommunityToolkit.Aspire.Hosting.Perl.Tests;
Expand Down Expand Up @@ -47,6 +48,36 @@ public void PublishMode_CollidingModuleNames_RetainsRequestsWithoutInstallers()
#pragma warning restore ASPIRECOMMAND001
}

[Fact]
public async Task PublishMode_DoesNotConfigureCertificateTrustOrCreateInstallers()
{
var builder = DistributedApplication.CreateBuilder(["--publisher", "manifest"]);
Assert.True(builder.ExecutionContext.IsPublishMode);
var perlApp = builder.AddPerlScript("perl-app", "scripts", "app.pl")
.WithCpanMinus()
.WithPackage("Mojolicious")
.WithProjectDependencies();

using var app = builder.Build();

var environment = await perlApp.Resource.GetEnvironmentVariablesAsync(
DistributedApplicationOperation.Publish, app.Services);

Assert.Equal("otlp", environment["OTEL_TRACES_EXPORTER"]);
foreach (var variable in new[]
{
"SSL_CERT_FILE", "PERL_LWP_SSL_CA_FILE", "MOJO_CA_FILE",
"OTEL_EXPORTER_OTLP_CERTIFICATE", "OTEL_PERL_EXPORTER_OTLP_CERTIFICATE"
})
{
Assert.DoesNotContain(variable, environment.Keys);
}

var appModel = app.Services.GetRequiredService<DistributedApplicationModel>();
Assert.Empty(appModel.Resources.OfType<PerlModuleInstallerResource>());
Assert.Empty(perlApp.Resource.Annotations.OfType<WaitAnnotation>());
}

[Fact]
public void RunMode_DoesNotAddDockerfileAnnotation()
{
Expand Down
Loading
Loading