This backports changes made in the 2.2 build tools. This is anticipation of Arcade convergence. We already stopped using signrequest.xml in other parts of the stack. New tools replace this functionality.

* Backport implementation of Arcade code signing
* Remove sign request generation and validation
* Sign .Sources packages by default
* Use built-in dotnet-tool shim generation
This commit is contained in:
Nate McMaster 2018-10-25 18:30:32 -07:00 коммит произвёл GitHub
Родитель 3965b17663
Коммит 979736d4d4
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
55 изменённых файлов: 406 добавлений и 1083 удалений

Просмотреть файл

@ -12,8 +12,7 @@
<GenerateSourceLinkFile>false</GenerateSourceLinkFile>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
<EnableApiCheck>false</EnableApiCheck>
<!-- workaround https://github.com/aspnet/CoreCLR/issues/223 -->
<NoWarn>$(NoWarn);NU1603</NoWarn>
<NoWarn>$(NoWarn);NU5105</NoWarn>
<Serviceable>false</Serviceable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<SuppressNETCoreSdkPreviewMessage>true</SuppressNETCoreSdkPreviewMessage>

Просмотреть файл

@ -13,11 +13,11 @@ See [docs/README.md](./docs/README.md).
Channel | Latest Build
---------------|:---------------
dev | ![badge][dev-badge]
master | ![badge][master-badge]
release/2.1 | ![badge][rel-2.1-badge]
release/2.0 | ![badge][rel-2.0-badge]
[dev-badge]: https://aspnetcore.blob.core.windows.net/buildtools/korebuild/channels/dev/badge.svg
[master-badge]: https://aspnetcore.blob.core.windows.net/buildtools/korebuild/channels/master/badge.svg
[rel-2.1-badge]: https://aspnetcore.blob.core.windows.net/buildtools/korebuild/channels/release/2.1/badge.svg
[rel-2.0-badge]: https://aspnetcore.blob.core.windows.net/buildtools/korebuild/channels/release/2.0/badge.svg

Просмотреть файл

@ -1,8 +1,10 @@
<Project>
<PropertyGroup>
<HtmlAgilityPackPackageVersion>1.5.1</HtmlAgilityPackPackageVersion>
<MicroBuildCorePackageVersion>0.3.0</MicroBuildCorePackageVersion>
<MicrosoftDotNetPlatformAbstractionsVersion>2.0.0</MicrosoftDotNetPlatformAbstractionsVersion>
<MicrosoftNETTestSdkPackageVersion>15.6.1</MicrosoftNETTestSdkPackageVersion>
<MicrosoftDotNetSignToolPackageVersion>1.0.0-beta.18515.2</MicrosoftDotNetSignToolPackageVersion>
<MicrosoftNETTestSdkPackageVersion>15.9.0</MicrosoftNETTestSdkPackageVersion>
<MicrosoftWin32RegistryPackageVersion>4.4.0</MicrosoftWin32RegistryPackageVersion>
<MonoCecilPackageVersion>0.10.0-beta6</MonoCecilPackageVersion>
<MoqPackageVersion>4.7.99</MoqPackageVersion>

Просмотреть файл

@ -5,9 +5,7 @@
<RestoreSources>$(DotNetRestoreSources)</RestoreSources>
<RestoreSources Condition="'$(DotNetBuildOffline)' != 'true'">
$(RestoreSources);
https://dotnet.myget.org/F/dotnet-core/api/v3/index.json;
https://dotnet.myget.org/F/nuget-build/api/v3/index.json;
https://dotnet.myget.org/F/msbuild/api/v3/index.json;
https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json;
https://api.nuget.org/v3/index.json;
</RestoreSources>
</PropertyGroup>

Просмотреть файл

@ -1,27 +1,7 @@
Signing
=======
KoreBuild supports generating a signing request manfiest. This includes a list of all files that should be signed
and information about the strongname or certificate that should be used.
## Format
The signing request manifest supports three element types. A minimal example looks like this. See [Elements](#Elements) below for details
```xml
<SigningRequest>
<File Path="MyAssembly.dll" Certificate="MyCert" StrongName="MyStrongName" />
<File Path="build/Another.dll" Certificate="MyCert" />
<Container Path="MyLib.1.0.0.nupkg" Type="nupkg" Certificate="NuGetCert">
<File Path="lib/netstandard2.0/MyLib.dll" Certificate="MyCert" />
</Container>
<Container Path="MyVSTool.vsix" Type="vsix" Certificate="VsixCert">
<File Path="MyVSTool.dll" Certificate="MyCert" />
<!-- excluded from signing, but useful if you want to assert all files in a container are accounted for. -->
<ExcludedFile Path="NotMyLib.dll" />
</Container>
</SigningRequest>
```
KoreBuild supports code signing files and using MSBuild to configure the list of files which are code-signed.
## Config via csproj
@ -38,32 +18,16 @@ To sign assemblies, set the AssemblySigningCertName and AssemblySigningStrongNam
</PropertyGroup>
```
This will generate a signing request like this:
```xml
<SigningRequest>
<File Path="MyLib.dll" Certificate="MyCert" StrongName="PrivateStrongName" />
</SigningRequest>
```
### NuGet packages
To sign NuGet packages, set the PackageSigningCertName property in the \*.csproj that produces the nupkg.
```xml
<PropertyGroup>
<PackageSigningCertName>NuGetCert</PackageSigningCertName>
<PackageSigningCertName>MyNuGetCert</PackageSigningCertName>
</PropertyGroup>
```
This will generate a signing request like this:
```xml
<SigningRequest>
<Container Path="MyLib.1.0.0.nupkg" Type="nupkg" Certificate="NuGetCert" />
</SigningRequest>
```
### NuGet packages with assemblies
For assemblies that ship in a NuGet package, you can specify multiple properties.
@ -71,18 +35,21 @@ For assemblies that ship in a NuGet package, you can specify multiple properties
```xml
<PropertyGroup>
<AssemblySigningCertName>MyCert</AssemblySigningCertName>
<PackageSigningCertName>NuGetCert</PackageSigningCertName>
<PackageSigningCertName>MyNuGetCert</PackageSigningCertName>
</PropertyGroup>
```
This will generate a signing request like this:
### Recommended cert names for Microsoft projects
The following certificate names should be used for Microsoft projects. These MSBuild properties are also available by using Internal.AspNetCore.SDK.
```xml
<SigningRequest>
<Container Path="MyLib.1.0.0.nupkg" Type="nupkg" Certificate="NuGetCert">
<File Path="lib/netstandard2.0/MyLib.dll" Certificate="MyCert" />
</Container>
</SigningRequest>
<AssemblySigningCertName>Microsoft400</AssemblySigningCertName>
<AssemblySigning3rdPartyCertName>3PartySHA2</AssemblySigning3rdPartyCertName>
<PowerShellSigningCertName>Microsoft400</PowerShellSigningCertName>
<PackageSigningCertName>NuGet</PackageSigningCertName>
<VsixSigningCertName>VsixSHA2</VsixSigningCertName>
<JarSigningCertName>MicrosoftJAR</JarSigningCertName>
```
### Projects using nuspec
@ -108,20 +75,24 @@ Sometimes other signable assemblies end up in a nupkg. Signing for these file ty
```xml
<ItemGroup>
<!-- Files that come from other ASP.NET Core projects -->
<SignedPackageFile Include="$(PublishDir)Microsoft.Extensions.Configuration.Abstractions.dll" Certificate="$(AssemblySigningCertName)" PackagePath="tools/Microsoft.Extensions.Configuration.Abstractions.dll" Visible="false" />
<!-- Specifying signing for a file in a package. -->
<SignedPackageFile Include="tools/Microsoft.Extensions.Configuration.Abstractions.dll" Certificate="$(AssemblySigningCertName)" Visible="false" />
<!-- Specifying signing for a file in a package using an explicit path within the NuGet package. -->
<SignedPackageFile Include="$(OutputPath)$(TargetFileName)" Certificate="$(AssemblySigningCertName)"
PackagePath="tasks/net461/$(TargetFileName)" Visible="false" />
<!-- Third-party cert -->
<SignedPackageFile Include="$(PublishDir)Newtonsoft.Json.dll" Certificate="3PartyDual" PackagePath="tools/Newtonsoft.Json.dll" Visible="false" />
<SignedPackageFile Include="tools/Newtonsoft.Json.dll" Certificate="3PartySHA2" Visible="false" />
<!-- This should already be signed by the dotnet-core team -->
<ExcludePackageFileFromSigning Include="$(PublishDir)System.Runtime.CompilerServices.Unsafe.dll" PackagePath="tools/System.Runtime.CompilerServices.Unsafe.dll" Visible="false" />
<ExcludePackageFileFromSigning Include="tools/System.Runtime.CompilerServices.Unsafe.dll" />
</ItemGroup>
```
### Disabling signing
You can disable sign request generation on an MSBuild project by setting DisableCodeSigning.
You can disable sign request generation on an MSBuild project by setting DisableCodeSigning, or for an entire repo (via repo.props).
```xml
<PropertyGroup>
@ -137,50 +108,9 @@ these elements to the `build/repo.props` file. (See also [KoreBuild.md](./KoreBu
```xml
<!-- build/repo.props -->
<ItemGroup>
<FilesToSign Include="$(ArtifactsDir)libuv.dll" Certificate="3PartyDual" />
<FilesToSign Include="$(ArtifactsDir)libuv.dll" Certificate="3PartySHA2" />
<!-- Files can also be listed as "do not sign", for completeness -->
<FilesToExcludeFromSigning Include="$(ArtifactsDir)my.test.dll" Certificate="3PartyDual" />
<FilesToExcludeFromSigning Include="$(ArtifactsDir)my.test.dll" Certificate="3PartySHA2" />
</ItemGroup>
```
## Elements
#### `SigningRequest`
Root element. No options.
#### `File`
A file to be signed.
**Path** - file path, relative to the file path. If nested in a `<Container>`, is relative to the organization within the container
**Certificate** - the name of the certificate to use
**StrongName** - for assemblies only. This is used to strong name assemblies that were delay signed in public.
#### `Container`
A container is an archive file, installer, or some kind of bundle that can be signed, or that has files that can be signed
inside it. Nested elements can be added for `<File>` and `<ExcludedFile>`.
**Path** - file path to the container
**Certificate** - the name of the certificate to use
**Type** - The type of the container. Instructs the consumer how to extract the container. Example values:
- zip
- tar.gz
- vsix
- nupkg
- msi
#### `ExcludedFile`
This is useful when you want to exclude files within a container from being signed, but want to assert that
all files in a container are accounted for.
**Path** - file path to a file to be ignored by the signing tool

Просмотреть файл

@ -39,6 +39,22 @@ Default layout and configuration.
<BuildDir>$(ArtifactsDir)build\</BuildDir>
<LogOutputDir>$(ArtifactsDir)logs\</LogOutputDir>
<IntermediateDir>$([MSBuild]::NormalizeDirectory('$(RepositoryRoot)'))obj\</IntermediateDir>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(NUGET_PACKAGES)</NuGetPackageRoot>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' AND '$(USERPROFILE)' != '' ">$(USERPROFILE)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' AND '$(HOME)' != '' ">$(HOME)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(RepositoryRoot)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageRoot>$([MSBuild]::NormalizeDirectory('$(NuGetPackageRoot)'))</NuGetPackageRoot>
</PropertyGroup>
<!-- Code signing certificate names -->
<PropertyGroup Condition=" '$(DisableCodeSigning)' != 'true' ">
<AssemblySigningCertName>Microsoft400</AssemblySigningCertName>
<AssemblySigning3rdPartyCertName>3PartySHA2</AssemblySigning3rdPartyCertName>
<PowerShellSigningCertName>Microsoft400</PowerShellSigningCertName>
<PackageSigningCertName>NuGet</PackageSigningCertName>
<VsixSigningCertName>VsixSHA2</VsixSigningCertName>
<JarSigningCertName>MicrosoftJAR</JarSigningCertName>
</PropertyGroup>
<!-- Use build number from CI if available -->

Просмотреть файл

@ -26,6 +26,10 @@ set_korebuildsettings() {
[ -z "${tools_source:-}" ] && tools_source="$default_tools_source"
# This is required for NuGet and MSBuild
if [[ -z "${HOME:-}" ]]; then
export HOME="$repo_path/.build/home"
fi
if [ "$ci" = true ]; then
export CI=true
@ -40,7 +44,7 @@ set_korebuildsettings() {
mkdir -p "$HOME"
mkdir -p "$dot_net_home"
if [[ -z "${NUGET_PACKAGES:-}" ]]; then
export NUGET_PACKAGES="$repo_path/.build/.nuget/packages"
export NUGET_PACKAGES="$repo_path/.nuget/packages"
fi
else
if [[ -z "${NUGET_PACKAGES:-}" ]]; then
@ -48,7 +52,7 @@ set_korebuildsettings() {
fi
fi
export DOTNET_ROOT="$DOTNET_HOME"
export DOTNET_ROOT="$dot_net_home"
# Workaround perpetual issues in node reuse and custom task assemblies
export MSBUILDDISABLENODEREUSE=1
@ -123,6 +127,18 @@ __install_tools() {
# Set environment variables
export PATH="$install_dir:$PATH"
# This is a workaround for https://github.com/Microsoft/msbuild/issues/2914.
# Currently, the only way to configure the NuGetSdkResolver is with NuGet.config, which is not generally used in aspnet org projects.
# This project is restored so that it pre-populates the NuGet cache with SDK packages.
local restorerfile="$__korebuild_dir/modules/BundledPackages/BundledPackageRestorer.csproj"
local restorerfilelock="$NUGET_PACKAGES/internal.aspnetcore.sdk/$(__get_korebuild_version)/korebuild.sentinel"
if [[ -e "$restorerfile" ]] && [[ ! -e "$restorerfilelock" ]]; then
mkdir -p "$(dirname $restorerfilelock)"
touch "$restorerfilelock"
__exec dotnet msbuild -t:restore -v:q "$restorerfile"
fi
# end workaround
}
__show_version_info() {

Просмотреть файл

@ -26,15 +26,25 @@ that matches "$(RepositoryRoot)/shared/*.Sources".
Properties="$(_SharedSourcesPackageProperties);NuspecBasePath=$([MSBuild]::NormalizeDirectory('%(SharedSourceDirectories.Identity)'));PackageId=%(FileName)%(Extension)"
Condition="@(SharedSourceDirectories->Count()) != 0"
BuildInParallel="true">
<Output TaskParameter="TargetOutputs" ItemName="ArtifactInfo" />
<Output TaskParameter="TargetOutputs" ItemName="FilesToExcludeFromSigning" Condition="'$(SignSourcesPackages)' != 'true'" />
<Output TaskParameter="TargetOutputs" ItemName="FilesToSign" Condition="'$(SignSourcesPackages)' == 'true'" />
<Output TaskParameter="TargetOutputs" ItemName="_SharedSrcPkgArtifactInfo" />
</MSBuild>
<ItemGroup>
<ArtifactInfo Include="@(_SharedSrcPkgArtifactInfo)" />
<FilesToExcludeFromSigning Include="@(_SharedSrcPkgArtifactInfo)" Condition="'%(_SharedSrcPkgArtifactInfo.ShouldBeSigned)' != 'true' " />
<FilesToSign Include="@(_SharedSrcPkgArtifactInfo)" Condition="'%(_SharedSrcPkgArtifactInfo.ShouldBeSigned)' == 'true' " />
</ItemGroup>
</Target>
<Target Name="_SetSharedSourcesProperties">
<PropertyGroup>
<_SharedSourcesPackageProperties>PackageOutputPath=$(BuildDir);RepositoryRoot=$(RepositoryRoot);ImportDirectoryBuildProps=false;BuildNumber=$(BuildNumber);</_SharedSourcesPackageProperties>
<_SharedSourcesPackageProperties>
PackageOutputPath=$(BuildDir);
RepositoryRoot=$(RepositoryRoot);
ImportDirectoryBuildProps=false;
BuildNumber=$(BuildNumber);
RepositoryCommit=$(RepositoryCommit)
</_SharedSourcesPackageProperties>
</PropertyGroup>
</Target>

Просмотреть файл

@ -37,6 +37,13 @@
<ContentTargetFolders>contentFiles</ContentTargetFolders>
<DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
<DefaultExcludeItems>$(DefaultExcludeItems);$(BaseOutputPath);$(BaseIntermediateOutputPath);</DefaultExcludeItems>
<!-- Suppress warnings about using semver 2.0 versions in packages -->
<NoWarn>$(NoWarn);NU5105</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(DisableCodeSigning)' != 'true' ">
<!-- Only specify the package signing cert. Do not specify AssemblySigningCertName because .Sources packages should not have binaries. -->
<PackageSigningCertName>NuGet</PackageSigningCertName>
</PropertyGroup>
<ItemGroup Condition="'$(NuspecBasePath)'!=''">
@ -73,7 +80,7 @@
<Category>$(PackageArtifactCategory)</Category>
<IsContainer>true</IsContainer>
<Certificate>$(PackageSigningCertName)</Certificate>
<ShouldBeSigned Condition=" '$(PackageSigningCertName)' != '' ">true</ShouldBeSigned>
<ShouldBeSigned Condition=" '$(PackageSigningCertName)' != '' AND '$(DisableCodeSigning)' != 'true' ">true</ShouldBeSigned>
</ArtifactInfo>
</ItemGroup>
</Target>

Просмотреть файл

@ -1,7 +1,7 @@
<Project>
<Target Name="GetArtifactInfo"
DependsOnTargets="GetSignedPackageFiles"
DependsOnTargets="GetSignedPackageFiles;GetPackageFilesExcludedFromSigning"
Returns="@(ArtifactInfo)">
<PropertyGroup>
@ -15,12 +15,20 @@
Workaround for design time builds on projects using Internal.AspNetCore.Sdk that have not yet been restored.
IncludeSymbols and IncludeSource are off by default but are enabled in Internal.AspNetCore.Sdk.
-->
<_ReferencesInternalAspNetCoreSdk>@(PackageReference->AnyHaveMetadataValue('Identity', 'Internal.AspNetCore.Sdk'))</_ReferencesInternalAspNetCoreSdk>
<_ReferencesInternalAspNetCoreSdk Condition="'$(_ReferencesInternalAspNetCoreSdk)' == ''">@(PackageReference->AnyHaveMetadataValue('Identity', 'Internal.AspNetCore.Sdk'))</_ReferencesInternalAspNetCoreSdk>
<IncludeSymbols Condition="'$(IncludeSymbols)' == '' AND $(_ReferencesInternalAspNetCoreSdk)">true</IncludeSymbols>
<IncludeSource Condition="'$(IncludeSource)' == '' AND $(_ReferencesInternalAspNetCoreSdk)">true</IncludeSource>
</PropertyGroup>
<ItemGroup Condition="'$(IsPackable)' == 'true' ">
<ConvertToAbsolutePath Paths="@(SignedPackageFile)">
<Output TaskParameter="AbsolutePaths" ItemName="_SignedPackageFile" />
</ConvertToAbsolutePath>
<ConvertToAbsolutePath Paths="@(ExcludePackageFileFromSigning)">
<Output TaskParameter="AbsolutePaths" ItemName="_ExcludePackageFileFromSigning" />
</ConvertToAbsolutePath>
<ItemGroup Condition="'$(IsPackable)' != 'false' ">
<ArtifactInfo Include="$(FullPackageOutputPath)">
<ArtifactType>NuGetPackage</ArtifactType>
<PackageId>$(PackageId)</PackageId>
@ -32,7 +40,7 @@
<RepositoryUrl>$(RepositoryUrl)</RepositoryUrl>
<Category>$(PackageArtifactCategory)</Category>
<Certificate>$(PackageSigningCertName)</Certificate>
<ShouldBeSigned Condition="'$(PackageSigningCertName)' != '' OR @(SignedPackageFile->Count()) != 0 ">true</ShouldBeSigned>
<ShouldBeSigned Condition="'$(PackageSigningCertName)' != '' OR @(_SignedPackageFile->Count()) != 0 ">true</ShouldBeSigned>
<ShouldBeSigned Condition=" '$(DisableCodeSigning)' == 'true' ">false</ShouldBeSigned>
<IsContainer>true</IsContainer>
</ArtifactInfo>
@ -49,27 +57,27 @@
<RepositoryUrl>$(RepositoryUrl)</RepositoryUrl>
<Category>$(PackageArtifactCategory)</Category>
<Certificate>$(PackageSigningCertName)</Certificate>
<ShouldBeSigned Condition="'$(PackageSigningCertName)' != '' OR @(SignedPackageFile->Count()) != 0 ">true</ShouldBeSigned>
<ShouldBeSigned Condition="'$(PackageSigningCertName)' != '' OR @(_SignedPackageFile->Count()) != 0 ">true</ShouldBeSigned>
<ShouldBeSigned Condition=" '$(DisableCodeSigning)' == 'true' ">false</ShouldBeSigned>
<IsContainer>true</IsContainer>
</ArtifactInfo>
<ArtifactInfo Include="@(SignedPackageFile)" Condition=" '$(DisableCodeSigning)' != 'true' ">
<ArtifactInfo Include="@(_SignedPackageFile)" Condition=" '$(DisableCodeSigning)' != 'true' ">
<ShouldBeSigned>true</ShouldBeSigned>
<Container>$(FullPackageOutputPath)</Container>
</ArtifactInfo>
<ArtifactInfo Include="@(ExcludePackageFileFromSigning)">
<ArtifactInfo Include="@(_ExcludePackageFileFromSigning)">
<ShouldBeSigned>false</ShouldBeSigned>
<Container>$(FullPackageOutputPath)</Container>
</ArtifactInfo>
<ArtifactInfo Include="@(SignedPackageFile)" Condition=" '$(DisableCodeSigning)' != 'true' AND '$(IncludeSymbols)' == 'true' ">
<ArtifactInfo Include="@(_SignedPackageFile)" Condition=" '$(DisableCodeSigning)' != 'true' AND '$(IncludeSymbols)' == 'true' ">
<ShouldBeSigned>true</ShouldBeSigned>
<Container>$(SymbolsPackageOutputPath)</Container>
</ArtifactInfo>
<ArtifactInfo Include="@(ExcludePackageFileFromSigning)" Condition="'$(IncludeSymbols)' == 'true' ">
<ArtifactInfo Include="@(_ExcludePackageFileFromSigning)" Condition="'$(IncludeSymbols)' == 'true' ">
<ShouldBeSigned>false</ShouldBeSigned>
<Container>$(SymbolsPackageOutputPath)</Container>
</ArtifactInfo>
@ -77,6 +85,43 @@
</Target>
<!--
####################################################################################
Target: GetPackageFilesExcludedFromSigning
Collect ExcludePackageFileFromSigning items in multi-TFM projects
Items:
[out] ExcludePackageFileFromSigning
#####################################################################################
-->
<PropertyGroup>
<!-- For single-TFM projects -->
<GetPackageFilesExcludedFromSigningDependsOn Condition=" '$(TargetFramework)' != '' ">
_GetPackageFilesExcludedFromSigning
</GetPackageFilesExcludedFromSigningDependsOn>
</PropertyGroup>
<Target Name="GetPackageFilesExcludedFromSigning" DependsOnTargets="$(GetPackageFilesExcludedFromSigningDependsOn)" Returns="@(ExcludePackageFileFromSigning)">
<ItemGroup Condition=" '$(TargetFramework)' == '' ">
<_TargetFrameworks Remove="@(_TargetFrameworks)" />
<_TargetFrameworks Include="$(TargetFrameworks)" />
</ItemGroup>
<MSBuild Projects="$(MSBuildProjectFullPath)"
Properties="TargetFramework=%(_TargetFrameworks.Identity)"
Targets="GetPackageFilesExcludedFromSigning"
Condition=" '%(_TargetFrameworks.Identity)' != '' AND '$(TargetFramework)' == '' "
BuildInParallel="true">
<Output TaskParameter="TargetOutputs" ItemName="ExcludePackageFileFromSigning" />
</MSBuild>
</Target>
<Target Name="_GetPackageFilesExcludedFromSigning"
Condition=" '$(TargetFramework)' != '' AND '$(DisableCodeSigning)' != 'true' "
Returns="@(ExcludePackageFileFromSigning)" />
<!--
####################################################################################
Target: GetSignedPackageFiles
@ -112,18 +157,24 @@ Items:
</Target>
<Target Name="_GetSignedPackageFiles"
Condition=" '$(TargetFramework)' != '' "
Condition=" '$(TargetFramework)' != '' AND '$(DisableCodeSigning)' != 'true' "
DependsOnTargets="BuiltProjectOutputGroup;SatelliteDllsProjectOutputGroup">
<ItemGroup Condition=" '$(NuspecFile)' == '' AND '$(IncludeBuildOutput)' != 'false' AND ('$(AssemblySigningCertName)' != '' OR '$(AssemblySigningStrongName)' != '') ">
<PropertyGroup>
<_PackageBasePath>$(BuildOutputTargetFolder.TrimEnd('/'))</_PackageBasePath>
<_PackageBasePath>$(_PackageBasePath.TrimEnd('\'))</_PackageBasePath>
<_IsTestProject Condition=" '$(IsTestProject)' == 'true' OR ('$(IsTestProject)' == '' AND @(PackageReference->WithMetadataValue('Identity', 'Microsoft.NET.Test.Sdk')->Count()) != 0)">true</_IsTestProject>
</PropertyGroup>
<ItemGroup Condition=" '$(_IsTestProject)' != 'true' AND '$(NuspecFile)' == '' AND '$(IncludeBuildOutput)' != 'false' AND ('$(AssemblySigningCertName)' != '' OR '$(AssemblySigningStrongName)' != '') ">
<SignedPackageFile Include="@(BuiltProjectOutputGroupOutput)" Condition="'%(BuiltProjectOutputGroupOutput.Extension)' == '.dll' OR '%(BuiltProjectOutputGroupOutput.Extension)' == '.exe'">
<PackagePath>$(BuildOutputTargetFolder)/$(TargetFramework)/%(BuiltProjectOutputGroupOutput.FileName)%(BuiltProjectOutputGroupOutput.Extension)</PackagePath>
<PackagePath>$(_PackageBasePath)/$(TargetFramework)/%(BuiltProjectOutputGroupOutput.FileName)%(BuiltProjectOutputGroupOutput.Extension)</PackagePath>
<Certificate>$(AssemblySigningCertName)</Certificate>
<StrongName>$(AssemblySigningStrongName)</StrongName>
</SignedPackageFile>
<SignedPackageFile Include="@(SatelliteDllsProjectOutputGroupOutput)" Condition="'%(SatelliteDllsProjectOutputGroupOutput.Extension)' == '.dll' OR '%(SatelliteDllsProjectOutputGroupOutput.Extension)' == '.exe'">
<PackagePath>$(BuildOutputTargetFolder)/$(TargetFramework)/%(SatelliteDllsProjectOutputGroupOutput.FileName)%(SatelliteDllsProjectOutputGroupOutput.Extension)</PackagePath>
<PackagePath>$(_PackageBasePath)/$(TargetFramework)/%(SatelliteDllsProjectOutputGroupOutput.FileName)%(SatelliteDllsProjectOutputGroupOutput.Extension)</PackagePath>
<Certificate>$(AssemblySigningCertName)</Certificate>
<StrongName>$(AssemblySigningStrongName)</StrongName>
</SignedPackageFile>

Просмотреть файл

@ -125,15 +125,16 @@ Executes /t:Pack on all projects matching src/*/*.csproj.
-->
<Target Name="PackageProjects" DependsOnTargets="ResolveSolutions">
<PropertyGroup>
<PackageNoBuild Condition="'$(PackageNoBuild)' == ''">$(_SolutionWasBuilt)</PackageNoBuild>
<PackProperties>$(SolutionProperties);PackageOutputPath=$(BuildDir);</PackProperties>
<PackProperties Condition="'$(_SolutionWasBuilt)' == 'true'">$(PackProperties);NoBuild=true;BuildProjectReferences=false</PackProperties>
</PropertyGroup>
<MSBuild Targets="Pack"
Projects="@(ProjectsToPack)"
Condition="@(ProjectsToPack->Count()) != 0"
Properties="$(SolutionProperties);PackageOutputPath=$(BuildDir);NoBuild=$(PackageNoBuild)"
Properties="$(PackProperties)"
BuildInParallel="$(BuildInParallel)"
RemoveProperties="$(_BuildPropertiesToRemove);PackageNoBuild" />
RemoveProperties="$(_BuildPropertiesToRemove)" />
</Target>
<Target Name="GetProjectPackageInfo" Returns="@(ArtifactInfo)">
@ -150,7 +151,7 @@ Executes /t:Pack on all projects matching src/*/*.csproj.
Condition="@(ProjectsToPack->Count()) != 0"
Properties="$(SolutionProperties);EnableApiCheck=false;NoBuild=true;RepositoryRoot=$(RepositoryRoot);PackageOutputPath=$(BuildDir);CustomAfterMicrosoftCommonTargets=$(_InspectionTargetsFile);CustomAfterMicrosoftCommonCrossTargetingTargets=$(_InspectionTargetsFile)"
BuildInParallel="$(BuildInParallel)"
RemoveProperties="$(_BuildPropertiesToRemove);PackageNoBuild">
RemoveProperties="$(_BuildPropertiesToRemove)">
<Output TaskParameter="TargetOutputs" ItemName="_Temp" />
</MSBuild>

Просмотреть файл

@ -221,6 +221,18 @@ function Install-Tools(
else {
Write-Host -ForegroundColor DarkGray ".NET Core SDK $version is already installed. Skipping installation."
}
# This is a workaround for https://github.com/Microsoft/msbuild/issues/2914.
# Currently, the only way to configure the NuGetSdkResolver is with NuGet.config, which is not generally used in aspnet org projects.
# This project is restored so that it pre-populates the NuGet cache with SDK packages.
$restorerfile = "$PSScriptRoot/../modules/BundledPackages/BundledPackageRestorer.csproj"
$restorerfilelock="$env:NUGET_PACKAGES/internal.aspnetcore.sdk/$(Get-KoreBuildVersion)/korebuild.sentinel"
if ((Test-Path $restorerfile) -and -not (Test-Path $restorerfilelock)) {
New-Item -ItemType Directory $(Split-Path -Parent $restorerfilelock) -ErrorAction Ignore | Out-Null
New-Item -ItemType File $restorerfilelock -ErrorAction Ignore | Out-Null
__exec $global:dotnet msbuild '-t:restore' '-v:q' "$restorerfile"
}
# end workaround
}
<#

Просмотреть файл

@ -1,4 +1,5 @@
<Project>
<Import Project="..\..\build\dependencies.props" />
<Target Name="Publish">
@ -22,7 +23,13 @@
-->
<BundledPackageRestorerContent>
<![CDATA[
<Project Sdk="Microsoft.NET.Sdk">
<Project>
<PropertyGroup>
<ImportDirectoryBuildProps>false</ImportDirectoryBuildProps>
<ImportDirectoryBuildTargets>false</ImportDirectoryBuildTargets>
</PropertyGroup>
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<Sdk Name="Microsoft.DotNet.GlobalTools.Sdk" Version="$(Version)" />
@ -32,16 +39,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MicroBuild.Core" Version="$(MicroBuildCorePackageVersion)" />
<PackageReference Include="Internal.AspNetCore.Sdk" Version="$(Version)" />
</ItemGroup>
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>
]]>
</BundledPackageRestorerContent>
</PropertyGroup>
<WriteLinesToFile File="$(PublishDir)BundledPackageRestorer.csproj" Lines="$(BundledPackageRestorerContent)" Overwrite="true" />
<Copy SourceFiles="module.props;module.targets;NuGet.config" DestinationFolder="$(PublishDir)" />
<Copy SourceFiles="NuGet.config" DestinationFolder="$(PublishDir)" />
<DownloadFile SourceUrl="https://www.nuget.org/api/v2/package/MicroBuild.Core/$(MicroBuildCorePackageVersion)" DestinationFolder="$(PublishDir)" DestinationFileName="MicroBuild.Core.$(MicroBuildCorePackageVersion).nupkg" />
</Target>
</Project>

Просмотреть файл

@ -1,6 +0,0 @@
<Project>
<PropertyGroup>
<KoreBuildBundledPackageFolder>$(MSBuildThisFileDirectory)</KoreBuildBundledPackageFolder>
<SolutionProperties>$(SolutionProperties);KoreBuildBundledPackageFolder=$(KoreBuildBundledPackageFolder)</SolutionProperties>
</PropertyGroup>
</Project>

Просмотреть файл

@ -1,24 +0,0 @@
<Project InitialTargets="PreinstallBundledPackages">
<!--
This is a workaround for https://github.com/Microsoft/msbuild/issues/2914.
This pre-populates the NuGet cache with bundled packages.
-->
<Target Name="PreinstallBundledPackages" Condition="'$(DisableBundledPackages)' != 'true'">
<PropertyGroup>
<_BundledRestoreSentinel>$(MSBuildThisFileDirectory)restore.sentinel</_BundledRestoreSentinel>
<_ShouldRunBundledRestore Condition="Exists('$(_BundledRestoreSentinel)')">false</_ShouldRunBundledRestore>
</PropertyGroup>
<Touch
Files="$(_BundledRestoreSentinel)"
AlwaysCreate="true"
Condition=" ! Exists('$(_BundledRestoreSentinel)') "
ContinueOnError="true" />
<MSBuild Targets="Restore"
Projects="$(MSBuildThisFileDirectory)BundledPackageRestorer.csproj"
Properties="RestoreSources=$(KoreBuildBundledPackageFolder)"
Condition="'$(_ShouldRunBundledRestore)' != 'false'"
ContinueOnError="true" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,57 @@
<Project>
<Import Project="SignTool/build/Microsoft.DotNet.SignTool.props" />
<PropertyGroup>
<DisableCodeSigning Condition=" '$(OS)' != 'Windows_NT' ">true</DisableCodeSigning>
<!-- Relative paths in SignToolData.json are relative to this path -->
<SignToolDataWorkingDir Condition=" '$(SignToolDataWorkingDir)' == '' ">$(RepositoryRoot)</SignToolDataWorkingDir>
<!-- Dry run checks signing config without code signing. -->
<SignToolDryRun Condition=" '$(SignType)' != 'real' AND '$(SignType)' != 'test' ">true</SignToolDryRun>
<SignToolDryRun Condition=" '$(SignToolDryRun)' == '' ">false</SignToolDryRun>
<!-- Test signing (not commonly used) -->
<SignToolTestSign>false</SignToolTestSign>
<SignToolTestSign Condition=" '$(SignType)' == 'test' ">true</SignToolTestSign>
</PropertyGroup>
<Target Name="CodeSign" Condition=" '$(DisableCodeSigning)' != 'true' "
AfterTargets="Package"
DependsOnTargets="$(CodeSignDependsOn)">
<GetPathToFullMSBuild>
<Output TaskParameter="MSBuildx86Path" PropertyName="MSBuildx86Path" />
</GetPathToFullMSBuild>
<ItemGroup>
<!-- Reset internal item groups. -->
<_FileSignInfo Remove="@(_FileSignInfo)" />
<_ItemsToSign Remove="@(_ItemsToSign)" />
<!--
Map KoreBuild items into SignTool task items.
-->
<_FileSignInfo Include="%(FilesToSign.FileName)%(FilesToSign.Extension)" CertificateName="%(FilesToSign.Certificate)" />
<_FileSignInfo Include="%(FilesToExcludeFromSigning.FileName)%(FilesToExcludeFromSigning.Extension)" CertificateName="None" />
<!--
Only pass in top-level items. FilesToSign contains items which will be nested in a .nupkg or .vsix.
If this list isn't filtered, SignTool task will overwrite files in the obj/ folders of projects which breaks
incremental compilation.
-->
<_ItemsToSign Include="%(FilesToSign.Identity)" Condition=" '%(FilesToSign.Container)' == '' " />
</ItemGroup>
<Microsoft.DotNet.SignTool.SignToolTask
DryRun="$(SignToolDryRun)"
TestSign="$(SignToolTestSign)"
ItemsToSign="@(_ItemsToSign)"
FileSignInfo="@(_FileSignInfo)"
TempDir="$(IntermediateDir)"
LogDir="$(LogOutputDir)"
MSBuildPath="$(MSBuildx86Path)"
MicroBuildCorePath="$(NuGetPackageRoot)microbuild.core\$(MicroBuildCorePackageVersion)" />
</Target>
</Project>

Просмотреть файл

@ -1,204 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Framework;
namespace KoreBuild.Tasks
{
/// <summary>
/// Generates an XML document that can be passed to a tool for signing.
/// <para>
/// The items are expected to be files.
/// </para>
/// </summary>
public class GenerateSignRequest : Microsoft.Build.Utilities.Task
{
/// <summary>
/// Files or containers of files that should be signed.
/// Required metadata 'Certificate' or 'StrongName'. Both can be specified.
/// Optional metadata: 'IsContainer'. Set this to true for files that can be extract and have inner parts signed. For example, nupkg and vsix files.
/// </summary>
[Required]
public ITaskItem[] Requests { get; set; }
/// <summary>
/// Items that should explicitly be marked as 'excluded' in the sign request.
/// Only files in listed as a request item will be signed, but excluded files can be
/// added as well so tests can validate that all files in a container are accounted for.
/// </summary>
public ITaskItem[] Exclusions { get; set; }
/// <summary>
/// The folder that conatins all items. The sign request file paths will be normalized to this path.
/// </summary>
[Required]
public string BasePath { get; set; }
/// <summary>
/// The output path of the sign request file.
/// </summary>
[Required]
[Output]
public string OutputPath { get; set; }
public override bool Execute()
{
OutputPath = OutputPath.Replace('\\', '/');
BasePath = BasePath.Replace('\\', '/');
return Execute(() =>
{
Directory.CreateDirectory(Path.GetDirectoryName(OutputPath));
return File.CreateText(OutputPath);
});
}
internal bool Execute(Func<TextWriter> writerFactory)
{
var signRequestCollection = new SignRequestCollection();
var containers = new Dictionary<string, SignRequestItem.Container>(StringComparer.OrdinalIgnoreCase);
var isContainer = new bool[Requests.Length];
for (var i = 0; i < Requests.Length; i++)
{
var item = Requests[i];
if (bool.TryParse(item.GetMetadata("IsContainer"), out var isc) && isc)
{
isContainer[i] = true;
var type = item.GetMetadata("Type");
if (string.IsNullOrEmpty(type))
{
type = GetKnownContainerTypes(item);
}
if (string.IsNullOrEmpty(type))
{
Log.LogError($"Unknown container type for signed file request:'{item.ItemSpec}'. Signing request container must specify the metadata 'Type'.");
continue;
}
var normalizedPath = NormalizePath(BasePath, item.ItemSpec);
var container = new SignRequestItem.Container(
normalizedPath,
type,
item.GetMetadata("Certificate"),
item.GetMetadata("StrongName"));
containers[item.ItemSpec] = container;
signRequestCollection.Add(container);
}
}
for (var i = 0; i < Requests.Length; i++)
{
if (isContainer[i])
{
continue;
}
var item = Requests[i];
var normalizedPath = NormalizePath(BasePath, item.ItemSpec);
var containerPath = item.GetMetadata("Container");
if (!string.IsNullOrEmpty(containerPath))
{
if (!containers.TryGetValue(containerPath, out var container))
{
Log.LogError($"Signing request item '{item.ItemSpec}' specifies an unknown container '{containerPath}'.");
continue;
}
var packagePath = item.GetMetadata("PackagePath");
normalizedPath = string.IsNullOrEmpty(packagePath) ? normalizedPath : packagePath.Replace('\\', '/');
var file = new SignRequestItem.File(normalizedPath,
item.GetMetadata("Certificate"),
item.GetMetadata("StrongName"));
container.AddItem(file);
}
else
{
var file = new SignRequestItem.File(normalizedPath,
item.GetMetadata("Certificate"),
item.GetMetadata("StrongName"));
signRequestCollection.Add(file);
}
}
if (Exclusions != null)
{
foreach (var item in Exclusions)
{
var normalizedPath = NormalizePath(BasePath, item.ItemSpec);
var containerPath = item.GetMetadata("Container");
if (!string.IsNullOrEmpty(containerPath))
{
if (!containers.TryGetValue(containerPath, out var container))
{
Log.LogError($"Exclusion item '{item.ItemSpec}' specifies an unknown container '{containerPath}'.");
continue;
}
var packagePath = item.GetMetadata("PackagePath");
normalizedPath = string.IsNullOrEmpty(packagePath) ? normalizedPath : packagePath.Replace('\\', '/');
var file = new SignRequestItem.Exclusion(normalizedPath);
container.AddItem(file);
}
else
{
var file = new SignRequestItem.Exclusion(normalizedPath);
signRequestCollection.Add(file);
}
}
}
if (Log.HasLoggedErrors)
{
return false;
}
using (var stream = writerFactory())
using (var writer = new SignRequestCollectionXmlWriter(stream))
{
writer.Write(signRequestCollection);
}
Log.LogMessage($"Generated bill of materials in {OutputPath}");
return !Log.HasLoggedErrors;
}
private static string GetKnownContainerTypes(ITaskItem item)
{
string type = null;
switch (Path.GetExtension(item.ItemSpec).ToLowerInvariant())
{
case ".nupkg":
type = "nupkg";
break;
case ".zip":
type = "zip";
break;
case ".tar.gz":
case ".tgz":
type = "tar.gz";
break;
case ".vsix":
type = "vsix";
break;
case ".msi":
type = "msi";
break;
}
return type;
}
private static string NormalizePath(string basePath, string path)
{
return Path.GetRelativePath(basePath, path).Replace('\\', '/');
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.InteropServices;
using KoreBuild.Tasks.Utilities;
using Microsoft.Build.Framework;
namespace KoreBuild.Tasks
{
/// <summary>
/// Finds toolset information as listed in korebuild.json
/// </summary>
public class GetPathToFullMSBuild : Microsoft.Build.Utilities.Task
{
/// <summary>
/// The path to MSBuild.exe (x86).
/// </summary>
[Output]
public string MSBuildx86Path { get; set; }
public override bool Execute()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Log.LogError("Full MSBuild is not available on non-Windows.");
return false;
}
var vs = VsWhere.FindLatestInstallation(includePrerelease: true, Log);
if (vs == null)
{
Log.LogError($"Could not find an installation of Visual Studio.");
return false;
}
MSBuildx86Path = vs.GetMSBuildx86SubPath();
return !Log.HasLoggedErrors;
}
}
}

Просмотреть файл

@ -97,8 +97,8 @@ namespace KoreBuild.Tasks
{
if (vsToolset.Required != KoreBuildSettings.RequiredPlatforms.None)
{
Log.LogError($"Could not find an installation of Visual Studio that satisifies the specified requirements in {ConfigFile}. " +
"See https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community for more details on any missing components.");
Log.LogError($"Could not find an installation of Visual Studio that satisifies the specified requirements in '{ConfigFile}'. " +
"Execute `./run.ps1 install vs` to update or install the current VS installation.");
}
return;
}

Просмотреть файл

@ -1,23 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace KoreBuild.Tasks
{
internal class SignRequestCollection : IEnumerable<SignRequestItem>
{
private SortedDictionary<string, SignRequestItem> _items = new SortedDictionary<string, SignRequestItem>(StringComparer.Ordinal);
public IEnumerator<SignRequestItem> GetEnumerator() => _items.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _items.Values.GetEnumerator();
public void Add(SignRequestItem item)
{
_items.Add(item.Path, item);
}
}
}

Просмотреть файл

@ -1,104 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace KoreBuild.Tasks
{
internal class SignRequestCollectionXmlWriter : IDisposable
{
private readonly TextWriter output;
private readonly XDocument document;
public SignRequestCollectionXmlWriter(TextWriter output)
{
this.output = output;
document = new XDocument(new XElement("SignRequest"));
}
public void Save()
{
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
OmitXmlDeclaration = true,
Indent = true,
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace,
};
using (var writer = XmlWriter.Create(output, settings))
{
document.Save(writer);
}
}
public void Write(SignRequestCollection signRequestCollection)
{
var node = document.Root;
foreach (var request in signRequestCollection)
{
AddRequest(node, request);
}
}
private static void AddRequest(XElement parent, SignRequestItem item)
{
var path = new XAttribute("Path", item.Path);
switch (item)
{
case SignRequestItem.Container c:
var container = new XElement("Container",
path,
new XAttribute("Type", c.Type));
if (!string.IsNullOrEmpty(c.Certificate))
{
container.Add(new XAttribute("Certificate", c.Certificate));
}
if (!string.IsNullOrEmpty(c.StrongName))
{
container.Add(new XAttribute("StrongName", c.StrongName));
}
parent.Add(container);
foreach (var i in c.Items)
{
AddRequest(container, i);
}
break;
case SignRequestItem.Exclusion e:
parent.Add(new XElement("ExcludedFile", path));
break;
case SignRequestItem.File f:
var file = new XElement("File", path);
if (!string.IsNullOrEmpty(f.Certificate))
{
file.Add(new XAttribute("Certificate", f.Certificate));
}
if (!string.IsNullOrEmpty(f.StrongName))
{
file.Add(new XAttribute("StrongName", f.StrongName));
}
parent.Add(file);
break;
throw new InvalidOperationException("Unrecognized sign request item");
}
}
public void Dispose()
{
Save();
}
}
}

Просмотреть файл

@ -1,57 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace KoreBuild.Tasks
{
internal abstract class SignRequestItem
{
public SignRequestItem(string path)
{
Path = path ?? throw new ArgumentNullException(nameof(path));
}
public string Path { get; }
public class Exclusion : SignRequestItem
{
public Exclusion(string path) : base(path)
{
}
}
public class File : SignRequestItem
{
public File(string path, string certificate, string strongName) : base(path)
{
Certificate = certificate;
StrongName = strongName;
}
public string Certificate { get; }
public string StrongName { get; }
}
public class Container : File
{
private readonly SignRequestCollection _items = new SignRequestCollection();
public Container(string path, string type, string certificate, string strongName) : base(path, certificate, strongName)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
}
public IEnumerable<SignRequestItem> Items => _items;
public string Type { get; }
public Container AddItem(SignRequestItem item)
{
_items.Add(item);
return this;
}
}
}
}

Просмотреть файл

@ -3,7 +3,8 @@
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AssemblyName>Internal.AspNetCore.KoreBuild.Tasks</AssemblyName>
</PropertyGroup>
<SignToolDir>$(NuGetPackageRoot)/microsoft.dotnet.signtool/$(MicrosoftDotNetSignToolPackageVersion)/</SignToolDir>
</PropertyGroup>
<ItemGroup>
<Content Include="*.props" CopyToPublishDirectory="PreserveNewest" />
@ -12,8 +13,10 @@
<Compile Include="..\..\shared\Utilities\MSBuildListSplitter.cs" />
<Compile Include="..\..\tools\KoreBuildSettings.cs" />
<Content Include="$(VSWhereDir)vswhere.exe" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="$(SignToolDir)tools\**\*" Link="SignTool\tools\%(RecursiveDir)%(FileName)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="$(SignToolDir)build\**\*" Link="SignTool\build\%(RecursiveDir)%(FileName)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="$(MSBuildThisFileDirectory)SkipStrongNames.xml" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</ItemGroup>
<ItemGroup>
<!-- set as private assets all so these assemblies get resolved from the version bundled in the .NET Core SDK -->
@ -25,6 +28,23 @@
<PackageReference Include="NuGet.Build.Tasks" Version="$(Tooling_NuGetBuildTasksPackageVersion)" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.Json" Version="$(Tooling_NewtonsoftJsonPackageVersion)" PrivateAssets="All" />
<PackageReference Include="vswhere" Version="$(VSWherePackageVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.DotNet.SignTool" Version="$(MicrosoftDotNetSignToolPackageVersion)" ExcludeAssets="All" PrivateAssets="All" />
</ItemGroup>
<Target Name="PublishGeneratedProps" BeforeTargets="Publish">
<PropertyGroup>
<PackageVersionsPropsContent>
<![CDATA[
<Project>
<PropertyGroup>
<MicroBuildCorePackageVersion>$(MicroBuildCorePackageVersion)</MicroBuildCorePackageVersion>
</PropertyGroup>
</Project>
]]>
</PackageVersionsPropsContent>
</PropertyGroup>
<WriteLinesToFile File="$(PublishDir)PackageVersions.props" Lines="$(PackageVersionsPropsContent)" Overwrite="true" />
</Target>
</Project>

Просмотреть файл

@ -1,6 +1,13 @@
<Project>
<Import Project="PackageVersions.props" />
<PropertyGroup>
<KoreBuildTasksDll>$(MSBuildThisFileDirectory)Internal.AspNetCore.KoreBuild.Tasks.dll</KoreBuildTasksDll>
<CodeSignDependsOn>
GetArtifactInfo;
$(CodeSignDependsOn)
</CodeSignDependsOn>
</PropertyGroup>
<UsingTask TaskName="KoreBuild.Tasks.CheckPackageReferences" AssemblyFile="$(KoreBuildTasksDll)" />
@ -12,7 +19,7 @@
<UsingTask TaskName="KoreBuild.Tasks.FindVisualStudio" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.GenerateDependenciesPropsFile" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.GeneratePackageVersionPropsFile" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.GenerateSignRequest" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.GetPathToFullMSBuild" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.GetToolsets" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.InstallDotNet" AssemblyFile="$(KoreBuildTasksDll)" />
<UsingTask TaskName="KoreBuild.Tasks.PackNuSpec" AssemblyFile="$(KoreBuildTasksDll)" />

Просмотреть файл

@ -1,16 +1,13 @@
<Project>
<Import Project="CodeSign.targets" />
<PropertyGroup>
<PrepareDependsOn Condition=" '$(DisableDefaultTargets)' != 'true' ">GetToolsets;$(PrepareDependsOn)</PrepareDependsOn>
<RestoreDependsOn Condition=" '$(DisableDefaultTargets)' != 'true' ">InstallDotNet;CheckPackageReferences;$(RestoreDependsOn)</RestoreDependsOn>
<PackageDependsOn Condition=" '$(DisableDefaultTargets)' != 'true' ">$(PackageDependsOn);GenerateSignRequest</PackageDependsOn>
<GenerateSignRequest Condition="'$(GenerateSignRequest)' == ''">true</GenerateSignRequest>
<DisablePackageReferenceRestrictions Condition=" '$(DisablePackageReferenceRestrictions)' == '' ">false</DisablePackageReferenceRestrictions>
<KoreBuildConfigFile Condition="'$(KoreBuildConfigFile)' == ''">$(RepositoryRoot)korebuild.json</KoreBuildConfigFile>
<DependencyVersionsFile Condition="'$(DependencyVersionsFile)' == ''">$(RepositoryRoot)build\dependencies.props</DependencyVersionsFile>
<SignRequestOutputPath>$(ArtifactsDir)signrequest.xml</SignRequestOutputPath>
</PropertyGroup>
<!--
@ -145,7 +142,6 @@ and NodeJS.
</GetToolsets>
</Target>
<!--
####################################################################################
Target: VerifySignRequestItems
@ -155,28 +151,13 @@ Verifies all artifact items have a corresponding sign item.
-->
<Target Name="VerifySignRequestItems"
DependsOnTargets="GetArtifactInfo"
Condition="'$(GenerateSignRequest)' == 'true' AND '$(SkipArtifactVerification)' != 'true'">
Condition="'$(DisableCodeSigning)' != 'true' AND '$(SkipArtifactVerification)' != 'true'">
<ItemGroup>
<_ExpectedFileToSign Remove="@(_ExpectedFileToSign)" />
<_ExpectedFileToSign Include="@(ArtifactInfo)" />
<_ExpectedFileToSign Remove="@(FilesToSign);@(FilesToExcludeFromSigning);$(SignRequestOutputPath)" />
<_FilesToSignMissingConfig Remove="@(_FilesToSignMissingConfig)" />
<_FilesToSignMissingConfig Include="@(FilesToSign)" Condition=" '%(FilesToSign.Certificate)' == '' AND '%(FilesToSign.StrongName)' == '' AND '%(FilesToSign.IsContainer)' != 'true' " />
</ItemGroup>
<PropertyGroup>
<_SigningErrorMessage Condition=" @(_ExpectedFileToSign->Count()) != 0 ">
Could not determine signing information for all ArtifactInfo items.
Fix this error by adding these items to FilesToSign or FilesToExcludeFromSigning:
- @(_ExpectedFileToSign, '%0A - ')
</_SigningErrorMessage>
</PropertyGroup>
<Error Text="$(_SigningErrorMessage.Trim())"
Code="KRB5003"
Condition=" @(_ExpectedFileToSign->Count()) != 0 " />
<PropertyGroup>
<_SigningErrorMessage Condition=" @(_FilesToSignMissingConfig->Count()) != 0 ">
The following FilesToSign did not specify a Certificate or StrongName to use.
@ -189,34 +170,4 @@ The following FilesToSign did not specify a Certificate or StrongName to use.
Condition=" @(_FilesToSignMissingConfig->Count()) != 0 " />
</Target>
<!--
####################################################################################
Target: GenerateSignRequest
Generates a manifest that contains signing requests for files.
[in] (items) FilesToSign
[in] (items) FilesToExcludeFromSigning
[out] SignRequestOutputPath - the bom file
####################################################################################
-->
<ItemGroup Condition=" '$(GenerateSignRequest)' == 'true' ">
<ArtifactInfo Include="$(SignRequestOutputPath)">
<ArtifactType>XmlFile</ArtifactType>
<Category>noship</Category>
</ArtifactInfo>
</ItemGroup>
<Target Name="GenerateSignRequest"
DependsOnTargets="GetArtifactInfo;VerifySignRequestItems"
Condition=" '$(GenerateSignRequest)' == 'true' ">
<GenerateSignRequest
Requests="@(FilesToSign)"
Exclusions="@(FilesToExcludeFromSigning)"
BasePath="$(ArtifactsDir)"
OutputPath="$(SignRequestOutputPath)" />
</Target>
</Project>

Просмотреть файл

@ -31,7 +31,6 @@ namespace NuGetPackageVerifier.Rules
new PrereleaseDependenciesVersionRule(),
new PackageVersionMatchesAssemblyVersionRule(),
new BuildItemsRule(),
new SignRequestListsAllSignableFiles(),
};
}
}

Просмотреть файл

@ -34,7 +34,7 @@ namespace NuGetPackageVerifier.Logging
status = "NORMAL";
break;
default:
status = "INFORMATION";
status = "NORMAL";
break;
}

Просмотреть файл

@ -1,13 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace NuGetPackageVerifier.Manifests
{
public class PackageSignRequest
{
public ISet<string> FilesExcludedFromSigning { get; set; }
public ISet<string> FilesToSign { get; set; }
}
}

Просмотреть файл

@ -1,55 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace NuGetPackageVerifier.Manifests
{
public class SignRequestManifest
{
/// <summary>
/// Represents all signing requests in the sign request manifest that are for nupkg files.
/// </summary>
public IReadOnlyDictionary<string, PackageSignRequest> PackageSignRequests { get; private set; }
public static SignRequestManifest Parse(string filePath)
{
using (var reader = File.OpenText(filePath))
{
return Parse(reader, Path.GetDirectoryName(filePath));
}
}
public static SignRequestManifest Parse(TextReader reader, string manifestBasePath)
{
var doc = XDocument.Load(reader);
var requests = new Dictionary<string, PackageSignRequest>(StringComparer.OrdinalIgnoreCase);
var manifest = new SignRequestManifest { PackageSignRequests = requests };
var nupkgContainers = doc.Root
.Elements("Container")
.Where(c => "nupkg".Equals(c.Attribute("Type")?.Value, StringComparison.Ordinal));
foreach (var container in nupkgContainers)
{
var request = new PackageSignRequest
{
FilesToSign = container.Elements("File").Select(GetPath).ToHashSet(StringComparer.Ordinal),
FilesExcludedFromSigning = container.Elements("ExcludedFile").Select(GetPath).ToHashSet(StringComparer.Ordinal),
};
var path = new FileInfo(Path.Combine(manifestBasePath, GetPath(container))).FullName;
requests.Add(path, request);
}
return manifest;
}
private static string GetPath(XElement element) => element.Attribute("Path")?.Value;
}
}

Просмотреть файл

@ -6,7 +6,6 @@ using System.Collections.Generic;
using System.IO;
using NuGet.Packaging;
using NuGetPackageVerifier.Logging;
using NuGetPackageVerifier.Manifests;
namespace NuGetPackageVerifier
{
@ -15,7 +14,6 @@ namespace NuGetPackageVerifier
private PackageArchiveReader _reader;
public FileInfo PackageFileInfo { get; set; }
public PackageSignRequest SignRequest { get; set; }
public IPackageMetadata Metadata { get; set; }
public PackageVerifierOptions Options { get; set; }
public IPackageVerifierLogger Logger { get; set; }

Просмотреть файл

@ -37,15 +37,6 @@ namespace NuGetPackageVerifier
);
}
public static PackageVerifierIssue SignRequestMissingPackageFile(string id, string filePath)
{
return new PackageVerifierIssue(
"FILE_MISSING_FROM_SIGN_REQUEST",
filePath,
string.Format("The sign request for package {0} does not specify what to do with signable file {1}", id, filePath),
PackageIssueLevel.Error);
}
public static PackageVerifierIssue PackageTypeMissing(string packageType)
{
return new PackageVerifierIssue(

Просмотреть файл

@ -10,7 +10,6 @@ using Microsoft.Extensions.CommandLineUtils;
using Newtonsoft.Json;
using NuGet.Packaging;
using NuGetPackageVerifier.Logging;
using NuGetPackageVerifier.Manifests;
namespace NuGetPackageVerifier
{
@ -71,16 +70,17 @@ namespace NuGetPackageVerifier
});
var signRequestManifest = signRequest.HasValue()
? SignRequestManifest.Parse(signRequest.Value())
: default;
if (signRequest.HasValue())
{
Console.WriteLine("The --sign-request parameter is obsolete and will be ignored. It will be removed in a future version");
}
logger.LogNormal("Read {0} package set(s) from {1}", packageSets.Count, ruleFile.Value());
var nupkgs = new DirectoryInfo(packageDirectory.Value).EnumerateFiles("*.nupkg", SearchOption.TopDirectoryOnly)
.Where(p => !p.Name.EndsWith(".symbols.nupkg"))
.ToArray();
logger.LogNormal("Found {0} packages in {1}", nupkgs.Length, packageDirectory.Value);
var exitCode = Execute(packageSets, nupkgs, signRequestManifest, excludedRules.Values, logger, ignoreAssistanceMode);
var exitCode = Execute(packageSets, nupkgs, excludedRules.Values, logger, ignoreAssistanceMode);
totalTimeStopWatch.Stop();
logger.LogNormal("Total took {0}ms", totalTimeStopWatch.ElapsedMilliseconds);
@ -93,7 +93,6 @@ namespace NuGetPackageVerifier
private static int Execute(
IDictionary<string, PackageSet> packageSets,
IEnumerable<FileInfo> nupkgs,
SignRequestManifest signRequestManifest,
List<string> excludedRuleNames,
IPackageVerifierLogger logger,
IgnoreAssistanceMode ignoreAssistanceMode)
@ -185,9 +184,6 @@ namespace NuGetPackageVerifier
var package = packagePair.Key;
logger.LogInfo("Analyzing {0} ({1})", package.Id, package.Version);
PackageSignRequest signRequest = null;
signRequestManifest?.PackageSignRequests.TryGetValue(packagePair.Value.FullName, out signRequest);
List<PackageVerifierIssue> issues;
using (var context = new PackageAnalysisContext
{
@ -195,7 +191,6 @@ namespace NuGetPackageVerifier
Metadata = package,
Logger = logger,
Options = packageInfo.Value,
SignRequest = signRequest,
})
{
issues = analyzer.AnalyzePackage(context).ToList();
@ -250,9 +245,6 @@ namespace NuGetPackageVerifier
{
logger.LogInfo("Analyzing {0} ({1})", unlistedPackage.Id, unlistedPackage.Version);
PackageSignRequest signRequest = null;
signRequestManifest?.PackageSignRequests.TryGetValue(packages[unlistedPackage].FullName, out signRequest);
List<PackageVerifierIssue> issues;
PackageVerifierOptions packageOptions = null;
defaultPackageSet?.Packages?.TryGetValue(unlistedPackage.Id, out packageOptions);
@ -262,7 +254,6 @@ namespace NuGetPackageVerifier
PackageFileInfo = packages[unlistedPackage],
Metadata = unlistedPackage,
Logger = logger,
SignRequest = signRequest,
Options = packageOptions,
})
{

Просмотреть файл

@ -1,47 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using NuGetPackageVerifier.Logging;
namespace NuGetPackageVerifier.Rules
{
public class SignRequestListsAllSignableFiles : IPackageVerifierRule
{
private static readonly HashSet<string> SignableExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".dll",
".exe",
".ps1",
".psd1",
".psm1",
".psc1",
".ps1xml",
};
public IEnumerable<PackageVerifierIssue> Validate(PackageAnalysisContext context)
{
if (context.SignRequest == null)
{
context.Logger.Log(LogLevel.Info, "Skipping signing rule request verification for " + context.PackageFileInfo.FullName);
yield break;
}
foreach (var file in context.PackageReader.GetFiles())
{
var ext = Path.GetExtension(file);
if (!SignableExtensions.Contains(ext))
{
continue;
}
if (!context.SignRequest.FilesToSign.Contains(file) && !context.SignRequest.FilesExcludedFromSigning.Contains(file))
{
yield return PackageIssueFactory.SignRequestMissingPackageFile(context.Metadata.Id, file);
}
}
}
}
}

Просмотреть файл

@ -25,18 +25,12 @@ repository root.
<Packages Include="$(BuildDir)*.nupkg" />
</ItemGroup>
<PropertyGroup>
<_VerifierSignRequestPath />
<_VerifierSignRequestPath Condition=" '$(GenerateSignRequest)' == 'true' ">$(SignRequestOutputPath)</_VerifierSignRequestPath>
</PropertyGroup>
<Warning Text="No nupkg found in '$(BuildDir)'." Condition="$(Packages -> Count()) == 0" />
<Warning Text="Skipping nuget package verification because artifacts directory could not be found"
Condition="!Exists('$(BuildDir)')" />
<VerifyPackages ArtifactDirectory="$(BuildDir)"
RuleFile="$(NuGetVerifierRuleFile)"
SignRequestManifest="$(_VerifierSignRequestPath)"
Condition="Exists('$(BuildDir)')" />
</Target>

Просмотреть файл

@ -27,8 +27,6 @@ namespace NuGetPackagerVerifier
public string[] ExcludedRules { get; set; }
public string SignRequestManifest { get; set; }
public override bool Execute()
{
if (string.IsNullOrEmpty(RuleFile) || !File.Exists(RuleFile))
@ -59,18 +57,6 @@ namespace NuGetPackagerVerifier
ArtifactDirectory,
};
if (!string.IsNullOrEmpty(SignRequestManifest))
{
if (!File.Exists(SignRequestManifest))
{
Log.LogError($"SignRequestManifest file {SignRequestManifest} does not exist.");
return false;
}
arguments.Add("--sign-request");
arguments.Add(SignRequestManifest);
}
foreach (var rule in ExcludedRules ?? Enumerable.Empty<string>())
{
arguments.Add("--excluded-rule");

Просмотреть файл

@ -52,8 +52,8 @@ in the file are overridden by command line parameters.
Example config file:
```json
{
"$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json",
"channel": "dev",
"$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json",
"channel": "master",
"toolsSource": "https://aspnetcore.blob.core.windows.net/buildtools"
}
```
@ -179,8 +179,9 @@ if (Test-Path $ConfigFile) {
}
}
catch {
Write-Warning "$ConfigFile could not be read. Its settings will be ignored."
Write-Warning $Error[0]
Write-Host -ForegroundColor Red $Error[0]
Write-Error "$ConfigFile contains invalid JSON."
exit 1
}
}

Просмотреть файл

@ -222,17 +222,28 @@ if [ -f "$config_file" ]; then
config_channel="$(jq -r 'select(.channel!=null) | .channel' "$config_file")"
config_tools_source="$(jq -r 'select(.toolsSource!=null) | .toolsSource' "$config_file")"
else
__warn "$config_file is invalid JSON. Its settings will be ignored."
__error "$config_file contains invalid JSON."
exit 1
fi
elif __machine_has python ; then
if python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then
config_channel="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")"
config_tools_source="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")"
else
__warn "$config_file is invalid JSON. Its settings will be ignored."
__error "$config_file contains invalid JSON."
exit 1
fi
elif __machine_has python3 ; then
if python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then
config_channel="$(python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")"
config_tools_source="$(python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")"
else
__error "$config_file contains invalid JSON."
exit 1
fi
else
__warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.'
__error 'Missing required command: jq or python. Could not parse the JSON file.'
exit 1
fi
[ ! -z "${config_channel:-}" ] && channel="$config_channel"

Просмотреть файл

@ -28,6 +28,16 @@ Usage: this should be imported once via NuGet at the top of the file.
<SuppressNETCoreSdkPreviewMessage>true</SuppressNETCoreSdkPreviewMessage>
</PropertyGroup>
<!-- Code signing certificate names -->
<PropertyGroup Condition=" '$(DisableCodeSigning)' != 'true' ">
<AssemblySigningCertName>Microsoft400</AssemblySigningCertName>
<AssemblySigning3rdPartyCertName>3PartySHA2</AssemblySigning3rdPartyCertName>
<PowerShellSigningCertName>Microsoft400</PowerShellSigningCertName>
<PackageSigningCertName>NuGet</PackageSigningCertName>
<VsixSigningCertName>VsixSHA2</VsixSigningCertName>
<JarSigningCertName>MicrosoftJAR</JarSigningCertName>
</PropertyGroup>
<!-- common build options -->
<PropertyGroup>
<!-- make disabling warnings opt-out -->

Просмотреть файл

@ -10,8 +10,9 @@ For single-tfm projects, this will be imported from build/Internal.AspNetCore.Sd
-->
<Project>
<!-- workaround https://github.com/NuGet/Home/issues/4726 -->
<PropertyGroup>
<!-- Suppress warnings about using semver 2.0 versions in packages -->
<NoWarn>$(NoWarn);NU5105</NoWarn>
<IncludeSymbols Condition="'$(NuspecFile)'!=''">false</IncludeSymbols>
</PropertyGroup>

Просмотреть файл

@ -0,0 +1,21 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<GetSignedPackageFilesDependsOn>$(GetSignedPackageFilesDependsOn);_GetSignedPackageFilesForGeneratedShims</GetSignedPackageFilesDependsOn>
<PackagedShimOutputRootDirectory>$(OutDir)</PackagedShimOutputRootDirectory>
</PropertyGroup>
<Target Name="_GetSignedPackageFilesForGeneratedShims" Condition="'$(AssemblySigningCertName)' != ''">
<ItemGroup>
<_ShimRids Include="$(PackAsToolShimRuntimeIdentifiers)" />
<SignedPackageFile Condition="'%(_ShimRids.Identity)' != ''" Include="$(PackagedShimOutputRootDirectory)shims/$(TargetFramework)/%(_ShimRids.Identity)/$(AssemblyName).exe" Certificate="$(AssemblySigningCertName)">
<PackagePath>tools/$(TargetFramework)/any/shims/%(_ShimRids.Identity)/</PackagePath>
</SignedPackageFile>
<SignedPackageFile Include="$(TargetPath)" Certificate="$(AssemblySigningCertName)">
<PackagePath>tools/$(TargetFramework)/any/$(TargetFileName)</PackagePath>
</SignedPackageFile>
</ItemGroup>
</Target>
</Project>

Просмотреть файл

@ -18,7 +18,7 @@
Only set this in CI builds, otherwise it will mess up the debugger.
-->
<DeterministicSourceRoot Condition=" '$(CI)' == 'true' ">/_/</DeterministicSourceRoot>
<DeterministicSourceRoot Condition=" '$(CI)' == 'true' AND '$(RepositoryRoot)' != '' ">/_/</DeterministicSourceRoot>
<SourceLinkRoot Condition="'$(DeterministicSourceRoot)' != ''">$(DeterministicSourceRoot)</SourceLinkRoot>
<SourceLinkRoot Condition="'$(SourceLinkRoot)' == '' AND '$(RepositoryRoot)' != ''">$([MSBuild]::NormalizeDirectory($(RepositoryRoot)))</SourceLinkRoot>

Просмотреть файл

@ -9,6 +9,10 @@ for use outside of Microsoft.
<Import Project="$(MSBuildThisFileDirectory)GenerateAssemblyInfo.targets" />
<Import Project="$(MSBuildThisFileDirectory)Git.targets" />
<Import
Project="DotNetTool.targets"
Condition="'$(PackAsTool)' == 'true' AND '$(TargetFramework)' != ''" />
<Target Name="Resx"
DependsOnTargets="PrepareResourceNames;_CoreGenerateCSharpForResources" />

Просмотреть файл

@ -4,6 +4,15 @@ for use outside of Microsoft.
-->
<Project>
<ItemDefinitionGroup>
<SignedPackageFile>
<Visible>false</Visible>
</SignedPackageFile>
<ExcludePackageFileFromSigning>
<Visible>false</Visible>
</ExcludePackageFileFromSigning>
</ItemDefinitionGroup>
<Import Project="$(MSBuildThisFileDirectory)..\build\Common.props" />
</Project>

Просмотреть файл

@ -57,67 +57,6 @@ namespace KoreBuild.FunctionalTests
Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.CliTool.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages");
Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.Lib.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages");
Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.Sources.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages");
// /t:GenerateSigningRequest
var signRequest = Path.Combine(app.WorkingDirectory, "artifacts", "signrequest.xml");
Assert.True(File.Exists(signRequest), "Sign requests should have been generated");
var sign = XDocument.Load(signRequest);
var excluded = Assert.Single(sign.Descendants("ExcludedFile"));
Assert.Equal("build/Simple.Sources.1.0.0-beta-0001.nupkg", excluded.Attribute("Path")?.Value);
Assert.Collection(sign.Descendants("Container"),
pkg =>
{
Assert.Equal("build/Simple.CliTool.1.0.0-beta-0001.nupkg", pkg.Attribute("Path")?.Value);
Assert.Null(pkg.Attribute("Certificate"));
Assert.Equal("nupkg", pkg.Attribute("Type")?.Value);
Assert.Collection(pkg.Descendants("File"),
a =>
{
Assert.Equal("tools/any/any/Newtonsoft.Json.dll", a.Attribute("Path")?.Value);
Assert.Equal("Test3rdPartyCert", a.Attribute("Certificate")?.Value);
},
a =>
{
Assert.Equal("tools/any/any/cowsay.dll", a.Attribute("Path")?.Value);
Assert.Equal("TestCert", a.Attribute("Certificate")?.Value);
});
},
pkg =>
{
Assert.Equal("build/Simple.Lib.1.0.0-beta-0001.nupkg", pkg.Attribute("Path")?.Value);
Assert.Null(pkg.Attribute("Certificate"));
Assert.Equal("nupkg", pkg.Attribute("Type")?.Value);
Assert.Collection(pkg.Descendants("File"),
a =>
{
Assert.Equal("lib/net461/Simple.Lib.dll", a.Attribute("Path")?.Value);
Assert.Equal("TestCert", a.Attribute("Certificate")?.Value);
},
a =>
{
Assert.Equal("lib/netstandard2.0/Simple.Lib.dll", a.Attribute("Path")?.Value);
Assert.Equal("TestCert", a.Attribute("Certificate")?.Value);
});
},
pkg =>
{
Assert.Equal("build/Simple.Lib.1.0.0-beta-0001.symbols.nupkg", pkg.Attribute("Path")?.Value);
Assert.Null(pkg.Attribute("Certificate"));
Assert.Equal("nupkg", pkg.Attribute("Type")?.Value);
Assert.Equal("nupkg", pkg.Attribute("Type")?.Value);
Assert.Collection(pkg.Descendants("File"),
a =>
{
Assert.Equal("lib/net461/Simple.Lib.dll", a.Attribute("Path")?.Value);
Assert.Equal("TestCert", a.Attribute("Certificate")?.Value);
},
a =>
{
Assert.Equal("lib/netstandard2.0/Simple.Lib.dll", a.Attribute("Path")?.Value);
Assert.Equal("TestCert", a.Attribute("Certificate")?.Value);
});
});
}
[Fact]

Просмотреть файл

@ -1,92 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.IO;
using System.Text;
using BuildTools.Tasks.Tests;
using Microsoft.Build.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace KoreBuild.Tasks.Tests
{
public class GenerateSignRequestTests
{
private readonly ITestOutputHelper _output;
public GenerateSignRequestTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ItCreatesSignRequest()
{
var nupkgPath = Path.Combine(AppContext.BaseDirectory, "build", "MyLib.nupkg");
var requests = new[]
{
new TaskItem(Path.Combine(AppContext.BaseDirectory, "build", "ZZApp.vsix"),
new Hashtable
{
["IsContainer"] = "true",
["Certificate"] = "Cert4",
}),
new TaskItem(nupkgPath,
new Hashtable
{
["IsContainer"] = "true",
["Type"] = "zip",
}),
new TaskItem(Path.Combine(AppContext.BaseDirectory, "MyLib.dll"),
new Hashtable
{
["Container"] = nupkgPath,
["PackagePath"] = "lib/netstandard2.0/MyLib.dll",
["Certificate"] = "Cert1",
["StrongName"] = "Key1",
}),
new TaskItem(Path.Combine(AppContext.BaseDirectory, "build", "MyLib.dll"),
new Hashtable
{
["Certificate"] = "Cert1",
}),
};
var exclusions = new[]
{
new TaskItem(Path.Combine(AppContext.BaseDirectory, "NotMyLib.dll"),
new Hashtable
{
["PackagePath"] = "lib/NotMyLib.dll",
["Container"] = nupkgPath,
})
};
var task = new GenerateSignRequest
{
Requests = requests,
BasePath = AppContext.BaseDirectory,
Exclusions = exclusions,
BuildEngine = new MockEngine(_output),
};
var sb = new StringBuilder();
Assert.True(task.Execute(() => new StringWriter(sb)), "Task should pass");
var expected = $@"<SignRequest>
<File Path=`build/MyLib.dll` Certificate=`Cert1` />
<Container Path=`build/MyLib.nupkg` Type=`zip`>
<ExcludedFile Path=`lib/NotMyLib.dll` />
<File Path=`lib/netstandard2.0/MyLib.dll` Certificate=`Cert1` StrongName=`Key1` />
</Container>
<Container Path=`build/ZZApp.vsix` Type=`vsix` Certificate=`Cert4` />
</SignRequest>".Replace('`', '"');
_output.WriteLine(sb.ToString());
Assert.Equal(expected, sb.ToString(), ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
}
}

Просмотреть файл

@ -1,93 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using NuGetPackageVerifier.Rules;
using NuGetPackageVerifier.Tests.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace NuGetPackageVerifier.Tests
{
public class SignRequestListsAllSignableFilesRuleTests
{
private readonly ITestOutputHelper _output;
public SignRequestListsAllSignableFilesRuleTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ItFailsWhenPackageContainsUnlistedFiles()
{
var signRequest = @"
<SignRequest>
<Container Path=""TestPackage.1.0.0.nupkg"" Type=""nupkg"">
</Container>
</SignRequest>";
var context = TestHelper.CreateAnalysisContext(_output,
new[] { "lib/netstandard2.0/Test.dll", "tools/MyScript.psd1" },
signRequest: signRequest);
var rule = new SignRequestListsAllSignableFiles();
var errors = rule.Validate(context);
Assert.NotEmpty(errors);
Assert.Contains(errors, e =>
e.Instance.Equals("lib/netstandard2.0/Test.dll", StringComparison.Ordinal)
&& e.IssueId.Equals("FILE_MISSING_FROM_SIGN_REQUEST", StringComparison.Ordinal));
Assert.Contains(errors, e =>
e.Instance.Equals("tools/MyScript.psd1", StringComparison.Ordinal)
&& e.IssueId.Equals("FILE_MISSING_FROM_SIGN_REQUEST", StringComparison.Ordinal));
}
[Fact]
public void DoesNotFailWhenSignRequestIncludesAllFiles()
{
var signRequest = @"
<SignRequest>
<Container Path=""TestPackage.1.0.0.nupkg"" Type=""nupkg"">
<File Path=""lib/netstandard2.0/Test.dll"" />
<File Path=""tools/MyScript.psd1"" />
</Container>
</SignRequest>";
var context = TestHelper.CreateAnalysisContext(_output,
new[] { "lib/netstandard2.0/Test.dll", "tools/MyScript.psd1" },
signRequest: signRequest);
var rule = new SignRequestListsAllSignableFiles();
var errors = rule.Validate(context);
Assert.Empty(errors);
}
[Fact]
public void DoesNotFailWhenSignRequestListsAllFiles()
{
var signRequest = @"
<SignRequest>
<Container Path=""TestPackage.1.0.0.nupkg"" Type=""nupkg"">
<ExcludedFile Path=""lib/netstandard2.0/Test.dll"" />
<ExcludedFile Path=""tools/MyScript.psd1"" />
</Container>
</SignRequest>";
var context = TestHelper.CreateAnalysisContext(_output,
new[] { "lib/netstandard2.0/Test.dll", "tools/MyScript.psd1" },
signRequest: signRequest);
var rule = new SignRequestListsAllSignableFiles();
var errors = rule.Validate(context);
Assert.Empty(errors);
}
}
}

Просмотреть файл

@ -5,14 +5,13 @@ using System;
using System.IO;
using NuGet.Packaging;
using NuGet.Versioning;
using NuGetPackageVerifier.Manifests;
using Xunit.Abstractions;
namespace NuGetPackageVerifier.Tests.Utilities
{
public class TestHelper
{
public static PackageAnalysisContext CreateAnalysisContext(ITestOutputHelper output, string[] emptyFiles, string version = "1.0.0", string signRequest = null)
public static PackageAnalysisContext CreateAnalysisContext(ITestOutputHelper output, string[] emptyFiles, string version = "1.0.0")
{
const string packageId = "TestPackage";
var basePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName());
@ -45,20 +44,10 @@ namespace NuGetPackageVerifier.Tests.Utilities
builder.Save(nupkg);
}
PackageSignRequest packageSignRequest = null;
if (signRequest != null)
{
var reader = new StringReader(signRequest);
var signManifest = SignRequestManifest.Parse(reader, basePath);
packageSignRequest = signManifest.PackageSignRequests[nupkgPath];
}
var context = new TempPackageAnalysisContext(basePath)
{
Logger = new TestLogger(output),
PackageFileInfo = new FileInfo(nupkgPath),
SignRequest = packageSignRequest,
Metadata = builder,
};

Просмотреть файл

@ -1,12 +1,10 @@
<Project>
<Sdk Name="Microsoft.NET.Sdk" />
<Sdk Name="Microsoft.DotNet.GlobalTools.Sdk" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<PackAsTool>true</PackAsTool>
<GenerateToolShims>true</GenerateToolShims>
<PackAsToolShimRuntimeIdentifiers>win-x64;win-x86</PackAsToolShimRuntimeIdentifiers>
</PropertyGroup>
</Project>

Просмотреть файл

@ -3,6 +3,15 @@
"rules": [
"AssemblyHasVersionAttributesRule",
"DotNetToolPackageRule"
]
],
"packages": {
"Simple.CliTool": {
"Exclusions": {
"VERSION_INFORMATIONALVERSION": {
"tools/netcoreapp2.1/any/Newtonsoft.Json.dll": "Example exclusion"
}
}
}
}
}
}

Просмотреть файл

@ -1,5 +1,5 @@
<Project>
<ItemGroup>
<DotNetCoreRuntime Include="1.1.4" />
<DotNetCoreRuntime Include="2.1.5" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,12 +0,0 @@
<Project>
<Import Project="..\Directory.Build.targets" />
<Target Name="PackGlobalTool" Condition="'$(PackageType)' == 'DotnetTool'" BeforeTargets="GenerateNuspec" DependsOnTargets="Publish">
<PropertyGroup>
<NuspecProperties>
publishDir=$(PublishDir);
version=$(PackageVersion);
targetframework=$(TargetFramework);
</NuspecProperties>
</PropertyGroup>
</Target>
</Project>

Просмотреть файл

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<DotNetCliTool>
<Commands>
<Command Name="cowsay" EntryPoint="cowsay.dll" Runner="dotnet" />
</Commands>
</DotNetCliTool>

Просмотреть файл

@ -6,21 +6,18 @@
<PackageType>DotnetTool</PackageType>
<AssemblyName>cowsay</AssemblyName>
<PackageId>Simple.CliTool</PackageId>
<PackAsTool>true</PackAsTool>
<PackAsToolShimRuntimeIdentifiers>win-x64;win-x86</PackAsToolShimRuntimeIdentifiers>
<AssemblySigningCertName>TestCert</AssemblySigningCertName>
<PackageSigningCertName></PackageSigningCertName>
<NuspecFile>$(MSBuildProjectName).nuspec</NuspecFile>
<PackageSigningCertName>MyPackageSigningCert</PackageSigningCertName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" PrivateAssets="All" Version="$(NewtonsoftJsonPackageVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonPackageVersion)" />
<PackageReference Include="Internal.AspNetCore.Sdk" PrivateAssets="All" Version="$(InternalAspNetCoreSdkPackageVersion)" />
<!-- Required to specify manually when using nuspec. -->
<SignedPackageFile Include="$(TargetPath)" Certificate="$(AssemblySigningCertName)" Visible="false">
<PackagePath>tools/any/any/$(TargetFileName)</PackagePath>
</SignedPackageFile>
<SignedPackageFile Include="$(PublishDir)Newtonsoft.Json.dll" Certificate="Test3rdPartyCert" Visible="false">
<PackagePath>tools/any/any/Newtonsoft.Json.dll</PackagePath>
<SignedPackageFile Include="$(PublishDir)Newtonsoft.Json.dll" Certificate="Test3rdPartyCert">
<PackagePath>tools/$(TargetFramework)/any/Newtonsoft.Json.dll</PackagePath>
</SignedPackageFile>
</ItemGroup>

Просмотреть файл

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>Simple.CliTool</id>
<version>$version$</version>
<authors>Microsoft</authors>
<description>Test</description>
<packageTypes>
<packageType name="DotnetTool" />
</packageTypes>
<dependencies />
</metadata>
<files>
<file src="$publishdir$" target="tools/any/any/" />
<file src="DotnetToolSettings.xml" target="tools/any/any/DotnetToolSettings.xml" />
</files>
</package>

Просмотреть файл

@ -3,8 +3,6 @@
<PropertyGroup>
<TargetFrameworks>netcoreapp2.1;net461</TargetFrameworks>
<TargetFrameworks Condition="'$(OS)' != 'Windows_NT'">netcoreapp2.1</TargetFrameworks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>