private DefaultProfile(ICredentialProvider icredential, String region, FormatType format) { this.regionId = region; this.AcceptFormat = format; this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); }
public ConnectionManager(ILogger logger, ICredentialProvider credentialProvider, INetworkConnection networkConnectivity, IServerLocator serverDiscovery, string applicationName, string applicationVersion, IDevice device, ClientCapabilities clientCapabilities, ICryptographyProvider cryptographyProvider, Func<IClientWebSocket> webSocketFactory = null, ILocalAssetManager localAssetManager = null) { _credentialProvider = credentialProvider; _networkConnectivity = networkConnectivity; _logger = logger; _serverDiscovery = serverDiscovery; _httpClient = AsyncHttpClientFactory.Create(logger); ClientCapabilities = clientCapabilities; _webSocketFactory = webSocketFactory; _cryptographyProvider = cryptographyProvider; _localAssetManager = localAssetManager; Device = device; ApplicationVersion = applicationVersion; ApplicationName = applicationName; ApiClients = new Dictionary<string, IApiClient>(StringComparer.OrdinalIgnoreCase); SaveLocalCredentials = true; Device.ResumeFromSleep += Device_ResumeFromSleep; var jsonSerializer = new NewtonsoftJsonSerializer(); _connectService = new ConnectService(jsonSerializer, _logger, _httpClient, _cryptographyProvider, applicationName, applicationVersion); }
public InMemoryTokenManager(ITokenRetriever tokenRetriever, ICredentialProvider credentialProvider) { _tokenRetriever = tokenRetriever; _credential = credentialProvider.GenerateCredential(); _memoryTokens = new ConcurrentDictionary<ApplicationCredential, ApplicationToken>(); }
public ProxyService(ICredentialProvider credentialProvider) { if (null == credentialProvider) { throw new ArgumentNullException("credentialProvider"); } _credentialProvider = credentialProvider; }
public CredentialIdentity(string credentialId, ICredentialProvider provider = null) { if(string.IsNullOrWhiteSpace(credentialId)) throw new ArgumentNullException("credentialId"); _credentialId = credentialId; _provider = provider; }
public DeploymentsController(IApplicationService applicationService, ICredentialProvider credentialProvider, ISettingsResolver settingsResolver) { _applicationService = applicationService; _credentialProvider = credentialProvider; _settingsResolver = settingsResolver; }
public ApplicationController(IApplicationService applicationService, ICredentialProvider credentialProvider, KuduEnvironment environment) { _applicationService = applicationService; _credentialProvider = credentialProvider; _environment = environment; }
/// <summary> /// Creates a new caching dectorator. /// </summary> /// <param name="inner">The inner <see cref="ICredentialProvider"/> to wrap.</param> public CachedCredentialProvider([NotNull] ICredentialProvider inner) { #region Sanity checks if (inner == null) throw new ArgumentNullException(nameof(inner)); #endregion _inner = inner; _cache = new TransparentCache<Uri, NetworkCredential>(uri => inner.GetCredential(uri, null)); }
public ApplicationController(IApplicationService applicationService, ICredentialProvider credentialProvider, KuduEnvironment environment, ISettingsResolver settingsResolver) { _applicationService = applicationService; _credentialProvider = credentialProvider; _environment = environment; _settingsResolver = settingsResolver; }
public DeploymentsController(IApplicationService applicationService, ICredentialProvider credentialProvider, IKuduContext context, ICertificateSearcher certificates) { _applicationService = applicationService; _credentialProvider = credentialProvider; _context = context; _certificates = certificates; }
internal static void Initialize () { credentialStore = new CredentialStore (); proxyCache = new ProxyCache (); credentialProvider = AddinManager.GetExtensionObjects<ICredentialProvider> (WebCredentialProvidersPath).FirstOrDefault (); if (credentialProvider == null) { LoggingService.LogWarning ("No proxy credential provider was found"); credentialProvider = new NullCredentialProvider (); } }
public static Authorization GetAuthorization(ICredentialProvider credentialProvider) { Credentials.Credentials credentials = credentialProvider.GetCredentials(); var authService = new AuthorizationService(credentials.Username, credentials.Password) { UserAgent = Program.UserAgent, AgentVersion = Program.AgentVersion }; return GetAuthorization(authService); }
public RequestHelper(Func<HttpWebRequest> createRequest, Action<HttpWebRequest> prepareRequest, IProxyCache proxyCache, ICredentialCache credentialCache, ICredentialProvider credentialProvider) { _createRequest = createRequest; _prepareRequest = prepareRequest; _proxyCache = proxyCache; _credentialCache = credentialCache; _credentialProvider = credentialProvider; }
public ApplicationController(IApplicationService applicationService, ICredentialProvider credentialProvider, KuduEnvironment environment, IKuduContext context, ICertificateSearcher certificates) { _applicationService = applicationService; _credentialProvider = credentialProvider; _environment = environment; _context = context; _certificates = certificates; }
public PackageChooserViewModel(IMruPackageSourceManager packageSourceManager) { Packages = new ObservableCollection<PackageInfo>(); NavigationCommand = new NavigateCommand(this); SortCommand = new RelayCommand<string>(Sort, column => TotalPackageCount > 0); SearchCommand = new RelayCommand<string>(Search); LoadedCommand = new RelayCommand(() => Sort("VersionDownloadCount", ListSortDirection.Descending)); ChangePackageSourceCommand = new RelayCommand<string>(ChangePackageSource); _credentialProvider = new AutoDiscoverCredentialProvider(); _proxyService = new ProxyService(_credentialProvider); _packageSourceManager = packageSourceManager; }
public RequestHelper(Func<WebRequest> createRequest, Action<WebRequest> prepareRequest, IProxyCache proxyCache, ICredentialCache credentialCache, ICredentialProvider credentialProvider, bool disableBuffering) { _createRequest = createRequest; _prepareRequest = prepareRequest; _proxyCache = proxyCache; _credentialCache = credentialCache; _credentialProvider = credentialProvider; _disableBuffering = disableBuffering; }
public SettingsCredentialProvider(ICredentialProvider credentialProvider, IPackageSourceProvider packageSourceProvider, ILogger logger) { if (credentialProvider == null) { throw new ArgumentNullException("credentialProvider"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } _credentialProvider = credentialProvider; _packageSourceProvider = packageSourceProvider; _logger = logger; }
/// <summary> /// Creates a new task tracking dialog. /// </summary> /// <param name="task">The trackable task to execute and display.</param> /// <param name="credentialProvider">Object used to retrieve credentials for specific <see cref="Uri"/>s on demand; can be <c>null</c>.</param> /// <param name="cancellationTokenSource">Used to signal if the user pressed the Cancel button.</param> public TaskRunDialog([NotNull] ITask task, [CanBeNull] ICredentialProvider credentialProvider, CancellationTokenSource cancellationTokenSource) { #region Sanity checks if (task == null) throw new ArgumentNullException(nameof(task)); #endregion InitializeComponent(); buttonCancel.Text = Resources.Cancel; buttonCancel.Enabled = task.CanCancel; Text = task.Name; _task = task; _taskThread = new Thread(RunTask); _cancellationTokenSource = cancellationTokenSource; _credentialProvider = credentialProvider; }
public TaskRunDialog([NotNull] ITask task, ICredentialProvider credentialProvider, CancellationTokenSource cancellationTokenSource, [CanBeNull] Widget parent = null) { #region Sanity checks if (task == null) throw new ArgumentNullException(nameof(task)); #endregion Parent = parent; // ReSharper disable once DoNotCallOverridableMethodsInConstructor Build(); Title = task.Name; buttonCancel.Sensitive = task.CanCancel; _task = task; _taskThread = new Thread(RunTask); _cancellationTokenSource = cancellationTokenSource; _credentialProvider = credentialProvider; }
public SiteConfiguration(IApplication application, ICredentialProvider credentialProvider) { ServiceUrl = application.ServiceUrl; SiteUrl = application.SiteUrl; Name = application.Name; // This is to work around a SignalR bug where the hub is still created // even if IDisconnect isn't implemented if (String.IsNullOrEmpty(ServiceUrl)) { return; } SiteConfiguration config; if (_cache.TryGetValue(ServiceUrl, out config)) { Repository = config.Repository; ProjectSystem = config.ProjectSystem; DevProjectSystem = config.DevProjectSystem; DeploymentManager = config.DeploymentManager; CommandExecutor = config.CommandExecutor; DevCommandExecutor = config.DevCommandExecutor; } else { var repository = new RemoteRepository(ServiceUrl + "scm"); repository.Credentials = credentialProvider.GetCredentials(); Repository = repository; var projectSystem = new RemoteProjectSystem(ServiceUrl + "live/files"); projectSystem.Credentials = credentialProvider.GetCredentials(); ProjectSystem = projectSystem; var devProjectSystem = new RemoteProjectSystem(ServiceUrl + "dev/files"); devProjectSystem.Credentials = credentialProvider.GetCredentials(); DevProjectSystem = devProjectSystem; SubscribeToEvents(credentialProvider); _cache[ServiceUrl] = this; } }
/// <inheritdoc/> public void Run(CancellationToken cancellationToken = default(CancellationToken), ICredentialProvider credentialProvider = null, IProgress<TaskSnapshot> progress = null) { cancellationToken.ThrowIfCancellationRequested(); CancellationToken = cancellationToken; _progress = progress; CredentialProvider = credentialProvider; State = TaskState.Started; try { // Run task with privileges of original user if possible if (_originalIdentity != null) { using (_originalIdentity.Impersonate()) Execute(); } else Execute(); } #region Error handling catch (OperationCanceledException) { State = TaskState.Canceled; throw; } catch (IOException) { State = TaskState.IOError; throw; } catch (UnauthorizedAccessException) { State = TaskState.IOError; throw; } catch (WebException) { State = TaskState.WebError; throw; } #endregion }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger logger, ExecutionContext context) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } using (var scope = logger.BeginScope($"{nameof(MessagesHttpFunction.Run)}")) { if (req == null) { throw new ArgumentNullException(nameof(req)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } logger.LogInformation("Messages function received a request."); // Use the configured service for tests or create ones to use. ISettings settings = this.settings ?? new Settings(logger, context); IStickerSetRepository stickerSetRepository = this.stickerSetRepository ?? new StickerSetRepository(logger, settings); IStickerSetIndexer stickerSetIndexer = this.stickerSetIndexer ?? new StickerSetIndexer(logger); ICredentialProvider credentialProvider = this.credentialProvider ?? new SimpleCredentialProvider(settings.MicrosoftAppId, null); IChannelProvider channelProvider = this.channelProvider ?? new SimpleChannelProvider(); // Parse the incoming activity and authenticate the request Activity activity; try { var authorizationHeader = GetAuthorizationHeader(req); activity = await ParseRequestBody(req); await JwtTokenValidation.AuthenticateRequest(activity, authorizationHeader, credentialProvider, channelProvider); } catch (JsonReaderException e) { logger.LogDebug(e, "JSON parser failed to parse request payload."); return(new BadRequestResult()); } catch (UnauthorizedAccessException e) { logger.LogDebug(e, "Request was not propertly authorized."); return(new UnauthorizedResult()); } // Log telemetry about the activity try { this.LogActivityTelemetry(activity); } catch (Exception ex) { logger.LogWarning(ex, "Error sending user activity telemetry"); } // Reject all activity types other than those related to messaging extensions if (!activity.IsComposeExtensionQuery()) { logger.LogDebug("Request payload was not a messaging extension query."); return(new BadRequestObjectResult($"App only supports messaging extension query activity types.")); } // Get the query string. We expect exactly 1 parameter, so we take the first parameter, regardless of the name. var skip = 0; var count = 25; var query = string.Empty; if (activity.Value != null) { var queryValue = JObject.FromObject(activity.Value).ToObject <ComposeExtensionValue>(); query = queryValue.GetParameterValue(); if (queryValue?.QueryOptions != null) { skip = queryValue.QueryOptions.Skip; count = queryValue.QueryOptions.Count; } } // Find matching stickers var stickerSet = await stickerSetRepository.FetchStickerSetAsync(); await stickerSetIndexer.IndexStickerSetAsync(stickerSet); var stickers = await stickerSetIndexer.FindStickersByQuery(query, skip, count); var result = new ComposeExtensionResponse { ComposeExtensionResult = new ComposeExtensionResult { Type = "result", AttachmentLayout = "grid", Attachments = stickers.Select(sticker => new StickerComposeExtensionCard(sticker).ToAttachment()).ToArray() } }; return(new OkObjectResult(result)); } }
/// <summary> /// Authenticates the request and adds the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, HttpClient httpClient = null) { return(await AuthenticateRequest(activity, authHeader, credentials, provider, new AuthenticationConfiguration(), httpClient).ConfigureAwait(false)); }
public SkillAdapterWithErrorHandler(IConfiguration configuration, ICredentialProvider credentialProvider, AuthenticationConfiguration authConfig, ILogger <BotFrameworkHttpAdapter> logger) : base(configuration, credentialProvider, authConfig, logger: logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); OnTurnError = HandleTurnError; }
private void SubscribeToEvents(ICredentialProvider credentialProvider) { var deploymentManager = new RemoteDeploymentManager(ServiceUrl + "deploy"); deploymentManager.Credentials = credentialProvider.GetCredentials(); DeploymentManager = deploymentManager; DeploymentManager.StatusChanged += OnDeploymentStatusChanged; var commandExecutor = new RemoteCommandExecutor(ServiceUrl + "live/command"); commandExecutor.Credentials = credentialProvider.GetCredentials(); CommandExecutor = commandExecutor; CommandExecutor.CommandEvent += OnCommandEvent; var devCommandExecutor = new RemoteCommandExecutor(ServiceUrl + "dev/command"); devCommandExecutor.Credentials = credentialProvider.GetCredentials(); DevCommandExecutor = devCommandExecutor; DevCommandExecutor.CommandEvent += OnCommandEvent; //try //{ // // Start the connections // deploymentManager.Start(); // commandExecutor.Start(); // devCommandExecutor.Start(); //} //catch(Exception ex) //{ // Debug.WriteLine("Failed to subcribe for updates => " + ex.Message); //} }
private static string GetUriKey(Uri uri, CredentialRequestType type, ICredentialProvider provider) { return($"{provider.Id}_{type == CredentialRequestType.Proxy}_{uri}"); }
private DefaultProfile(String region, ICredentialProvider icredential) { this.regionId = region; this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); }
public StateClient(ICredentialProvider credentialProvider, ClaimsIdentity claimsIdentity = null, params DelegatingHandler[] handlers) : this(null, credentialProvider, claimsIdentity, handlers : handlers) { }
public SettingsService(IApplicationService applicationService, ICredentialProvider credentialProvider) { _applicationService = applicationService; _credentialProvider = credentialProvider; }
public async Task ConfigureAsync(CommandSettings command) { Trace.Info(nameof(ConfigureAsync)); if (IsConfigured()) { throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError")); } // Populate proxy setting from commandline args var vstsProxy = HostContext.GetService <IVstsAgentWebProxy>(); bool saveProxySetting = false; string proxyUrl = command.GetProxyUrl(); if (!string.IsNullOrEmpty(proxyUrl)) { if (!Uri.IsWellFormedUriString(proxyUrl, UriKind.Absolute)) { throw new ArgumentOutOfRangeException(nameof(proxyUrl)); } Trace.Info("Reset proxy base on commandline args."); string proxyUserName = command.GetProxyUserName(); string proxyPassword = command.GetProxyPassword(); (vstsProxy as VstsAgentWebProxy).SetupProxy(proxyUrl, proxyUserName, proxyPassword); saveProxySetting = true; } // Populate cert setting from commandline args var agentCertManager = HostContext.GetService <IAgentCertificateManager>(); bool saveCertSetting = false; bool skipCertValidation = command.GetSkipCertificateValidation(); string caCert = command.GetCACertificate(); string clientCert = command.GetClientCertificate(); string clientCertKey = command.GetClientCertificatePrivateKey(); string clientCertArchive = command.GetClientCertificateArchrive(); string clientCertPassword = command.GetClientCertificatePassword(); // We require all Certificate files are under agent root. // So we can set ACL correctly when configure as service if (!string.IsNullOrEmpty(caCert)) { caCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), caCert); ArgUtil.File(caCert, nameof(caCert)); } if (!string.IsNullOrEmpty(clientCert) && !string.IsNullOrEmpty(clientCertKey) && !string.IsNullOrEmpty(clientCertArchive)) { // Ensure all client cert pieces are there. clientCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCert); clientCertKey = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertKey); clientCertArchive = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertArchive); ArgUtil.File(clientCert, nameof(clientCert)); ArgUtil.File(clientCertKey, nameof(clientCertKey)); ArgUtil.File(clientCertArchive, nameof(clientCertArchive)); } else if (!string.IsNullOrEmpty(clientCert) || !string.IsNullOrEmpty(clientCertKey) || !string.IsNullOrEmpty(clientCertArchive)) { // Print out which args are missing. ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCert, Constants.Agent.CommandLine.Args.SslClientCert); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertKey, Constants.Agent.CommandLine.Args.SslClientCertKey); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertArchive, Constants.Agent.CommandLine.Args.SslClientCertArchive); } if (skipCertValidation || !string.IsNullOrEmpty(caCert) || !string.IsNullOrEmpty(clientCert)) { Trace.Info("Reset agent cert setting base on commandline args."); (agentCertManager as AgentCertificateManager).SetupCertificate(skipCertValidation, caCert, clientCert, clientCertKey, clientCertArchive, clientCertPassword); saveCertSetting = true; } AgentSettings agentSettings = new AgentSettings(); // TEE EULA agentSettings.AcceptTeeEula = false; switch (PlatformUtil.HostOS) { case PlatformUtil.OS.OSX: case PlatformUtil.OS.Linux: // Write the section header. WriteSection(StringUtil.Loc("EulasSectionHeader")); // Verify the EULA exists on disk in the expected location. string eulaFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory, "license.html"); ArgUtil.File(eulaFile, nameof(eulaFile)); // Write elaborate verbiage about the TEE EULA. _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile)); _term.WriteLine(); // Prompt to acccept the TEE EULA. agentSettings.AcceptTeeEula = command.GetAcceptTeeEula(); break; case PlatformUtil.OS.Windows: // Warn and continue if .NET 4.6 is not installed. if (!NetFrameworkUtil.Test(new Version(4, 6), Trace)) { WriteSection(StringUtil.Loc("PrerequisitesSectionHeader")); // Section header. _term.WriteLine(StringUtil.Loc("MinimumNetFrameworkTfvc")); // Warning. } break; default: throw new NotSupportedException(); } // Create the configuration provider as per agent type. string agentType; if (command.DeploymentGroup) { agentType = Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration; } else if (command.DeploymentPool) { agentType = Constants.Agent.AgentConfigurationProvider.SharedDeploymentAgentConfiguration; } else if (command.EnvironmentVMResource) { agentType = Constants.Agent.AgentConfigurationProvider.EnvironmentVMResourceConfiguration; } else { agentType = Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; } var extensionManager = HostContext.GetService <IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()) .FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); bool isHostedServer = false; // Loop getting url and creds until you can connect ICredentialProvider credProvider = null; VssCredentials creds = null; WriteSection(StringUtil.Loc("ConnectSectionHeader")); while (true) { // Get the URL agentProvider.GetServerUrl(agentSettings, command); // Get the credentials credProvider = GetCredentialProvider(command, agentSettings.ServerUrl); creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); try { // Determine the service deployment type based on connection data. (Hosted/OnPremises) isHostedServer = await IsHostedServer(agentSettings.ServerUrl, creds); // Get the collection name for deployment group agentProvider.GetCollectionName(agentSettings, command, isHostedServer); // Validate can connect. await agentProvider.TestConnectionAsync(agentSettings, creds, isHostedServer); Trace.Info("Test Connection complete."); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToConnect")); } } _agentServer = HostContext.GetService <IAgentServer>(); // We want to use the native CSP of the platform for storage, so we use the RSACSP directly RSAParameters publicKey; var keyManager = HostContext.GetService <IRSAKeyManager>(); using (var rsa = keyManager.CreateKey()) { publicKey = rsa.ExportParameters(false); } // Loop getting agent name and pool name WriteSection(StringUtil.Loc("RegisterAgentSectionHeader")); while (true) { try { await agentProvider.GetPoolIdAndName(agentSettings, command); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(agentProvider.GetFailedToFindPoolErrorString()); } } TaskAgent agent; while (true) { agentSettings.AgentName = command.GetAgentName(); // Get the system capabilities. // TODO: Hook up to ctrl+c cancellation token. _term.WriteLine(StringUtil.Loc("ScanToolCapabilities")); Dictionary <string, string> systemCapabilities = await HostContext.GetService <ICapabilitiesManager>().GetCapabilitiesAsync(agentSettings, CancellationToken.None); _term.WriteLine(StringUtil.Loc("ConnectToServer")); agent = await agentProvider.GetAgentAsync(agentSettings); if (agent != null) { if (command.GetReplace()) { // Update existing agent with new PublicKey, agent version and SystemCapabilities. agent = UpdateExistingAgent(agent, publicKey, systemCapabilities); try { agent = await agentProvider.UpdateAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentReplaced")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToReplaceAgent")); } } else if (command.Unattended) { // if not replace and it is unattended config. agentProvider.ThrowTaskAgentExistException(agentSettings); } } else { // Create a new agent. agent = CreateNewAgent(agentSettings.AgentName, publicKey, systemCapabilities); try { agent = await agentProvider.AddAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("AddAgentFailed")); } } } // Add Agent Id to settings agentSettings.AgentId = agent.Id; // respect the serverUrl resolve by server. // in case of agent configured using collection url instead of account url. string agentServerUrl; if (agent.Properties.TryGetValidatedValue <string>("ServerUrl", out agentServerUrl) && !string.IsNullOrEmpty(agentServerUrl)) { Trace.Info($"Agent server url resolve by server: '{agentServerUrl}'."); // we need make sure the Schema/Host/Port component of the url remain the same. UriBuilder inputServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder serverReturnedServerUrl = new UriBuilder(agentServerUrl); if (Uri.Compare(inputServerUrl.Uri, serverReturnedServerUrl.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { inputServerUrl.Path = serverReturnedServerUrl.Path; Trace.Info($"Replace server returned url's scheme://host:port component with user input server url's scheme://host:port: '{inputServerUrl.Uri.AbsoluteUri}'."); agentSettings.ServerUrl = inputServerUrl.Uri.AbsoluteUri; } else { agentSettings.ServerUrl = agentServerUrl; } } // See if the server supports our OAuth key exchange for credentials if (agent.Authorization != null && agent.Authorization.ClientId != Guid.Empty && agent.Authorization.AuthorizationUrl != null) { // We use authorizationUrl as the oauth endpoint url by default. // For TFS, we need make sure the Schema/Host/Port component of the oauth endpoint url also match configuration url. (Incase of customer's agent configure URL and TFS server public URL are different) // Which means, we will keep use the original authorizationUrl in the VssOAuthJwtBearerClientCredential (authorizationUrl is the audience), // But might have different Url in VssOAuthCredential (connection url) // We can't do this for VSTS, since its SPS/TFS urls are different. UriBuilder configServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder oauthEndpointUrlBuilder = new UriBuilder(agent.Authorization.AuthorizationUrl); if (!isHostedServer && Uri.Compare(configServerUrl.Uri, oauthEndpointUrlBuilder.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { oauthEndpointUrlBuilder.Scheme = configServerUrl.Scheme; oauthEndpointUrlBuilder.Host = configServerUrl.Host; oauthEndpointUrlBuilder.Port = configServerUrl.Port; Trace.Info($"Set oauth endpoint url's scheme://host:port component to match agent configure url's scheme://host:port: '{oauthEndpointUrlBuilder.Uri.AbsoluteUri}'."); } var credentialData = new CredentialData { Scheme = Constants.Configuration.OAuth, Data = { { "clientId", agent.Authorization.ClientId.ToString("D") }, { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri }, { "oauthEndpointUrl", oauthEndpointUrlBuilder.Uri.AbsoluteUri }, }, }; // Save the negotiated OAuth credential data _store.SaveCredential(credentialData); } else { switch (PlatformUtil.HostOS) { case PlatformUtil.OS.OSX: case PlatformUtil.OS.Linux: // Save the provided admin cred for compat with previous agent. _store.SaveCredential(credProvider.CredentialData); break; case PlatformUtil.OS.Windows: // Not supported against TFS 2015. _term.WriteError(StringUtil.Loc("Tfs2015NotSupported")); return; default: throw new NotSupportedException(); } } // Testing agent connection, detect any protential connection issue, like local clock skew that cause OAuth token expired. _term.WriteLine(StringUtil.Loc("TestAgentConnection")); var credMgr = HostContext.GetService <ICredentialManager>(); VssCredentials credential = credMgr.LoadCredentials(); var agentSvr = HostContext.GetService <IAgentServer>(); try { await agentSvr.ConnectAsync(new Uri(agentSettings.ServerUrl), credential); } catch (VssOAuthTokenRequestException ex) when(ex.Message.Contains("Current server time is")) { // there are two exception messages server send that indicate clock skew. // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}. // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}. Trace.Error("Catch exception during test agent connection."); Trace.Error(ex); throw new Exception(StringUtil.Loc("LocalClockSkewed")); } // We will Combine() what's stored with root. Defaults to string a relative path agentSettings.WorkFolder = command.GetWork(); // notificationPipeName for Hosted agent provisioner. agentSettings.NotificationPipeName = command.GetNotificationPipeName(); agentSettings.MonitorSocketAddress = command.GetMonitorSocketAddress(); agentSettings.NotificationSocketAddress = command.GetNotificationSocketAddress(); _store.SaveSettings(agentSettings); if (saveProxySetting) { Trace.Info("Save proxy setting to disk."); (vstsProxy as VstsAgentWebProxy).SaveProxySetting(); } if (saveCertSetting) { Trace.Info("Save agent cert setting to disk."); (agentCertManager as AgentCertificateManager).SaveCertificateSetting(); } _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow)); bool saveRuntimeOptions = false; var runtimeOptions = new AgentRuntimeOptions(); if (PlatformUtil.RunningOnWindows && command.GitUseSChannel) { saveRuntimeOptions = true; runtimeOptions.GitUseSecureChannel = true; } if (saveRuntimeOptions) { Trace.Info("Save agent runtime options to disk."); _store.SaveAgentRuntimeOptions(runtimeOptions); } if (PlatformUtil.RunningOnWindows) { // config windows service bool runAsService = command.GetRunAsService(); if (runAsService) { Trace.Info("Configuring to run the agent as service"); var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>(); serviceControlManager.ConfigureService(agentSettings, command); } // config auto logon else if (command.GetRunAsAutoLogon()) { Trace.Info("Agent is going to run as process setting up the 'AutoLogon' capability for the agent."); var autoLogonConfigManager = HostContext.GetService <IAutoLogonManager>(); await autoLogonConfigManager.ConfigureAsync(command); //Important: The machine may restart if the autologon user is not same as the current user //if you are adding code after this, keep that in mind } } else if (PlatformUtil.RunningOnLinux) { // generate service config script for Linux var serviceControlManager = HostContext.GetService <ILinuxServiceControlManager>(); serviceControlManager.GenerateScripts(agentSettings); } else if (PlatformUtil.RunningOnMacOS) { // generate service config script for macOS var serviceControlManager = HostContext.GetService <IMacOSServiceControlManager>(); serviceControlManager.GenerateScripts(agentSettings); } }
public NuGetSettingsCredentialProvider(ICredentialProvider credentialProvider, IPackageSourceProvider packageSourceProvider, ILogger logger) : base(credentialProvider, packageSourceProvider, logger) { }
/// <summary> /// Validate the ClaimsIdentity as sent from a Bot Framework Government Channel Service. /// </summary> /// <param name="identity">The claims identity to validate.</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="serviceUrl">The service url from the request.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task ValidateIdentity(ClaimsIdentity identity, ICredentialProvider credentials, string serviceUrl) { if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException(); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException(); } // Now check that the AppID in the claimset matches // what we're looking for. Note that in a multi-tenant bot, this value // comes from developer code that may be reaching out to a service, hence the // Async validation. // Look for the "aud" claim, but only if issued from the Bot Framework Claim audienceClaim = identity.Claims.FirstOrDefault( c => c.Issuer == GovernmentAuthenticationConstants.ToBotFromChannelTokenIssuer && c.Type == AuthenticationConstants.AudienceClaim); if (audienceClaim == null) { // The relevant audience Claim MUST be present. Not Authorized. throw new UnauthorizedAccessException(); } // The AppId from the claim in the token must match the AppId specified by the developer. // In this case, the token is destined for the app, so we find the app ID in the audience claim. string appIdFromClaim = audienceClaim.Value; if (string.IsNullOrWhiteSpace(appIdFromClaim)) { // Claim is present, but doesn't have a value. Not Authorized. throw new UnauthorizedAccessException(); } if (!await credentials.IsValidAppIdAsync(appIdFromClaim)) { // The AppId is not valid. Not Authorized. throw new UnauthorizedAccessException($"Invalid AppId passed on token: {appIdFromClaim}"); } if (serviceUrl != null) { var serviceUrlClaim = identity.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.ServiceUrlClaim)?.Value; if (string.IsNullOrWhiteSpace(serviceUrlClaim)) { // Claim must be present. Not Authorized. throw new UnauthorizedAccessException(); } if (!string.Equals(serviceUrlClaim, serviceUrl)) { // Claim must match. Not Authorized. throw new UnauthorizedAccessException(); } } }
/// <summary> /// Validate the incoming Auth Header as a token sent from a Bot Framework Government Channel Service. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="serviceUrl">The service url from the request.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <param name="authConfig">The authentication configuration.</param> /// <returns>ClaimsIdentity.</returns> public static async Task <ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, string serviceUrl, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig) { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } var tokenExtractor = new JwtTokenExtractor( httpClient, ToBotFromGovernmentChannelTokenValidationParameters, OpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false); await ValidateIdentity(identity, credentials, serviceUrl).ConfigureAwait(false); return(identity); }
/// <summary> /// Validate the incoming Auth Header as a token sent from a Bot Framework Government Channel Service. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="serviceUrl">The service url from the request.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <returns>ClaimsIdentity.</returns> public static async Task <ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, string serviceUrl, HttpClient httpClient, string channelId) { return(await AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false)); }
private TestCredentialProvider(ICredentialProvider provider) { this.provider = provider; Credentials = new Dictionary<Uri, ICredentials>(); }
/// <summary> /// Create virtual machine factory /// </summary> /// <param name="creds"></param> /// <param name="selector"></param> /// <param name="logger"></param> public VirtualMachineFactory(ICredentialProvider creds, ISubscriptionInfoSelector selector, ILogger logger) : this(creds, selector, null, logger) { }
/// <summary> /// Keeps sending requests until a response code that doesn't require authentication happens or if /// the request requires authentication and the user has stopped trying to enter them (i.e. they hit cancel when they are prompted). /// </summary> internal static WebResponse GetResponse(Func<WebRequest> createRequest, Action<WebRequest> prepareRequest, IProxyCache proxyCache, ICredentialCache credentialCache, ICredentialProvider credentialProvider) { IHttpWebResponse previousResponse = null; HttpStatusCode? previousStatusCode = null; bool usingSTSAuth = false; bool continueIfFailed = true; int proxyCredentialsRetryCount = 0; int credentialsRetryCount = 0; while (true) { // Create the request var request = (HttpWebRequest)createRequest(); request.Proxy = proxyCache.GetProxy(request.RequestUri); if (request.Proxy != null && request.Proxy.Credentials == null) { request.Proxy.Credentials = CredentialCache.DefaultCredentials; } if (previousResponse == null) { // Try to use the cached credentials (if any, for the first request) request.Credentials = credentialCache.GetCredentials(request.RequestUri); // If there are no cached credentials, use the default ones if (request.Credentials == null) { request.UseDefaultCredentials = true; } } else if (previousStatusCode == HttpStatusCode.ProxyAuthenticationRequired) { request.Proxy.Credentials = credentialProvider.GetCredentials(request, CredentialType.ProxyCredentials, retrying: proxyCredentialsRetryCount > 0); continueIfFailed = request.Proxy.Credentials != null; proxyCredentialsRetryCount++; } else if ((previousStatusCode == HttpStatusCode.Unauthorized) && !usingSTSAuth) { // If we are using STS, the auth's being performed by a request header. We do not need to ask the user for credentials at this point. request.Credentials = credentialProvider.GetCredentials(request, CredentialType.RequestCredentials, retrying: credentialsRetryCount > 0); continueIfFailed = request.Credentials != null; credentialsRetryCount++; } try { ICredentials credentials = request.Credentials; SetKeepAliveHeaders(request, previousResponse); if (usingSTSAuth) { // Add request headers if the server requires STS based auth. STSAuthHelper.PrepareSTSRequest(request); } // Prepare the request, we do something like write to the request stream // which needs to happen last before the request goes out prepareRequest(request); // Wrap the credentials in a CredentialCache in case there is a redirect // and credentials need to be kept around. request.Credentials = request.Credentials.AsCredentialCache(request.RequestUri); WebResponse response = request.GetResponse(); // Cache the proxy and credentials proxyCache.Add(request.Proxy); credentialCache.Add(request.RequestUri, credentials); credentialCache.Add(response.ResponseUri, credentials); return response; } catch (WebException ex) { using (IHttpWebResponse response = GetResponse(ex.Response)) { if (response == null && ex.Status != WebExceptionStatus.SecureChannelFailure) { // No response, something went wrong so just rethrow throw; } // Special case https connections that might require authentication if (ex.Status == WebExceptionStatus.SecureChannelFailure) { if (continueIfFailed) { // Act like we got a 401 so that we prompt for credentials on the next request previousStatusCode = HttpStatusCode.Unauthorized; continue; } throw; } // If we were trying to authenticate the proxy or the request and succeeded, cache the result. if (previousStatusCode == HttpStatusCode.ProxyAuthenticationRequired && response.StatusCode != HttpStatusCode.ProxyAuthenticationRequired) { proxyCache.Add(request.Proxy); } else if (previousStatusCode == HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.Unauthorized) { credentialCache.Add(request.RequestUri, request.Credentials); credentialCache.Add(response.ResponseUri, request.Credentials); } usingSTSAuth = STSAuthHelper.TryRetrieveSTSToken(request.RequestUri, response); if (!IsAuthenticationResponse(response) || !continueIfFailed) { throw; } previousResponse = response; previousStatusCode = previousResponse.StatusCode; } } } }
/// <summary> /// Authenticates the auth header token from the request. /// </summary> private static async Task <ClaimsIdentity> AuthenticateTokenAsync(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, AuthenticationConfiguration authConfig, string serviceUrl, HttpClient httpClient) { if (SkillValidation.IsSkillToken(authHeader)) { return(await SkillValidation.AuthenticateChannelToken(authHeader, credentials, channelProvider, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (EmulatorValidation.IsTokenFromEmulator(authHeader)) { return(await EmulatorValidation.AuthenticateEmulatorToken(authHeader, credentials, channelProvider, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (channelProvider == null || channelProvider.IsPublicAzure()) { // No empty or null check. Empty can point to issues. Null checks only. if (serviceUrl != null) { return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (channelProvider.IsGovernment()) { return(await GovernmentChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } return(await EnterpriseChannelValidation.AuthenticateChannelToken(authHeader, credentials, channelProvider, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); }
/// <summary> /// Authenticates the request and adds the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="authConfig">The optional authentication configuration.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, AuthenticationConfiguration authConfig, HttpClient httpClient = null) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } if (string.IsNullOrWhiteSpace(authHeader)) { var isAuthDisabled = await credentials.IsAuthenticationDisabledAsync().ConfigureAwait(false); if (!isAuthDisabled) { // No Auth Header and Auth is required. Request is not authorized. throw new UnauthorizedAccessException(); } // Check if the activity is for a skill call and is coming from the Emulator. if (activity.ChannelId == Channels.Emulator && activity.Recipient?.Role == RoleTypes.Skill) { // Return an anonymous claim with an anonymous skill AppId return(SkillValidation.CreateAnonymousSkillClaim()); } // In the scenario where Auth is disabled, we still want to have the // IsAuthenticated flag set in the ClaimsIdentity. To do this requires // adding in an empty claim. return(new ClaimsIdentity(new List <Claim>(), AuthenticationConstants.AnonymousAuthType)); } // Validate the header and extract claims. var claimsIdentity = await ValidateAuthHeader(authHeader, credentials, provider, activity.ChannelId, authConfig, activity.ServiceUrl, httpClient ?? _httpClient).ConfigureAwait(false); return(claimsIdentity); }
public static DefaultProfile GetProfile(string regionId, ICredentialProvider icredential) { profile = new DefaultProfile(regionId, icredential); return(profile); }
private DefaultProfile(ICredentialProvider icredential) { this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); }
/// <summary> /// Initializes a new instance of the <see cref="BotFrameworkHttpAdapterBase"/> class. /// </summary> /// <param name="credentialProvider">The credential provider.</param> /// <param name="channelProvider">The channel provider.</param> /// <param name="httpClient">The HTTP client.</param> /// <param name="logger">The ILogger implementation this adapter should use.</param> public BotFrameworkHttpAdapterBase(ICredentialProvider credentialProvider, IChannelProvider channelProvider, HttpClient httpClient, ILogger <BotFrameworkHttpAdapterBase> logger) : this(credentialProvider ?? new SimpleCredentialProvider(), new AuthenticationConfiguration(), channelProvider, null, httpClient, null, logger) { }
private static string CredentialCacheKey(Uri uri, CredentialRequestType type, ICredentialProvider provider) { var rootUri = new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)); return(GetUriKey(rootUri, type, provider)); }
public async Task ConfigureAsync(CommandSettings command) { Trace.Info(nameof(ConfigureAsync)); if (IsConfigured()) { throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError")); } // TEE EULA bool acceptTeeEula = false; switch (Constants.Agent.Platform) { case Constants.OSPlatform.OSX: case Constants.OSPlatform.Linux: // Write the section header. WriteSection(StringUtil.Loc("EulasSectionHeader")); // Verify the EULA exists on disk in the expected location. string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html"); ArgUtil.File(eulaFile, nameof(eulaFile)); // Write elaborate verbiage about the TEE EULA. _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile)); _term.WriteLine(); // Prompt to acccept the TEE EULA. acceptTeeEula = command.GetAcceptTeeEula(); break; case Constants.OSPlatform.Windows: break; default: throw new NotSupportedException(); } // Create the configuration provider as per agent type..... string agentType = command.MachineGroup ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; var extensionManager = HostContext.GetService <IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); // TODO: Check if its running with elevated permission and stop early if its not // Loop getting url and creds until you can connect string serverUrl = null; ICredentialProvider credProvider = null; VssCredentials creds = null; WriteSection(StringUtil.Loc("ConnectSectionHeader")); while (true) { // Get the URL serverUrl = agentProvider.GetServerUrl(command); // Get the credentials credProvider = GetCredentialProvider(command, serverUrl); creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); try { // Validate can connect. await agentProvider.TestConnectionAsync(serverUrl, creds); Trace.Info("Test Connection complete."); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToConnect")); } } _agentServer = HostContext.GetService <IAgentServer>(); // We want to use the native CSP of the platform for storage, so we use the RSACSP directly RSAParameters publicKey; var keyManager = HostContext.GetService <IRSAKeyManager>(); using (var rsa = keyManager.CreateKey()) { publicKey = rsa.ExportParameters(false); } // Loop getting agent name and pool name string poolName = null; int poolId = 0; string agentName = null; WriteSection(StringUtil.Loc("RegisterAgentSectionHeader")); while (true) { try { poolId = await agentProvider.GetPoolId(command); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(agentProvider.GetFailedToFindPoolErrorString()); } } TaskAgent agent; while (true) { agentName = command.GetAgentName(); // Get the system capabilities. // TODO: Hook up to ctrl+c cancellation token. _term.WriteLine(StringUtil.Loc("ScanToolCapabilities")); Dictionary <string, string> systemCapabilities = await HostContext.GetService <ICapabilitiesManager>().GetCapabilitiesAsync( new AgentSettings { AgentName = agentName }, CancellationToken.None); _term.WriteLine(StringUtil.Loc("ConnectToServer")); agent = await GetAgent(agentName, poolId); if (agent != null) { if (command.GetReplace()) { // Update existing agent with new PublicKey, agent version and SystemCapabilities. agent = UpdateExistingAgent(agent, publicKey, systemCapabilities); try { agent = await agentProvider.UpdateAgentAsync(poolId, agent); _term.WriteLine(StringUtil.Loc("AgentReplaced")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToReplaceAgent")); } } else if (command.Unattended) { // if not replace and it is unattended config. throw new TaskAgentExistsException(StringUtil.Loc("AgentWithSameNameAlreadyExistInPool", poolId, agentName)); } } else { // Create a new agent. agent = CreateNewAgent(agentName, publicKey, systemCapabilities); try { agent = await agentProvider.AddAgentAsync(poolId, agent); _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("AddAgentFailed")); } } } // respect the serverUrl resolve by server. // in case of agent configured using collection url instead of account url. string agentServerUrl; if (agent.Properties.TryGetValidatedValue <string>("ServerUrl", out agentServerUrl) && !string.IsNullOrEmpty(agentServerUrl)) { Trace.Info($"Agent server url resolve by server: '{agentServerUrl}'."); // we need make sure the Host component of the url remain the same. UriBuilder inputServerUrl = new UriBuilder(serverUrl); UriBuilder serverReturnedServerUrl = new UriBuilder(agentServerUrl); if (Uri.Compare(inputServerUrl.Uri, serverReturnedServerUrl.Uri, UriComponents.Host, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { inputServerUrl.Path = serverReturnedServerUrl.Path; Trace.Info($"Replace server returned url's host component with user input server url's host: '{inputServerUrl.Uri.AbsoluteUri}'."); serverUrl = inputServerUrl.Uri.AbsoluteUri; } else { serverUrl = agentServerUrl; } } // See if the server supports our OAuth key exchange for credentials if (agent.Authorization != null && agent.Authorization.ClientId != Guid.Empty && agent.Authorization.AuthorizationUrl != null) { var credentialData = new CredentialData { Scheme = Constants.Configuration.OAuth, Data = { { "clientId", agent.Authorization.ClientId.ToString("D") }, { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri }, }, }; // Save the negotiated OAuth credential data _store.SaveCredential(credentialData); } else { // Save the provided admin credential data for compat with existing agent _store.SaveCredential(credProvider.CredentialData); } // Testing agent connection, detect any protential connection issue, like local clock skew that cause OAuth token expired. _term.WriteLine(StringUtil.Loc("TestAgentConnection")); var credMgr = HostContext.GetService <ICredentialManager>(); VssCredentials credential = credMgr.LoadCredentials(); VssConnection conn = ApiUtil.CreateConnection(new Uri(serverUrl), credential); var agentSvr = HostContext.GetService <IAgentServer>(); try { await agentSvr.ConnectAsync(conn); } catch (VssOAuthTokenRequestException ex) when(ex.Message.Contains("Current server time is")) { // there are two exception messages server send that indicate clock skew. // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}. // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}. Trace.Error("Catch exception during test agent connection."); Trace.Error(ex); throw new Exception(StringUtil.Loc("LocalClockSkewed")); } // We will Combine() what's stored with root. Defaults to string a relative path string workFolder = command.GetWork(); // notificationPipeName for Hosted agent provisioner. string notificationPipeName = command.GetNotificationPipeName(); // Get Agent settings var settings = new AgentSettings { AcceptTeeEula = acceptTeeEula, AgentId = agent.Id, AgentName = agentName, NotificationPipeName = notificationPipeName, PoolId = poolId, PoolName = poolName, ServerUrl = serverUrl, WorkFolder = workFolder }; // This is required in case agent is configured as DeploymentAgent. It will make entry for projectName and MachineGroup agentProvider.UpdateAgentSetting(settings); _store.SaveSettings(settings); _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow)); #if OS_WINDOWS // config windows service as part of configuration bool runAsService = command.GetRunAsService(); if (!runAsService) { return; } else { if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { Trace.Error("Needs Administrator privileges for configure agent as windows service."); throw new SecurityException(StringUtil.Loc("NeedAdminForConfigAgentWinService")); } Trace.Info("Configuring to run the agent as service"); var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>(); serviceControlManager.ConfigureService(settings, command); } #elif OS_LINUX || OS_OSX // generate service config script for OSX and Linux, GenerateScripts() will no-opt on windows. var serviceControlManager = HostContext.GetService <ILinuxServiceControlManager>(); serviceControlManager.GenerateScripts(settings); #endif }
static SettingsCredentialProvider CreateSettingsCredentialProvider (ICredentialProvider credentialProvider) { ISettings settings = LoadSettings (); var packageSourceProvider = new PackageSourceProvider (settings); return new SettingsCredentialProvider(credentialProvider, packageSourceProvider); }
public SettingsCredentialProvider(ICredentialProvider credentialProvider, IPackageSourceProvider packageSourceProvider) : this(credentialProvider, packageSourceProvider, NullLogger.Instance) { }
public ProxyProvider(string configurationDirectory, string configurationFile, ICredentialProvider credentialProvider) { _configuration = new ConfigurationBuilder() .SetBasePath(configurationDirectory) .AddJsonFile(configurationFile, optional: true, reloadOnChange: true) .Build(); _credentialsWrapper = new CredentialsWrapper(CredentialCache.DefaultNetworkCredentials); _credentialProvider = credentialProvider; }
public BotFrameworkHttpAdapter(ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILogger <BotFrameworkHttpAdapter> logger = null) : this(credentialProvider ?? new SimpleCredentialProvider(), new AuthenticationConfiguration(), channelProvider, null, null, null, logger) { }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, string serviceUrl = null, HttpClient httpClient = null) { return(await ValidateAuthHeader(authHeader, credentials, channelProvider, channelId, new AuthenticationConfiguration(), serviceUrl, httpClient).ConfigureAwait(false)); }
private bool TryFromCredentialCache(Uri uri, CredentialRequestType type, bool isRetry, ICredentialProvider provider, out CredentialResponse credentials) { credentials = null; var key = CredentialCacheKey(uri, type, provider); if (isRetry) { CredentialResponse removed; _providerCredentialCache.TryRemove(key, out removed); return(false); } return(_providerCredentialCache.TryGetValue(key, out credentials)); }
/// <summary> /// Authenticates the request and adds the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="authConfig">The optional authentication configuration.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, AuthenticationConfiguration authConfig, HttpClient httpClient = null) { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } if (string.IsNullOrWhiteSpace(authHeader)) { var isAuthDisabled = await credentials.IsAuthenticationDisabledAsync().ConfigureAwait(false); if (isAuthDisabled) { // In the scenario where Auth is disabled, we still want to have the // IsAuthenticated flag set in the ClaimsIdentity. To do this requires // adding in an empty claim. return(new ClaimsIdentity(new List <Claim>(), "anonymous")); } // No Auth Header. Auth is required. Request is not authorized. throw new UnauthorizedAccessException(); } var claimsIdentity = await ValidateAuthHeader(authHeader, credentials, provider, activity.ChannelId, authConfig, activity.ServiceUrl, httpClient ?? _httpClient).ConfigureAwait(false); AppCredentials.TrustServiceUrl(activity.ServiceUrl); return(claimsIdentity); }
private void AddToCredentialCache(Uri uri, CredentialRequestType type, ICredentialProvider provider, CredentialResponse credentials) { _providerCredentialCache[CredentialCacheKey(uri, type, provider)] = credentials; }
static SettingsCredentialProvider CreateSettingsCredentialProvider (ICredentialProvider credentialProvider) { ISettings settings = Settings.LoadDefaultSettings (null, null, null); var packageSourceProvider = new PackageSourceProvider (settings); return new SettingsCredentialProvider(credentialProvider, packageSourceProvider); }
private static string RetryCacheKey(Uri uri, CredentialRequestType type, ICredentialProvider provider) { return(GetUriKey(uri, type, provider)); }
public TeamCityMultipleCredentialProvider(IEnumerable <INuGetSource> sources, ICredentialProvider next = null) { mySources = sources .Where(x => x.HasCredentials) .ToDictionary( x => UriEquals(x.Source), x => new TeamCitySingleCredentialProvider(x) ); myNext = next; }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="authConfig">The authentication configuration.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, AuthenticationConfiguration authConfig, string serviceUrl = null, HttpClient httpClient = null) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { if (string.IsNullOrEmpty(authHeader)) { throw new ArgumentNullException(nameof(authHeader)); } if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } httpClient = httpClient ?? _httpClient; var identity = await AuthenticateTokenAsync(authHeader, credentials, channelProvider, channelId, authConfig, serviceUrl, httpClient).ConfigureAwait(false); await ValidateClaimsAsync(authConfig, identity.Claims).ConfigureAwait(false); return(identity); }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, string serviceUrl = null, HttpClient httpClient = null) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { return(await ValidateAuthHeader(authHeader, credentials, channelProvider, channelId, new AuthenticationConfiguration(), serviceUrl, httpClient).ConfigureAwait(false)); }
public async Task <int> RunAsync(CommandSettings command, CancellationToken token) { Trace.Info(nameof(RunAsync)); var configStore = HostContext.GetService <IConfigurationStore>(); AgentSettings settings = configStore.GetSettings(); // Store the HTTP client. // todo: fix in master to allow URL to be empty and then rebase on master. const string DefaultUrl = "http://127.0.0.1/local-runner-default-url"; string url = command.GetUrl(DefaultUrl); if (!string.Equals(url, DefaultUrl, StringComparison.Ordinal)) { var credentialManager = HostContext.GetService <ICredentialManager>(); string authType = command.GetAuth(defaultValue: Constants.Configuration.Integrated); ICredentialProvider provider = credentialManager.GetCredentialProvider(authType); provider.EnsureCredential(HostContext, command, url); _httpClient = new TaskAgentHttpClient(new Uri(url), provider.GetVssCredentials(HostContext)); } // Load the YAML file. string yamlFile = command.GetYaml(); ArgUtil.File(yamlFile, nameof(yamlFile)); var parseOptions = new ParseOptions { MaxFiles = 10, MustacheEvaluationMaxResultLength = 512 * 1024, // 512k string length MustacheEvaluationTimeout = TimeSpan.FromSeconds(10), MustacheMaxDepth = 5, }; var pipelineParser = new PipelineParser(new PipelineTraceWriter(), new PipelineFileProvider(), parseOptions); Pipelines.Process process = pipelineParser.Load( defaultRoot: Directory.GetCurrentDirectory(), path: yamlFile, mustacheContext: null, cancellationToken: HostContext.AgentShutdownToken); ArgUtil.NotNull(process, nameof(process)); if (command.WhatIf) { return(Constants.Agent.ReturnCode.Success); } // Create job message. IJobDispatcher jobDispatcher = null; try { jobDispatcher = HostContext.CreateService <IJobDispatcher>(); foreach (JobInfo job in await ConvertToJobMessagesAsync(process, token)) { job.RequestMessage.Environment.Variables[Constants.Variables.Agent.RunMode] = RunMode.Local.ToString(); jobDispatcher.Run(job.RequestMessage); Task jobDispatch = jobDispatcher.WaitAsync(token); if (!Task.WaitAll(new[] { jobDispatch }, job.Timeout)) { jobDispatcher.Cancel(job.CancelMessage); // Finish waiting on the same job dispatch task. The first call to WaitAsync dequeues // the dispatch task and then proceeds to wait on it. So we need to continue awaiting // the task instance (queue is now empty). await jobDispatch; } } } finally { if (jobDispatcher != null) { await jobDispatcher.ShutdownAsync(); } } return(Constants.Agent.ReturnCode.Success); }
private TestCredentialProvider(ICredentialProvider provider) { this.provider = provider; Credentials = new Dictionary <Uri, ICredentials>(); }
/// <summary> /// Authenticates the request and adds the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, HttpClient httpClient = null) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { return(await AuthenticateRequest(activity, authHeader, credentials, provider, new AuthenticationConfiguration(), httpClient).ConfigureAwait(false)); }