Ejemplo n.º 1
0
        public void InitializeForDotNetSdk_WhenArgumentIsNull_Throws()
        {
            ArgumentNullException exception = Assert.Throws <ArgumentNullException>(
                () => X509TrustStore.InitializeForDotNetSdk(logger: null));

            Assert.Equal("logger", exception.ParamName);
        }
Ejemplo n.º 2
0
        public void CreateX509ChainFactory_Always_ReturnsInstance()
        {
            IX509ChainFactory factory = X509TrustStore.CreateX509ChainFactory(_logger);

            Assert.IsType <DotNetDefaultTrustStoreX509ChainFactory>(factory);
            Assert.Equal(1, _logger.Messages.Count);
            Assert.Equal(1, _logger.VerboseMessages.Count);
            Assert.True(_logger.VerboseMessages.TryDequeue(out string actualMessage));
            Assert.Equal(Strings.ChainBuilding_UsingDefaultTrustStore, actualMessage);
        }
Ejemplo n.º 3
0
        public void CreateX509ChainFactoryForDotNetSdk_OnWindowsAlways_ReturnsInstance()
        {
            IX509ChainFactory factory = X509TrustStore.CreateX509ChainFactoryForDotNetSdk(
                _logger,
                _fallbackCertificateBundle);

            Assert.IsType <DotNetDefaultTrustStoreX509ChainFactory>(factory);

            // 1 message from the API under test and 2 messages from this test class's constructor
            Assert.Equal(3, _logger.Messages.Count);
            Assert.Equal(1, _logger.VerboseMessages.Count);
            Assert.True(_logger.VerboseMessages.TryDequeue(out string actualMessage));
            Assert.Equal(Strings.ChainBuilding_UsingDefaultTrustStore, actualMessage);
        }
Ejemplo n.º 4
0
        public void CreateX509ChainFactoryForDotNetSdk_OnLinuxAlways_ReturnsInstance()
        {
            IX509ChainFactory factory = X509TrustStore.CreateX509ChainFactoryForDotNetSdk(
                _logger,
                _fallbackCertificateBundle);

            bool wasFound = TryReadFirstBundle(
                SystemCertificateBundleX509ChainFactory.ProbePaths,
                out X509Certificate2Collection certificates,
                out string _);
            var certificateBundleFactory = (CertificateBundleX509ChainFactory)factory;

            if (wasFound)
            {
                Assert.IsType <SystemCertificateBundleX509ChainFactory>(factory);
                Assert.Equal(certificates.Count, certificateBundleFactory.Certificates.Count);
            }
            else
            {
                Assert.IsType <FallbackCertificateBundleX509ChainFactory>(factory);
                Assert.True(certificateBundleFactory.Certificates.Count > 0);
            }

            // 1 message from the API under test and 2 messages from this test class's constructor
            Assert.Equal(3, _logger.Messages.Count);
            Assert.Equal(1, _logger.VerboseMessages.Count);
            Assert.True(_logger.VerboseMessages.TryDequeue(out string actualMessage));

            string expectedMessage;

            if (wasFound)
            {
                expectedMessage = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.ChainBuilding_UsingSystemCertificateBundle,
                    certificateBundleFactory.FilePath);
            }
            else
            {
                expectedMessage = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.ChainBuilding_UsingFallbackCertificateBundle,
                    certificateBundleFactory.FilePath);
            }

            Assert.Equal(expectedMessage, actualMessage);
        }
Ejemplo n.º 5
0
        public void CreateX509ChainFactoryForDotNetSdk_OnMacOsAlways_ReturnsInstance()
        {
            IX509ChainFactory factory = X509TrustStore.CreateX509ChainFactoryForDotNetSdk(
                _logger,
                _fallbackCertificateBundle);

            Assert.IsType <FallbackCertificateBundleX509ChainFactory>(factory);

            string expectedMessage = string.Format(
                CultureInfo.CurrentCulture,
                Strings.ChainBuilding_UsingFallbackCertificateBundle,
                ((CertificateBundleX509ChainFactory)factory).FilePath);

            // 1 message from the API under test and 2 messages from this test class's constructor
            Assert.Equal(3, _logger.Messages.Count);
            Assert.Equal(1, _logger.VerboseMessages.Count);
            Assert.True(_logger.VerboseMessages.TryDequeue(out string actualMessage));
            Assert.Equal(expectedMessage, actualMessage);
        }
Ejemplo n.º 6
0
        public static async Task <bool> RestoreAsync(
            DependencyGraphSpec dependencyGraphSpec,
            bool interactive,
            bool recursive,
            bool noCache,
            bool ignoreFailedSources,
            bool disableParallel,
            bool force,
            bool forceEvaluate,
            bool hideWarningsAndErrors,
            bool restorePC,
            bool cleanupAssetsForUnsupportedProjects,
            Common.ILogger log,
            CancellationToken cancellationToken)
        {
            if (dependencyGraphSpec == null)
            {
                throw new ArgumentNullException(nameof(dependencyGraphSpec));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                // Set connection limit
                NetworkProtocolUtility.SetConnectionLimit();

                // Set user agent string used for network calls
#if IS_CORECLR
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet .NET Core MSBuild Task")
                                             .WithOSDescription(RuntimeInformation.OSDescription));
#else
                // OS description is set by default on Desktop
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet Desktop MSBuild Task"));
#endif

                X509TrustStore.InitializeForDotNetSdk(log);

                var restoreSummaries = new List <RestoreSummary>();
                var providerCache    = new RestoreCommandProvidersCache();

#if IS_DESKTOP
                if (restorePC && dependencyGraphSpec.Projects.Any(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
                {
                    var v2RestoreResult = await PerformNuGetV2RestoreAsync(log, dependencyGraphSpec, noCache, disableParallel, interactive);

                    restoreSummaries.Add(v2RestoreResult);

                    if (restoreSummaries.Count < 1)
                    {
                        var message = string.Format(
                            Strings.InstallCommandNothingToInstall,
                            "packages.config"
                            );

                        log.LogMinimal(message);
                    }

                    if (!v2RestoreResult.Success)
                    {
                        v2RestoreResult
                        .Errors
                        .Where(l => l.Level == LogLevel.Warning)
                        .ForEach(message =>
                        {
                            log.LogWarning(message.Message);
                        });
                    }
                }
#endif

                using (var cacheContext = new SourceCacheContext())
                {
                    cacheContext.NoCache             = noCache;
                    cacheContext.IgnoreFailedSources = ignoreFailedSources;

                    // Pre-loaded request provider containing the graph file
                    var providers = new List <IPreLoadedRestoreRequestProvider>();

                    if (dependencyGraphSpec.Restore.Count > 0)
                    {
                        // Add all child projects
                        if (recursive)
                        {
                            AddAllProjectsForRestore(dependencyGraphSpec);
                        }

                        providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dependencyGraphSpec));

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext    = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                            // The workaround is to pass the '--disable-parallel' option.
                            // We apply the workaround by default when the system has 1 cpu.
                            // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                            DisableParallel           = Environment.ProcessorCount == 1 ? true : disableParallel,
                            Log                       = log,
                            MachineWideSettings       = new XPlatMachineWideSetting(),
                            PreLoadedRequestProviders = providers,
                            AllowNoOp                 = !force,
                            HideWarningsAndErrors     = hideWarningsAndErrors,
                            RestoreForceEvaluate      = forceEvaluate
                        };

                        if (restoreContext.DisableParallel)
                        {
                            HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        restoreSummaries.AddRange(await RestoreRunner.RunAsync(restoreContext, cancellationToken));
                    }

                    if (cleanupAssetsForUnsupportedProjects)
                    {
                        // Restore assets are normally left on disk between restores for all projects.  This can cause a condition where a project that supports PackageReference was restored
                        // but then a user changes a branch or some other condition and now the project does not use PackageReference. Since the restore assets are left on disk, the build
                        // consumes them which can cause build errors. The code below cleans up all of the files that we write so that they are not used during build
                        Parallel.ForEach(dependencyGraphSpec.Projects.Where(i => !DoesProjectSupportRestore(i)), project =>
                        {
                            if (project.RestoreMetadata == null || string.IsNullOrWhiteSpace(project.RestoreMetadata.OutputPath) || string.IsNullOrWhiteSpace(project.RestoreMetadata.ProjectPath))
                            {
                                return;
                            }

                            // project.assets.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName));

                            // project.csproj.nuget.cache
                            FileUtility.Delete(project.RestoreMetadata.CacheFilePath);

                            // project.csproj.nuget.g.props
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.PropsExtension));

                            // project..csproj.nuget.g.targets
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.TargetsExtension));

                            // project.csproj.nuget.dgspec.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, DependencyGraphSpec.GetDGSpecFileName(Path.GetFileName(project.RestoreMetadata.ProjectPath))));
                        });
                    }
                }

                if (restoreSummaries.Count < 1)
                {
                    log.LogMinimal(Strings.NoProjectsToRestore);
                }
                else
                {
                    RestoreSummary.Log(log, restoreSummaries);
                }
                return(restoreSummaries.All(x => x.Success));
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
Ejemplo n.º 7
0
        private static async Task <int> ExecuteCommand(TrustCommand action,
                                                       CommandOption algorithm,
                                                       bool allowUntrustedRootOption,
                                                       CommandOption owners,
                                                       CommandOption verbosity,
                                                       CommandOption configFile,
                                                       Func <ILogger> getLogger,
                                                       Action <LogLevel> setLogLevel,
                                                       string name        = null,
                                                       string sourceUrl   = null,
                                                       string packagePath = null,
                                                       string fingerprint = null)
        {
            ILogger logger = getLogger();

            try
            {
                ISettings settings = XPlatUtility.ProcessConfigFile(configFile.Value());

                var trustedSignersArgs = new TrustedSignersArgs()
                {
                    Action                 = MapTrustEnumAction(action),
                    PackagePath            = packagePath,
                    Name                   = name,
                    ServiceIndex           = sourceUrl,
                    CertificateFingerprint = fingerprint,
                    FingerprintAlgorithm   = algorithm?.Value(),
                    AllowUntrustedRoot     = allowUntrustedRootOption,
                    Author                 = action == TrustCommand.Author,
                    Repository             = action == TrustCommand.Repository,
                    Owners                 = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners?.Values),
                    Logger                 = logger
                };

                setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));

                // Add is the only action which does certificate chain building.
                if (trustedSignersArgs.Action == TrustedSignersAction.Add)
                {
                    X509TrustStore.InitializeForDotNetSdk(logger);
                }

#pragma warning disable CS0618 // Type or member is obsolete
                var sourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false);
#pragma warning restore CS0618 // Type or member is obsolete
                var trustedSignersProvider = new TrustedSignersProvider(settings);

                var        runner          = new TrustedSignersCommandRunner(trustedSignersProvider, sourceProvider);
                Task <int> trustedSignTask = runner.ExecuteCommandAsync(trustedSignersArgs);
                return(await trustedSignTask);
            }
            catch (InvalidOperationException e)
            {
                // nuget trust command handled exceptions.
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var error_TrustedSignerAlreadyExistsMessage = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedSignerAlreadyExists, name);

                    if (e.Message == error_TrustedSignerAlreadyExistsMessage)
                    {
                        logger.LogError(error_TrustedSignerAlreadyExistsMessage);
                        return(1);
                    }
                }

                if (!string.IsNullOrWhiteSpace(sourceUrl))
                {
                    var error_TrustedRepoAlreadyExists = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedRepoAlreadyExists, sourceUrl);

                    if (e.Message == error_TrustedRepoAlreadyExists)
                    {
                        logger.LogError(error_TrustedRepoAlreadyExists);
                        return(1);
                    }
                }

                throw;
            }
            catch (ArgumentException e)
            {
                if (e.Data is System.Collections.IDictionary)
                {
                    logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustFingerPrintAlreadyExist));
                    return(1);
                }

                throw;
            }
        }
Ejemplo n.º 8
0
        internal static void Register(CommandLineApplication app,
                                      Func <ILogger> getLogger,
                                      Action <LogLevel> setLogLevel,
                                      Func <IVerifyCommandRunner> getCommandRunner)
        {
            app.Command("verify", verifyCmd =>
            {
                CommandArgument packagePaths = verifyCmd.Argument(
                    "<package-paths>",
                    Strings.VerifyCommandPackagePathDescription,
                    multipleValues: true);

                CommandOption all = verifyCmd.Option(
                    "--all",
                    Strings.VerifyCommandAllDescription,
                    CommandOptionType.NoValue);

                CommandOption fingerPrint = verifyCmd.Option(
                    "--certificate-fingerprint",
                    Strings.VerifyCommandCertificateFingerprintDescription,
                    CommandOptionType.MultipleValue);

                CommandOption configFile = verifyCmd.Option(
                    "--configfile",
                    Strings.Option_ConfigFile,
                    CommandOptionType.SingleValue);

                CommandOption verbosity = verifyCmd.Option(
                    "-v|--verbosity",
                    Strings.Verbosity_Description,
                    CommandOptionType.SingleValue);

                verifyCmd.HelpOption(XPlatUtility.HelpOption);
                verifyCmd.Description = Strings.VerifyCommandDescription;

                verifyCmd.OnExecute(async() =>
                {
                    ValidatePackagePaths(packagePaths);

                    VerifyArgs args    = new VerifyArgs();
                    args.PackagePaths  = packagePaths.Values;
                    args.Verifications = all.HasValue() ?
                                         new List <Verification>()
                    {
                        Verification.All
                    } :
                    new List <Verification>()
                    {
                        Verification.Signatures
                    };
                    args.CertificateFingerprint = fingerPrint.Values;
                    args.Logger   = getLogger();
                    args.Settings = XPlatUtility.ProcessConfigFile(configFile.Value());
                    setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));

                    X509TrustStore.InitializeForDotNetSdk(args.Logger);

                    var runner     = getCommandRunner();
                    var verifyTask = runner.ExecuteCommandAsync(args);
                    await verifyTask;

                    return(verifyTask.Result);
                });
            });
        }
Ejemplo n.º 9
0
        internal static void Register(CommandLineApplication app,
                                      Func <ILogger> getLogger,
                                      Action <LogLevel> setLogLevel,
                                      Func <ISignCommandRunner> getCommandRunner)
        {
            app.Command(CommandName, signCmd =>
            {
                CommandArgument packagePaths = signCmd.Argument(
                    "<package-paths>",
                    Strings.SignCommandPackagePathDescription,
                    multipleValues: true);

                CommandOption outputDirectory = signCmd.Option(
                    "-o|--output",
                    Strings.SignCommandOutputDirectoryDescription,
                    CommandOptionType.SingleValue);

                CommandOption path = signCmd.Option(
                    "--certificate-path",
                    Strings.SignCommandCertificatePathDescription,
                    CommandOptionType.SingleValue);

                CommandOption store = signCmd.Option(
                    "--certificate-store-name",
                    Strings.SignCommandCertificateStoreNameDescription,
                    CommandOptionType.SingleValue);

                CommandOption location = signCmd.Option(
                    "--certificate-store-location",
                    Strings.SignCommandCertificateStoreLocationDescription,
                    CommandOptionType.SingleValue);

                CommandOption subject = signCmd.Option(
                    "--certificate-subject-name",
                    Strings.SignCommandCertificateSubjectNameDescription,
                    CommandOptionType.SingleValue);

                CommandOption fingerprint = signCmd.Option(
                    "--certificate-fingerprint",
                    Strings.SignCommandCertificateFingerprintDescription,
                    CommandOptionType.SingleValue);

                CommandOption password = signCmd.Option(
                    "--certificate-password",
                    Strings.SignCommandCertificatePasswordDescription,
                    CommandOptionType.SingleValue);

                CommandOption algorithm = signCmd.Option(
                    "--hash-algorithm",
                    Strings.SignCommandHashAlgorithmDescription,
                    CommandOptionType.SingleValue);

                CommandOption timestamper = signCmd.Option(
                    "--timestamper",
                    Strings.SignCommandTimestamperDescription,
                    CommandOptionType.SingleValue);

                CommandOption timestamperAlgorithm = signCmd.Option(
                    "--timestamp-hash-algorithm",
                    Strings.SignCommandTimestampHashAlgorithmDescription,
                    CommandOptionType.SingleValue);

                CommandOption overwrite = signCmd.Option(
                    "--overwrite",
                    Strings.SignCommandOverwriteDescription,
                    CommandOptionType.NoValue);

                CommandOption verbosity = signCmd.Option(
                    "-v|--verbosity",
                    Strings.Verbosity_Description,
                    CommandOptionType.SingleValue);

                signCmd.HelpOption(XPlatUtility.HelpOption);

                signCmd.Description = Strings.SignCommandDescription;

                signCmd.OnExecute(async() =>
                {
                    ILogger logger = getLogger();

                    ValidatePackagePaths(packagePaths);
                    WarnIfNoTimestamper(logger, timestamper);
                    ValidateCertificateInputs(path, fingerprint, subject, store, location);
                    ValidateAndCreateOutputDirectory(outputDirectory);

                    SigningSpecificationsV1 signingSpec = SigningSpecifications.V1;
                    StoreLocation storeLocation         = ValidateAndParseStoreLocation(location);
                    StoreName storeName                      = ValidateAndParseStoreName(store);
                    HashAlgorithmName hashAlgorithm          = CommandLineUtility.ParseAndValidateHashAlgorithm(algorithm.Value(), algorithm.LongName, signingSpec);
                    HashAlgorithmName timestampHashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(timestamperAlgorithm.Value(), timestamperAlgorithm.LongName, signingSpec);

                    var args = new SignArgs()
                    {
                        PackagePaths             = packagePaths.Values,
                        OutputDirectory          = outputDirectory.Value(),
                        CertificatePath          = path.Value(),
                        CertificateStoreName     = storeName,
                        CertificateStoreLocation = storeLocation,
                        CertificateSubjectName   = subject.Value(),
                        CertificateFingerprint   = fingerprint.Value(),
                        CertificatePassword      = password.Value(),
                        SignatureHashAlgorithm   = hashAlgorithm,
                        Logger    = logger,
                        Overwrite = overwrite.HasValue(),
                        //The interactive option is not enabled at first, so the NonInteractive is always set to true. This is tracked by https://github.com/NuGet/Home/issues/10620
                        NonInteractive         = true,
                        Timestamper            = timestamper.Value(),
                        TimestampHashAlgorithm = timestampHashAlgorithm
                    };

                    setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));

                    X509TrustStore.InitializeForDotNetSdk(args.Logger);

                    ISignCommandRunner runner = getCommandRunner();
                    int result = await runner.ExecuteCommandAsync(args);
                    return(result);
                });
            });
        }