Exemple #1
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 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();
                    setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));

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

                    return(verifyTask.Result);
                });
            });
        }
        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()));

                    ISignCommandRunner runner = getCommandRunner();
                    int result = await runner.ExecuteCommandAsync(args);
                    return(result);
                });
            });
        }
        internal static void Register(CommandLineApplication app,
                                      Func <ILogger> getLogger,
                                      Action <LogLevel> setLogLevel)
        {
            app.Command("trust", trustedSignersCmd =>
            {
                CommandArgument command = trustedSignersCmd.Argument(
                    "<command>",
                    Strings.TrustCommandActionDescription,
                    multipleValues: true);

                CommandOption algorithm = trustedSignersCmd.Option(
                    "--algorithm",
                    Strings.TrustCommandAlgorithm,
                    CommandOptionType.SingleValue);

                CommandOption allowUntrustedRootOption = trustedSignersCmd.Option(
                    "--allow-untrusted-root",
                    Strings.TrustCommandAllowUntrustedRoot,
                    CommandOptionType.NoValue);

                CommandOption owners = trustedSignersCmd.Option(
                    "--owners",
                    Strings.TrustCommandOwners,
                    CommandOptionType.MultipleValue);

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

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

                trustedSignersCmd.HelpOption(XPlatUtility.HelpOption);
                trustedSignersCmd.Description = Strings.TrustCommandDescription;

                trustedSignersCmd.OnExecute(async() =>
                {
                    TrustCommand action;

                    if (!command.Values.Any() || string.IsNullOrEmpty(command.Values[0]))
                    {
                        action = TrustCommand.List;
                    }
                    else if (!Enum.TryParse(command.Values[0], ignoreCase: true, result: out action))
                    {
                        throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_UnknownAction, command.Values[0]));
                    }

                    string name = null;

                    if (command.Values.Count > 1)
                    {
                        name = command.Values[1];
                    }

                    string packagePath = null;
                    string sourceUrl   = null;
                    string fingerprint = null;
                    if (command.Values.Count() > 2)
                    {
                        if (action == TrustCommand.Author || action == TrustCommand.Repository)
                        {
                            packagePath = command.Values[2];
                        }
                        else if (action == TrustCommand.Source)
                        {
                            sourceUrl = command.Values[2];
                        }
                        else if (action == TrustCommand.Certificate)
                        {
                            fingerprint = command.Values[2];
                        }
                    }

                    ISettings settings = ProcessConfigFile(configFile.Value());

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

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

#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);
                });
            });
        }
        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;
            }
        }
        public static void Register(
            CommandLineApplication app,
            Func <ILogger> getLogger,
            Action <LogLevel> setLogLevel,
            Func <IListPackageCommandRunner> getCommandRunner)
        {
            app.Command("list", listpkg =>
            {
                listpkg.Description = Strings.ListPkg_Description;
                listpkg.HelpOption(XPlatUtility.HelpOption);

                listpkg.Option(
                    CommandConstants.ForceEnglishOutputOption,
                    Strings.ForceEnglishOutput_Description,
                    CommandOptionType.NoValue);

                var path = listpkg.Argument(
                    "<PROJECT | SOLUTION>",
                    Strings.ListPkg_PathDescription,
                    multipleValues: false);

                var framework = listpkg.Option(
                    "--framework",
                    Strings.ListPkg_FrameworkDescription,
                    CommandOptionType.MultipleValue);

                var deprecatedReport = listpkg.Option(
                    "--deprecated",
                    Strings.ListPkg_DeprecatedDescription,
                    CommandOptionType.NoValue);

                var outdatedReport = listpkg.Option(
                    "--outdated",
                    Strings.ListPkg_OutdatedDescription,
                    CommandOptionType.NoValue);

                var vulnerableReport = listpkg.Option(
                    "--vulnerable",
                    Strings.ListPkg_VulnerableDescription,
                    CommandOptionType.NoValue);

                var includeTransitive = listpkg.Option(
                    "--include-transitive",
                    Strings.ListPkg_TransitiveDescription,
                    CommandOptionType.NoValue);

                var prerelease = listpkg.Option(
                    "--include-prerelease",
                    Strings.ListPkg_PrereleaseDescription,
                    CommandOptionType.NoValue);

                var highestPatch = listpkg.Option(
                    "--highest-patch",
                    Strings.ListPkg_HighestPatchDescription,
                    CommandOptionType.NoValue);

                var highestMinor = listpkg.Option(
                    "--highest-minor",
                    Strings.ListPkg_HighestMinorDescription,
                    CommandOptionType.NoValue);

                var source = listpkg.Option(
                    "--source",
                    Strings.ListPkg_SourceDescription,
                    CommandOptionType.MultipleValue);

                var config = listpkg.Option(
                    "--config",
                    Strings.ListPkg_ConfigDescription,
                    CommandOptionType.SingleValue);

                var interactive = listpkg.Option(
                    "--interactive",
                    Strings.NuGetXplatCommand_Interactive,
                    CommandOptionType.NoValue);

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

                listpkg.OnExecute(async() =>
                {
                    var logger = getLogger();

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

                    var settings = ProcessConfigFile(config.Value(), path.Value);
                    var sources  = source.Values;

                    var packageSources = GetPackageSources(settings, sources, config);

                    VerifyValidFrameworks(framework);

                    var reportType = GetReportType(
                        isOutdated: outdatedReport.HasValue(),
                        isDeprecated: deprecatedReport.HasValue(),
                        isVulnerable: vulnerableReport.HasValue());

                    var packageRefArgs = new ListPackageArgs(
                        path.Value,
                        packageSources,
                        framework.Values,
                        reportType,
                        includeTransitive.HasValue(),
                        prerelease.HasValue(),
                        highestPatch.HasValue(),
                        highestMinor.HasValue(),
                        logger,
                        CancellationToken.None);

                    DisplayMessages(packageRefArgs);

                    DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue());

                    var listPackageCommandRunner = getCommandRunner();
                    await listPackageCommandRunner.ExecuteCommandAsync(packageRefArgs);
                    return(0);
                });
            });
        }