Details
| ID | AWS - S3 |
|---|---|
| Provider | Amazon |
| Category | IT Services |
| From Version | 5.0.0 |
| Docker Image | demisto/boto3py3:1.0.0.10221838 |
| Supported Modules | Agentix XSIAM |
README
Amazon Web Services Simple Storage Service (S3).
This integration was integrated and tested with API Version 2012-11-05.
For detailed instructions about setting up authentication, see: AWS Integrations - Authentication.
Configure AWS - S3 in Cortex
| Parameter | Description | Required |
|---|---|---|
| roleArn | Role Arn | False |
| roleSessionName | Role Session Name | False |
| defaultRegion | AWS Default Region | False |
| sessionDuration | Role Session Duration | False |
| access_key | Access Key | False |
| secret_key | Secret Key | False |
| timeout | The time in seconds till a timeout exception is reached. You can specify just the read timeout (for example 60) or also the connect timeout followed after a comma (for example 60,10). If a connect timeout is not specified, a default of 10 second will be used. | False |
| retries | The maximum number of retry attempts when connection or throttling errors are encountered. Set to 0 to disable retries. The default value is 5 and the limit is 10. Note: Increasing the number of retries will increase the execution time. | False |
| insecure | Trust any certificate (not secure) | False |
| proxy | Use system proxy settings | False |
| Bucket | Bucket used for network connectivity testing. | False |
Commands
You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.
aws-s3-create-bucket
Create AWS S3 bucket.
Base Command
aws-s3-create-bucket
Input
| Argument Name | Description | Required |
|---|---|---|
| bucket | The name of S3 bucket to create (in lowercase). | Required |
| acl | ACL for S3 bucket. Possible values are: private, public-read, public-read-write, authenticated-read. | Optional |
| locationConstraint | Specifies the region where the bucket will be created. If you don’t specify a region, the bucket will be created in US Standard. | Optional |
| grantFullControl | Allows grantee the read, write, read ACP, and write ACP permissions on the bucket. | Optional |
| grantRead | Allows grantee to list the objects in the bucket. | Optional |
| grantReadACP | Allows grantee to read the bucket ACL. | Optional |
| grantWrite | Allows grantee to create, overwrite, and delete any object in the bucket. | Optional |
| grantWriteACP | Allows grantee to write the ACL for the applicable bucket. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
Context Output
| Path | Type | Description |
|---|---|---|
| AWS.S3.Buckets.BucketName | string | The name of the bucket that was created. |
| AWS.S3.Buckets.Location | string | The AWS Region the bucket was created. |
Command Example
!aws-s3-create-bucket bucket=test acl=private
Human Readable Output
AWS S3 Buckets
| BucketName | Location |
|---|---|
| test | test |
aws-s3-delete-bucket
Delete AWS S3 bucket.
Base Command
aws-s3-delete-bucket
Input
| Argument Name | Description | Required |
|---|---|---|
| bucket | Name of S3 bucket to delete. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
Context Output
There is no context output for this command.
Command Example
!aws-s3-delete-bucket bucket=test
Human Readable Output
The bucket was deleted.
aws-s3-list-buckets
List all S3 buckets in AWS account
Base Command
aws-s3-list-buckets
Input
| Argument Name | Description | Required |
|---|---|---|
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
Context Output
| Path | Type | Description |
|---|---|---|
| AWS.S3.Buckets.BucketName | string | The name of the bucket. |
| AWS.S3.Buckets.CreationDate | date | Date the bucket was created. |
Command Example
#### Human Readable Output
AWS S3 Buckets
| BucketName | CreationDate |
| --- | --- |
| backup-lab | 2018-04-29T13:31:57 |
| test | 2018-05-06T06:34:30 |
### aws-s3-get-bucket-policy
***
Get AWS S3 Bucket Policy
#### Base Command
`aws-s3-get-bucket-policy`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | Name of bucket. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.S3.Buckets.Policy.Version | string | S3 Bucket Policy Version. |
| AWS.S3.Buckets.Policy.PolicyId | string | S3 Bucket Policy ID. |
| AWS.S3.Buckets.Policy.Sid | string | S3 Bucket Policy Statment ID. |
| AWS.S3.Buckets.Policy.Action | string | S3 Bucket Policy Statment Action. |
| AWS.S3.Buckets.Policy.Principal | string | S3 Bucket Policy Statment Principal. |
| AWS.S3.Buckets.Policy.Resource | string | S3 Bucket Policy Statment Resource. |
| AWS.S3.Buckets.Policy.Effect | string | S3 Bucket Policy Statment Effect. |
| AWS.S3.Buckets.Policy.Json | string | AWS S3 Policy Json output. |
| AWS.S3.Buckets.Policy.BucketName | string | S3 Bucket Name. |
#### Command Example
```!aws-s3-get-bucket-policy bucket=test```
### aws-s3-delete-bucket-policy
***
Deletes the policy from the bucket.
#### Base Command
`aws-s3-delete-bucket-policy`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | Name of S3 bucket. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
There is no context output for this command.
#### Command Example
```!aws-s3-delete-bucket-policy bucket=test```
#### Human Readable Output
Policy deleted from test.
### aws-s3-download-file
***
Download a file from S3 bucket to war room.
#### Base Command
`aws-s3-download-file`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | The name of S3 bucket. | Optional |
| key | The S3 object key to download. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
There is no context output for this command.
#### Command Example
```!aws-s3-download-file bucket=test key=test.txt```
### aws-s3-list-bucket-objects
***
List object in S3 bucket.
#### Base Command
`aws-s3-list-bucket-objects`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | The name of S3 bucket. | Required |
| prefix | Limits the response to keys that begin with the specified prefix. | Optional |
| delimiter | A delimiter is a character you use to group keys. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.S3.Buckets.Objects.Key | Unknown | The name of S3 object. |
| AWS.S3.Buckets.Objects.Size | Unknown | Object size. |
| AWS.S3.Buckets.Objects.LastModified | Unknown | Last date object was modified. |
#### Command Example
```!aws-s3-list-bucket-objects bucket=test prefix=testing delimiter='/'```
#### Human Readable Output
AWS S3 Bucket Objects
| Key | Size | LastModified |
| --- | --- | --- |
| demi2018-04-05-14-29-49-76DA472F25CB951F | 323.0 B | 2018-04-05T14:29:51 |
### aws-s3-put-bucket-policy
***
Replaces a policy on a bucket. If the bucket already has a policy, the one in this request completely replaces it.
#### Base Command
`aws-s3-put-bucket-policy`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | Name of S3 bucket. | Required |
| policy | The bucket policy to apply in json format. | Required |
| confirmRemoveSelfBucketAccess | Set this parameter to true to confirm that you want to remove your permissions to change this bucket policy in the future. Possible values are: True, False. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
There is no context output for this command.
#### Command Example
```!aws-s3-put-bucket-policy bucket=test policy={"Version":"2012-10-17","Id":"Policy1519481415511","Statement":[{"Sid":"Stmt1519ds34548138sf5929","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789:user/itai"},"Action":"s3:","Resource":"arn:aws:s3:::test"},{"Sid":"Stmt1345519481414395","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789:user/bob"},"Action":"s3:","Resource":"arn:aws:s3:::test"}]}```
#### Human Readable Output
Successfully applied bucket policy to test bucket.
### aws-s3-upload-file
***
Upload file to S3 bucket
#### Base Command
`aws-s3-upload-file`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| entryID | Entry ID of the file to upload. | Required |
| bucket | The name of the bucket to upload to. | Required |
| key | The name of the key to upload to. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
There is no context output for this command.
#### Command Example
```!aws-s3-upload-file bucket="bucket name" key="file name to be displayed" entryID=##@##```
#### Human Readable Output
File {file name to be displayed} was uploaded successfully to {bucket name}'
### aws-s3-get-public-access-block
***
Retrieves the PublicAccessBlock configuration for an Amazon S3 bucket.
#### Base Command
`aws-s3-get-public-access-block`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | The name of the Amazon S3 bucket whose PublicAccessBlock configuration you want to retrieve. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.S3.Buckets.BucketName.PublicAccessBlockConfiguration.BlockPublicAcls | Boolean | Specifies whether Amazon S3 should block public access control lists (ACLs) for this bucket and objects in this bucket. |
| AWS.S3.Buckets.BucketName.PublicAccessBlockConfiguration.IgnorePublicAcls | Boolean | Specifies whether Amazon S3 should ignore public ACLs for this bucket and objects in this bucket. |
| AWS.S3.Buckets.BucketName.PublicAccessBlockConfiguration.BlockPublicPolicy | Boolean | Specifies whether Amazon S3 should block public bucket policies for this bucket. |
| AWS.S3.Buckets.BucketName.PublicAccessBlockConfiguration.RestrictPublicBuckets | Boolean | Specifies whether Amazon S3 should restrict public bucket policies for this bucket. |
#### Command Example
```!aws-s3-get-public-access-block bucket="bucket name"```
#### Human Readable Output
AWS S3 Bucket Public Access Block
| BlockPublicAcls | IgnorePublicAcls | BlockPublicPolicy | RestrictPublicBuckets |
| --- | --- | --- | --- |
| True | False | True | False |
### aws-s3-put-public-access-block
***
Creates or modifies the PublicAccessBlock configuration for an Amazon S3 bucket.
#### Base Command
`aws-s3-put-public-access-block`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | The name of the bucket to upload to. | Required |
| BlockPublicAcls | Specifies whether Amazon S3 should block public access control lists (ACLs) for this bucket and objects in this bucket. | Required |
| IgnorePublicAcls | Specifies whether Amazon S3 should ignore public ACLs for this bucket and objects in this bucket. | Required |
| BlockPublicPolicy | Specifies whether Amazon S3 should block public bucket policies for this bucket. | Required |
| RestrictPublicBuckets | Specifies whether Amazon S3 should restrict public bucket policies for this bucket. | Required |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
There is no context output for this command.
#### Command Example
```!aws-s3-put-public-access-block bucket="bucket name" BlockPublicAcls=True IgnorePublicAcls=False BlockPublicPolicy=True RestrictPublicBuckets=True```
#### Human Readable Output
Successfully applied public access block to the {bucket} bucket.
### aws-s3-get-bucket-encryption
***
Get AWS S3 Bucket Encryption
#### Base Command
`aws-s3-get-bucket-encryption`
#### Input
| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| bucket | The name of the bucket from which the server-side encryption configuration is retrieved. | Required |
| expectedBucketOwner | The account ID of the exepcted bucket owner. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |
#### Context Output
| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.S3.Buckets.BucketName.ServerSideEncryptionConfiguration.Rules.ApplyServerSideEncryptionByDefault.SSEAlgorithm | String | S3 Bucket Encryption SSE Algorithm. |
| AWS.S3.Buckets.BucketName.ServerSideEncryptionConfiguration.Rules.ApplyServerSideEncryptionByDefault.KMSMasterKeyID | String | S3 Bucket Encryption KMS Master Key ID. |
| AWS.S3.Buckets.BucketName.ServerSideEncryptionConfiguration.Rules.BucketKeyEnabled | Boolean | S3 Bucket Encryption Key Enabled. |
#### Command Example
```!aws-s3-put-public-access-block bucket="bucket name" BlockPublicAcls=True IgnorePublicAcls=False BlockPublicPolicy=True RestrictPublicBuckets=True```
#### Context Example
{
“AWS”: {
“S3”: {
“Buckets”: [
{
“BucketName”: “bucket-a”,
“ServerSideEncryptionConfiguration”: {
“Rules”: [
{
“ApplyServerSideEncryptionByDefault”: {
“SSEAlgorithm”: “AES256”
}
}
]
}
}
]
}
}
}
```
Configuration parameters
roleArn— Role ArnroleSessionName— Role Session NamedefaultRegion— AWS Default Region (required)sessionDuration— Role Session Durationcredentials— Access Keyaccess_key— Access Keysecret_key— Secret Keytimeout— Timeoutretries— Retriesendpoint_url— PrivateLink service URL.sts_endpoint_url— STS PrivateLink URL.sts_regional_endpoint— AWS STS Regional Endpointsbucket— Bucketinsecure— Trust any certificate (not secure)proxy— Use system proxy settings
Commands (12)
-
aws-s3-create-bucketCreate AWS S3 bucket.
-
aws-s3-delete-bucketDelete AWS S3 bucket.
-
aws-s3-delete-bucket-policyDeletes the policy from the bucket.
-
aws-s3-download-fileDownload a file from S3 bucket to war room.
-
aws-s3-get-bucket-encryptionGet AWS S3 Bucket Encryption.
-
aws-s3-get-bucket-policyGet AWS S3 Bucket Policy.
-
aws-s3-get-public-access-blockRetrieves the PublicAccessBlock configuration for an Amazon S3 bucket.
-
aws-s3-list-bucket-objectsList object in S3 bucket.
-
aws-s3-list-bucketsList all S3 buckets in AWS account.
-
aws-s3-put-bucket-policyReplaces a policy on a bucket. If the bucket already has a policy, the one in this request completely replaces it.
-
aws-s3-put-public-access-blockCreates or modifies the PublicAccessBlock configuration for an Amazon S3 bucket.
-
aws-s3-upload-fileUpload file to S3 bucket.
import importlib import json from http import HTTPStatus import pytest AWS_S3 = importlib.import_module("AWS-S3") TEST_PARAMS = { "region": "test_region", "roleArn": "test_arn", "roleSessionName": "test_role_session", "roleSessionDuration": "test_role_session_duration", } class AWSClient: def aws_session(self): pass class Boto3Client: def create_bucket(self): pass def delete_bucket(self): pass def list_buckets(self): pass def get_bucket_policy(self): pass def put_bucket_policy(self): pass def delete_bucket_policy(self): pass def download_fileobj(self): pass def list_objects(self): pass def get_paginator(self): pass def put_public_access_block(self): pass def get_bucket_encryption(self): pass def list_objects_v2(self): pass class paginator: def paginate(self): pass def util_load_json(path: str): with open(path, encoding="utf-8") as f: return json.loads(f.read()) def convert_size(size_bytes): import math if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return f"{s} {size_name[i]}" def test_create_bucket_command(mocker): """ Given: - A bucket name and location. When: - Calling create_bucket_command method. Then: - Ensure that the bucket was successfully created. """ from CommonServerPython import tableToMarkdown args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) response = {"Location": "us-west-2"} mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "create_bucket", return_value=response) client = AWSClient() data = [{"BucketName": args.get("bucket"), "Location": response["Location"]}] res = AWS_S3.create_bucket_command(args, client) assert tableToMarkdown("AWS S3 Buckets", data) == res.readable_output @pytest.mark.parametrize( "res, excepted", [ ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.NO_CONTENT}}, "deleted"), ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.NOT_FOUND}}, "not found"), ], ) def test_delete_bucket_command(mocker, res, excepted): """ Given: - A bucket name. When: - Calling delete_bucket_command method. Then: - Ensure that the bucket was successfully deleted. """ args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "delete_bucket", return_value=res) client = AWSClient() res = AWS_S3.delete_bucket_command(args, client) assert res.readable_output == f"The requested bucket '{args.get('bucket')}' was {excepted}" def test_list_bucket_command(mocker): """ Given: - A bucket name. When: - Calling list_bucket_command method. Then: - Ensure that the bucket list was successfully retrieve. """ from datetime import datetime args = TEST_PARAMS response = { "Buckets": [ {"Name": "test_1", "CreationDate": datetime(2022, 1, 1)}, {"Name": "test_2", "CreationDate": datetime(2022, 2, 2)}, ] } excepted = [ {"BucketName": bucket.get("Name"), "CreationDate": datetime.strftime(bucket["CreationDate"], "%Y-%m-%dT%H:%M:%S")} for bucket in response.get("Buckets") ] mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_buckets", return_value=response) client = AWSClient() res = AWS_S3.list_buckets_command(args, client) assert res.outputs == excepted TEST_POLICY = { "Policy": """ { "Id": "1", "Version": "1.0.0", "Statement": [ { "BucketName": "bucket_name_1", "Sid": "Sid_1", "Action": "action_1", "Principal": "principal_1", "Resource": "resource_1", "Effect": "effect_1" }, { "BucketName": "bucket_name_2", "Sid": "Sid_2", "Action": "action_2", "Principal": "principal_2", "Resource": "resource_2", "Effect": "effect_2" } ] } """ } def test_get_bucket_policy_command(mocker): """ Given: - A bucket name. When: - Calling get_bucket_policy_command method. Then: - Ensure that the bucket policy was successfully retrieve. """ args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) excepted = util_load_json("test_data/get_bucket_policy.json") mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "get_bucket_policy", return_value=TEST_POLICY) client = AWSClient() res = AWS_S3.get_bucket_policy_command(args, client) for output in res.outputs: output.pop("Json") assert res.outputs == excepted @pytest.mark.parametrize( "res, excepted", [ ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.OK}}, "Successfully applied"), ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.NOT_FOUND}}, "Couldn't apply"), ], ) def test_put_bucket_policy_command(mocker, res, excepted): """ Given: - A bucket name and bucket policy. When: - Calling put_bucket_policy_command method. Then: - Ensure that the bucket policy was successfully applied. """ args = {"bucket": "test_bucket", "Policy": "test_policy"} args.update(TEST_PARAMS) mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "put_bucket_policy", return_value=res) client = AWSClient() res = AWS_S3.put_bucket_policy_command(args, client) assert res.readable_output == f"{excepted} bucket policy to {args.get('bucket')} bucket" def test_delete_bucket_policy(mocker): """ Given: - A bucket name. When: - Calling delete_bucket_policy method. Then: - Ensure that the bucket policy was successfully deleted. """ args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "delete_bucket_policy") client = AWSClient() res = AWS_S3.delete_bucket_policy_command(args, client) assert res.readable_output == f"Policy deleted from {args.get('bucket')}" def test_list_objects_command(mocker): """ Given: - A bucket name. When: - Calling list_objects_command method. Then: - Ensure that the bucket object list was successfully retrieve. """ from datetime import datetime args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) contents = {"Key": "key_1", "Size": 1024, "LastModified": datetime(2020, 1, 1)} mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_objects") mocker.patch.object(Boto3Client, "get_paginator", return_value=paginator()) mocker.patch.object(paginator, "paginate", return_value=[{"Contents": [contents]}]) client = AWSClient() res = AWS_S3.list_objects_command(args, client) assert res.outputs[0].get("Key") == contents.get("Key") assert res.outputs[0].get("Size") == convert_size(contents.get("Size")) assert res.outputs[0].get("LastModified") == datetime.strftime(contents.get("LastModified"), "%Y-%m-%dT%H:%M:%S") @pytest.mark.parametrize( "res, excepted", [ ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.OK}}, "Successfully applied"), ({"ResponseMetadata": {"HTTPStatusCode": HTTPStatus.NOT_FOUND}}, "Couldn't apply"), ], ) def test_put_public_access_block_command(mocker, res, excepted): """ Given: - A bucket name, block public Acls, Ignore public, block public policy and restrict public buckets. When: - Calling put_public_access_block method. Then: - Ensure that the bucket public access block has been updated. """ args = { "bucket": "test_bucket", "BlockPublicAcls": "false", "IgnorePublicAcls": "false", "BlockPublicPolicy": "false", "RestrictPublicBuckets": "false", } args.update(TEST_PARAMS) mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "put_public_access_block", return_value=res) client = AWSClient() res = AWS_S3.put_public_access_block(args, client) assert res.readable_output == f"{excepted} public access block to the {args.get('bucket')} bucket" def test_get_bucket_encryption(mocker): """ Given: - A bucket name. When: - Calling get_bucket_encryption method. Then: - Ensure that the bucket encryption was successfully retrieved. """ from CommonServerPython import tableToMarkdown args = {"bucket": "test_bucket"} args.update(TEST_PARAMS) encryption = {"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]} response = {"ServerSideEncryptionConfiguration": encryption} mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "get_bucket_encryption", return_value=response) client = AWSClient() data = [{"BucketName": args.get("bucket"), "ServerSideEncryptionConfiguration": encryption}] res = AWS_S3.get_bucket_encryption(args, client) assert tableToMarkdown("AWS S3 Bucket Encryption", data) == res.readable_output def test_module_success(mocker): """ Given: - A successful connection to AWS S3. When: - Calling test_module method. Then: - Ensure that the connection was successful. """ mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_buckets", return_value={"ResponseMetadata": {"HTTPStatusCode": 200}}) client = AWSClient() assert AWS_S3.test_module(client, "") == "ok" def test_module_list_buckets_fail_list_objects_success(mocker): """ Given: - A failed connection to AWS S3, but a bucket is provided. When: - Calling test_module method. Then: - Ensure that the connection was successful. """ mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_buckets", side_effect=Exception) list_objects_v2_mock = mocker.patch.object( Boto3Client, "list_objects_v2", return_value={"ResponseMetadata": {"HTTPStatusCode": 200}} ) client = AWSClient() assert AWS_S3.test_module(client, "test_bucket") == "ok" list_objects_v2_mock.assert_called_once_with(Bucket="test_bucket") def test_module_list_buckets_fail_list_objects_fail(mocker): """ Given: - A failed connection to AWS S3, and a bucket is provided, but list_objects_v2 fails. When: - Calling test_module method. Then: - Ensure that the connection failed. """ from CommonServerPython import CommandResults, EntryFormat, EntryType mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_buckets", side_effect=Exception) mocker.patch.object(Boto3Client, "list_objects_v2", return_value={"ResponseMetadata": {"HTTPStatusCode": 404}}) client = AWSClient() result = AWS_S3.test_module(client, "test_bucket") assert isinstance(result, CommandResults) assert result.content_format == EntryFormat.TEXT assert result.entry_type == EntryType.ERROR def test_module_fail(mocker): """ Given: - A failed connection to AWS S3, and no bucket is provided. When: - Calling test_module method. Then: - Ensure that the connection failed and an exception is raised. """ mocker.patch.object(AWSClient, "aws_session", return_value=Boto3Client()) mocker.patch.object(Boto3Client, "list_buckets", side_effect=Exception) mocker.patch.object(AWS_S3.demisto, "params", return_value={}) client = AWSClient() with pytest.raises(Exception): AWS_S3.test_module(client)