Exemple #1
0
    private async Task <GitHubClient> CreateClientAsync(Component component, string acceptHeader = null)
    {
        if (component is null)
        {
            throw new ArgumentNullException(nameof(component));
        }

        var deploymentScope = await deploymentScopeRepository
                              .GetAsync(component.Organization, component.DeploymentScopeId, true)
                              .ConfigureAwait(false);

        return(await CreateClientAsync(deploymentScope, acceptHeader)
               .ConfigureAwait(false));
    }
Exemple #2
0
    protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
    {
        var authenticateResult = await base
                                 .HandleAuthenticateAsync()
                                 .ConfigureAwait(false);

        if (authenticateResult.None && Request.RouteValues.TryGetValue("organizationId", out var organizationId) && Request.RouteValues.TryGetValue("deploymentScopeId", out var deploymentScopeId))
        {
            var deploymentScope = await deploymentScopeRepository
                                  .GetAsync($"{organizationId}", $"{deploymentScopeId}")
                                  .ConfigureAwait(false);

            var adapter = deploymentScope is null
                ? default(Adapter)
                : adapterProvider.GetAdapter(deploymentScope.Type);

            if (adapter is IAdapterAuthorize adapterAuthorize)
            {
                var servicePrincial = await adapterAuthorize
                                      .ResolvePrincipalAsync(deploymentScope, Context.Request)
                                      .ConfigureAwait(false);

                if (servicePrincial is not null)
                {
                    var claimsIdentity = servicePrincial.ToClaimsIdentity(AdapterAuthenticationDefaults.AuthenticationType);

                    claimsIdentity.AddClaims(await Context
                                             .ResolveClaimsAsync(servicePrincial.TenantId.ToString(), servicePrincial.Id.ToString())
                                             .ConfigureAwait(false));

                    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                    authenticateResult = AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, AdapterAuthenticationDefaults.AuthenticationScheme));
                }
            }
        }

        return(authenticateResult);
    }
    private async Task <IEnumerable <Guid> > GetSubscriptionIdsAsync(Component component)
    {
        var deploymentScope = await deploymentScopeRepository
                              .GetAsync(component.Organization, component.DeploymentScopeId, true)
                              .ConfigureAwait(false);

        IEnumerable <Guid> subscriptionIds;

        if (AzureResourceIdentifier.TryParse(deploymentScope.ManagementGroupId, out var managementGroupResourceId))
        {
            try
            {
                var client = await azureResourceService.AzureSessionService
                             .CreateClientAsync <ManagementGroupsAPIClient>()
                             .ConfigureAwait(false);

                var group = await client.ManagementGroups
                            .GetAsync(managementGroupResourceId.ResourceTypes.Last().Value, expand : "children")
                            .ConfigureAwait(false);

                subscriptionIds = group.Children
                                  .Where(child => child.Type.Equals("/subscriptions", StringComparison.OrdinalIgnoreCase))
                                  .Select(child => Guid.Parse(child.Name));
            }
            catch
            {
                subscriptionIds = Enumerable.Empty <Guid>();
            }
        }
        else
        {
            try
            {
                var session = await azureResourceService.AzureSessionService
                              .CreateSessionAsync()
                              .ConfigureAwait(false);

                var subscriptions = await session.Subscriptions
                                    .ListAsync(loadAllPages : true)
                                    .ConfigureAwait(false);

                subscriptionIds = subscriptions
                                  .Where(subscription => deploymentScope.SubscriptionIds.Contains(Guid.Parse(subscription.SubscriptionId)))
                                  .Select(subscription => Guid.Parse(subscription.SubscriptionId));
            }
            catch
            {
                subscriptionIds = Enumerable.Empty <Guid>();
            }
        }

        var identity = await azureResourceService.AzureSessionService
                       .GetIdentityAsync()
                       .ConfigureAwait(false);

        var subscriptionIdsValidated = await Task
                                       .WhenAll(subscriptionIds.Select(subscriptionId => ProveOwnershipAsync(subscriptionId, identity.ObjectId)))
                                       .ConfigureAwait(false);

        return(subscriptionIdsValidated
               .Where(subscriptionId => subscriptionId != Guid.Empty));

        async Task <Guid> ProveOwnershipAsync(Guid subscriptionId, Guid userObjectId)
        {
            var subscription = await azureResourceService
                               .GetSubscriptionAsync(subscriptionId)
                               .ConfigureAwait(false);

            var hasOwnership = await subscription
                               .HasRoleAssignmentAsync(userObjectId.ToString(), AzureRoleDefinition.Owner, true)
                               .ConfigureAwait(false);

            return(hasOwnership ? subscriptionId : Guid.Empty);
        }
    }
    public override async Task <ICommandResult> HandleAsync(ComponentCreateCommand command, IAsyncCollector <ICommand> commandQueue, IDurableOrchestrationContext orchestrationContext, ILogger log)
    {
        if (command is null)
        {
            throw new ArgumentNullException(nameof(command));
        }

        if (commandQueue is null)
        {
            throw new ArgumentNullException(nameof(commandQueue));
        }

        var commandResult = command.CreateResult();

        try
        {
            commandResult.Result = await componentRepository
                                   .AddAsync(command.Payload)
                                   .ConfigureAwait(false);

            var deploymentScope = await deploymentScopeRepository
                                  .GetAsync(commandResult.Result.Organization, commandResult.Result.DeploymentScopeId)
                                  .ConfigureAwait(false);

            if (adapterProvider.GetAdapter(deploymentScope.Type) is IAdapterIdentity adapterIdentity)
            {
                var servicePrincipal = await adapterIdentity
                                       .GetServiceIdentityAsync(commandResult.Result)
                                       .ConfigureAwait(false);

                var servicePrincipalUser = await userRepository
                                           .GetAsync(commandResult.Result.Organization, servicePrincipal.Id.ToString())
                                           .ConfigureAwait(false);

                if (servicePrincipalUser is null)
                {
                    servicePrincipalUser ??= new User
                    {
                        Id               = servicePrincipal.Id.ToString(),
                        Role             = OrganizationUserRole.Adapter,
                        UserType         = Model.Data.UserType.Service,
                        Organization     = commandResult.Result.Organization,
                        OrganizationName = commandResult.Result.OrganizationName
                    };

                    servicePrincipalUser.EnsureProjectMembership(commandResult.Result.ProjectId, ProjectUserRole.Adapter);

                    await commandQueue
                    .AddAsync(new ProjectUserCreateCommand(command.User, servicePrincipalUser, commandResult.Result.ProjectId))
                    .ConfigureAwait(false);
                }
            }

            var componentTask = new ComponentTask
            {
                Organization     = commandResult.Result.Organization,
                OrganizationName = commandResult.Result.OrganizationName,
                ComponentId      = commandResult.Result.Id,
                ComponentName    = commandResult.Result.Slug,
                ProjectId        = commandResult.Result.ProjectId,
                ProjectName      = commandResult.Result.ProjectName,
                Type             = ComponentTaskType.Create,
                RequestedBy      = commandResult.Result.Creator,
                InputJson        = commandResult.Result.InputJson
            };

            await commandQueue
            .AddAsync(new ComponentTaskCreateCommand(command.User, componentTask))
            .ConfigureAwait(false);

            commandResult.RuntimeStatus = CommandRuntimeStatus.Completed;
        }
        catch (Exception exc)
        {
            commandResult.Errors.Add(exc);
        }

        return(commandResult);
    }