Skip to content

fix(auth): deduplicate ECR, ECR Public, and EKS integrations to once per process - #2564

Merged
Andriy Knysh (aknysh) merged 3 commits into
cloudposse:mainfrom
MrZablah:fix/ecr-login-dedup
Jun 4, 2026
Merged

Andriy Knysh (aknysh) merged 3 commits into
cloudposse:mainfrom
MrZablah:fix/ecr-login-dedup

Conversation

@MrZablah

@MrZablah Miguel Zablah (MrZablah) commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds a process-level execution cache to triggerIntegrations so that
auto-provisioned integrations (aws/ecr, aws/ecr-public, aws/eks)
fire at most once per atmos invocation, regardless of how many times
Authenticate is called or how many AuthManager instances are created.

The cache key is the integration's canonical target endpoint rather than
its config entry name:

  • aws/ecr → "aws/ecr:<account_id>:<region>"
  • aws/ecr-public → "aws/ecr-public" (single global registry)
  • aws/eks → "aws/eks:<cluster_name>:<region>"
  • everything else → integration name (no behaviour change)

This means two config entries that point at the same registry — e.g. one
from global atmos.yaml and one from a component stack file — are
collapsed to a single execution.

Why

atmos terraform plan calls Authenticate from at least three internal
paths: setupTerraformAuth, TerraformPreHook, and one call per YAML
function (!store.get, !terraform.state). With a 6-tool .tool-versions
this produced 6 ECR logins per command. Switching to a name-keyed cache
reduced it to 2 because merged configs can carry two integration entries
with different names for the same registry. Keying by target endpoint
reduces this to exactly 1.

Changes

  • pkg/auth/manager_integrations.go — adds processIntegrationCache sync.Map, resetProcessIntegrationCache() (test helper),
    integrationTargetKey() (canonical key helper covering aws/ecr,
    aws/ecr-public, aws/eks); updates triggerIntegrations to use
    LoadOrStore on the target key.
  • pkg/auth/manager_integrations_test.go — adds
    TestIntegrationTargetKey (table-driven tests for all key variants
    including ECR Public) and TestIntegrationTargetKey_Deduplication
    (verifies that two same-registry entries produce one cache hit).

Notes

aws/ecr-public was added to upstream/main in #2231 after this branch
diverged; coverage for it was added here to keep deduplication consistent
across all three AWS integration kinds.

references

ECR / ECR Public Login Executes Multiple Times Per atmos terraform Invocation
#2562

Summary by CodeRabbit

  • New Features

    • Added process-level deduplication for auto-provisioned integrations to prevent redundant provisioning of the same target within a single process.
    • Failed provisioning attempts are evicted from the dedupe cache so retries can proceed.
  • Tests

    • Added unit tests validating cache key behavior and deduplication scenarios to ensure consistent provisioning outcomes.

@MrZablah
Miguel Zablah (MrZablah) requested a review from a team as a code owner June 3, 2026 18:09
@atmos-pro

atmos-pro Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions github-actions Bot added the size/m Medium size PR label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7b73525c-929b-4416-b7fc-deea5983ed6f

📥 Commits

Reviewing files that changed from the base of the PR and between bf2f27c and 5f4992f.

📒 Files selected for processing (1)
  • pkg/auth/manager_integrations.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/auth/manager_integrations.go

📝 Walkthrough

Walkthrough

This change adds a process-wide deduplication cache for auto-provisioned integrations (ECR, EKS, ECR-Public). The cache uses sync.Map for concurrency-safe lookups and prevents repeated execution of integrations targeting the same resource within a single process. Failed executions evict their cache entry to allow retry.

Changes

Integration Deduplication

Layer / File(s) Summary
Cache mechanism and target key generation
pkg/auth/manager_integrations.go
Adds sync import and introduces processIntegrationCache (sync.Map), resetProcessIntegrationCache (test helper), and integrationTargetKey (canonical key computation for ECR/EKS targets with spec-aware keying and name fallback).
Integration triggering with deduplication and error recovery
pkg/auth/manager_integrations.go
Modifies triggerIntegrations to check cache before execution via LoadOrStore, skip already-provisioned targets with logging, and delete failed entries to enable retry.
Cache key and deduplication tests
pkg/auth/manager_integrations_test.go
Table-driven TestIntegrationTargetKey validates key formatting across ECR/EKS (with spec vs. fallback to name), ECR-Public (fixed key), and unknown kinds. TestIntegrationTargetKey_Deduplication confirms same-target keys prevent re-execution.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Suggested labels

patch

Suggested reviewers

  • aknysh
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.72% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding deduplication for AWS integrations (ECR, ECR Public, EKS) at the process level, which matches the core objective of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 2

🧹 Nitpick comments (2)
pkg/auth/manager_integrations.go (1)

25-32: 💤 Low value

Consider using sync.Map.Clear() directly.

Go 1.23+ provides Clear() on sync.Map, which simplifies this helper.

Proposed simplification
 func resetProcessIntegrationCache() {
-	processIntegrationCache.Range(func(key, _ any) bool {
-		processIntegrationCache.Delete(key)
-		return true
-	})
+	processIntegrationCache.Clear()
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/auth/manager_integrations.go` around lines 25 - 32, The helper
resetProcessIntegrationCache currently iterates and deletes entries manually;
replace its body with a single call to processIntegrationCache.Clear() (requires
Go 1.23+), i.e. update resetProcessIntegrationCache to invoke
processIntegrationCache.Clear() to simplify and improve clarity while keeping
the same function name and behavior.
pkg/toolchain/checksum/parse.go (1)

49-55: 💤 Low value

Consider returning scanner errors even when partial entries exist.

The current implementation silently discards scanner errors when len(entries) > 0, but the comment states callers should decide whether partial data is useful. By returning nil error, callers have no signal that parsing was incomplete. For diagnostics and reproducible-builds guarantees, consider returning the scanner error wrapped with context (e.g., fmt.Errorf("incomplete parse (%d entries): %w", len(entries), err)) so callers can log/handle partial success explicitly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/toolchain/checksum/parse.go` around lines 49 - 55, The scanner error is
currently swallowed when partial entries exist; change the logic so the function
returns the parsed entries along with the scanner error (wrapped with context)
instead of returning nil error. In the block that checks scanner.Err() use
something like returning entries, fmt.Errorf("incomplete parse (%d entries):
%w", len(entries), err) so callers can detect and handle partial results; ensure
you import fmt if needed and keep the existing behavior of returning nil, err
when no entries were parsed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/auth/manager_integrations_test.go`:
- Around line 207-279: Add a new test case to TestIntegrationTargetKey for the
aws/ecr-public kind to assert the integrationTargetKey returns the fixed key
"aws/ecr-public" when Kind is "aws/ecr-public"; update the tests slice (in the
TestIntegrationTargetKey function) with an entry named "ECR Public uses fixed
key" using intName "my-ecr-public", integration.Kind "aws/ecr-public", and want
"aws/ecr-public" so the behavior is validated once the KindAWSECRPublic branch
is implemented in integrationTargetKey.

In `@pkg/auth/manager_integrations.go`:
- Around line 39-51: The switch in integrationTargetKey currently lacks a branch
for integrations.KindAWSECRPublic, so ECR Public configs don't deduplicate; add
a case for integrations.KindAWSECRPublic in the integrationTargetKey function
that returns the fixed key "aws/ecr-public" (i.e., treat ECR Public as a single
global registry key) alongside the existing KindAWSECR and KindAWSEKS cases so
all ECR Public integrations map to the same cache key.

---

Nitpick comments:
In `@pkg/auth/manager_integrations.go`:
- Around line 25-32: The helper resetProcessIntegrationCache currently iterates
and deletes entries manually; replace its body with a single call to
processIntegrationCache.Clear() (requires Go 1.23+), i.e. update
resetProcessIntegrationCache to invoke processIntegrationCache.Clear() to
simplify and improve clarity while keeping the same function name and behavior.

In `@pkg/toolchain/checksum/parse.go`:
- Around line 49-55: The scanner error is currently swallowed when partial
entries exist; change the logic so the function returns the parsed entries along
with the scanner error (wrapped with context) instead of returning nil error. In
the block that checks scanner.Err() use something like returning entries,
fmt.Errorf("incomplete parse (%d entries): %w", len(entries), err) so callers
can detect and handle partial results; ensure you import fmt if needed and keep
the existing behavior of returning nil, err when no entries were parsed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 73e6e29d-ef30-4e1f-8c6b-4ad0939f2461

📥 Commits

Reviewing files that changed from the base of the PR and between 4427fbb and f35c6dc.

📒 Files selected for processing (6)
  • pkg/auth/manager_integrations.go
  • pkg/auth/manager_integrations_test.go
  • pkg/toolchain/checksum/checksum.go
  • pkg/toolchain/checksum/checksum_test.go
  • pkg/toolchain/checksum/parse.go
  • pkg/toolchain/checksum/parse_test.go

Comment thread pkg/auth/manager_integrations_test.go Resolved
Comment thread pkg/auth/manager_integrations.go Resolved
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Jun 3, 2026
@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.22222% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.83%. Comparing base (4427fbb) to head (5f4992f).

Files with missing lines Patch % Lines
pkg/auth/manager_integrations.go 72.22% 5 Missing ⚠️

❌ Your patch check has failed because the patch coverage (72.22%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2564      +/-   ##
==========================================
+ Coverage   78.82%   78.83%   +0.01%     
==========================================
  Files        1195     1195              
  Lines      114267   114285      +18     
==========================================
+ Hits        90067    90093      +26     
+ Misses      19248    19240       -8     
  Partials     4952     4952              
Flag Coverage Δ
unittests 78.83% <72.22%> (+0.01%) ⬆️

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

Files with missing lines Coverage Δ
pkg/auth/manager_integrations.go 50.58% <72.22%> (+2.56%) ⬆️

... and 9 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@aknysh Andriy Knysh (aknysh) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@aknysh
Andriy Knysh (aknysh) merged commit f848b73 into cloudposse:main Jun 4, 2026
63 of 65 checks passed
@atmos-pro

atmos-pro Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown

These changes were released in v1.221.0-rc.4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/m Medium size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants