Exemplo n.º 1
0
        private async Task <ResourceAccessRuleSet> DownloadBlobAsync(string id, string eTag)
        {
            BlockBlobClient blob = this.Container.GetBlockBlobClient(id);

            // Can't use DownloadContentAsync because of https://github.com/Azure/azure-sdk-for-net/issues/22598
            try
            {
                Response <BlobDownloadStreamingResult> response = await blob.DownloadStreamingAsync(
                    conditions : string.IsNullOrEmpty(eTag)?null : new BlobRequestConditions {
                    IfNoneMatch = new ETag(eTag !)
                })
                                                                  .ConfigureAwait(false);

                int status = response.GetRawResponse().Status;
                if (status == 304)
                {
                    // NOP - we are quite happy to ignore that, as the blob hasn't changed.
                    return(null);
                }

                // Note: it is technically possible to use System.Text.Json to work directly from
                // the UTF-8 data, which is more efficient than decoding to a .NET UTF-16 string
                // first. However, we have to do this for the time being because we are in the world of
                // IJsonSerializerSettingsProvider, where all serialization options are managed in
                // terms of JSON.NET.
                using BlobDownloadStreamingResult blobDownloadStreamingResult = response.Value;
                BinaryData data = await BinaryData.FromStreamAsync(blobDownloadStreamingResult.Content).ConfigureAwait(false);

                string ruleSetJson = data.ToString();

                ResourceAccessRuleSet ruleSet = JsonConvert.DeserializeObject <ResourceAccessRuleSet>(ruleSetJson, this.serializerSettings);
                ruleSet.ETag = response.Value.Details.ETag.ToString("G");
                return(ruleSet);
            }
Exemplo n.º 2
0
        public async Task <OpenApiResult> CreateResourceAccessRuleSetAsync(
            string tenantId,
            ResourceAccessRuleSet body)
        {
            ITenant tenant = await this.tenancyHelper.GetRequestingTenantAsync(tenantId).ConfigureAwait(false);

            IResourceAccessRuleSetStore store = await this.permissionsStoreFactory.GetResourceAccessRuleSetStoreAsync(tenant).ConfigureAwait(false);

            ResourceAccessRuleSet result = await store.PersistAsync(body).ConfigureAwait(false);

            return(this.OkResult(result, "application/json"));
        }
Exemplo n.º 3
0
        public async Task <OpenApiResult> GetResourceAccessRuleSetAsync(
            string tenantId,
            string resourceAccessRuleSetId)
        {
            ITenant tenant = await this.tenancyHelper.GetRequestingTenantAsync(tenantId).ConfigureAwait(false);

            IResourceAccessRuleSetStore store = await this.permissionsStoreFactory.GetResourceAccessRuleSetStoreAsync(tenant).ConfigureAwait(false);

            try
            {
                ResourceAccessRuleSet result = await store.GetAsync(resourceAccessRuleSetId).ConfigureAwait(false);

                return(this.OkResult(result, "application/json"));
            }
            catch (ResourceAccessRuleSetNotFoundException)
            {
                return(this.NotFoundResult());
            }
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public async Task <ResourceAccessRuleSet> PersistAsync(ResourceAccessRuleSet ruleSet)
        {
            if (ruleSet is null)
            {
                throw new ArgumentNullException(nameof(ruleSet));
            }

            BlockBlobClient blob = this.Container.GetBlockBlobClient(ruleSet.Id);
            string          serializedPermissions = JsonConvert.SerializeObject(ruleSet, this.serializerSettings);

            using var content = BinaryData.FromString(serializedPermissions).ToStream();
            Response <BlobContentInfo> response = await blob.UploadAsync(
                content,
                new BlobUploadOptions { Conditions = new BlobRequestConditions {
                                            IfMatch = new ETag(ruleSet.ETag)
                                        } })
                                                  .ConfigureAwait(false);

            ruleSet.ETag = response.Value.ETag.ToString("G");
            return(ruleSet);
        }
        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);
        }
 /// <summary>
 /// Create a resource access rule set
 /// </summary>
 /// <remarks>
 /// Creates a resource access rule set
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='tenantId'>
 /// The tenant within which the request should operate
 /// </param>
 /// <param name='body'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <object> CreateResourceAccessRuleSetAsync(this IClaimsService operations, string tenantId, ResourceAccessRuleSet body, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateResourceAccessRuleSetWithHttpMessagesAsync(tenantId, body, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Create a resource access rule set
 /// </summary>
 /// <remarks>
 /// Creates a resource access rule set
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='tenantId'>
 /// The tenant within which the request should operate
 /// </param>
 /// <param name='body'>
 /// </param>
 public static object CreateResourceAccessRuleSet(this IClaimsService operations, string tenantId, ResourceAccessRuleSet body)
 {
     return(operations.CreateResourceAccessRuleSetAsync(tenantId, body).GetAwaiter().GetResult());
 }
Exemplo n.º 8
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, ResourceAccessRuleSet Result)> CreateResourceAccessRuleSetAsync(ResourceAccessRuleSet newClaimPermissions)
        {
            OpenApiResult result = await this.ruleSetService.CreateResourceAccessRuleSetAsync(
                this.testTenants.TransientClientTenantId, newClaimPermissions);

            result.Results.TryGetValue("application/json", out object claimPermissions);
            return(result.StatusCode, claimPermissions as ResourceAccessRuleSet);
        }