Ejemplo n.º 1
0
        public void OverridesServiceCredentialWithPerCallCredential_TwoCallCredentials()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
            var callCredential1   = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN_1", new BearerToken.QueryParameterAccessMethod());
            var callCredential2   = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN_2", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete

            var request = BuildListBucketsRequest(serviceCredential, callCredential1);
            request.AddCredential(callCredential2);

            // This should throw unauthorized, the credentials are fake, but let's make sure the
            // request got to the server so we know all appropiate interceptors executed.
            var exception = Assert.ThrowsAny <GoogleApiException>(() => request.Execute());
            Assert.Equal(401, exception.Error.Code);

            string query = serviceCredential.Request.RequestUri.Query;

            int serviceIndex = query.IndexOf("access_token=SERVICE_CREDENTIAL_TOKEN", StringComparison.OrdinalIgnoreCase);
            int call1Index   = query.LastIndexOf("access_token=CALL_CREDENTIAL_TOKEN_1", StringComparison.OrdinalIgnoreCase);
            int call2Index   = query.LastIndexOf("access_token=CALL_CREDENTIAL_TOKEN_2", StringComparison.OrdinalIgnoreCase);

            Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
            Assert.DoesNotContain("access_token=CALL_CREDENTIAL_TOKEN_1", query, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("access_token=CALL_CREDENTIAL_TOKEN_2", query, StringComparison.OrdinalIgnoreCase);
        }
        /// <summary>
        /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
        /// </summary>
        /// <param name="context"></param>
        public ActiveDirectoryClient(AzureContext context)
        {
            AccessTokenCredential creds = (AccessTokenCredential)AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);

            GraphClient = AzureSession.ClientFactory.CreateCustomClient <GraphRbacManagementClient>(
                creds.TenantID,
                creds,
                context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.Graph));
        }
Ejemplo n.º 3
0
        public bool InitiateTokenRefresh()
        {
            var userProfile = userProfileProvider.GetUserProfile();

            if (null == userProfile)
            {
                return(false);
            }
            Console.WriteLine("The session token has expired, attempting to refresh.");
            AccessTokenCredential credentials = userProfileProvider.GetCredentials();

            if (null == credentials)
            {
                Console.WriteLine("No credentials available to implictly connect the cluster.");
                return(false);
            }

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "public/accessTokens")
            {
                Content = new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json")
            };

            try
            {
                var httpClient      = BuildClient(userProfile.ClusterUri, true);
                var response        = httpClient.SendAsync(httpRequest).Result;
                var responseContent = response.Content.ReadAsStringAsync().Result;

                if (response.StatusCode != HttpStatusCode.Created)
                {
                    var           error = JsonConvert.DeserializeObject <ErrorProto>(responseContent);
                    StringBuilder sb    = new StringBuilder();
                    sb.AppendLine(error.ErrorMsg);
                    Console.WriteLine("Exception : Refreshing the token, " + sb.ToString());
                    return(false);
                }

                var accessToken = JsonConvert.DeserializeObject <AccessToken>(responseContent);

                userProfile.AccessToken = accessToken;
                userProfileProvider.SetUserProfile(userProfile);
                Console.WriteLine("The session token has been refreshed.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : Refreshing the token, " + ex.Message);
                return(false);
            }
            return(true);
        }
        public void OverridesServiceCredentialWithPerCallCredential_QueryString()
        {
            var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
            var callCredential    = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());

            var request = BuildListBucketsRequest(serviceCredential, callCredential);

            // This should throw unauthorized, the credentials are fake, but let's make sure the
            // request got to the server so we know all appropiate interceptors executed.
            var exception = Assert.ThrowsAny <GoogleApiException>(() => request.Execute());

            Assert.Equal(401, exception.Error.Code);

            string query = serviceCredential.Request.RequestUri.Query;

            Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("access_token=CALL_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
        }
Ejemplo n.º 5
0
        public void OverridesServiceCredentialWithPerCallCredential_Mixed_Query_Header()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete
            var callCredential = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN", new BearerToken.AuthorizationHeaderAccessMethod());

            var request = BuildListBucketsRequest(serviceCredential, callCredential);

            // This should throw unauthorized, the credentials are fake, but let's make sure the
            // request got to the server so we know all appropiate interceptors executed.
            var exception = Assert.ThrowsAny <GoogleApiException>(() => request.Execute());
            Assert.Equal(401, exception.Error.Code);

            HttpRequestMessage httpRequest = serviceCredential.Request;
            string             query       = httpRequest.RequestUri.Query;

            Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
            Assert.Equal("CALL_CREDENTIAL_TOKEN", httpRequest.Headers.Authorization.Parameter);
        }
        public async Task <IEnumerable <ProviderResourceSuggestion> > EnumerateProviders(AccessTokenCredential credential, IAuthJanitorProvider provider)
        {
            provider.Credential = credential;
            if (provider is ICanEnumerateResourceCandidates)
            {
                var enumerable = provider as ICanEnumerateResourceCandidates;
                try
                {
                    var results = await enumerable.EnumerateResourceCandidates(GetProviderConfiguration(provider.GetType().AssemblyQualifiedName, provider.SerializedConfiguration));

                    return(results.Select(r => new ProviderResourceSuggestion()
                    {
                        Name = r.Name,
                        ProviderType = r.ProviderType,
                        Configuration = r.Configuration,
                        SerializedConfiguration = JsonSerializer.Serialize <object>(r.Configuration),
                        AddressableNames = r.AddressableNames.Distinct(),
                        ResourceValues = r.ResourceValues.Distinct(),
                        ResourcesAddressingThis = r.ResourcesAddressingThis
                    }));
                }
                catch (Exception ex)
                {
                    _serviceProvider.GetRequiredService <ILogger <ProviderManagerService> >().LogError(ex, "Error enumerating resource candidates for provider type " + provider.GetType().AssemblyQualifiedName);
                }
            }
            return(new ProviderResourceSuggestion[0]);
        }
        public async Task <IEnumerable <ProviderResourceSuggestion> > EnumerateProviders(AccessTokenCredential credential)
        {
            var providers = (await Task.WhenAll(
                                 LoadedProviders.Select(p => GetProviderInstanceDefault(p.ProviderTypeName))
                                 .OfType <ICanEnumerateResourceCandidates>()
                                 .Select(p => EnumerateProviders(credential, p))))
                            .Where(c => c != null)
                            .SelectMany(c => c);

            foreach (var provider in providers.Where(p => p.AddressableNames.Any()))
            {
                foreach (var name in provider.AddressableNames)
                {
                    var refs = providers.Where(p => p.ResourceValues.Any(r => r.Contains(name)));
                    provider.ResourcesAddressingThis.AddRange(refs);
                }
            }

            return(providers);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> TestConfiguration(
            string providerConfiguration,
            HttpRequest req,
            string providerType,
            string testContext)
        {
            _ = req;

            if (!_identityService.IsUserLoggedIn)
            {
                return(new UnauthorizedResult());
            }

            Enum.TryParse <TestAsContexts>(testContext, true, out TestAsContexts testContextEnum);
            AccessTokenCredential credential = null;

            try
            {
                switch (testContextEnum)
                {
                case TestAsContexts.AsApp:
                    credential = await _identityService.GetAccessTokenForApplicationAsync();

                    break;

                case TestAsContexts.AsUser:
                    credential = await _identityService.GetAccessTokenOnBehalfOfCurrentUserAsync();

                    break;

                default:
                    return(new BadRequestErrorMessageResult("Invalid test context"));
                }
                if (credential == null || string.IsNullOrEmpty(credential.AccessToken))
                {
                    throw new Exception("Credential was empty!");
                }
            }
            catch (Exception ex)
            {
                return(new BadRequestErrorMessageResult(
                           "Error retrieving Access Token: " + Environment.NewLine +
                           ex.Message + Environment.NewLine +
                           ex.StackTrace));
            }

            var provider = _providerManager.LoadedProviders.FirstOrDefault(p => p.ProviderTypeName == providerType);

            if (provider == null)
            {
                await _eventDispatcher.DispatchEvent(AuthJanitorSystemEvents.AnomalousEventOccurred, nameof(ProvidersService.GetBlankConfiguration), "Invalid Provider specified");

                return(new NotFoundResult());
            }

            if (typeof(ICanRunSanityTests).IsAssignableFrom(provider.ProviderType))
            {
                try
                {
                    var instance = _providerManager.GetProviderInstance(provider.ProviderTypeName, providerConfiguration);
                    if (instance == null)
                    {
                        return(new BadRequestErrorMessageResult("Provider configuration is invalid!"));
                    }
                    instance.Credential = credential;
                    await(instance as ICanRunSanityTests).Test();
                }
                catch (Exception ex)
                {
                    return(new BadRequestErrorMessageResult(ex.Message));
                }
            }
            else
            {
                return(new BadRequestErrorMessageResult("Provider does not support testing!"));
            }

            return(new OkResult());
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Credential to be authenticated
        /// </summary>
        /// <param name="value"></param>
        public void SetCredential(AccessTokenCredential value)
        {
            this.isValidated = false;

            this.credential = value;
        }
        /// <summary>
        /// Process Records
        /// </summary>
        protected override void ProcessRecord()
        {
            var networkCredential = Credential.GetNetworkCredential();
            var domain            = string.IsNullOrWhiteSpace(networkCredential.Domain) ? LocalDomain : networkCredential.Domain;

            var credentials = new AccessTokenCredential
            {
                Domain   = domain,
                Username = networkCredential.UserName,
                Password = networkCredential.Password
            };

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "public/accessTokens")
            {
                Content = new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json")
            };

            try
            {
                var httpClient      = Session.ApiClient.BuildClient(clusterUri, true);
                var response        = httpClient.SendAsync(httpRequest).Result;
                var responseContent = response.Content.ReadAsStringAsync().Result;

                if (response.StatusCode != HttpStatusCode.Created)
                {
                    var           error = JsonConvert.DeserializeObject <Error>(responseContent);
                    StringBuilder sb    = new StringBuilder();
                    sb.AppendLine("Failed to connect to the Cohesity Cluster");
                    sb.AppendLine(error.Message);
                    throw new Exception(sb.ToString());
                }

                var accessToken = JsonConvert.DeserializeObject <AccessTokenObject>(responseContent);

                var userProfile = new UserProfile
                {
                    ClusterUri  = clusterUri,
                    AccessToken = accessToken,
                    AllowInvalidServerCertificates = true
                };

                userProfileProvider.SetUserProfile(userProfile);

                WriteObject($"Connected to the Cohesity Cluster {Server} Successfully");
            }
            catch (AggregateException ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Failed to connect to the Cohesity Cluster");

                foreach (Exception exInnerException in ex.Flatten().InnerExceptions)
                {
                    Exception exNestedInnerException = exInnerException;
                    do
                    {
                        if (!string.IsNullOrEmpty(exNestedInnerException.Message))
                        {
                            sb.AppendLine(exNestedInnerException.Message);
                        }

                        exNestedInnerException = exNestedInnerException.InnerException;
                    } while (exNestedInnerException != null);
                }

                throw new Exception(sb.ToString());
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Failed to connect to the Cohesity Cluster");
                sb.AppendLine(ex.Message);
                throw new Exception(sb.ToString());
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RegisterRemoteCluster" /> class.
 /// </summary>
 /// <param name="allEndpointsReachable">Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable from this local Cluster. If true, a service running on the local Cluster can communicate directly with any of its peers running on the remote Cluster, without using a proxy..</param>
 /// <param name="bandwidthLimit">Specifies settings for limiting the data transfer rate between the local and remote Clusters..</param>
 /// <param name="clearInterfaces">clearInterfaces.</param>
 /// <param name="clearVlanId">Specifies whether to clear the vlanId field, and thus stop using only the IPs in the VLAN for communicating with the remote Cluster..</param>
 /// <param name="clusterId">Specifies the unique id of the remote Cluster..</param>
 /// <param name="compressionEnabled">Specifies whether to compress the outbound data when transferring the replication data over the network to the remote Cluster..</param>
 /// <param name="encryptionKey">Specifies the encryption key used for encrypting the replication data from a local Cluster to a remote Cluster. If a key is not specified, replication traffic encryption is disabled. When Snapshots are replicated from a local Cluster to a remote Cluster, the encryption key specified on the local Cluster must be the same as the key specified on the remote Cluster..</param>
 /// <param name="networkInterfaceGroup">Specifies the group name of the network interfaces to use for communicating with the remote Cluster..</param>
 /// <param name="networkInterfaceIds">Specifies the ids of the network interfaces to use for communicating with the remote Cluster..</param>
 /// <param name="password">Specifies the password for Cohesity user to use when connecting to the remote Cluster..</param>
 /// <param name="purposeRemoteAccess">Whether the remote cluster will be used for remote access for SPOG..</param>
 /// <param name="purposeReplication">Whether the remote cluster will be used for replication..</param>
 /// <param name="remoteAccessCredentials">Optional field for the user credentials to connect to Iris for remote access for SPOG. If this is not specified, then credentials specified for replication set up will be used for remote access for SPOG. Allowing a different user credentials to be set up for SPOG permits having different roles for remote access for SPOG and replication set up..</param>
 /// <param name="remoteIps">Specifies the IP addresses of the Nodes on the remote Cluster to connect with. These IP addresses can also be VIPS. Specifying hostnames is not supported..</param>
 /// <param name="remoteIrisPorts">Specifies the ports to use when connecting to the Nodes of the remote Cluster..</param>
 /// <param name="userName">Specifies the Cohesity user name used to connect to the remote Cluster..</param>
 /// <param name="validateOnly">Whether to only validate the credentials without saving the information..</param>
 /// <param name="viewBoxPairInfo">Specifies pairings between Storage Domains (View Boxes) on the local Cluster with Storage Domains (View Boxes) on a remote Cluster that are used in replication..</param>
 /// <param name="vlanId">Specifies the Id of the VLAN to use for communicating with the remote Cluster..</param>
 public RegisterRemoteCluster(bool?allEndpointsReachable = default(bool?), BandwidthLimit bandwidthLimit = default(BandwidthLimit), bool?clearInterfaces = default(bool?), bool?clearVlanId = default(bool?), long?clusterId = default(long?), bool?compressionEnabled = default(bool?), string encryptionKey = default(string), string networkInterfaceGroup = default(string), List <long?> networkInterfaceIds = default(List <long?>), string password = default(string), bool?purposeRemoteAccess = default(bool?), bool?purposeReplication = default(bool?), AccessTokenCredential remoteAccessCredentials = default(AccessTokenCredential), List <string> remoteIps = default(List <string>), List <long?> remoteIrisPorts = default(List <long?>), string userName = default(string), bool?validateOnly = default(bool?), List <ViewBoxPairInfo> viewBoxPairInfo = default(List <ViewBoxPairInfo>), int?vlanId = default(int?))
 {
     this.AllEndpointsReachable = allEndpointsReachable;
     this.BandwidthLimit        = bandwidthLimit;
     this.ClearInterfaces       = clearInterfaces;
     this.ClearVlanId           = clearVlanId;
     this.ClusterId             = clusterId;
     this.CompressionEnabled    = compressionEnabled;
     this.EncryptionKey         = encryptionKey;
     this.NetworkInterfaceGroup = networkInterfaceGroup;
     this.NetworkInterfaceIds   = networkInterfaceIds;
     this.Password                = password;
     this.PurposeRemoteAccess     = purposeRemoteAccess;
     this.PurposeReplication      = purposeReplication;
     this.RemoteAccessCredentials = remoteAccessCredentials;
     this.RemoteIps               = remoteIps;
     this.RemoteIrisPorts         = remoteIrisPorts;
     this.UserName                = userName;
     this.ValidateOnly            = validateOnly;
     this.ViewBoxPairInfo         = viewBoxPairInfo;
     this.VlanId = vlanId;
 }
Ejemplo n.º 12
0
 public static TokenCredential CreateTokenCredential(this AccessTokenCredential accessTokenCredential) =>
 new ExistingTokenCredential(accessTokenCredential.AccessToken, accessTokenCredential.ExpiresOnDateTime);
Ejemplo n.º 13
0
 public static AzureCredentials CreateAzureCredentials(this AccessTokenCredential accessTokenCredential) =>
 new AzureCredentials(
     new TokenCredentials(accessTokenCredential.AccessToken, accessTokenCredential.TokenType),
     new TokenCredentials(accessTokenCredential.AccessToken, accessTokenCredential.TokenType),
     Environment.GetEnvironmentVariable("TENANT_ID", EnvironmentVariableTarget.Process),
     AzureEnvironment.AzureGlobalCloud);
Ejemplo n.º 14
0
        public async Task <AccessTokenCredential> GetTokenCredentialAsync(Guid taskId, CancellationToken cancellationToken)
        {
            var task = await _rekeyingTasks.GetOne(taskId, cancellationToken);

            // Retrieve credentials for Task
            AccessTokenCredential credential = null;

            try
            {
                if (task.ConfirmationType == TaskConfirmationStrategies.AdminCachesSignOff)
                {
                    if (task.PersistedCredentialId == default)
                    {
                        throw new KeyNotFoundException("Cached sign-off is preferred but no credentials were persisted!");
                    }

                    if (_secureStorageProvider == null)
                    {
                        throw new NotSupportedException("Must register an ISecureStorageProvider");
                    }

                    credential = await _secureStorageProvider.Retrieve <AccessTokenCredential>(task.PersistedCredentialId);
                }
                else if (task.ConfirmationType == TaskConfirmationStrategies.AdminSignsOffJustInTime)
                {
                    credential = await _identityService.GetAccessTokenOnBehalfOfCurrentUserAsync();
                }
                else if (task.ConfirmationType.UsesServicePrincipal())
                {
                    credential = await _identityService.GetAccessTokenForApplicationAsync();
                }
                else
                {
                    throw new NotSupportedException("No Access Tokens could be generated for this Task!");
                }

                if (credential == null || string.IsNullOrEmpty(credential.AccessToken))
                {
                    throw new InvalidOperationException("Access Token was found, but was blank or invalid");
                }

                credential.DisplayUserName = credential.Username;
                credential.DisplayEmail    = credential.Username;
                if (task.ConfirmationType.UsesOBOTokens())
                {
                    if (!string.IsNullOrEmpty(task.PersistedCredentialUser))
                    {
                        credential.DisplayUserName = task.PersistedCredentialUser;
                    }
                    else
                    {
                        credential.DisplayUserName = _identityService.UserName;
                        credential.DisplayEmail    = _identityService.UserEmail;
                    }
                }

                return(credential);
            }
            catch (Exception ex)
            {
                await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task);

                throw ex;
            }
        }
 public static ExistingTokenCredential FromAccessToken(AccessTokenCredential token) =>
 new ExistingTokenCredential(token.AccessToken, token.ExpiresOnDateTime);
Ejemplo n.º 16
0
        public async Task ExecuteTask(Guid taskId, CancellationToken cancellationToken)
        {
            // Prepare record
            var task = await _rekeyingTasks.GetOne(taskId, cancellationToken);

            task.RekeyingInProgress = true;
            var rekeyingAttemptLog = new RekeyingAttemptLogger();

            task.Attempts.Add(rekeyingAttemptLog);
            await _rekeyingTasks.Update(task, cancellationToken);

            var logUpdateCancellationTokenSource = new CancellationTokenSource();
            var logUpdateTask = Task.Run(async() =>
            {
                while (task.RekeyingInProgress)
                {
                    await Task.Delay(15 * 1000);
                    await _rekeyingTasks.Update(task, cancellationToken);
                }
            }, logUpdateCancellationTokenSource.Token);

            // Retrieve credentials for Task
            AccessTokenCredential credential = null;

            try
            {
                if (task.ConfirmationType == TaskConfirmationStrategies.AdminCachesSignOff)
                {
                    if (task.PersistedCredentialId == default)
                    {
                        throw new KeyNotFoundException("Cached sign-off is preferred but no credentials were persisted!");
                    }

                    if (_secureStorageProvider == null)
                    {
                        throw new NotSupportedException("Must register an ISecureStorageProvider");
                    }

                    credential = await _secureStorageProvider.Retrieve <AccessTokenCredential>(task.PersistedCredentialId);
                }
                else if (task.ConfirmationType == TaskConfirmationStrategies.AdminSignsOffJustInTime)
                {
                    credential = await _identityService.GetAccessTokenOnBehalfOfCurrentUserAsync();
                }
                else if (task.ConfirmationType.UsesServicePrincipal())
                {
                    credential = await _identityService.GetAccessTokenForApplicationAsync();
                }
                else
                {
                    throw new NotSupportedException("No Access Tokens could be generated for this Task!");
                }

                if (credential == null || string.IsNullOrEmpty(credential.AccessToken))
                {
                    throw new InvalidOperationException("Access Token was found, but was blank or invalid");
                }
            }
            catch (Exception ex)
            {
                await EmbedException(task, ex, cancellationToken, "Exception retrieving Access Token");

                await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task);

                return;
            }

            // Embed credential context in attempt log
            rekeyingAttemptLog.UserDisplayName = credential.Username;
            rekeyingAttemptLog.UserEmail       = credential.Username;
            if (task.ConfirmationType.UsesOBOTokens())
            {
                if (!string.IsNullOrEmpty(task.PersistedCredentialUser))
                {
                    rekeyingAttemptLog.UserDisplayName = task.PersistedCredentialUser;
                }
                else
                {
                    rekeyingAttemptLog.UserDisplayName = _identityService.UserName;
                    rekeyingAttemptLog.UserEmail       = _identityService.UserEmail;
                }
            }

            // Retrieve targets
            var secret = await _managedSecrets.GetOne(task.ManagedSecretId, cancellationToken);

            rekeyingAttemptLog.LogInformation("Beginning rekeying of secret ID {SecretId}", task.ManagedSecretId);
            var resources = await _resources.Get(r => secret.ResourceIds.Contains(r.ObjectId), cancellationToken);

            await _rekeyingTasks.Update(task, cancellationToken);

            // Execute rekeying workflow
            try
            {
                var providers = resources.Select(r => _providerManagerService.GetProviderInstance(
                                                     r.ProviderType,
                                                     r.ProviderConfiguration)).ToList();

                // Link in automation bindings from the outer flow
                providers.ForEach(p => p.Credential = credential);

                await _providerManagerService.ExecuteRekeyingWorkflow(rekeyingAttemptLog, secret.ValidPeriod, providers);
            }
            catch (Exception ex)
            {
                rekeyingAttemptLog.IsComplete = true;
                await EmbedException(task, ex, cancellationToken, "Error executing rekeying workflow!");

                await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task);
            }

            // Update Task record
            task.RekeyingInProgress = false;
            task.RekeyingCompleted  = rekeyingAttemptLog.IsSuccessfulAttempt;
            task.RekeyingFailed     = !rekeyingAttemptLog.IsSuccessfulAttempt;

            logUpdateCancellationTokenSource.Cancel();

            await _rekeyingTasks.Update(task, cancellationToken);

            // Run cleanup if Task is complete
            if (task.RekeyingCompleted)
            {
                try
                {
                    secret.LastChanged = DateTimeOffset.UtcNow;
                    await _managedSecrets.Update(secret, cancellationToken);

                    if (task.PersistedCredentialId != default && task.PersistedCredentialId != Guid.Empty)
                    {
                        rekeyingAttemptLog.LogInformation("Destroying persisted credential");
                        await _secureStorageProvider.Destroy(task.PersistedCredentialId);

                        task.PersistedCredentialId   = default;
                        task.PersistedCredentialUser = default;
                    }

                    rekeyingAttemptLog.LogInformation("Completed rekeying workflow for ManagedSecret '{ManagedSecretName}' (ID {ManagedSecretId})", secret.Name, secret.ObjectId);
                    rekeyingAttemptLog.LogInformation("Rekeying task completed");

                    await _rekeyingTasks.Update(task, cancellationToken);
                }
                catch (Exception ex)
                {
                    await EmbedException(task, ex, cancellationToken, "Error cleaning up after rekeying!");
                }


                if (task.ConfirmationType.UsesOBOTokens())
                {
                    await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskCompletedManually, nameof(TaskExecutionMetaService.ExecuteTask), task);
                }
                else
                {
                    await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskCompletedAutomatically, nameof(TaskExecutionMetaService.ExecuteTask), task);
                }
            }
            else
            {
                await _eventDispatcherMetaService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task);
            }
        }
Ejemplo n.º 17
0
        internal void SaveCredentials(AccessTokenCredential credentials)
        {
            var credentialsJson = JsonConvert.SerializeObject(credentials);

            Environment.SetEnvironmentVariable("cohesityCredentials", credentialsJson, EnvironmentVariableTarget.Process);
        }
            public async Task <HttpResponseMessage> Post(AccessTokenCredential credential)
            {
                HttpResponseMessage returnValue = null;
                AccessTokensControllerPostCommand postCommand;

                Debug.Print("[AccessTokensController.Post] Entering");
                DatabaseSettings databaseSettings = new DatabaseSettings();
                Guid             accessTokenID    = Guid.Empty;

                try
                {
                    if (credential == null)
                    {
                        Debug.Print("[AccessTokensController.Post] credential is null.]");

                        returnValue = this.Request.CreateResponse <ErrorOut>(HttpStatusCode.BadRequest, new ErrorOut(0, "Request cannot be null. (1080)"));
                        returnValue.ReasonPhrase = "Request cannot be null. (1080)";
                    }

                    if (databaseSettings == null)
                    {
                        Debug.Print("[AccessTokensController.Post] No DatabaseSettings.]");
                        returnValue = this.Request.CreateResponse <ErrorOut>(HttpStatusCode.InternalServerError, new ErrorOut(0, "Database not configured. (1085)"));
                        returnValue.ReasonPhrase = "Database not configured. (1085)";
                    }
                    else
                    {
                        // IEnumerable<string> apiTokenHeaderValues = null;
                        // Guid accessTokenID = Guid.Empty;

                        postCommand = new AccessTokensControllerPostCommand(databaseSettings);

                        if (Guid.Empty.Equals(accessTokenID) == false)
                        {
                            postCommand.SetAccessTokenID(accessTokenID);
                        }

                        if (Guid.Empty.Equals(accessTokenID) == false)
                        {
                            postCommand.SetAccessTokenID(accessTokenID);
                        }

                        if (returnValue == null)
                        {
                            postCommand.SetCredential(credential);

                            if (await postCommand.Validate() == false)
                            {
                                returnValue = this.Request.CreateResponse <ErrorOut>(postCommand.HttpStatusCode, postCommand.ErrorOut);
                                if (postCommand.ErrorOut != null)
                                {
                                    returnValue.ReasonPhrase = postCommand.ErrorOut.MessageText;
                                }
                            }
                            else
                            {
                                await postCommand.Execute();

                                if (postCommand.ErrorOut == null)
                                {
                                    if (postCommand.AccessToken == null)
                                    {
                                        returnValue = this.Request.CreateResponse(postCommand.HttpStatusCode);
                                    }
                                    else
                                    {
                                        returnValue = this.Request.CreateResponse <AccessToken>(HttpStatusCode.OK, postCommand.AccessToken);
                                    }
                                }
                                else
                                {
                                    returnValue = this.Request.CreateResponse <ErrorOut>(postCommand.HttpStatusCode, postCommand.ErrorOut);
                                    returnValue.ReasonPhrase = postCommand.ErrorOut.MessageText;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    returnValue = this.Request.CreateResponse(HttpStatusCode.InternalServerError);
                    Debug.Print("[AccessTokensController.Post] Unhandled Exception: " + ex.ToString());
                }

                Debug.Print("[AccessTokensController.Post] Exiting");
                return(returnValue);
            }