Skip to content

Refactored RDS IAM authentication logic into a dedicated rdsauth package - #36847

Merged
getvictor merged 3 commits into
mainfrom
victor/36846-rdsauth-refactor
Dec 10, 2025
Merged

Refactored RDS IAM authentication logic into a dedicated rdsauth package#36847
getvictor merged 3 commits into
mainfrom
victor/36846-rdsauth-refactor

Conversation

@getvictor

@getvictor getvictor commented Dec 7, 2025

Copy link
Copy Markdown
Member

Simplified and modularized IAM auth setup for MySQL connections.

Related issue: Resolves #36846

Manually QA'ed by setting up RDS with IAM and running Fleet like:

FLEET_MYSQL_ADDRESS=fleet-iam-test-public.xxxxxxxxx.us-east-2.rds.amazonaws.com:3306 \
  FLEET_MYSQL_USERNAME=fleet_iam \
  FLEET_MYSQL_DATABASE=fleet \
  FLEET_MYSQL_REGION=us-east-2 \
./build/fleet serve

Checklist for submitter

If some of the following don't apply, delete the relevant line.

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

Summary by CodeRabbit

  • Refactor
    • Reorganized IAM authentication infrastructure for RDS databases to improve code organization and maintainability.
    • Enhanced the database connection layer to support flexible authentication configuration methods while maintaining full backward compatibility with existing configurations.

✏️ Tip: You can customize this high-level summary in your review settings.

…ckage.

Simplified and modularized IAM auth setup for MySQL connections.
@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Dec 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@getvictor getvictor changed the title Refactored RDS IAM authentication logic into a dedicated rdsauth pa… Refactored RDS IAM authentication logic into a dedicated rdsauth package Dec 7, 2025
@coderabbitai

coderabbitai Bot commented Dec 7, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactored RDS IAM authentication logic from common_mysql into a dedicated rdsauth package using dependency injection. Introduced ConnectorFactory interface in DBOptions to decouple AWS-specific dependencies from the common MySQL package, reducing cognitive complexity and build time impact.

Changes

Cohort / File(s) Change Summary
Dependency Injection in common_mysql
server/datastore/mysql/common_mysql/common.go
Added ConnectorFactory type and field to DBOptions struct for injecting custom driver connectors. Modified NewDB to use injected factory when present, otherwise fall back to standard sqlx.Open.
IAM Integration in datastore
server/datastore/mysql/mysql.go
Added setupIAMAuthIfNeeded() helper function to conditionally configure IAM authentication. Updated constructor signature (configconf parameter). Applied IAM setup to both primary and replica database connections. Extended imports to include net and rdsauth.
RDS IAM Authentication Package
server/datastore/mysql/rdsauth/connector.go
New package containing refactored IAM authentication logic. Renamed internal types (awsIAMAuthTokenGeneratoriamAuthTokenGenerator, awsIAMAuthConnectorConnector). Added public NewConnectorFactory() function to create driver connectors with IAM token generation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25–30 minutes

  • Attention areas:
    • Verify IAM connector factory correctly initializes and maintains state across primary/replica connections
    • Ensure setupIAMAuthIfNeeded() logic correctly detects when IAM auth is required (password absent, region/address present)
    • Confirm replica connection handling properly resets ConnectorFactory and reapplies IAM setup
    • Review host/port parsing from Address field and DSN construction for correctness
    • Validate that non-IAM code paths remain unchanged and backward-compatible

Suggested reviewers

  • sgress454
  • lucasmrod
  • JordanMontgomery

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main refactoring change: moving RDS IAM authentication logic into a dedicated rdsauth package.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements: new rdsauth package created, ConnectorFactory injection added to DBOptions, NewDB updated to use factory, IAM auth moved to mysql.New(), and aws_iam_auth.go removed from common_mysql.
Out of Scope Changes check ✅ Passed All changes are directly related to the refactoring objectives: rdsauth package creation, ConnectorFactory injection, IAM setup relocation, and removal of IAM code from common_mysql. No extraneous changes detected.
Description check ✅ Passed The PR description covers the main changes and includes manual QA testing details, though it lacks comprehensive coverage of the template's full checklist.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/36846-rdsauth-refactor

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
server/datastore/mysql/rdsauth/connector.go (1)

71-76: Unused driverName field.

The driverName field is stored in the Connector struct but never used. The Driver() method returns mysql.MySQLDriver{} directly regardless of this field. Consider removing it if not needed, or document why it's retained for future use.

 type Connector struct {
-	driverName string
 	baseDSN    string
 	tokenGen   *iamAuthTokenGenerator
 	logger     log.Logger
 }

And update the factory:

 	return func(driverName, dsn string, logger log.Logger) (driver.Connector, error) {
 		return &Connector{
-			driverName: driverName,
 			baseDSN:    dsn,
 			tokenGen:   tokenGen,
 			logger:     logger,
 		}, nil
 	}, nil
server/datastore/mysql/common_mysql/common.go (1)

67-80: Unused err variable declaration on line 68.

The err variable declared on line 68 is never used because both branches of the if-else create their own scoped err variables with :=. This is not a bug but adds unnecessary clutter.

 	dsn := generateMysqlConnectionString(*conf)
 
 	var db *sqlx.DB
-	var err error
 	if opts.ConnectorFactory != nil {
 		connector, err := opts.ConnectorFactory(driverName, dsn, opts.Logger)
 		if err != nil {
 			return nil, fmt.Errorf("failed to create connector: %w", err)
 		}
 		db = sqlx.NewDb(sql.OpenDB(connector), driverName)
 	} else {
-		db, err = sqlx.Open(driverName, dsn)
+		var err error
+		db, err = sqlx.Open(driverName, dsn)
 		if err != nil {
 			return nil, err
 		}
 	}

Or alternatively, keep line 68 and use = instead of := in the else branch to be consistent.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae66a83 and 57ee0b0.

📒 Files selected for processing (4)
  • changes/36846-refactor-rds-iam (1 hunks)
  • server/datastore/mysql/common_mysql/common.go (4 hunks)
  • server/datastore/mysql/mysql.go (7 hunks)
  • server/datastore/mysql/rdsauth/connector.go (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

When reviewing SQL queries that are added or modified, ensure that appropriate filtering criteria are applied—especially when a query is intended to return data for a specific entity (e.g., a single host). Check for missing WHERE clauses or incorrect filtering that could lead to incorrect or non-deterministic results (e.g., returning the first row instead of the correct one). Flag any queries that may return unintended results due to lack of precise scoping.

Files:

  • server/datastore/mysql/mysql.go
  • server/datastore/mysql/common_mysql/common.go
  • server/datastore/mysql/rdsauth/connector.go
🧠 Learnings (3)
📓 Common learnings
Learnt from: sgress454
Repo: fleetdm/fleet PR: 31075
File: server/datastore/mysql/common_mysql/aws_iam_auth.go:111-130
Timestamp: 2025-08-20T21:24:59.261Z
Learning: In Fleet's MySQL IAM authentication implementation, the TLS and AllowCleartextPasswords configuration is handled in the generateMysqlConnectionString function in server/datastore/mysql/common_mysql/common.go. When no password is configured and the endpoint is an RDS endpoint, the function automatically sets allowCleartextPasswords=true and configures appropriate TLS settings. The awsIAMAuthConnector receives a properly configured base DSN and only needs to inject the IAM token as the password.
Learnt from: sgress454
Repo: fleetdm/fleet PR: 31075
File: server/datastore/mysql/common_mysql/aws_iam_auth.go:111-130
Timestamp: 2025-08-20T21:24:59.261Z
Learning: In Fleet's MySQL IAM authentication implementation, the TLS and AllowCleartextPasswords configuration is handled in the generateMysqlConnectionString function in server/datastore/mysql/common_mysql/common.go, not in the awsIAMAuthConnector.Connect method. The connector receives a base DSN that already includes the necessary IAM authentication parameters.
📚 Learning: 2025-08-20T21:24:59.261Z
Learnt from: sgress454
Repo: fleetdm/fleet PR: 31075
File: server/datastore/mysql/common_mysql/aws_iam_auth.go:111-130
Timestamp: 2025-08-20T21:24:59.261Z
Learning: In Fleet's MySQL IAM authentication implementation, the TLS and AllowCleartextPasswords configuration is handled in the generateMysqlConnectionString function in server/datastore/mysql/common_mysql/common.go. When no password is configured and the endpoint is an RDS endpoint, the function automatically sets allowCleartextPasswords=true and configures appropriate TLS settings. The awsIAMAuthConnector receives a properly configured base DSN and only needs to inject the IAM token as the password.

Applied to files:

  • changes/36846-refactor-rds-iam
  • server/datastore/mysql/mysql.go
  • server/datastore/mysql/common_mysql/common.go
  • server/datastore/mysql/rdsauth/connector.go
📚 Learning: 2025-08-20T21:24:59.261Z
Learnt from: sgress454
Repo: fleetdm/fleet PR: 31075
File: server/datastore/mysql/common_mysql/aws_iam_auth.go:111-130
Timestamp: 2025-08-20T21:24:59.261Z
Learning: In Fleet's MySQL IAM authentication implementation, the TLS and AllowCleartextPasswords configuration is handled in the generateMysqlConnectionString function in server/datastore/mysql/common_mysql/common.go, not in the awsIAMAuthConnector.Connect method. The connector receives a base DSN that already includes the necessary IAM authentication parameters.

Applied to files:

  • changes/36846-refactor-rds-iam
  • server/datastore/mysql/mysql.go
  • server/datastore/mysql/common_mysql/common.go
  • server/datastore/mysql/rdsauth/connector.go
🧬 Code graph analysis (1)
server/datastore/mysql/rdsauth/connector.go (2)
server/aws_common/iam_auth.go (1)
  • IAMAuthTokenManager (30-37)
server/config/config.go (1)
  • MysqlConfig (37-56)
🔇 Additional comments (10)
server/datastore/mysql/rdsauth/connector.go (3)

1-2: LGTM on package structure.

Clean extraction of AWS IAM auth logic into a dedicated package. This aligns well with the PR objective of reducing AWS SDK dependencies in common_mysql.


79-98: LGTM on Connect implementation.

The approach of creating a fresh mysql.Connector per connection ensures the IAM token is properly injected each time. The token caching is handled by the IAMAuthTokenManager, which is the correct architecture per the existing Fleet patterns.


105-129: LGTM on factory pattern.

The NewConnectorFactory properly creates the token generator once and returns a closure that shares it across all connector instances. This ensures efficient token caching while enabling clean dependency injection into common_mysql.

changes/36846-refactor-rds-iam (1)

1-1: LGTM on changelog entry.

Appropriate description for this internal refactoring.

server/datastore/mysql/common_mysql/common.go (2)

20-24: LGTM on ConnectorFactory type.

Well-documented type that cleanly abstracts the connector creation, enabling IAM auth injection without coupling common_mysql to AWS dependencies.


42-45: LGTM on DBOptions extension.

The optional ConnectorFactory field is well-documented and maintains backward compatibility.

server/datastore/mysql/mysql.go (4)

259-262: LGTM on primary IAM auth setup.

Clean integration point for IAM authentication before creating the primary DB connection.


269-281: LGTM on replica IAM auth handling.

Correctly resets ConnectorFactory before setting up IAM auth for replica, allowing replicas to have independent authentication configurations (e.g., different regions).


398-418: LGTM on setupIAMAuthIfNeeded implementation.

The detection logic correctly identifies when IAM auth should be used (no password provided but region is configured). The host/port parsing with fallback to default MySQL port 3306 is appropriate.


9-9: LGTM on import additions.

The net and rdsauth imports are appropriately used for the IAM authentication setup.

Also applies to: 29-29

@codecov

codecov Bot commented Dec 7, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 20.75472% with 42 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.91%. Comparing base (ae66a83) to head (ab3a96a).
⚠️ Report is 106 commits behind head on main.

Files with missing lines Patch % Lines
server/datastore/mysql/rdsauth/connector.go 0.00% 24 Missing ⚠️
server/datastore/mysql/mysql.go 39.13% 11 Missing and 3 partials ⚠️
server/datastore/mysql/common_mysql/common.go 33.33% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #36847      +/-   ##
==========================================
- Coverage   65.91%   65.91%   -0.01%     
==========================================
  Files        2259     2259              
  Lines      184211   184233      +22     
  Branches     7646     7646              
==========================================
+ Hits       121430   121438       +8     
- Misses      51695    51711      +16     
+ Partials    11086    11084       -2     
Flag Coverage Δ
backend 67.71% <20.75%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@getvictor
getvictor marked this pull request as ready for review December 8, 2025 00:15
@getvictor
getvictor requested a review from a team as a code owner December 8, 2025 00:15
@getvictor

getvictor commented Dec 8, 2025

Copy link
Copy Markdown
Member Author

@sgress454 I'm assigning this refactoring to you since you worked on RDS IAM. I'm trying to reduce the dependencies of the mysql_common package.

@sgress454 sgress454 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm, nice update 👍

Comment on lines 68 to 77

// awsIAMAuthConnector implements driver.Connector for IAM authentication
type awsIAMAuthConnector struct {
driverName string
baseDSN string
tokenGen *awsIAMAuthTokenGenerator
logger log.Logger
// Connector implements driver.Connector for IAM authentication
type Connector struct {
baseDSN string
tokenGen *iamAuthTokenGenerator
logger log.Logger
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks like we weren't using the connector driverName ourselves, and sql.OpenDB(connector) only looks for the connector to meet a certain interface (not be a type including driverName), so 👍 to drop this.

@getvictor
getvictor merged commit 276af0f into main Dec 10, 2025
42 checks passed
@getvictor
getvictor deleted the victor/36846-rdsauth-refactor branch December 10, 2025 22:21
@coderabbitai coderabbitai Bot mentioned this pull request Dec 31, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AWS IAM auth code in common_mysql increases complexity

2 participants