/// <summary> /// Creates an Amazon S3 bucket and adds and an ACL to control /// access to the bucket and the objects stored in it. /// </summary> /// <param name="client">The initialized client object used to create /// the ACL, create an S3 bucket, and then apply the ACL to the bucket. /// </param> /// <param name="newBucketName">The name of the bucket to create.</param> /// <returns>A boolean value indicating success or failure.</returns> public static async Task <bool> CreateBucketUseCannedACLAsync(IAmazonS3 client, string newBucketName) { try { // Create a new S3 bucket with Canned ACL. PutBucketRequest putBucketRequest = new () { BucketName = newBucketName, BucketRegion = S3Region.USE2, // S3Region.US, CannedACL = S3CannedACL.LogDeliveryWrite, }; PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest); // Retrieve bucket ACL to show that the Access Control List // was properly applied to the new bucket. GetACLResponse getACLResponse = await client.GetACLAsync(new GetACLRequest { BucketName = newBucketName, }); return(getACLResponse.HttpStatusCode == System.Net.HttpStatusCode.OK); } catch (AmazonS3Exception ex) { Console.WriteLine($"S3 error: {ex.Message}"); } return(false); }
public static GetACLResponse GetACLHelper(AmazonS3Client client, string bucketName, string key) { GetACLResponse r = null; Exception responseException = null; AutoResetEvent ars = new AutoResetEvent(false); client.GetACLAsync(new GetACLRequest() { BucketName = bucketName, Key = key }, (response) => { responseException = response.Exception; if (responseException == null) { r = response.Response; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); if (responseException != null) { throw responseException; } return(r); }
static void ReadObjectAcl() { string id = Common.InputString("Key:", null, false); GetACLRequest request = new GetACLRequest(); request.BucketName = _Bucket; request.Key = id; GetACLResponse response = _S3Client.GetACLAsync(request).Result; if (response != null) { if (response.AccessControlList != null) { Console.WriteLine("Owner: " + response.AccessControlList.Owner.DisplayName + " ID " + response.AccessControlList.Owner.Id); Console.WriteLine("Grants:"); foreach (S3Grant grant in response.AccessControlList.Grants) { Console.WriteLine("| Grantee : " + grant.Grantee.DisplayName); Console.WriteLine("| Permission : " + grant.Permission); } } Console.WriteLine("Success"); } else { Console.WriteLine("Failed"); } }
private static async Task CreateBucketUseCannedACLAsync() { try { // Add bucket (specify canned ACL). PutBucketRequest putBucketRequest = new PutBucketRequest() { BucketName = newBucketName, BucketRegion = S3Region.EUW1, // S3Region.US, // Add canned ACL. CannedACL = S3CannedACL.LogDeliveryWrite }; PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest); // Retrieve bucket ACL. GetACLResponse getACLResponse = await client.GetACLAsync(new GetACLRequest { BucketName = newBucketName }); } catch (AmazonS3Exception amazonS3Exception) { Console.WriteLine("S3 error occurred. Exception: " + amazonS3Exception.ToString()); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); } }
/// <summary> /// Sets the storage class for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object whose storage class needs changing</param> /// <param name="version">The version of the S3 Object whose storage class needs changing</param> /// <param name="sClass">The new Storage Class for the object</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> /// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/> public static void SetObjectStorageClass(string bucketName, string key, string version, S3StorageClass sClass, AmazonS3 s3Client) { if (sClass > S3StorageClass.ReducedRedundancy || sClass < S3StorageClass.Standard) { throw new ArgumentException("Invalid value specified for storage class."); } if (null == s3Client) { throw new ArgumentNullException("s3Client", "Please specify an S3 Client to make service requests."); } // Get the existing ACL of the object GetACLRequest getACLRequest = new GetACLRequest(); getACLRequest.BucketName = bucketName; getACLRequest.Key = key; if (version != null) { getACLRequest.VersionId = version; } GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest); GetObjectMetadataResponse getMetadataResponse = s3Client.GetObjectMetadata(new GetObjectMetadataRequest() .WithBucketName(bucketName) .WithKey(key)); // Set the storage class on the object CopyObjectRequest copyRequest = new CopyObjectRequest(); copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName; copyRequest.SourceKey = copyRequest.DestinationKey = key; copyRequest.ServerSideEncryptionMethod = getMetadataResponse.ServerSideEncryptionMethod; if (version != null) { copyRequest.SourceVersionId = version; } copyRequest.StorageClass = sClass; // The copyRequest's Metadata directive is COPY by default CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); // Set the object's original ACL back onto it because a COPY // operation resets the ACL on the destination object. SetACLRequest setACLRequest = new SetACLRequest(); setACLRequest.BucketName = bucketName; setACLRequest.Key = key; if (version != null) { setACLRequest.VersionId = copyResponse.VersionId; } setACLRequest.ACL = getACLResponse.AccessControlList; s3Client.SetACL(setACLRequest); }
/// <summary> /// Retrieves the ACL associated with the S3 bucket name in the /// bucketName parameter. /// </summary> /// <param name="client">The initialized client object used to call /// PutBucketAsync.</param> /// <param name="bucketName">The S3 bucket for which we want to get the /// ACL list.</param> /// <returns>Returns an S3AccessCntrolList returned from the call to /// GetACLAsync.</returns> public static async Task <S3AccessControlList> GetBucketACLAsync(IAmazonS3 client, string bucketName) { GetACLResponse response = await client.GetACLAsync(new GetACLRequest { BucketName = bucketName, }); return(response.AccessControlList); }
private static async Task TestObjectACLTestAsync() { try { // Retrieve the ACL for the object. GetACLResponse aclResponse = await client.GetACLAsync(new GetACLRequest { BucketName = bucketName, Key = keyName }); S3AccessControlList acl = aclResponse.AccessControlList; // Retrieve the owner (we use this to re-add permissions after we clear the ACL). Owner owner = acl.Owner; // Clear existing grants. acl.Grants.Clear(); // Add a grant to reset the owner's full permission (the previous clear statement removed all permissions). S3Grant fullControlGrant = new S3Grant { Grantee = new S3Grantee { CanonicalUser = owner.Id }, Permission = S3Permission.FULL_CONTROL }; // Describe the grant for the permission using an email address. S3Grant grantUsingEmail = new S3Grant { Grantee = new S3Grantee { EmailAddress = emailAddress }, Permission = S3Permission.WRITE_ACP }; acl.Grants.AddRange(new List <S3Grant> { fullControlGrant, grantUsingEmail }); // Set a new ACL. PutACLResponse response = await client.PutACLAsync(new PutACLRequest { BucketName = bucketName, Key = keyName, AccessControlList = acl }); } catch (AmazonS3Exception amazonS3Exception) { Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString()); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); } }
static async Task GetBucketACLAsync(string bucketName) { GetACLResponse response = await client.GetACLAsync(new GetACLRequest { BucketName = bucketName }); S3AccessControlList accessControlList = response.AccessControlList; }
/// <summary> /// Sets the server side encryption method for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object</param> /// <param name="version">The version of the S3 Object</param> /// <param name="method">The server side encryption method</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> /// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/> public static void SetServerSideEncryption(string bucketName, string key, string version, ServerSideEncryptionMethod method, AmazonS3 s3Client) { if (null == s3Client) { throw new ArgumentNullException("s3Client", "Please specify an S3 Client to make service requests."); } // Get the existing ACL of the object GetACLRequest getACLRequest = new GetACLRequest(); getACLRequest.BucketName = bucketName; getACLRequest.Key = key; if (version != null) { getACLRequest.VersionId = version; } GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest); ListObjectsResponse listObjectResponse = s3Client.ListObjects(new ListObjectsRequest() .WithBucketName(bucketName) .WithPrefix(key) .WithMaxKeys(1)); if (listObjectResponse.S3Objects.Count != 1) { throw new ArgumentNullException("No object exists with this bucket name and key."); } // Set the storage class on the object CopyObjectRequest copyRequest = new CopyObjectRequest(); copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName; copyRequest.SourceKey = copyRequest.DestinationKey = key; copyRequest.StorageClass = listObjectResponse.S3Objects[0].StorageClass == "STANDARD" ? S3StorageClass.Standard : S3StorageClass.ReducedRedundancy; if (version != null) { copyRequest.SourceVersionId = version; } copyRequest.ServerSideEncryptionMethod = method; // The copyRequest's Metadata directive is COPY by default CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); // Set the object's original ACL back onto it because a COPY // operation resets the ACL on the destination object. SetACLRequest setACLRequest = new SetACLRequest(); setACLRequest.BucketName = bucketName; setACLRequest.Key = key; if (version != null) { setACLRequest.VersionId = copyResponse.VersionId; } setACLRequest.ACL = getACLResponse.AccessControlList; s3Client.SetACL(setACLRequest); }
/// <summary> /// Sets up the request needed to make an exact copy of the object leaving the parent method /// the ability to change just the attribute being requested to change. /// </summary> /// <param name="bucketName"></param> /// <param name="key"></param> /// <param name="version"></param> /// <param name="s3Client"></param> /// <param name="copyRequest"></param> /// <param name="putACLRequest"></param> static void SetupForObjectModification(IAmazonS3 s3Client, string bucketName, string key, string version, out CopyObjectRequest copyRequest, out PutACLRequest putACLRequest) { // Get the existing ACL of the object GetACLRequest getACLRequest = new GetACLRequest(); getACLRequest.BucketName = bucketName; getACLRequest.Key = key; if (version != null) { getACLRequest.VersionId = version; } GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest); // Set the object's original ACL back onto it because a COPY // operation resets the ACL on the destination object. putACLRequest = new PutACLRequest(); putACLRequest.BucketName = bucketName; putACLRequest.Key = key; putACLRequest.AccessControlList = getACLResponse.AccessControlList; ListObjectsResponse listObjectResponse = s3Client.ListObjects(new ListObjectsRequest { BucketName = bucketName, Prefix = key, MaxKeys = 1 }); if (listObjectResponse.S3Objects.Count != 1) { throw new InvalidOperationException("No object exists with this bucket name and key."); } GetObjectMetadataRequest getMetaRequest = new GetObjectMetadataRequest() { BucketName = bucketName, Key = key }; GetObjectMetadataResponse getMetaResponse = s3Client.GetObjectMetadata(getMetaRequest); // Set the storage class on the object copyRequest = new CopyObjectRequest(); copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName; copyRequest.SourceKey = copyRequest.DestinationKey = key; copyRequest.StorageClass = listObjectResponse.S3Objects[0].StorageClass == "STANDARD" ? S3StorageClass.Standard : S3StorageClass.ReducedRedundancy; if (version != null) { copyRequest.SourceVersionId = version; } copyRequest.WebsiteRedirectLocation = getMetaResponse.WebsiteRedirectLocation; copyRequest.ServerSideEncryptionMethod = getMetaResponse.ServerSideEncryptionMethod; }
/// <summary> /// Get the access control list (ACL) for the new bucket. /// </summary> /// <param name="client">The initialized client object used to get the /// access control list (ACL) of the bucket.</param> /// <param name="newBucketName">The name of the newly created bucket.</param> /// <returns>An S3AccessControlList.</returns> public static async Task <S3AccessControlList> GetACLForBucketAsync(IAmazonS3 client, string newBucketName) { // Retrieve bucket ACL to show that the ACL was properly applied to // the new bucket. GetACLResponse getACLResponse = await client.GetACLAsync(new GetACLRequest { BucketName = newBucketName, }); return(getACLResponse.AccessControlList); }
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { GetACLResponse getACLResponse = new GetACLResponse(); while (context.Read()) { if (context.get_IsStartElement()) { UnmarshallResult(context, getACLResponse); } } return(getACLResponse); }
private static void UnmarshallResult(XmlUnmarshallerContext context, GetACLResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) { targetDepth += 2; } while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Owner", targetDepth)) { if (null == response.AccessControlList) { response.AccessControlList = new S3AccessControlList(); } response.AccessControlList.Owner = OwnerUnmarshaller.Instance.Unmarshall(context); continue; } if (context.TestExpression("Grant", targetDepth + 1)) { if (null == response.AccessControlList) { response.AccessControlList = new S3AccessControlList(); } response.AccessControlList.Grants.Add(GrantUnmarshaller.Instance.Unmarshall(context)); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; }
/// <summary> /// Return the ACL and stat of the node of the given path. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @param path /// the given path for the node /// @param stat /// the stat of the node will be copied to this parameter. /// @return the ACL array of the given node. /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> public IEnumerable <ACL> GetACL(string path, Stat stat) { string clientPath = path; PathUtils.ValidatePath(clientPath); string serverPath = PrependChroot(clientPath); RequestHeader h = new RequestHeader(); h.Type = (int)OpCode.GetACL; GetACLRequest request = new GetACLRequest(serverPath); GetACLResponse response = new GetACLResponse(); ReplyHeader r = cnxn.SubmitRequest(h, request, response, null); if (r.Err != 0) { throw KeeperException.Create((KeeperException.Code)Enum.ToObject(typeof(KeeperException.Code), r.Err), clientPath); } DataTree.CopyStat(response.Stat, stat); return(response.Acl); }
private void setS3Permission(String bucketName, String key) { // Get the ACL for the file and retrieve the owner ID (not sure how to get it otherwise). GetACLRequest getAclRequest = new GetACLRequest().WithBucketName(bucketName).WithKey(key); GetACLResponse aclResponse = s3.GetACL(getAclRequest); Owner owner = aclResponse.AccessControlList.Owner; // Create a grantee as the MessageGears account S3Grantee grantee = new S3Grantee().WithCanonicalUser(properties.MessageGearsAWSCanonicalId, "MessageGears"); // Grant MessageGears Read-only access S3Permission messageGearsPermission = S3Permission.READ; S3AccessControlList acl = new S3AccessControlList().WithOwner(owner); acl.AddGrant(grantee, messageGearsPermission); // Create a new ACL granting the owner full control. grantee = new S3Grantee().WithCanonicalUser(owner.Id, "MyAWSId"); acl.AddGrant(grantee, S3Permission.FULL_CONTROL); SetACLRequest aclRequest = new SetACLRequest().WithACL(acl).WithBucketName(bucketName).WithKey(key); s3.SetACL(aclRequest); }
private async Task <IEnumerable <ACL> > GetACLAsyncInternal(string path, Stat stat, bool sync) { string clientPath = path; PathUtils.ValidatePath(clientPath); string serverPath = PrependChroot(clientPath); RequestHeader h = new RequestHeader(); h.Type = (int)OpCode.GetACL; GetACLRequest request = new GetACLRequest(serverPath); GetACLResponse response = new GetACLResponse(); ReplyHeader r = sync ? cnxn.SubmitRequest(h, request, response, null) : await cnxn.SubmitRequestAsync(h, request, response, null).ConfigureAwait(false); if (r.Err != 0) { throw KeeperException.Create((KeeperException.Code)Enum.ToObject(typeof(KeeperException.Code), r.Err), clientPath); } DataTree.CopyStat(response.Stat, stat); return(response.Acl); }
private static void UnmarshallResult(XmlUnmarshallerContext context, GetACLResponse response) { int currentDepth = context.get_CurrentDepth(); int num = currentDepth + 1; if (context.get_IsStartOfDocument()) { num += 2; } while (context.Read()) { if (context.get_IsStartElement() || context.get_IsAttribute()) { if (context.TestExpression("Owner", num)) { if (response.AccessControlList == null) { response.AccessControlList = new S3AccessControlList(); } response.AccessControlList.Owner = OwnerUnmarshaller.Instance.Unmarshall(context); } else if (context.TestExpression("Grant", num + 1)) { if (response.AccessControlList == null) { response.AccessControlList = new S3AccessControlList(); } response.AccessControlList.Grants.Add(GrantUnmarshaller.Instance.Unmarshall(context)); } } else if (context.get_IsEndElement() && context.get_CurrentDepth() < currentDepth) { break; } } }
static async Task AddACLToExistingObjectAsync(string bucketName, string keyName) { // Retrieve the ACL for an object. GetACLResponse aclResponse = await client.GetACLAsync(new GetACLRequest { BucketName = bucketName, Key = keyName }); S3AccessControlList acl = aclResponse.AccessControlList; // Retrieve the owner. Owner owner = acl.Owner; // Clear existing grants. acl.Grants.Clear(); // Add a grant to reset the owner's full permission // (the previous clear statement removed all permissions). S3Grant fullControlGrant = new S3Grant { Grantee = new S3Grantee { CanonicalUser = acl.Owner.Id } }; acl.AddGrant(fullControlGrant.Grantee, S3Permission.FULL_CONTROL); // Specify email to identify grantee for granting permissions. S3Grant grantUsingEmail = new S3Grant { Grantee = new S3Grantee { EmailAddress = emailAddress }, Permission = S3Permission.WRITE_ACP }; // Specify log delivery group as grantee. S3Grant grantLogDeliveryGroup = new S3Grant { Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/s3/LogDelivery" }, Permission = S3Permission.WRITE }; // Create a new ACL. S3AccessControlList newAcl = new S3AccessControlList { Grants = new List <S3Grant> { grantUsingEmail, grantLogDeliveryGroup }, Owner = owner }; // Set the new ACL. PutACLResponse response = await client.PutACLAsync(new PutACLRequest { BucketName = bucketName, Key = keyName, AccessControlList = newAcl }); }