Exemplo n.º 1
0
        /// <summary>
        /// Default private constructor.
        /// </summary>
        private App()
        {
            // Create the resource handler
            Resources = new ResourceHandler();

            // Create the handler collection
            Handlers = new RequestHandlerCollection();
        }
Exemplo n.º 2
0
        public static async Task <int> Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            var parsedArgs = await Args.ParseAsync <CredentialProviderArgs>(args);

            var multiLogger = new MultiLogger();
            var fileLogger  = GetFileLogger();

            if (fileLogger != null)
            {
                multiLogger.Add(fileLogger);
            }

            // Cancellation listener
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
            {
                // ConsoleCancelEventArgs.Cancel defaults to false which terminates the current process.
                multiLogger.Verbose(Resources.CancelMessage);
                tokenSource.Cancel();
            };

            var authUtil                    = new AuthUtil(multiLogger);
            var adalTokenCache              = AdalTokenCacheUtils.GetAdalTokenCache(multiLogger);
            var adalTokenProviderFactory    = new VstsAdalTokenProviderFactory(adalTokenCache);
            var bearerTokenProvidersFactory = new BearerTokenProvidersFactory(multiLogger, adalTokenProviderFactory);
            var vstsSessionTokenProvider    = new VstsSessionTokenFromBearerTokenProvider(authUtil, multiLogger);

            List <ICredentialProvider> credentialProviders = new List <ICredentialProvider>
            {
                new VstsBuildTaskServiceEndpointCredentialProvider(multiLogger),
                new VstsBuildTaskCredentialProvider(multiLogger),
                new VstsCredentialProvider(multiLogger, authUtil, bearerTokenProvidersFactory, vstsSessionTokenProvider),
            };

            try
            {
                IRequestHandlers requestHandlers = new RequestHandlerCollection
                {
                    { MessageMethod.GetAuthenticationCredentials, new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.GetOperationClaims, new GetOperationClaimsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.Initialize, new InitializeRequestHandler(multiLogger) },
                    { MessageMethod.SetLogLevel, new SetLogLevelRequestHandler(multiLogger) },
                    { MessageMethod.SetCredentials, new SetCredentialsRequestHandler(multiLogger) },
                };

                // Help
                if (parsedArgs.Help)
                {
                    Console.WriteLine(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));
                    Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                    Console.WriteLine(
                        string.Format(
                            Resources.EnvironmentVariableHelp,
                            EnvUtil.LogPathEnvVar,
                            EnvUtil.SessionTokenCacheEnvVar,
                            EnvUtil.AuthorityEnvVar,
                            EnvUtil.AdalFileCacheEnvVar,
                            EnvUtil.PpeHostsEnvVar,
                            EnvUtil.SupportedHostsEnvVar,
                            EnvUtil.SessionTimeEnvVar,
                            EnvUtil.TokenTypeEnvVar,
                            EnvUtil.BuildTaskUriPrefixes,
                            EnvUtil.BuildTaskAccessToken,
                            EnvUtil.BuildTaskExternalEndpoints,
                            EnvUtil.AdalTokenCacheLocation,
                            EnvUtil.SessionTokenCacheLocation,
                            EnvUtil.WindowsIntegratedAuthenticationEnvVar,
                            EnvUtil.DeviceFlowTimeoutEnvVar
                            ));
                    return(0);
                }

                // Plug-in mode
                if (parsedArgs.Plugin)
                {
                    using (IPlugin plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false))
                    {
                        multiLogger.Add(new PluginConnectionLogger(plugin.Connection));
                        multiLogger.Verbose(Resources.RunningInPlugin);
                        multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                        await RunNuGetPluginsAsync(plugin, multiLogger, TimeSpan.FromMinutes(2), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
                    }

                    return(0);
                }

                // Stand-alone mode
                if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) && requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler)
                {
                    multiLogger.Add(new ConsoleLogger());
                    multiLogger.SetLogLevel(parsedArgs.Verbosity);
                    multiLogger.Verbose(Resources.RunningInStandAlone);
                    multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                    if (parsedArgs.Uri == null)
                    {
                        Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                        return(1);
                    }

                    GetAuthenticationCredentialsRequest  request  = new GetAuthenticationCredentialsRequest(parsedArgs.Uri, isRetry: parsedArgs.IsRetry, isNonInteractive: parsedArgs.NonInteractive, parsedArgs.CanShowDialog);
                    GetAuthenticationCredentialsResponse response = await getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).ConfigureAwait(continueOnCapturedContext: false);

                    multiLogger.Info($"{Resources.Username}: {response?.Username}");
                    multiLogger.Info($"{Resources.Password}: {(parsedArgs.RedactPassword ? Resources.Redacted : response?.Password)}");
                    return(0);
                }

                return(-1);
            }
            finally
            {
                foreach (ICredentialProvider credentialProvider in credentialProviders)
                {
                    credentialProvider.Dispose();
                }
            }
        }
Exemplo n.º 3
0
        public static async Task <int> Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            var parsedArgs = await Args.ParseAsync <CredentialProviderArgs>(args);

            var multiLogger = new MultiLogger();
            var fileLogger  = GetFileLogger();

            if (fileLogger != null)
            {
                multiLogger.Add(fileLogger);
            }

            // Cancellation listener
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
            {
                // ConsoleCancelEventArgs.Cancel defaults to false which terminates the current process.
                multiLogger.Verbose(Resources.CancelMessage);
                tokenSource.Cancel();
            };

            var authUtil                    = new AuthUtil(multiLogger);
            var adalTokenCache              = AdalTokenCacheUtils.GetAdalTokenCache(multiLogger);
            var adalTokenProviderFactory    = new VstsAdalTokenProviderFactory(adalTokenCache);
            var bearerTokenProvidersFactory = new BearerTokenProvidersFactory(multiLogger, adalTokenProviderFactory);
            var vstsSessionTokenProvider    = new VstsSessionTokenFromBearerTokenProvider(authUtil, multiLogger);

            List <ICredentialProvider> credentialProviders = new List <ICredentialProvider>
            {
                new VstsBuildTaskServiceEndpointCredentialProvider(multiLogger),
                new VstsBuildTaskCredentialProvider(multiLogger),
                new VstsCredentialProvider(multiLogger, authUtil, bearerTokenProvidersFactory, vstsSessionTokenProvider),
            };

            try
            {
                IRequestHandlers requestHandlers = new RequestHandlerCollection
                {
                    { MessageMethod.GetAuthenticationCredentials, new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.GetOperationClaims, new GetOperationClaimsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.Initialize, new InitializeRequestHandler(multiLogger) },
                    { MessageMethod.SetLogLevel, new SetLogLevelRequestHandler(multiLogger) },
                    { MessageMethod.SetCredentials, new SetCredentialsRequestHandler(multiLogger) },
                };

                // Help
                if (parsedArgs.Help)
                {
                    Console.WriteLine(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));
                    Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                    Console.WriteLine(
                        string.Format(
                            Resources.EnvironmentVariableHelp,
                            EnvUtil.LogPathEnvVar,
                            EnvUtil.SessionTokenCacheEnvVar,
                            EnvUtil.AuthorityEnvVar,
                            EnvUtil.AdalFileCacheEnvVar,
                            EnvUtil.PpeHostsEnvVar,
                            EnvUtil.SupportedHostsEnvVar,
                            EnvUtil.SessionTimeEnvVar,
                            EnvUtil.TokenTypeEnvVar,
                            EnvUtil.BuildTaskUriPrefixes,
                            EnvUtil.BuildTaskAccessToken,
                            EnvUtil.BuildTaskExternalEndpoints,
                            EnvUtil.AdalTokenCacheLocation,
                            EnvUtil.SessionTokenCacheLocation,
                            EnvUtil.WindowsIntegratedAuthenticationEnvVar,
                            EnvUtil.DeviceFlowTimeoutEnvVar
                            ));
                    return(0);
                }

                // Plug-in mode
                if (parsedArgs.Plugin)
                {
                    try
                    {
                        using (IPlugin plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false))
                        {
                            multiLogger.Add(new PluginConnectionLogger(plugin.Connection));
                            multiLogger.Verbose(Resources.RunningInPlugin);
                            multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                            await WaitForPluginExitAsync(plugin, multiLogger, TimeSpan.FromMinutes(2)).ConfigureAwait(continueOnCapturedContext: false);
                        }
                    }
                    catch (OperationCanceledException ex)
                    {
                        // When restoring from multiple sources, one of the sources will throw an unhandled TaskCanceledException
                        // if it has been restored successfully from a different source.

                        // This is probably more confusing than interesting to users, but may be helpful in debugging,
                        // so log the exception but not to the console.
                        multiLogger.Log(LogLevel.Verbose, allowOnConsole: false, ex.ToString());
                    }

                    return(0);
                }

                // Stand-alone mode
                if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) && requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler)
                {
                    // When emitting machine-readable output to standard out, logging (including Device Code prompts) must be emitted to standard error
                    if (parsedArgs.OutputFormat == OutputFormat.Json)
                    {
                        multiLogger.Add(new StandardErrorLogger());
                    }
                    else
                    {
                        multiLogger.Add(new StandardOutputLogger());
                    }

                    multiLogger.SetLogLevel(parsedArgs.Verbosity);
                    multiLogger.Verbose(Resources.RunningInStandAlone);
                    multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                    if (parsedArgs.Uri == null)
                    {
                        Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                        return(1);
                    }

                    GetAuthenticationCredentialsRequest  request  = new GetAuthenticationCredentialsRequest(parsedArgs.Uri, isRetry: parsedArgs.IsRetry, isNonInteractive: parsedArgs.NonInteractive, parsedArgs.CanShowDialog);
                    GetAuthenticationCredentialsResponse response = await getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).ConfigureAwait(continueOnCapturedContext: false);

                    // Fail if credentials are not found
                    if (response?.ResponseCode != MessageResponseCode.Success)
                    {
                        return(2);
                    }

                    string resultUsername = response?.Username;
                    string resultPassword = parsedArgs.RedactPassword ? Resources.Redacted : response?.Password;
                    if (parsedArgs.OutputFormat == OutputFormat.Json)
                    {
                        // Manually write the JSON output, since we don't use ConsoleLogger in JSON mode (see above)
                        Console.WriteLine(JsonConvert.SerializeObject(new CredentialResult(resultUsername, resultPassword)));
                    }
                    else
                    {
                        multiLogger.Info($"{Resources.Username}: {resultUsername}");
                        multiLogger.Info($"{Resources.Password}: {resultPassword}");
                    }
                    return(0);
                }

                return(-1);
            }
            finally
            {
                foreach (ICredentialProvider credentialProvider in credentialProviders)
                {
                    credentialProvider.Dispose();
                }
            }
        }
        public static async Task <int> Main(string[] args)
        {
            DebugBreakIfPluginDebuggingIsEnabled();

            var tokenSource = new CancellationTokenSource();
            var multiLogger = new MultiLogger();

            var fileLogger = GetFileLogger();

            if (fileLogger != null)
            {
                multiLogger.Add(fileLogger);
            }

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                tokenSource.Cancel();
                eventArgs.Cancel = true;
            };

            var credentialProvider = new TeamCityCredentialProvider(multiLogger);
            var sdkInfo            = new SdkInfo();
            var requestHandlers    = new RequestHandlerCollection
            {
                {
                    MessageMethod.GetAuthenticationCredentials,
                    new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProvider)
                },
                {
                    MessageMethod.GetOperationClaims,
                    new GetOperationClaimsRequestHandler(multiLogger, credentialProvider, sdkInfo)
                },
                {
                    MessageMethod.SetLogLevel,
                    new SetLogLevelHandler(multiLogger)
                },
                {
                    MessageMethod.Initialize,
                    new InitializeRequestHandler(multiLogger)
                },
                {
                    MessageMethod.SetCredentials,
                    new SetCredentialsRequestHandler(multiLogger)
                }
            };

            if (String.Equals(args.SingleOrDefault(), "-plugin", StringComparison.OrdinalIgnoreCase))
            {
                multiLogger.Log(LogLevel.Verbose, "Running in plug-in mode");

                using (IPlugin plugin = await PluginFactory
                                        .CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), CancellationToken.None)
                                        .ConfigureAwait(continueOnCapturedContext: false))
                {
                    multiLogger.Add(new PluginConnectionLogger(plugin.Connection));
                    await RunNuGetPluginsAsync(plugin, multiLogger, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
                }

                return(0);
            }

            if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) &&
                requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler)
            {
                multiLogger.Log(LogLevel.Verbose, "Running in stand-alone mode");

                if (args.Length == 0)
                {
                    Console.WriteLine("Usage: CredentialProvider.TeamCity.exe <NuGetFeedUrl>");
                    return(1);
                }

                var request = new GetAuthenticationCredentialsRequest(
                    uri: new Uri(args[0]),
                    isRetry: false,
                    isNonInteractive: true,
                    canShowDialog: false
                    );
                var response = getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).GetAwaiter().GetResult();

                Console.WriteLine(response?.Username);
                Console.WriteLine(response?.Password);
                Console.WriteLine(response?.Password.ToJsonWebTokenString());

                return(0);
            }

            return(-1);
        }
Exemplo n.º 5
0
		/// <summary>
		/// Default private constructor.
		/// </summary>
		private App() { 
			// Create the resource handler
			Resources = new ResourceHandler();

			// Create the handler collection
			Handlers = new RequestHandlerCollection();
		}