Skip to content

Commit c2c0665

Browse files
authored
Merging internal commits for release/9.0.3xx (#10573)
Merges internal commit `1e47d4e42b876a31cc58385aa77ac4303756d018` into `release/9.0.3xx`.
2 parents d0d8d30 + 5c65ee2 commit c2c0665

9 files changed

Lines changed: 685 additions & 45 deletions

File tree

‎docs/api/Inside-the-Template-Engine.md‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ designed to separate gathering, instantiating and processing templates.
1818

1919
# Overview of the subsystems
2020

21-
## [IEngineEnvironmentSettings](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs)
21+
## [IEngineEnvironmentSettings](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs)
2222

2323
This is responsible for holding all properties of the environment.
2424

@@ -69,7 +69,7 @@ and
6969

7070
`ComponentManager` is responsible for loading [components](#components) provided by the host from
7171
`ITemplateEngineHost.BuiltIns`. Additional components can be added via
72-
`IComponentManager.AddComponent`. Similar to templates, components are also
72+
`IComponentManager.AddComponent`. Similar to templates, components are also
7373
dynamically loaded from template packages during scanning. `ComponentManager`
7474
implementation is not publicly accessible; however, it is used when default
7575
implementation of `IEngineEnvironmentSettings` is used.
@@ -120,9 +120,9 @@ instantiate the class when needed.
120120

121121
### Supplying parameters conditions results
122122

123-
It is possible to supply evaluation results of parameters conditions when instantiating template via Edge API [`TemplateCreator.InstantiateAsync`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs#L89). Example use case is instantiation from Visual Studio host, that will leverage condition evaluator integrated within the New Project Dialog.
123+
It is possible to supply evaluation results of parameters conditions when instantiating template via Edge API [`TemplateCreator.InstantiateAsync`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs#L89). Example use case is instantiation from Visual Studio host, that will leverage condition evaluator integrated within the New Project Dialog.
124124

125-
This can be achieved by passing the structured [`InputDataSet`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs) argument that is populated with [`EvaluatedInputParameterData`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs) objects for evaluated parameters.
125+
This can be achieved by passing the structured [`InputDataSet`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs) argument that is populated with [`EvaluatedInputParameterData`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs) objects for evaluated parameters.
126126

127127
It is currently not possible to provide just partial external evaluation - meaning that the template engine evaluates either all the parameter conditions or none. If the [`InputDataSet`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs) collection contains at least one [`EvaluatedInputParameterData`](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs) element, results of all parameter conditions are expected to be passed.
128128

@@ -178,7 +178,7 @@ be split into two main categories:
178178

179179
- mount points
180180

181-
## Template package providers
181+
## Template package providers
182182

183183
Template package providers responsible for providing template packages the
184184
template engine needs to manage. There are two kinds of providers:
@@ -243,6 +243,12 @@ Template engine provides two installer implementations:
243243
You can use them when implementing your own providers, they are available from
244244
IComponentManager.
245245

246+
When package verification is enabled, downloaded signed NuGet packages are
247+
verified using `dotnet nuget verify --all` before installation. Unsigned packages
248+
are accepted only when NuGet's `signatureValidationMode` is `accept` and the
249+
source does not declare `allRepositorySigned=true`. A client policy of `require`
250+
or a repository signing requirement rejects unsigned packages.
251+
246252
## [Mount point](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs)
247253

248254
Template package location is represented by mount point URI. Mount point that
@@ -268,14 +274,14 @@ Template engine host works with constraint using `TemplateConstraintManager` cla
268274

269275
The template may define `bind` symbols. Those symbols might be bound to values provided externally using bind symbol source components.
270276
Default sources are:
271-
- host provided parameters - uses prefix `host:`. Binds symbol to parameters provided by the host.
277+
- host provided parameters - uses prefix `host:`. Binds symbol to parameters provided by the host.
272278
- environment variables - uses prefix `env:`. Binds symbol to environment variables.
273279

274280
These components are defined in `Microsoft.TemplateEngine.Edge` and are part of mandatory components collection to be loaded.
275281

276-
If the `binding` does not have prefix, or prefixed value cannot be evaluated the evaluation without prefix is performed as the fallback.
282+
If the `binding` does not have prefix, or prefixed value cannot be evaluated the evaluation without prefix is performed as the fallback.
277283
In case there are more than one component which returns the value, the component priority will be used to define the value to be bounded. In case of same priorities, the evaluation results in error.
278-
The template author needs to explicitly specify the prefix in this case. It is possible to restrict usage of prefix with setting `IBindSymbolSource.RequiresPrefixMatch` to `true`.
284+
The template author needs to explicitly specify the prefix in this case. It is possible to restrict usage of prefix with setting `IBindSymbolSource.RequiresPrefixMatch` to `true`.
279285

280286

281287
## Registering the components
@@ -325,7 +331,7 @@ It is possible to register additional components to in the following way:
325331
Note that components are not persisted, so they should be added each time
326332
EngineEnvironmentSettings instance is created.
327333

328-
# Microsoft.TemplateEngine.IDE
334+
# Microsoft.TemplateEngine.IDE
329335

330336
The package provides
331337
[Bootstrapper](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.IDE/Bootstrapper.cs)
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.ComponentModel;
5+
using System.Diagnostics;
6+
using System.Runtime.InteropServices;
7+
using System.Security;
8+
using Microsoft.TemplateEngine.CommandUtils;
9+
using NuGet.Common;
10+
using NuGet.Configuration;
11+
using NuGet.Packaging;
12+
using NuGet.Packaging.Signing;
13+
using NuGet.Protocol;
14+
using NuGet.Protocol.Core.Types;
15+
16+
namespace Microsoft.TemplateEngine.Edge.Installers.NuGet
17+
{
18+
internal interface INuGetPackageVerifier
19+
{
20+
bool IsEnabled { get; }
21+
22+
Task VerifyAsync(string packagePath, SourceRepository repository, ISettings settings, ILogger logger, CancellationToken cancellationToken);
23+
}
24+
25+
internal sealed class DotnetNuGetPackageVerifier : INuGetPackageVerifier
26+
{
27+
private const string SignatureVerificationEnvironmentVariable = "DOTNET_NUGET_SIGNATURE_VERIFICATION";
28+
29+
public DotnetNuGetPackageVerifier()
30+
{
31+
bool? configuredValue = bool.TryParse(
32+
Environment.GetEnvironmentVariable(SignatureVerificationEnvironmentVariable),
33+
out bool shouldVerify)
34+
? shouldVerify
35+
: null;
36+
37+
IsEnabled = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
38+
|| configuredValue == true
39+
|| (configuredValue == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux));
40+
}
41+
42+
public bool IsEnabled { get; }
43+
44+
public async Task VerifyAsync(string packagePath, SourceRepository repository, ISettings settings, ILogger logger, CancellationToken cancellationToken)
45+
{
46+
_ = packagePath ?? throw new ArgumentNullException(nameof(packagePath));
47+
_ = repository ?? throw new ArgumentNullException(nameof(repository));
48+
_ = settings ?? throw new ArgumentNullException(nameof(settings));
49+
_ = logger ?? throw new ArgumentNullException(nameof(logger));
50+
cancellationToken.ThrowIfCancellationRequested();
51+
52+
bool isSigned;
53+
using (var reader = new PackageArchiveReader(packagePath))
54+
{
55+
isSigned = await reader.IsSignedAsync(cancellationToken).ConfigureAwait(false);
56+
}
57+
58+
if (!isSigned)
59+
{
60+
ClientPolicyContext clientPolicy = ClientPolicyContext.GetClientPolicy(settings, logger);
61+
RepositorySignatureResource? repositorySignature =
62+
await repository.GetResourceAsync<RepositorySignatureResource>(cancellationToken).ConfigureAwait(false);
63+
cancellationToken.ThrowIfCancellationRequested();
64+
if (clientPolicy.Policy == SignatureValidationMode.Require || repositorySignature?.AllRepositorySigned == true)
65+
{
66+
const string message = "The package is unsigned, but client or repository policy requires signing.";
67+
logger.LogDebug(message);
68+
throw new InvalidDataException(message);
69+
}
70+
71+
logger.LogDebug("Accepting unsigned package under accept policy.");
72+
return;
73+
}
74+
75+
await VerifySignedPackageAsync(packagePath, logger, cancellationToken).ConfigureAwait(false);
76+
}
77+
78+
private static async Task VerifySignedPackageAsync(string packagePath, ILogger logger, CancellationToken cancellationToken)
79+
{
80+
cancellationToken.ThrowIfCancellationRequested();
81+
using var process = new Process
82+
{
83+
StartInfo = new ProcessStartInfo
84+
{
85+
FileName = "dotnet",
86+
Arguments = $"nuget verify --all {ArgumentEscaper.EscapeSingleArg(packagePath)}",
87+
UseShellExecute = false,
88+
CreateNoWindow = true,
89+
RedirectStandardError = true,
90+
RedirectStandardOutput = true
91+
}
92+
};
93+
if (!process.Start())
94+
{
95+
throw new InvalidOperationException("Failed to start 'dotnet nuget verify'.");
96+
}
97+
98+
#if NET
99+
Task<string> standardOutput = process.StandardOutput.ReadToEndAsync(CancellationToken.None);
100+
Task<string> standardError = process.StandardError.ReadToEndAsync(CancellationToken.None);
101+
#else
102+
Task<string> standardOutput = process.StandardOutput.ReadToEndAsync();
103+
Task<string> standardError = process.StandardError.ReadToEndAsync();
104+
#endif
105+
await WaitForExitAsync(process, logger, cancellationToken).ConfigureAwait(false);
106+
107+
string output = await standardOutput.ConfigureAwait(false);
108+
string error = await standardError.ConfigureAwait(false);
109+
cancellationToken.ThrowIfCancellationRequested();
110+
111+
LogOutput(logger, output, LogLevel.Debug);
112+
LogOutput(logger, error, process.ExitCode == 0 ? LogLevel.Debug : LogLevel.Error);
113+
114+
if (process.ExitCode != 0)
115+
{
116+
string command = $"{process.StartInfo.FileName} {process.StartInfo.Arguments}";
117+
throw new SecurityException($"'{command}' failed with exit code {process.ExitCode}.");
118+
}
119+
120+
return;
121+
122+
static void LogOutput(ILogger logger, string output, LogLevel level)
123+
{
124+
if (!string.IsNullOrWhiteSpace(output))
125+
{
126+
logger.Log(level, output.Trim());
127+
}
128+
}
129+
}
130+
131+
private static async Task WaitForExitAsync(Process process, ILogger logger, CancellationToken cancellationToken)
132+
{
133+
using (cancellationToken.Register(() => TerminateProcess(process, logger)))
134+
{
135+
// Process.WaitForExitAsync is unavailable on netstandard2.0 and net472.
136+
await Task.Run(process.WaitForExit, CancellationToken.None).ConfigureAwait(false);
137+
}
138+
139+
return;
140+
141+
static void TerminateProcess(Process process, ILogger logger)
142+
{
143+
try
144+
{
145+
if (!process.HasExited)
146+
{
147+
process.Kill();
148+
}
149+
}
150+
catch (InvalidOperationException) when (process.HasExited)
151+
{
152+
// The process exited between checking HasExited and calling Kill.
153+
}
154+
catch (Win32Exception ex)
155+
{
156+
if (!process.HasExited)
157+
{
158+
logger.LogDebug($"Failed to terminate 'dotnet nuget verify': {ex}");
159+
}
160+
}
161+
}
162+
}
163+
}
164+
}

0 commit comments

Comments
 (0)