public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "secrets/{managedSecretId:guid}/{nonce}")] HttpRequest req, Guid managedSecretId, string nonce, ILogger log) { _ = req; // unused but required for attribute log.LogInformation("External signal called to check ManagedSecret ID {0} against nonce {1}", managedSecretId, nonce); var secret = await ManagedSecrets.GetAsync(managedSecretId); if (secret == null) { return(new BadRequestErrorMessageResult("Invalid ManagedSecret ID")); } if (!secret.TaskConfirmationStrategies.HasFlag(TaskConfirmationStrategies.ExternalSignal)) { return(new BadRequestErrorMessageResult("This ManagedSecret cannot be used with External Signals")); } if ((await RekeyingTasks.GetAsync(t => t.ManagedSecretId == secret.ObjectId)) .Any(t => t.RekeyingInProgress)) { return(new OkObjectResult(RETURN_RETRY_SHORTLY)); } if ((secret.IsValid && secret.TimeRemaining <= TimeSpan.FromHours(ServiceConfiguration.ExternalSignalRekeyableLeadTimeHours)) || !secret.IsValid) { var rekeyingTask = new Task(async() => { var task = new RekeyingTask() { ManagedSecretId = secret.ObjectId, Expiry = secret.Expiry, Queued = DateTimeOffset.UtcNow, RekeyingInProgress = true }; await RekeyingTasks.CreateAsync(task); var rekeyingAttemptLogger = new RekeyingAttemptLogger(log) { UserDisplayName = "Agent Identity", UserEmail = string.Empty }; try { await ExecuteRekeyingWorkflow(task, rekeyingAttemptLogger); } catch (Exception ex) { rekeyingAttemptLogger.OuterException = JsonConvert.SerializeObject(ex, Formatting.Indented); } task.RekeyingInProgress = false; task.RekeyingCompleted = rekeyingAttemptLogger.IsSuccessfulAttempt; task.RekeyingFailed = !rekeyingAttemptLogger.IsSuccessfulAttempt; task.Attempts.Add(rekeyingAttemptLogger); await RekeyingTasks.UpdateAsync(task); }, TaskCreationOptions.LongRunning); rekeyingTask.Start(); if (!rekeyingTask.Wait(TimeSpan.FromSeconds(MAX_EXECUTION_SECONDS_BEFORE_RETRY))) { log.LogInformation("Rekeying workflow was started but exceeded the maximum request time! ({0})", TimeSpan.FromSeconds(MAX_EXECUTION_SECONDS_BEFORE_RETRY)); return(new OkObjectResult(RETURN_RETRY_SHORTLY)); } else { log.LogInformation("Completed rekeying workflow within maximum time! ({0})", TimeSpan.FromSeconds(MAX_EXECUTION_SECONDS_BEFORE_RETRY)); return(new OkObjectResult(RETURN_CHANGE_OCCURRED)); } } return(new OkObjectResult(RETURN_NO_CHANGE)); }
protected async Task <RekeyingAttemptLogger> ExecuteRekeyingWorkflow(RekeyingTask task, RekeyingAttemptLogger log = null) { if (log == null) { log = new RekeyingAttemptLogger(); } MultiCredentialProvider.CredentialType credentialType; if (task.ConfirmationType == TaskConfirmationStrategies.AdminCachesSignOff) { if (task.PersistedCredentialId == default) { log.LogError("Cached sign-off is preferred but no credentials were persisted!"); throw new Exception("Cached sign-off is preferred but no credentials were persisted!"); } var token = await SecureStorageProvider.Retrieve <Azure.Core.AccessToken>(task.PersistedCredentialId); CredentialProvider.Register( MultiCredentialProvider.CredentialType.CachedCredential, token.Token, token.ExpiresOn); credentialType = MultiCredentialProvider.CredentialType.CachedCredential; } else if (task.ConfirmationType == TaskConfirmationStrategies.AdminSignsOffJustInTime) { credentialType = MultiCredentialProvider.CredentialType.UserCredential; } else { credentialType = MultiCredentialProvider.CredentialType.AgentServicePrincipal; } log.LogInformation("Using credential type {0} to access resources", credentialType); var secret = await ManagedSecrets.GetAsync(task.ManagedSecretId); log.LogInformation("Beginning rekeying for ManagedSecret '{0}' (ID {1})", secret.Name, secret.ObjectId); var resources = await Resources.GetAsync(r => secret.ResourceIds.Contains(r.ObjectId)); var workflow = new ProviderActionWorkflow(log, resources.Select(r => GetProvider(log, r.ProviderType, r.ProviderConfiguration, credentialType))); try { await workflow.InvokeAsync(secret.ValidPeriod); secret.LastChanged = DateTimeOffset.UtcNow; await ManagedSecrets.UpdateAsync(secret); log.LogInformation("Completed rekeying workflow for ManagedSecret '{0}' (ID {1})", secret.Name, secret.ObjectId); if (credentialType == MultiCredentialProvider.CredentialType.CachedCredential) { log.LogInformation("Destroying persisted credential"); await SecureStorageProvider.Destroy(task.PersistedCredentialId); } log.LogInformation("Rekeying task completed"); } catch (Exception ex) { log.LogCritical(ex, "Error running rekeying task!"); log.LogCritical(ex.Message); log.LogCritical(ex.StackTrace); log.OuterException = JsonConvert.SerializeObject(ex, Formatting.Indented); } return(log); }