Skip to content

fix(auth): unwrap Atmos Pro envelope in github/sts mint - #2568

Merged
Andriy Knysh (aknysh) merged 13 commits into
mainfrom
osterman/github-sts-envelope-unwrap
Jun 6, 2026
Merged

Andriy Knysh (aknysh) merged 13 commits into
mainfrom
osterman/github-sts-envelope-unwrap

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

what

  • Fix the github/sts auth integration ignoring a successfully minted Atmos Pro STS token because mint() decoded the response with a flat struct instead of the canonical API envelope.
  • Add a shared, reusable primitive — dtos.Envelope[T] + pro.DecodeEnvelope[T] — and route mint() through it so every Atmos Pro response unwraps the nested data payload through one sanctioned path.
  • Fix the bug-masking test fixture (the simulated broker now emits the real envelope shape) and add a regression test asserting mint() persists 1 token, not 0, plus decoder unit tests including a canary that a flat payload decodes to empty data.

why

  • Every Atmos Pro API route returns { "success": true, "status": 200, "data": { "tokens": [...], "excluded": [...] } }, but mint() decoded straight into the flat stsResponse (top-level tokens), so it always read 0 tokens — the CLI logged GitHub STS: no tokens granted, never wrote the git insteadOf config, and cross-repo import: calls fell back to the ambient GITHUB_TOKEN and failed with remote: Repository not found, even though the server had minted a valid token (HTTP 200, so no error surfaced).
  • The existing e2e test passed only because its simulated broker returned the unwrapped {tokens,excluded} shape the real server never sends; matching the fixture to the real envelope and adding the regression/canary tests prevents this whole class of "decoded a Pro response without the envelope" bug from recurring.

references

  • mint() was the only Pro call bypassing the shared AtmosApiResponse envelope that ExchangeOIDCToken / LockStack already use.

Summary by CodeRabbit

  • Bug Fixes

    • Clearer STS error messages and correct unwrapping of canonical API envelopes.
    • Prevent ambient tokens from being baked into Git URLs by honoring insteadOf rewrites (including file-mode).
    • Avoid invalid git checkout/fetch for empty refs by fetching default branch and skipping bad checkouts.
    • Warn when component source is misplaced under metadata and accept simple-form source strings.
  • New Features

    • Provision credential brokers before Git source detection so token rewrites apply.
  • Tests

    • Expanded tests covering envelope decoding, STS handling, broker provisioning, git insteadOf, and default-ref behavior.
  • Documentation

    • Added fix notes on STS envelope/token-shadowing and updated PRD guidance for source.

The github/sts integration decoded the mint response directly into the
flat stsResponse struct, reading top-level `tokens`/`excluded`. But every
Atmos Pro API route returns the canonical envelope `{success, status,
data: {...}}`, so tokens are nested under `data`. The flat decode always
yielded 0 tokens: the CLI logged "GitHub STS: no tokens granted", never
wrote the git insteadOf config, and cross-repo imports fell back to the
ambient GITHUB_TOKEN and 404'd — even though the server minted a token.

- Route mint() through a new shared `pro.DecodeEnvelope[T]` helper and
  honor `success` (surface EffectiveErrorMessage on 200-with-success=false)
- Add generic `dtos.Envelope[T]` type + `pro.DecodeEnvelope[T]` decoder so
  every Pro response unwraps `data` through one sanctioned primitive
- Fix the bug-masking test fixture (stsServer now emits the real envelope)
  and add a regression test asserting mint persists 1 token, not 0
- Add envelope decoder tests, including a canary proving a flat payload
  decodes to empty data — pinning why the envelope is mandatory

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@atmos-pro

atmos-pro Bot commented Jun 5, 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.

@osterman Erik Osterman (Cloud Posse) (osterman) added the patch A minor, backward compatible change label Jun 5, 2026
@github-actions github-actions Bot added the size/m Medium size PR label Jun 5, 2026
@github-actions

github-actions Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Too much diff to scan? Review this PR in Change Stack to start with the highest-impact changes.

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: fd25ef07-1f0a-4496-badc-ad6601e46c33

📥 Commits

Reviewing files that changed from the base of the PR and between c342d80 and 3b4a2da.

📒 Files selected for processing (1)
  • docs/fixes/2026-06-04-component-source-simple-form-and-metadata-misplacement.md
✅ Files skipped from review due to trivial changes (1)
  • docs/fixes/2026-06-04-component-source-simple-form-and-metadata-misplacement.md

📝 Walkthrough

Walkthrough

Adds a generic Envelope[T] DTO and DecodeEnvelope helper; updates GitHub STS to use the envelope decoder with tests. Extends broker/generic git insteadOf handling (file-mode and inline), provisions brokers before eager git detection, fixes empty-ref git update behavior, and records the fixes in documentation.

Changes

Envelope Infrastructure and Integration

Layer / File(s) Summary
Envelope DTO and decoder helper
pkg/pro/dtos/envelope.go, pkg/pro/envelope.go
Envelope[T] generic struct embeds AtmosApiResponse and exposes typed Data under data. DecodeEnvelope[T any] JSON-decodes an io.Reader into the canonical envelope and returns the typed envelope or a decoding error.
Envelope decoder test coverage
pkg/pro/envelope_test.go
Tests validate nested data unwrapping, that flat top-level payloads don't populate Data, that success=false surfaces server error messages (current and legacy fields), generic payload decoding, and malformed-JSON error handling.
GitHub STS envelope adoption and regression test
pkg/auth/integrations/github/sts.go, pkg/auth/integrations/github/sts_test.go
STS mint now uses proapi.DecodeEnvelope[stsResponse], treats env.Success=false as a mint failure and returns env.EffectiveErrorMessage() on failure. Test fixture now wraps successes in the canonical envelope and a regression test asserts correct unwrapping of the exact wire payload.

Credential Broker and Git insteadOf Handling

Layer / File(s) Summary
Broker test utility
pkg/auth/broker/broker.go
Adds SwapRegistryForTest() to clear and restore the global broker registry and reset the sync.Once guard for isolated tests.
File-mode insteadOf tests and helpers
pkg/downloader/broker_insteadof_filemode_test.go
Adds helpers to materialize a per-owner gitconfig file and set GIT_CONFIG_* envs, plus tests verifying file-mode insteadOf behavior and matching logic.
Custom git detector implementation
pkg/downloader/custom_git_detector.go
Extends gitConfigInsteadOfMatches to support both inline env and file-mode include.path modes, with helpers (insteadOfValueMatches, fileInsteadOfMatches, cutInsteadOfDirective) to validate HTTPS rewrites matching host+owner.
Provision broker before git detection and tests
pkg/stack/imports/remote.go, pkg/stack/imports/remote_broker_test.go
Calls broker.EnsureCredentials before detectGitSource in resolveGitSubdir. Adds a regression test registering a fake broker that injects GIT_CONFIG_* so detection observes insteadOf rewrites and avoids baking ambient tokens into detected URLs.

Git update/ref handling and importer tests

Layer / File(s) Summary
get_git: empty-ref fetch/reset and error formatting
pkg/downloader/get_git.go
Defaults empty ref to HEAD for fetch into FETCH_HEAD, hard-resets to it, and skips checkout/pull when no ref is provided; fixes git command error formatting to include combined output.
Importer tests and repo fixture tweaks
pkg/stack/imports/remote_test.go
Disables GPG signing in test repos and adds TestRemoteImporter_Resolve_GitSubdir_NoRef_DefaultsToBranch to assert Resolve uses the repository default branch when ?ref= is omitted.

Fix documentation

Layer / File(s) Summary
Fix note and verification record
docs/fixes/2026-06-04-github-sts-envelope-and-import-token-shadowing.md
Adds a detailed fix document describing CI symptoms, root causes, implemented changes (envelope decoding, broker timing, file-mode matching, test seam, ref-handling), and verification steps.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • aknysh
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main fix: unwrapping the Atmos Pro envelope in the GitHub STS mint function, which is the core issue addressed across multiple files in this PR.
Docstring Coverage ✅ Passed Docstring coverage is 87.80% which is sufficient. The required threshold is 80.00%.
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
  • Commit unit tests in branch osterman/github-sts-envelope-unwrap

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.

🧹 Nitpick comments (1)
pkg/pro/envelope.go (1)

14-20: 💤 Low value

Consider wrapping the decode error.

The function returns the raw json.Decode error. As per coding guidelines, errors should be wrapped with static errors from errors/errors.go. The caller currently provides context-specific wrapping (e.g., ErrSTSMintFailed in sts.go), which works, but a generic wrapper at this layer would make the error origin clearer.

Suggested approach

If a generic Pro API decode error exists or is added to errors/errors.go:

 func DecodeEnvelope[T any](r io.Reader) (*dtos.Envelope[T], error) {
 	var env dtos.Envelope[T]
 	if err := json.NewDecoder(r).Decode(&env); err != nil {
-		return nil, err
+		return nil, fmt.Errorf("%w: %w", errUtils.ErrProAPIDecodeFailed, err)
 	}
 	return &env, nil
 }

Note: This assumes ErrProAPIDecodeFailed is added to errors/errors.go.

As per coding guidelines, all errors must be wrapped using static errors from errors/errors.go.

🤖 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/pro/envelope.go` around lines 14 - 20, DecodeEnvelope currently returns
the raw json decode error; wrap that error with the package static sentinel from
errors/errors.go (e.g. ErrProAPIDecodeFailed) before returning so callers can
identify decode failures. In DecodeEnvelope, replace the direct return of err
with a wrapped error such as using fmt.Errorf("%w: %v",
errors.ErrProAPIDecodeFailed, err) (or your project's preferred wrap helper) and
keep returning (&env, nil) on success; reference function DecodeEnvelope and
sentinel ErrProAPIDecodeFailed when making the change.
🤖 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.

Nitpick comments:
In `@pkg/pro/envelope.go`:
- Around line 14-20: DecodeEnvelope currently returns the raw json decode error;
wrap that error with the package static sentinel from errors/errors.go (e.g.
ErrProAPIDecodeFailed) before returning so callers can identify decode failures.
In DecodeEnvelope, replace the direct return of err with a wrapped error such as
using fmt.Errorf("%w: %v", errors.ErrProAPIDecodeFailed, err) (or your project's
preferred wrap helper) and keep returning (&env, nil) on success; reference
function DecodeEnvelope and sentinel ErrProAPIDecodeFailed when making the
change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e27a59bc-5388-41a6-80ff-3d247c396312

📥 Commits

Reviewing files that changed from the base of the PR and between 860a0ec and 19a289d.

📒 Files selected for processing (5)
  • pkg/auth/integrations/github/sts.go
  • pkg/auth/integrations/github/sts_test.go
  • pkg/pro/dtos/envelope.go
  • pkg/pro/envelope.go
  • pkg/pro/envelope_test.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 5, 2026
@codecov

codecov Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.11881% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.90%. Comparing base (0946fbc) to head (3b4a2da).

Files with missing lines Patch % Lines
pkg/component/workdir_path.go 77.77% 4 Missing ⚠️
pkg/downloader/custom_git_detector.go 85.71% 2 Missing and 2 partials ⚠️
pkg/auth/integrations/github/sts.go 60.00% 1 Missing and 1 partial ⚠️
pkg/downloader/get_git.go 90.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2568      +/-   ##
==========================================
+ Coverage   78.87%   78.90%   +0.02%     
==========================================
  Files        1200     1201       +1     
  Lines      115889   115958      +69     
==========================================
+ Hits        91407    91493      +86     
+ Misses      19425    19403      -22     
- Partials     5057     5062       +5     
Flag Coverage Δ
unittests 78.90% <88.11%> (+0.02%) ⬆️

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

Files with missing lines Coverage Δ
...ack_processor_process_stacks_helpers_extraction.go 75.16% <100.00%> (+1.78%) ⬆️
internal/exec/stack_processor_utils.go 82.32% <100.00%> (ø)
pkg/auth/broker/broker.go 95.00% <100.00%> (+1.89%) ⬆️
pkg/pro/envelope.go 100.00% <100.00%> (ø)
pkg/stack/imports/remote.go 91.69% <100.00%> (+0.06%) ⬆️
pkg/auth/integrations/github/sts.go 84.14% <60.00%> (-0.55%) ⬇️
pkg/downloader/get_git.go 84.67% <90.00%> (+0.08%) ⬆️
pkg/component/workdir_path.go 84.04% <77.77%> (-1.49%) ⬇️
pkg/downloader/custom_git_detector.go 87.23% <85.71%> (-1.66%) ⬇️

... and 5 files with indirect coverage changes

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

…token

Downstream of the envelope fix: the token now mints and is received, but a
cross-repo remote `import:` from a second private repo still 404'd because
the ambient GITHUB_TOKEN (scoped to the calling repo) was applied to the
cross-repo URL instead of the minted, repo-scoped STS token. Two distinct
shadowing defects, both confirmed in code (not server/config):

- Env mode (ordering): RemoteImporter.resolveGitSubdir resolves a git-subdir
  import by running CustomGitDetector.Detect directly, BEFORE downloader.Fetch.
  The broker only exports GIT_CONFIG_* inside Fetch, so the eager detect ran
  before the insteadOf rewrite was live, missed it, and baked the ambient token
  into the URL. Fix: provision broker.EnsureCredentials before the eager detect.

- File mode (guard gap): the injection guard only matched url.*.insteadOf env
  keys; in GitConfigModeFile the broker emits include.path (rewrites live inside
  the referenced gitconfig), so the guard never matched and ambient injection
  always won. Fix: resolve include.path and scan the file for a matching https
  insteadOf.

Add SwapRegistryForTest to pkg/auth/broker so cross-package tests can isolate
broker state. Regression tests: file-mode include.path guard cases, and an
in-process git-subdir import-resolution test that fails against the unfixed
code with the exact ambient-token-in-URL symptom.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@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: 1

🧹 Nitpick comments (3)
pkg/stack/imports/remote_broker_test.go (1)

77-79: ⚡ Quick win

Add a compile-time sentinel for the schema.AtmosSettings fields used in this test.

Line 78 references concrete schema fields in the fixture; add a sentinel to fail fast on field renames.

Suggested patch
+var _ = schema.AtmosSettings{
+	InjectGithubToken: true,
+	GithubToken:       "compile-guard",
+}
+
 type fakeInsteadOfBroker struct {

As per coding guidelines, "Add compile-time sentinels for schema field references in tests: when a test uses a specific struct field ... add var _ = ... as a compile guard."

🤖 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/stack/imports/remote_broker_test.go` around lines 77 - 79, Add a
compile-time sentinel to guard the test's use of schema.AtmosSettings field
names so renames fail fast: add a package-level var assignment referencing
schema.AtmosSettings with the InjectGithubToken and GithubToken fields (e.g.,
var _ = schema.AtmosSettings{InjectGithubToken: false, GithubToken: ""}) in the
same test file near the fixtures so the compiler will break if those fields are
renamed.
pkg/downloader/broker_insteadof_filemode_test.go (1)

57-62: ⚡ Quick win

Add a compile-time sentinel for schema.AtmosSettings field references.

Line 58-Line 61 reference concrete schema fields in test fixtures; add a sentinel so schema field renames fail at compile time instead of silently weakening test intent.

Suggested patch
+var _ = schema.AtmosSettings{
+	InjectGithubToken: true,
+	GithubToken:       "compile-guard",
+}
+
 func TestCustomGitDetector_FileModeInsteadOf_NotShadowed(t *testing.T) {

As per coding guidelines, "Add compile-time sentinels for schema field references in tests: when a test uses a specific struct field ... add var _ = ... as a compile guard."

🤖 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/downloader/broker_insteadof_filemode_test.go` around lines 57 - 62, Add a
compile-time sentinel that references the specific schema.AtmosSettings fields
used by the test so renames fail compilation: near the test fixture (where
atmosConfig is built) add a var _ = schema.AtmosSettings{InjectGithubToken:
false, GithubToken: ""} (or similar literal) to force the compiler to check
those field names; this should be placed in
pkg/downloader/broker_insteadof_filemode_test.go alongside the test fixture that
constructs atmosConfig and will cause a compile error if InjectGithubToken or
GithubToken are renamed or removed.
pkg/stack/imports/remote.go (1)

15-23: ⚡ Quick win

Re-group imports to match repository ordering rules.

The current block mixes 3rd-party and Atmos imports (Line 15-Line 23). Please split into stdlib / 3rd-party / Atmos groups with blank lines.

Suggested patch
 	"time"
 
 	"github.com/bmatcuk/doublestar/v4"
+	"github.com/hashicorp/go-getter"
+
 	errUtils "github.com/cloudposse/atmos/errors"
 	"github.com/cloudposse/atmos/pkg/auth/broker"
 	"github.com/cloudposse/atmos/pkg/cache"
 	"github.com/cloudposse/atmos/pkg/downloader"
 	"github.com/cloudposse/atmos/pkg/perf"
 	"github.com/cloudposse/atmos/pkg/schema"
-	"github.com/hashicorp/go-getter"
 )

As per coding guidelines, "Organize imports in three groups separated by blank lines, sorted alphabetically: (1) Go stdlib, (2) 3rd-party, (3) Atmos packages."

🤖 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/stack/imports/remote.go` around lines 15 - 23, Reformat the import block
in pkg/stack/imports/remote.go to follow repository rules: split imports into
three groups (stdlib, 3rd-party, Atmos) separated by single blank lines, and
sort each group alphabetically; specifically ensure symbols like
"github.com/bmatcuk/doublestar/v4" and "github.com/hashicorp/go-getter" appear
in the 3rd-party group, and Atmos packages such as "errUtils"
(github.com/cloudposse/atmos/errors),
"github.com/cloudposse/atmos/pkg/auth/broker",
"github.com/cloudposse/atmos/pkg/cache",
"github.com/cloudposse/atmos/pkg/downloader",
"github.com/cloudposse/atmos/pkg/perf", and
"github.com/cloudposse/atmos/pkg/schema" are grouped together in the Atmos
section with a blank line separating from 3rd-party and stdlib imports.
🤖 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/stack/imports/remote.go`:
- Around line 251-259: The call to broker.EnsureCredentials in resolveGitSubdir
can hang because CredentialStore.Retrieve/Store and loadCredentialsWithFallback
are not context-aware; update the CredentialStore interface (methods Retrieve
and Store) and any implementations (e.g., systemKeyringStore.Retrieve) to accept
a context.Context, propagate that context through loadCredentialsWithFallback
and broker.EnsureCredentials callers, and thread ctx through any downstream I/O
so broker provisioning can be canceled; alternatively, if you cannot plumb
contexts now, ensure CI/in-process usage swaps the broker to a non-blocking
credential-store backend before calling broker.EnsureCredentials to avoid
blocking resolveGitSubdir.

---

Nitpick comments:
In `@pkg/downloader/broker_insteadof_filemode_test.go`:
- Around line 57-62: Add a compile-time sentinel that references the specific
schema.AtmosSettings fields used by the test so renames fail compilation: near
the test fixture (where atmosConfig is built) add a var _ =
schema.AtmosSettings{InjectGithubToken: false, GithubToken: ""} (or similar
literal) to force the compiler to check those field names; this should be placed
in pkg/downloader/broker_insteadof_filemode_test.go alongside the test fixture
that constructs atmosConfig and will cause a compile error if InjectGithubToken
or GithubToken are renamed or removed.

In `@pkg/stack/imports/remote_broker_test.go`:
- Around line 77-79: Add a compile-time sentinel to guard the test's use of
schema.AtmosSettings field names so renames fail fast: add a package-level var
assignment referencing schema.AtmosSettings with the InjectGithubToken and
GithubToken fields (e.g., var _ = schema.AtmosSettings{InjectGithubToken: false,
GithubToken: ""}) in the same test file near the fixtures so the compiler will
break if those fields are renamed.

In `@pkg/stack/imports/remote.go`:
- Around line 15-23: Reformat the import block in pkg/stack/imports/remote.go to
follow repository rules: split imports into three groups (stdlib, 3rd-party,
Atmos) separated by single blank lines, and sort each group alphabetically;
specifically ensure symbols like "github.com/bmatcuk/doublestar/v4" and
"github.com/hashicorp/go-getter" appear in the 3rd-party group, and Atmos
packages such as "errUtils" (github.com/cloudposse/atmos/errors),
"github.com/cloudposse/atmos/pkg/auth/broker",
"github.com/cloudposse/atmos/pkg/cache",
"github.com/cloudposse/atmos/pkg/downloader",
"github.com/cloudposse/atmos/pkg/perf", and
"github.com/cloudposse/atmos/pkg/schema" are grouped together in the Atmos
section with a blank line separating from 3rd-party and stdlib imports.
🪄 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: cf505514-2d23-4353-a6b2-27cf22fe5542

📥 Commits

Reviewing files that changed from the base of the PR and between 19a289d and 1462ad4.

📒 Files selected for processing (5)
  • pkg/auth/broker/broker.go
  • pkg/downloader/broker_insteadof_filemode_test.go
  • pkg/downloader/custom_git_detector.go
  • pkg/stack/imports/remote.go
  • pkg/stack/imports/remote_broker_test.go

Comment thread pkg/stack/imports/remote.go Resolved
…date path

With the github/sts auth fixes in place, a cross-repo remote `import:` got
past authentication but then failed with:

  fatal: empty string is not a valid pathspec. please use . instead if you
  meant to match all paths

RemoteImporter.resolveGitSubdir pre-creates the destination temp dir, so the
go-getter git getter takes the `update` path (os.Stat(dst) succeeds), not
`clone`. clone() defaults an empty ref to the remote's default branch via
findRemoteDefaultBranch; update() did not — so a ref-less import ran
`git fetch -- ""` and `git checkout ""`. This was masked because every existing
git-subdir test pins `?ref=main`, and on this path the clone previously 404'd on
auth before reaching checkout. It also affects ref-less public git-subdir imports.

- update() now defaults an empty ref to findRemoteDefaultBranch, mirroring clone()
- Add TestRemoteImporter_Resolve_GitSubdir_NoRef_DefaultsToBranch (verified to fail
  against the unfixed update with the exact "empty string is not a valid pathspec")
- initGitRepo disables commit.gpgsign so the real-git fixture is deterministic on
  dev machines whose global git config enables commit signing
- docs/fixes: capture this fourth layer of the github/sts -xl failure chain

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… ls-remote

Follow-up to the empty-ref fix. Defaulting update()'s empty ref via
findRemoteDefaultBranch surfaced a CI-only failure: `fatal: couldn't find
remote ref master`. findRemoteDefaultBranch runs `git ls-remote` in the process
CWD — the actions/checkout repo — whose local `http.<host>.extraheader` carries
the ambient repo-scoped token. That extraheader shadows the minted token for the
cross-repo ls-remote, so it fails and falls back to "master" while the repo's
default branch is "main" (the real fetch runs in the clean temp dir and authed
fine via the insteadOf — hence "couldn't find remote ref", not an auth error).

Fix: update() now fetches the remote's symbolic HEAD directly in the temp dir
(git fetch origin HEAD -> git reset --hard FETCH_HEAD) where the broker insteadOf
applies, and skips checkout/pull when no ref was given. This never runs ls-remote
in the CWD, so the extraheader can't shadow it, and avoids `git checkout ""`.

- get_git.go update(): HEAD-fetch + reset for empty ref; checkout/pull only for a
  named ref. clone()'s findRemoteDefaultBranch use is unchanged.
- docs/fixes: document layer 4a (CWD extraheader shadowing ls-remote)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
TestExecuteTerraform_ExportEnvVar intermittently failed on the Windows
acceptance job with "plugin cache dir cannot be opened" / "Required
plugins are not installed". Atmos enables a Terraform provider plugin
cache by default and points TF_PLUGIN_CACHE_DIR at a global XDG cache.
`make testacc` runs `go test ./...` with packages in parallel, so
concurrent terraform invocations from other packages hit the same global
cache. Terraform's plugin cache is not concurrency-safe, and the
contention races on Windows.

Redirect XDG_CACHE_HOME to a per-binary temp dir in the package's
existing TestMain so its (serial) real-terraform tests share a private,
isolated cache and never collide with concurrently-running packages.
Mirrors the isolation already used in tests/cli_plugin_cache_test.go.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Declaring a component's JIT-vendoring source under `metadata` (e.g.
`metadata.source: github.com/org/repo//module`) is a silent footgun: `source`
is a top-level component section (sibling of vars/settings/metadata), and
`metadata.source` is not a schema field, so it is dropped during decode. The
component then fails with a confusing "Terraform component does not exist"
error with no indication that a misplaced source was the cause.

ProvisionAndResolveComponentPath now warns, at the exact point it falls back to
the local component dir (no top-level source found), when the raw component
section carries a `source` nested under `metadata` — covering terraform,
helmfile, and packer through the single shared chokepoint. Behavior is
unchanged; only an actionable warning is added.

Also fix the one inconsistent example in docs/prd/source-provisioner.md (the
git-worktree section) that nested `source` under `metadata`, which is the form
that leaked into a downstream config.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add an explicit callout to the source-provisioner PRD: source is a top-level
component section (sibling of vars/settings/metadata); metadata.source is not a
schema field and is silently ignored (Atmos now warns). Distinguish from the
valid, unrelated metadata.component.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The component `source` section is documented (source-provisioner PRD) and
supported by the JIT provisioner (parseSource/HasSource) in two forms: a bare
go-getter URI string ("simple form") and a full map. The stack processor's
extraction only accepted the map form and rejected the string with "invalid
component source section", so `source: github.com/org/repo//module` failed during
stack processing before JIT provisioning ran. Every source-provisioner fixture
uses the map form, so the gap went unnoticed.

Add normalizeComponentSourceSection (string -> {uri: <string>}; empty string = no
source; map passthrough) and use it at both extraction sites (component source and
base-component source inheritance). The normalized map flows to the final `source`
section, which the JIT provisioner already reads as a map.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions github-actions Bot added size/l Large size PR and removed size/m Medium size PR labels Jun 5, 2026
…ck jobs

The `[mock-windows] examples/demo-vendoring` job failed at the
`hashicorp/setup-packer@main` step (every other mock job using the same step
passed — a transient failure of the unpinned external action). None of the
mock demos use Packer (demo-vendoring's test is `atmos vendor pull`; others use
terraform). The lint job runs tflint only and the localstack job runs terraform
only — both installed Packer but never used it.

Remove the Install Packer step from the mock, lint, and localstack jobs. This
fixes the failing job and eliminates the flaky external action wherever Packer
was never needed. The acceptance job (which actually runs `atmos packer` Go
tests) is left unchanged pending a separate toolchain-based migration.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mergify

mergify Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label Jun 5, 2026

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/downloader/get_git.go (1)

270-270: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Godot linter violation: comment must end with a period.

The comment on line 270 lacks a period at the end. As per coding guidelines, all comments must end with periods (enforced by godot linter).

✏️ Proposed fix
-// In the case an error happens.
+// In the case an error happens, capture output.

As per coding guidelines: "All comments must end with periods (enforced by godot linter)".

🤖 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/downloader/get_git.go` at line 270, Update the trailing punctuation of
the comment that reads "In the case an error happens" by adding a final period
so it ends with "In the case an error happens." to satisfy the godot linter;
locate the comment near the get_git.go code (the line containing that exact
comment text) and ensure the punctuation is corrected.
🧹 Nitpick comments (2)
internal/exec/stack_processor_source_normalize_test.go (1)

22-22: ⚡ Quick win

Use sourceURIKey in expected maps to avoid key drift.

This test currently hardcodes "uri" while production uses sourceURIKey; coupling to the constant keeps this canary aligned during future key renames.

Suggested patch
-			want:   map[string]any{"uri": "github.com/cloudposse-sandbox/atmos-pro-qa-2-xl//components/terraform/queue"},
+			want:   map[string]any{sourceURIKey: "github.com/cloudposse-sandbox/atmos-pro-qa-2-xl//components/terraform/queue"},
@@
-			raw:    map[string]any{"uri": "github.com/org/repo//mod", "version": "1.2.3"},
-			want:   map[string]any{"uri": "github.com/org/repo//mod", "version": "1.2.3"},
+			raw:    map[string]any{sourceURIKey: "github.com/org/repo//mod", "version": "1.2.3"},
+			want:   map[string]any{sourceURIKey: "github.com/org/repo//mod", "version": "1.2.3"},

Also applies to: 27-28

🤖 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 `@internal/exec/stack_processor_source_normalize_test.go` at line 22, The test
uses a hardcoded "uri" key in expected maps; update the expectations to use the
shared constant sourceURIKey so they won't drift if the key name changes. Locate
the expected map literals in
internal/exec/stack_processor_source_normalize_test.go (the entries with want:
map[string]any{...}) and replace the literal "uri" with sourceURIKey in those
maps (also apply the same change to the other occurrence on lines ~27-28),
ensuring imports/reference to sourceURIKey are available in the test file.
pkg/component/workdir_path.go (1)

272-279: ⚡ Quick win

Prefer a non-empty component identifier in warning context.

Using only info.ComponentFromArg can emit a blank component field in internal/non-CLI paths. Fall back to info.FinalComponent to keep this warning actionable.

Suggested patch
 func warnIfSourceMisplacedUnderMetadata(info *schema.ConfigAndStacksInfo) {
 	if !sourceMisplacedUnderMetadata(info.ComponentSection) {
 		return
 	}
+	componentID := info.ComponentFromArg
+	if componentID == "" {
+		componentID = info.FinalComponent
+	}
 	log.Warn("Ignoring `source` nested under `metadata`: JIT source provisioning reads a top-level "+
 		"`source:` on the component (a sibling of `vars`/`settings`/`metadata`), not `metadata.source`. "+
 		"Move `source` up one level to vendor this component on demand.",
-		"component", info.ComponentFromArg)
+		"component", componentID)
 }
🤖 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/component/workdir_path.go` around lines 272 - 279, In
warnIfSourceMisplacedUnderMetadata, the warning uses info.ComponentFromArg which
can be empty; change the logged component context to prefer
info.ComponentFromArg but fall back to info.FinalComponent when ComponentFromArg
is empty (e.g. compute a componentID := info.ComponentFromArg; if componentID ==
"" { componentID = info.FinalComponent } and pass that to log.Warn as the
"component" value) so the warning always contains a non-empty component
identifier.
🤖 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.

Outside diff comments:
In `@pkg/downloader/get_git.go`:
- Line 270: Update the trailing punctuation of the comment that reads "In the
case an error happens" by adding a final period so it ends with "In the case an
error happens." to satisfy the godot linter; locate the comment near the
get_git.go code (the line containing that exact comment text) and ensure the
punctuation is corrected.

---

Nitpick comments:
In `@internal/exec/stack_processor_source_normalize_test.go`:
- Line 22: The test uses a hardcoded "uri" key in expected maps; update the
expectations to use the shared constant sourceURIKey so they won't drift if the
key name changes. Locate the expected map literals in
internal/exec/stack_processor_source_normalize_test.go (the entries with want:
map[string]any{...}) and replace the literal "uri" with sourceURIKey in those
maps (also apply the same change to the other occurrence on lines ~27-28),
ensuring imports/reference to sourceURIKey are available in the test file.

In `@pkg/component/workdir_path.go`:
- Around line 272-279: In warnIfSourceMisplacedUnderMetadata, the warning uses
info.ComponentFromArg which can be empty; change the logged component context to
prefer info.ComponentFromArg but fall back to info.FinalComponent when
ComponentFromArg is empty (e.g. compute a componentID := info.ComponentFromArg;
if componentID == "" { componentID = info.FinalComponent } and pass that to
log.Warn as the "component" value) so the warning always contains a non-empty
component identifier.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ea214bbe-e1e7-41ef-8254-ed74f833bda1

📥 Commits

Reviewing files that changed from the base of the PR and between d9597bb and d15b76c.

📒 Files selected for processing (11)
  • .github/workflows/test.yml
  • docs/prd/source-provisioner.md
  • internal/exec/stack_processor_process_stacks_helpers_extraction.go
  • internal/exec/stack_processor_source_normalize_test.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/testmain_test.go
  • lychee.toml
  • pkg/component/workdir_path.go
  • pkg/component/workdir_path_test.go
  • pkg/downloader/get_git.go
  • pkg/downloader/get_git_test.go
💤 Files with no reviewable changes (1)
  • .github/workflows/test.yml
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/exec/testmain_test.go

@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: 1

🤖 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
`@docs/fixes/2026-06-04-component-source-simple-form-and-metadata-misplacement.md`:
- Line 22: Replace the lowercase product name "github/sts" with the properly
capitalized "GitHub/sts" in the document; search for the exact string
"github/sts" in the file and update it to "GitHub/sts" to ensure consistency
with the official product name.
🪄 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: 793515a5-f877-4f43-a7b0-d24166d253bb

📥 Commits

Reviewing files that changed from the base of the PR and between d15b76c and c342d80.

📒 Files selected for processing (1)
  • docs/fixes/2026-06-04-component-source-simple-form-and-metadata-misplacement.md

Address CodeRabbit feedback on PR #2568.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit 657a898 into main Jun 6, 2026
60 checks passed
@atmos-pro

atmos-pro Bot commented Jun 6, 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.

@aknysh
Andriy Knysh (aknysh) deleted the osterman/github-sts-envelope-unwrap branch June 6, 2026 00:59
@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Jun 6, 2026
Andriy Knysh (aknysh) added a commit that referenced this pull request Jun 6, 2026
Resolve conflict in pkg/stack/imports/resolveGitSubdir: main's auth fix
(#2568) added broker.EnsureCredentials before detectGitSource, but this
branch refactored resolveGitSubdir to delegate cloning to ensureSourceDir.
Port the credential-provisioning fix into ensureSourceDir (remote_nested.go),
immediately before its detectGitSource call — the spot where the detect now
runs — so both the clone-caching feature and the Atmos Pro github/sts broker
ordering are preserved. Moved the broker/context imports accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Jun 6, 2026

Copy link
Copy Markdown

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

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/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants