Exemplo n.º 1
0
        private async Task <int> OnExecuteAsync(CommandLineApplication app, CancellationToken cancellationToken = default)
        {
            var authenticationOptions            = AuthenticationOptions.BuildFrom(this.UseAzCliDevAuth, this.TenantId);
            IAppServiceManager appServiceManager = AppServiceManagerSource.Get(
                authenticationOptions, this.SubscriptionId);
            IWebAppAuthentication  webAppAuthConfig;
            ManagedServiceIdentity managedIdentity;
            IFunctionApp           function = null;

            try
            {
                function = appServiceManager.FunctionApps.GetByResourceGroup(this.ResourceGroupName, this.AppName);
            }
            catch (NullReferenceException)
            {
                // Unhelpfully, we seem to get a null reference exception if the app isn't found
            }

            if (function != null)
            {
                managedIdentity  = function.Inner.Identity;
                webAppAuthConfig = await function.GetAuthenticationConfigAsync(cancellationToken).ConfigureAwait(false);
            }
            else
            {
                IWebApp webApp = appServiceManager.WebApps.GetByResourceGroup(this.ResourceGroupName, this.AppName);
                if (webApp == null)
                {
                    app.Error.WriteLine($"Unable to find either a Function or Web App in resource group '{this.ResourceGroupName}' called '{this.AppName}'");
                    return(-1);
                }

                managedIdentity  = webApp.Inner.Identity;
                webAppAuthConfig = await webApp.GetAuthenticationConfigAsync(cancellationToken).ConfigureAwait(false);
            }

            if (webAppAuthConfig.Inner.Enabled == true)
            {
                app.Out.WriteLine($"Default Easy Auth: {webAppAuthConfig.Inner.DefaultProvider}");
                app.Out.WriteLine($" Client ID: {webAppAuthConfig.Inner.ClientId}");
            }
            else
            {
                app.Out.WriteLine("Easy Auth not enabled");
            }

            if (managedIdentity == null)
            {
                app.Out.WriteLine("No managed identity");
            }
            else
            {
                app.Out.WriteLine("Managed identity:");
                app.Out.WriteLine($" Type:                 {managedIdentity.Type}");
                app.Out.WriteLine($" TenantId:             {managedIdentity.TenantId}");
                app.Out.WriteLine($" PrincipalId:          {managedIdentity.PrincipalId}");

                if (managedIdentity.UserAssignedIdentities != null)
                {
                    foreach ((string id, ManagedServiceIdentityUserAssignedIdentitiesValue value) in managedIdentity.UserAssignedIdentities)
                    {
                        app.Out.WriteLine($" UserAssignedIdentity: Id = {id}, ClientId = {value.ClientId}, PrincipalId = {value.PrincipalId}");
                    }
                }
            }

            return(0);
        }
        private async Task <int> OnExecuteAsync(CommandLineApplication app, CancellationToken cancellationToken = default)
        {
            RulesetsAndClaimPermissions input = JsonConvert.DeserializeObject <RulesetsAndClaimPermissions>(
                File.ReadAllText(this.FilePath));

            ClaimsService claimsClient;

            if (string.IsNullOrEmpty(this.MarainClaimsHeaderRoleValue))
            {
                var authenticationOptions = AuthenticationOptions.BuildFrom(this.UseAzCliDevAuth, this.TenantId);

                ServiceClientCredentials credentials = await authenticationOptions.GetServiceClientCredentialsFromKeyVault(
                    this.ClaimsAppId, this.KeyVault, this.SecretName).ConfigureAwait(false);

                claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), credentials);
            }
            else
            {
                claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), new BasicAuthenticationCredentials());
                claimsClient.HttpClient.DefaultRequestHeaders.Add("X-MARAIN-CLAIMS", $"{{ \"roles\": [ \"{this.MarainClaimsHeaderRoleValue}\" ] }}");
            }

            using (claimsClient)
            {
                foreach (ResourceAccessRuleSet ruleSet in input.RuleSets)
                {
                    try
                    {
                        app.Out.WriteLine($"Ruleset {ruleSet.Id} ('{ruleSet.DisplayName}')");
                        HttpOperationResponse <ResourceAccessRuleSet> result = await claimsClient.GetResourceAccessRuleSetWithHttpMessagesAsync(
                            ruleSet.Id, this.MarainTenantId, cancellationToken : cancellationToken).ConfigureAwait(false);

                        if (result.Response.StatusCode == HttpStatusCode.NotFound)
                        {
                            app.Error.WriteLine("Does not yet exist. Creating.");
                            var request = new ResourceAccessRuleSet
                            {
                                Id          = ruleSet.Id,
                                DisplayName = ruleSet.DisplayName,
                                Rules       = ruleSet.Rules,
                            };
                            await claimsClient.CreateResourceAccessRuleSetAsync(
                                this.MarainTenantId, request, cancellationToken : cancellationToken).ConfigureAwait(false);
                        }
                        else if (result.Response.IsSuccessStatusCode)
                        {
                            app.Out.WriteLine("Already exists. Updating.");
                            await claimsClient.SetResourceAccessRuleSetResourceAccessRulesAsync(
                                this.MarainTenantId, ruleSet.Id, ruleSet.Rules, cancellationToken : cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            app.Error.WriteLine("Error: " + result.Response.StatusCode);
                            string body = await result.Response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);

                            if (!string.IsNullOrWhiteSpace(body))
                            {
                                app.Error.WriteLine(body);
                            }
                        }
                    }
                    catch (Exception x)
                    {
                        app.Error.WriteLine(x);
                        return(-1);
                    }
                }

                foreach (CreateClaimPermissionsRequest claimPermissions in input.ClaimPermissions)
                {
                    try
                    {
                        app.Out.WriteLine($"Claim Permissions {claimPermissions.Id}");
                        HttpOperationResponse <ClaimPermissions> result = await claimsClient.GetClaimPermissionsWithHttpMessagesAsync(
                            claimPermissions.Id, this.MarainTenantId, cancellationToken : cancellationToken).ConfigureAwait(false);

                        if (result.Response.StatusCode == HttpStatusCode.NotFound)
                        {
                            app.Out.WriteLine("Does not yet exist. Creating.");
                            var request = new CreateClaimPermissionsRequest
                            {
                                Id = claimPermissions.Id,
                                ResourceAccessRules    = claimPermissions.ResourceAccessRules,
                                ResourceAccessRuleSets = claimPermissions.ResourceAccessRuleSets,
                            };
                            await claimsClient.CreateClaimPermissionsAsync(
                                this.MarainTenantId, request, cancellationToken : cancellationToken).ConfigureAwait(false);
                        }
                        else if (result.Response.IsSuccessStatusCode)
                        {
                            app.Out.WriteLine("Already exists. Updating resource access rules.");
                            await claimsClient.SetClaimPermissionsResourceAccessRulesAsync(
                                this.MarainTenantId,
                                claimPermissions.Id,
                                claimPermissions.ResourceAccessRules,
                                cancellationToken : cancellationToken).ConfigureAwait(false);

                            app.Out.WriteLine("Updating resource access rule sets");
                            var ruleSetIds = claimPermissions
                                             .ResourceAccessRuleSets
                                             .Select(rs => new ResourceAccessRuleSetIdOnly(rs.Id))
                                             .ToList();
                            await claimsClient.SetClaimPermissionsResourceAccessRuleSetsAsync(
                                this.MarainTenantId,
                                claimPermissions.Id,
                                ruleSetIds,
                                cancellationToken : cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            app.Error.WriteLine("Error: " + result.Response.StatusCode);
                            string body = await result.Response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);

                            if (!string.IsNullOrWhiteSpace(body))
                            {
                                app.Error.WriteLine(body);
                            }
                        }
                    }
                    catch (Exception x)
                    {
                        app.Error.WriteLine(x);
                        return(-1);
                    }
                }
            }

            return(0);
        }
        private async Task <int> OnExecuteAsync(CommandLineApplication app, CancellationToken cancellationToken = default)
        {
            ClaimsService claimsClient;

            if (string.IsNullOrEmpty(this.MarainClaimsHeaderRoleValue))
            {
                var authenticationOptions = AuthenticationOptions.BuildFrom(this.UseAzCliDevAuth, this.TenantId);

                ServiceClientCredentials credentials = await authenticationOptions.GetServiceClientCredentialsFromKeyVault(
                    this.ClaimsAppId, this.KeyVault, this.SecretName).ConfigureAwait(false);

                claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), credentials);
            }
            else
            {
                claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), new BasicAuthenticationCredentials());
                claimsClient.HttpClient.DefaultRequestHeaders.Add("X-MARAIN-CLAIMS", $"{{ \"roles\": [ \"{this.MarainClaimsHeaderRoleValue}\" ] }}");
            }

            using (claimsClient)
            {
                try
                {
                    HttpOperationResponse <ProblemDetails> result = await claimsClient.InitializeTenantWithHttpMessagesAsync(
                        this.MarainTenantId,
                        new Body { AdministratorPrincipalObjectId = this.AdminPrincipalObjectId },
                        cancellationToken : cancellationToken)
                                                                    .ConfigureAwait(false);

                    if (result.Response.IsSuccessStatusCode)
                    {
                        app.Out.WriteLine("Succeeded");
                    }
                    else
                    {
                        app.Error.WriteLine($"Failed with status code {result.Response.StatusCode}");
                        if (result.Body != null)
                        {
                            app.Error.WriteLine(result.Body.Title);
                            app.Error.WriteLine(result.Body.Detail);
                        }
                    }
                }
                catch (HttpOperationException x)
                {
                    app.Error.WriteLine($"Failed with status code {x.Response.StatusCode}");
                    if (!string.IsNullOrWhiteSpace(x.Response.Content))
                    {
                        app.Error.WriteLine("Response content:");
                        app.Error.WriteLine(x.Response.Content);
                    }

                    if (x.Response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        app.Error.WriteLine();
                        app.Error.WriteLine("Check that you have specified the correct tenant and claims id");
                    }

                    if (x.Response.Headers.TryGetValue("WWW-Authenticate", out IEnumerable <string> values))
                    {
                        var valueList = values.ToList();
                        if (valueList.Count > 0)
                        {
                            Console.WriteLine("WWW-Authenticate header{0}:", valueList.Count > 1 ? "s" : string.Empty);
                            foreach (string value in valueList)
                            {
                                app.Error.WriteLine(value);
                            }
                        }
                    }

                    return(-1);
                }
            }

            return(0);
        }