public Policy AddBucketIamMember(
        string bucketName = "your-unique-bucket-name",
        string role       = "roles/storage.objectViewer",
        string member     = "serviceAccount:[email protected]")
    {
        var storage = StorageClient.Create();
        var policy  = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });

        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;

        Policy.BindingsData bindingToAdd = new Policy.BindingsData
        {
            Role    = role,
            Members = new List <string> {
                member
            }
        };

        policy.Bindings.Add(bindingToAdd);
        var bucketIamPolicy = storage.SetBucketIamPolicy(bucketName, policy);

        Console.WriteLine($"Added {member} with role {role} " + $"to {bucketName}");
        return(bucketIamPolicy);
    }
示例#2
0
        private void CreateBucketAndGrantStsPermissions(string bucketName)
        {
            var bucket = Storage.CreateBucket(ProjectId, new Bucket
            {
                Name = bucketName
            });

            string email = Sts.GetGoogleServiceAccount(new GetGoogleServiceAccountRequest()
            {
                ProjectId = ProjectId
            }).AccountEmail;
            string member       = "serviceAccount:" + email;
            string objectViewer = "roles/storage.objectViewer";
            string bucketReader = "roles/storage.legacyBucketReader";
            string bucketWriter = "roles/storage.legacyBucketWriter";

            var policy = Storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
            {
                RequestedPolicyVersion = 3
            });

            // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
            policy.Version = 3;

            Policy.BindingsData objectViewerBinding = new Policy.BindingsData
            {
                Role    = objectViewer,
                Members = new List <string> {
                    member
                }
            };
            Policy.BindingsData bucketReaderBinding = new Policy.BindingsData
            {
                Role    = bucketReader,
                Members = new List <string> {
                    member
                }
            };
            Policy.BindingsData bucketWriterBinding = new Policy.BindingsData
            {
                Role    = bucketWriter,
                Members = new List <string> {
                    member
                }
            };

            policy.Bindings.Add(objectViewerBinding);
            policy.Bindings.Add(bucketReaderBinding);
            policy.Bindings.Add(bucketWriterBinding);

            Storage.SetBucketIamPolicy(bucketName, policy);
        }
        public async Task SetBucketIamPolicy()
        {
            var projectId  = _fixture.ProjectId;
            var bucketName = Guid.NewGuid().ToString();

            _fixture.RegisterBucketToDelete(bucketName);

            // Snippet: SetBucketIamPolicy(string, *, *)
            // Create a new bucket and an empty file within it
            StorageClient client = StorageClient.Create();
            Bucket        bucket = client.CreateBucket(projectId, bucketName);
            var           obj    = client.UploadObject(bucketName, "empty.txt", "text/plain", new MemoryStream());

            // Demonstrate that without authentication, we can't download the object
            HttpClient          httpClient = new HttpClient();
            HttpResponseMessage response1  = await httpClient.GetAsync(obj.MediaLink);

            Console.WriteLine($"Response code before setting policy: {response1.StatusCode}");

            // Fetch the current IAM policy, and modify it in memory to allow all users
            // to view objects.
            Policy policy = client.GetBucketIamPolicy(bucketName);
            string role   = "roles/storage.objectViewer";

            Policy.BindingsData binding = policy.Bindings
                                          .Where(b => b.Role == role)
                                          .FirstOrDefault();
            if (binding == null)
            {
                binding = new Policy.BindingsData {
                    Role = role, Members = new List <string>()
                };
                policy.Bindings.Add(binding);
            }
            binding.Members.Add("allUsers");

            // Update the IAM policy on the bucket.
            client.SetBucketIamPolicy(bucketName, policy);

            // Download the object again: this time the response should be OK
            HttpResponseMessage response2 = await httpClient.GetAsync(obj.MediaLink);

            Console.WriteLine($"Response code after setting policy: {response2.StatusCode}");

            // End snippet

            Assert.Equal(HttpStatusCode.Unauthorized, response1.StatusCode);
            Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
        }
示例#4
0
        // [END view_bucket_iam_members]

        // [START add_bucket_iam_member]
        private void AddBucketIamMember(string bucketName,
                                        string role, string member)
        {
            var storage = StorageClient.Create();
            var policy  = storage.GetBucketIamPolicy(bucketName);

            Policy.BindingsData bindingToAdd = new Policy.BindingsData();
            bindingToAdd.Role = role;
            string[] members = { member };
            bindingToAdd.Members = members;
            policy.Bindings.Add(bindingToAdd);
            storage.SetBucketIamPolicy(bucketName, policy);
            Console.WriteLine($"Added {member} with role {role} "
                              + $"to {bucketName}");
        }
示例#5
0
    /// <summary>
    /// Adds a conditional Iam policy to a bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="role">The role that members may assume.</param>
    /// <param name="member">The identifier of the member who may assume the provided role.</param>
    /// <param name="title">Title for the expression.</param>
    /// <param name="description">Description of the expression.</param>
    /// <param name="expression">Describes the conditions that need to be met for the policy to be applied.
    /// It's represented as a string using Common Expression Language syntax.</param>
    public Policy AddBucketConditionalIamBinding(
        string bucketName  = "your-unique-bucket-name",
        string role        = "roles/storage.objectViewer",
        string member      = "serviceAccount:[email protected]",
        string title       = "title",
        string description = "description",
        string expression  = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")")
    {
        var storage = StorageClient.Create();
        var policy  = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });

        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;
        Policy.BindingsData bindingToAdd = new Policy.BindingsData
        {
            Role    = role,
            Members = new List <string> {
                member
            },
            Condition = new Expr
            {
                Title       = title,
                Description = description,
                Expression  = expression
            }
        };

        policy.Bindings.Add(bindingToAdd);

        var bucketIamPolicy = storage.SetBucketIamPolicy(bucketName, policy);

        Console.WriteLine($"Added {member} with role {role} " + $"to {bucketName}");
        return(bucketIamPolicy);
    }
示例#6
0
        private string CreateRequesterPaysBucket()
        {
            string name = IdGenerator.FromDateTime(prefix: "dotnet-requesterpays-");

            CreateBucket();
            AddServiceAccountBinding();
            CreateObject();
            return(name);

            // Adds the service account associated with the application default credentials as a writer for the bucket.
            // Note: this assumes the default credentials *are* a service account. If we've got a compute credential,
            // this will cause a problem - but in reality, our tests always run with a service account.
            void AddServiceAccountBinding()
            {
                var    credential          = (ServiceAccountCredential)GoogleCredential.GetApplicationDefault().UnderlyingCredential;
                string serviceAccountEmail = credential.Id;

                var policy = RequesterPaysClient.GetBucketIamPolicy(name,
                                                                    new GetBucketIamPolicyOptions {
                    UserProject = RequesterPaysProjectId
                });
                // Note: we assume there are no conditions in the policy, as we've only just created the bucket.
                var writerRole = "roles/storage.objectAdmin";

                Policy.BindingsData writerBinding = null;
                foreach (var binding in policy.Bindings)
                {
                    if (binding.Role == writerRole)
                    {
                        writerBinding = binding;
                        break;
                    }
                }
                if (writerBinding == null)
                {
                    writerBinding = new Policy.BindingsData {
                        Role = writerRole, Members = new List <string>()
                    };
                    policy.Bindings.Add(writerBinding);
                }
                writerBinding.Members.Add($"serviceAccount:{serviceAccountEmail}");
                RequesterPaysClient.SetBucketIamPolicy(name, policy,
                                                       new SetBucketIamPolicyOptions {
                    UserProject = RequesterPaysProjectId
                });
            }

            void CreateBucket()
            {
                RequesterPaysClient.CreateBucket(RequesterPaysProjectId,
                                                 new Bucket {
                    Name = name, Billing = new Bucket.BillingData {
                        RequesterPays = true
                    }
                });
                SleepAfterBucketCreateDelete();
            }

            void CreateObject()
            {
                RequesterPaysClient.UploadObject(name, SmallObject, "text/plain", new MemoryStream(SmallContent),
                                                 new UploadObjectOptions {
                    UserProject = RequesterPaysProjectId
                });
            }
        }