Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎉 Source S3: Add IAM Instance Profile Support #10676

Conversation

sidartha
Copy link

@sidartha sidartha commented Feb 27, 2022

What

This PR adds IAM instance profiles support for the S3 source connector to allow use of the instance profile instead of relying on Access Keys and Secrets (as described in #5282 and #5942). A similar feature was implemented for destination-s3 in #9399.

Screenshot 2022-02-27 at 10 22 01 AM

How

A new config option use_aws_default_credential_provider_chain is added and when set to true, we rely on Boto3 to identify the credentials (this is done by removing signature_version=UNSIGNED in the client config object).

The other option considered was to fall-back to the default credential provider chain if no access key & secret are provided but this would cause issues for those who are attempting to read a publicly available S3 file without using any credentials and also for those who are using this connector with non-AWS S3 storage.

I'm open to other ideas for implementing this too - this was just the simplest thing I could think of!

Recommended reading order

  1. x.java
  2. y.python

🚨 User Impact 🚨

Are there any breaking changes? What is the end result perceived by the user? If yes, please merge this PR with the 🚨🚨 emoji so changelog authors can further highlight this if needed.

Pre-merge Checklist

Expand the relevant checklist and delete the others.

Updating a connector

Community member or Airbyter

  • Grant edit access to maintainers (instructions)
  • Secrets in the connector's spec are annotated with airbyte_secret
  • Unit & integration tests added and passing. Community members, please provide proof of success locally e.g: screenshot or copy-paste unit, integration, and acceptance test output. To run acceptance tests for a Python connector, follow instructions in the README. For java connectors run ./gradlew :airbyte-integrations:connectors:<name>:integrationTest.
  • Code reviews completed
  • Documentation updated
    • Connector's README.md
    • Connector's bootstrap.md. See description and examples
    • Changelog updated in docs/integrations/<source or destination>/<name>.md including changelog. See changelog example
  • PR name follows PR naming conventions

Airbyter

If this is a community PR, the Airbyte engineer reviewing this PR is responsible for the below items.

  • Create a non-forked branch based on this PR and test the below items on it
  • Build is successful
  • Credentials added to Github CI. Instructions.
  • /test connector=connectors/<name> command is passing
  • New Connector version released on Dockerhub by running the /publish command described here
  • After the new connector version is published, connector version bumped in the seed directory as described here
  • Seed specs have been re-generated by building the platform and committing the changes to the seed spec files, as described here

Tests

Unit

Put your unit tests output here.

Integration

Put your integration tests output here.

Acceptance

Put your acceptance tests output here.

@CLAassistant
Copy link

CLAassistant commented Feb 27, 2022

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions bot added the area/connectors Connector related issues label Feb 27, 2022
@sidartha sidartha force-pushed the sidartha/source-s3-support-iam-ec2-profile branch from c8c4f73 to 1d6a0a7 Compare February 27, 2022 23:43
@sidartha sidartha changed the title Add IAM Instance Profile Support for S3 Source Source S3: Add IAM Instance Profile Support Feb 27, 2022
@sidartha sidartha changed the title Source S3: Add IAM Instance Profile Support 🎉 Source S3: Add IAM Instance Profile Support Feb 27, 2022
@sidartha sidartha marked this pull request as ready for review February 28, 2022 13:39
@ntkawasaki
Copy link

ntkawasaki commented Feb 28, 2022

Hey @sidartha I think the code changes here are straightforward and solid 👍 and thank you for adding a test

One thought I have is to change the boolean type of the connection option use_aws_default_credential_provider_chain to become a oneOf option like authentication_style where the users would choose use_aws_default_credential_provider_chain as the authentication strategy (maybe set this as the default, also). (Not required to do in this PR at all, just something that would set a nice base for adding future auth styles later on!)

Also, you'll need to update a couple more places around the repo such as the Dockerfile image tags, a STANDARD_SOURCE_DEFINTION.yaml file, and the spec.json file in the connector directory. See this PR for an example of the other places to update: https://github.com/airbytehq/airbyte/pull/9623/files#diff-0a23a52edd477f81527cdead182adda4e4d84ec23e10139bdbfecfd33ef6f071L5 (Note that this PR updates a destination and a source together, you only need to worry about the source files)

Copy link
Contributor

@alafanechere alafanechere left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @sidartha for this contribution!
I totally agree with @ntkawasaki about oneOf field to pick authentication method from.
I made a refactoring suggestion, it'd be great if you could find a way of not declaring multiple if/else statements on the authentication method.

I think we shall also add more acceptance test using a config that have use_aws_default_credential_provider_chain = true.

Finally, could you please bump the connector version (in the Dockerfile and in airbyte-config/init/src/main/resources/seed/source_definitions.yaml ), and update it's documentation (docs/integrations/sources/s3.md) . Please explain what is the default chain of credentials that Boto will try to use, and update the changelog.

Let me know what you think of my suggestions!

Comment on lines 36 to 41
elif self.use_aws_default_credential_provider_chain:
self._boto_session = boto3session.Session()
self._boto_s3_resource = make_s3_resource(self._provider, config=Config(), session=self._boto_session)
else:
self._boto_session = boto3session.Session()
self._boto_s3_resource = make_s3_resource(self._provider, config=Config(signature_version=UNSIGNED), session=self._boto_session)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't get the difference between the else and the elif block.

@@ -43,6 +46,10 @@ def use_aws_account(provider: Mapping[str, str]) -> bool:
aws_secret_access_key = provider.get("aws_secret_access_key")
return True if (aws_access_key_id is not None and aws_secret_access_key is not None) else False

@staticmethod
def use_aws_default_credential_provider_chain(provider: Mapping[str, str]) -> bool:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of refactoring this a bit:

  • create a AuthenticationMethod enum
  • create a method that returns the authentication method to use (get_authentication_method)
  • use get_authentication_method in _setup_boto_session to create session according to the authentication method to use

eg:

class AuthenticationMethod(Enum):
  ACCESS_KEY_SECRET_ACCESS_KEY = 1
  DEFAULT = 2
  
class S3File:
  def __init__(self, *args: Any, **kwargs: Any):
    super().__init__(*args, **kwargs)
    self.authentication_method = self.get_authentication_method()
    self._setup_boto_session()

  def get_authentication_method(self):
    if self._provider.get("aws_access_key_id") and self._provider.get("aws_secret_access_key"):
      return AuthenticationMethod.ACCESS_KEY_SECRET_ACCESS_KEY
    elif self._provider.get("use_aws_default_credential_provider_chain"):
      return AuthenticationMethod.DEFAULT
    else:
      raise Exception("Could not determine an authentication method according to current provider.")

  def _setup_boto_session(self):
    if self.authentication_method == AuthenticationMethod.ACCESS_KEY_SECRET_ACCESS_KEY:
      ...
    if self.authentication_method == AuthenticationMethod.DEFAULT:
      ...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be great if we could define at a single spot the specifics related to an authentication method (sessions and params definition) to make the rest of the implementation independent from the authentication method used. My point is to avoid several if / else statements on use_aws_account or use_aws_default_credential_provider_chain. It will improve maintainability and eventual iterations on authentication methods.

@github-actions github-actions bot added the area/documentation Improvements or additions to documentation label Mar 5, 2022
@sidartha
Copy link
Author

sidartha commented Mar 6, 2022

Thanks for the feedback @ntkawasaki and @alafanechere! I have updated the PR based on your suggestions.

Since both s3file.py and stream.py require auth to access S3, I moved the auth related logic to s3_utils.py.

For the acceptance test, do you have any suggestions on how to add a secrets/config.json file with use_aws_default_credential_provider_chain = true?

@sidartha sidartha requested a review from alafanechere March 6, 2022 01:03
Copy link
Contributor

@alafanechere alafanechere left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank @sidartha for the change! I've still one remaining blocking change in the spec.json.
I'll try to run the acceptance test with our current config using access key/secret key. If they pass I'll try to add a new one with use_aws_default_credential_provider_chain.

@@ -177,6 +177,11 @@
"default": "",
"type": "string"
},
"use_aws_default_credential_provider_chain": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please create an authentication_method oneOf field which for the user to chose between Default credential provider and Access Key/Secret Key?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alafanechere I am a little stuck here on how to implement this without causing a breaking change.

We have Default Credential Provider, Access Key/Secret Key and no authentication. The current behaviour defaults to Access Key/Secret Key if those values are included and falls back to no authentication if not included.
When introducing oneOf field authentication_method, I'm not sure what the default value can be set to.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of removing use_aws_default_credential_provider_chain field and changing the description of Access Key/Secret Key to explain that if not set it will fall back to the default boto credential chain?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we need to support those who don't use any credentials (e.g. those who use it with non-AWS storage or those who don't need any auth since they are accessing public buckets), I don't think this will work. In this case, the default boto credential chain won't be able to locate any credentials.

@alafanechere
Copy link
Contributor

alafanechere commented Mar 9, 2022

/test connector=connectors/source-s3

🕑 connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/1956014324
❌ connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/1956014324
🐛 https://gradle.com/s/crypsmlkullis

@alafanechere
Copy link
Contributor

alafanechere commented Mar 16, 2022

/test connector=connectors/source-s3

🕑 connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/1993148116
❌ connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/1993148116
🐛 https://gradle.com/s/qy3jelpctegm2
Python short test summary info:

=========================== short test summary info ============================
FAILED test_core.py::TestSpec::test_match_expected[inputs0] - AssertionError:...
=================== 1 failed, 43 passed in 85.89s (0:01:25) ====================

@alafanechere
Copy link
Contributor

alafanechere commented Mar 18, 2022

/test connector=connectors/source-s3

🕑 connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/2003070852
✅ connectors/source-s3 https://github.com/airbytehq/airbyte/actions/runs/2003070852
Python tests coverage:

Name                                                 Stmts   Miss  Cover
------------------------------------------------------------------------
source_acceptance_test/utils/__init__.py                 6      0   100%
source_acceptance_test/tests/__init__.py                 4      0   100%
source_acceptance_test/__init__.py                       2      0   100%
source_acceptance_test/tests/test_full_refresh.py       52      2    96%
source_acceptance_test/utils/asserts.py                 37      2    95%
source_acceptance_test/config.py                        74      6    92%
source_acceptance_test/utils/json_schema_helper.py     105     13    88%
source_acceptance_test/utils/common.py                  70     17    76%
source_acceptance_test/utils/compare.py                 62     23    63%
source_acceptance_test/tests/test_core.py              275    106    61%
source_acceptance_test/base.py                          10      4    60%
source_acceptance_test/utils/connector_runner.py       110     48    56%
source_acceptance_test/tests/test_incremental.py        69     38    45%
------------------------------------------------------------------------
TOTAL                                                  876    259    70%
Name                                                              Stmts   Miss  Cover
-------------------------------------------------------------------------------------
source_s3/source_files_abstract/formats/parquet_spec.py               9      0   100%
source_s3/source_files_abstract/formats/csv_spec.py                  16      0   100%
source_s3/s3file.py                                                  18      0   100%
source_s3/__init__.py                                                 2      0   100%
source_s3/source.py                                                  29      1    97%
source_s3/source_files_abstract/storagefile.py                       23      1    96%
source_s3/source_files_abstract/formats/abstract_file_parser.py      35      2    94%
source_s3/source_files_abstract/stream.py                           184     11    94%
source_s3/stream.py                                                  35      3    91%
source_s3/s3_utils.py                                                38      4    89%
source_s3/source_files_abstract/formats/csv_parser.py                74     18    76%
source_s3/source_files_abstract/file_info.py                         26      8    69%
source_s3/utils.py                                                   29     10    66%
source_s3/source_files_abstract/source.py                            37     14    62%
source_s3/source_files_abstract/spec.py                              42     22    48%
source_s3/source_files_abstract/formats/parquet_parser.py            61     44    28%
-------------------------------------------------------------------------------------
TOTAL                                                               658    138    79%
Name                                                              Stmts   Miss  Cover
-------------------------------------------------------------------------------------
source_s3/source_files_abstract/formats/parquet_spec.py               9      0   100%
source_s3/source_files_abstract/formats/csv_spec.py                  16      0   100%
source_s3/source_files_abstract/formats/abstract_file_parser.py      35      0   100%
source_s3/source.py                                                  29      0   100%
source_s3/__init__.py                                                 2      0   100%
source_s3/source_files_abstract/formats/parquet_parser.py            61      3    95%
source_s3/source_files_abstract/storagefile.py                       23      5    78%
source_s3/source_files_abstract/formats/csv_parser.py                74     18    76%
source_s3/utils.py                                                   29      8    72%
source_s3/source_files_abstract/file_info.py                         26     10    62%
source_s3/source_files_abstract/source.py                            37     15    59%
source_s3/source_files_abstract/stream.py                           184     91    51%
source_s3/s3file.py                                                  18      9    50%
source_s3/source_files_abstract/spec.py                              42     22    48%
source_s3/s3_utils.py                                                38     21    45%
source_s3/stream.py                                                  35     25    29%
-------------------------------------------------------------------------------------
TOTAL                                                               658    227    66%

@alafanechere
Copy link
Contributor

Hey @sidartha I run the acceptance tests to make sure your PR does not introduce any breaking change.
I'd still like the spec.json to be refactored a bit to introduce an Authentication Method dropdown menu with oneOf fields. I'll try to make the change myself if you don't feel like doing it.
I also still need to figure out a way to run the acceptance test with a config that is using the default credentials provider you introduced. This will probably lead me to some specific IAM settings I need to declare for the run of the tests.

@sidartha
Copy link
Author

Hi @alafanechere, I'd appreciate the help on editing the spec.json to add a oneOf authentication method field (or do you have any pointers to other sources that have implemented this where we are overriding the SourceFilesAbstractSpec?). Thanks!

@matthewhembree
Copy link

Question:
I don't intend to expand the scope of this PR, but I am interested if post-merge refactoring could be avoided.

What issues do you see could be encountered if an additional method like AuthenticationMethod.ACCESS_KEY_SECRET_ACCESS_KEY_ASSUME_ROLE would be added? I'd like to be able to specify in the UI:

  • access key id
  • secret access key
  • role to assume (ARN)

And those credentials could establish temporary STS credentials to pass to the S3 client.

My particular use case is cross-account role access.
Source: Account B
Destination: Account A
Airbyte instance homed in Account A

My org has a third party pulling data from our S3 bucket and if they could just assume a role in our account, then we wouldn't have to worry about rotating secret keys.

This is further useful if you have a single Airbyte instance that has sources/destinations in multiple foreign accounts. The default EC2 instance profile can only be tied to a single role ARN in the ~/.aws/config file which limits the instance to a single foreign account. It also separates the credentials on the instance in two places.

Maybe additional profiles could be added in ~/.aws/config and reference a source_profile of the instance profile.
e.g. This might be a good compromise, but still separates credentials in two places:

[default]
credential_source = Ec2InstanceMetadata

[profile accountb]
role_arn = arn:aws:iam::111111111111:role/ROLENAME
external_id = bbbbbbbb
source_profile = default

[profile accountc]
role_arn = arn:aws:iam::222222222222:role/ROLENAME
external_id = cccccccc
source_profile = default

...and then the UI could take a profile as input.

Would your implementation need to be refactored to add my use case at a future time?

Thanks!

@alafanechere
Copy link
Contributor

@matthewhembree thank you for this feedback! This is definitely a valid use case and goes in the direction that we shall implement a dropdown field to select authentication methods. I've been really swamped in the past week to suggest the change in spec.json but I will soon!

@alafanechere
Copy link
Contributor

alafanechere commented Apr 5, 2022

@sidartha, to implement the oneOf field for the autentication_method, I suggest you to have a look at how the format field is handled on the SourceFilesAbstractSpec parent class. You'll have to declare a base model for each authentication method and create an authentication_method field in SourceS3Spec. The type of authentication_method is the union of the base models you created. You'll then have to create a custom function similar to change_format_to_oneOf in airbyte-integrations/connectors/source-s3/source_s3/source_files_abstract/spec.py and call it from an overridden schema class method.

@alafanechere
Copy link
Contributor

I'm closing this PR as I don't have the bandwidth to iterate on the specs. @sidartha feel free to re-open if you want to tackle this.

@mc51
Copy link

mc51 commented Sep 20, 2022

Just FYI: I'm working on finishing this up. I'll open a new PR soon.

@mc51 mc51 mentioned this pull request Sep 28, 2022
14 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/connectors Connector related issues area/documentation Improvements or additions to documentation community connectors/source/s3 type/enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants