diff --git a/.gitignore b/.gitignore index 1cfe9270714..467a9f9a41e 100644 --- a/.gitignore +++ b/.gitignore @@ -79,6 +79,7 @@ tools/gomodcheck/.gomodcheck credentials # Authentication credential sources are code, not local credential files. !/pkg/auth/credentials/ +!/pkg/auth/providers/aws/saml2aws/helper/credentials/ # Tool version managers .tool-versions diff --git a/.golangci.yml b/.golangci.yml index 334edfaed82..cea15cbe469 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -447,6 +447,29 @@ linters: - lintroller path: ^magefiles/ text: "perf\\.Track" + # Vendored fork of the unmaintained saml2aws library (MIT, see its ATTRIBUTIONS.md). + # Atmos style and convention linters are relaxed for the upstream code; correctness + # linters (govet, staticcheck, unused, errorlint, bodyclose, nilerr, gosec) still apply. + - linters: + - cyclop + - depguard + - dogsled + - dupl + - err113 + - forbidigo + - funlen + - gocognit + - gocritic + - godot + - importas + - lintroller + - nestif + - paralleltest + - revive + - tparallel + - unparam + - whitespace + path: ^pkg/auth/providers/aws/saml2aws/ paths: - experiments/.* - third_party$ diff --git a/NOTICE b/NOTICE index efed364474a..528650246c0 100644 --- a/NOTICE +++ b/NOTICE @@ -1018,10 +1018,6 @@ BSD LICENSED DEPENDENCIES License: BSD-3-Clause URL: https://github.com/go-git/gcfg/blob/3a3c6141e376/LICENSE - - github.com/go-jose/go-jose/v3/json - License: BSD-3-Clause - URL: https://github.com/go-jose/go-jose/blob/v3.0.5/json/LICENSE - - github.com/go-jose/go-jose/v4/json License: BSD-3-Clause URL: https://github.com/go-jose/go-jose/blob/v4.1.6/json/LICENSE @@ -1524,10 +1520,6 @@ MIT LICENSED DEPENDENCIES License: MIT URL: https://github.com/Azure/azure-sdk-for-go/blob/sdk/storage/azblob/v1.7.0/sdk/storage/azblob/LICENSE.txt - - github.com/Azure/go-ntlmssp - License: MIT - URL: https://github.com/Azure/go-ntlmssp/blob/v0.1.1/LICENSE - - github.com/AzureAD/microsoft-authentication-library-for-go/apps License: MIT URL: https://github.com/AzureAD/microsoft-authentication-library-for-go/blob/v1.7.2/LICENSE @@ -1720,6 +1712,10 @@ MIT LICENSED DEPENDENCIES License: MIT URL: https://github.com/clipperhouse/uax29/blob/v2.7.0/LICENSE + - github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws + License: MIT + URL: https://github.com/cloudposse/atmos/blob/HEAD/pkg/auth/providers/aws/saml2aws/LICENSE.md + - github.com/cloudposse/atmos/pkg/config/homedir License: MIT URL: https://github.com/cloudposse/atmos/blob/HEAD/pkg/config/homedir/LICENSE @@ -2168,6 +2164,10 @@ MIT LICENSED DEPENDENCIES License: MIT URL: https://github.com/muesli/termenv/blob/v0.16.0/LICENSE + - github.com/mxschmitt/playwright-go + License: MIT + URL: https://github.com/mxschmitt/playwright-go/blob/v0.6401.0/LICENSE + - github.com/otiai10/copy License: MIT URL: https://github.com/otiai10/copy/blob/v1.14.1/LICENSE @@ -2180,10 +2180,6 @@ MIT LICENSED DEPENDENCIES License: MIT URL: https://github.com/peterbourgon/diskv/blob/v2.0.1/LICENSE - - github.com/playwright-community/playwright-go - License: MIT - URL: https://github.com/playwright-community/playwright-go/blob/v0.5700.1/LICENSE - - github.com/posthog/posthog-go License: MIT URL: https://github.com/posthog/posthog-go/blob/v1.17.4/LICENSE.md @@ -2320,10 +2316,6 @@ MIT LICENSED DEPENDENCIES License: MIT URL: https://github.com/vektah/gqlparser/blob/v2.5.33/LICENSE - - github.com/versent/saml2aws/v2 - License: MIT - URL: https://github.com/versent/saml2aws/blob/v2.36.19/LICENSE.md - - github.com/wlynxg/chardet License: MIT URL: https://github.com/wlynxg/chardet/blob/v1.0.5/LICENSE diff --git a/cmd/auth/exec_child_process_test.go b/cmd/auth/exec_child_process_test.go new file mode 100644 index 00000000000..e734262070f --- /dev/null +++ b/cmd/auth/exec_child_process_test.go @@ -0,0 +1,108 @@ +package auth + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + errUtils "github.com/cloudposse/atmos/errors" +) + +const ( + // Turns the test binary into the child process `auth exec` runs. + authExecChildEnv = "_ATMOS_TEST_AUTH_EXEC_CHILD" + // Names the file the child writes its observations to. + authExecChildReportEnv = "_ATMOS_TEST_AUTH_EXEC_REPORT" + // Exit code the child terminates with. + authExecChildExitEnv = "_ATMOS_TEST_AUTH_EXEC_EXIT" +) + +// authExecChildReport is what the child process observed. +type authExecChildReport struct { + Args []string `json:"args"` + Identity string `json:"identity"` +} + +// runAuthExecChild records the child's argv and authenticated identity, then +// exits with the requested code. It is invoked from TestMain. +func runAuthExecChild() int { + report, err := json.Marshal(authExecChildReport{Args: os.Args[1:], Identity: os.Getenv("ATMOS_IDENTITY")}) + if err != nil { + return 98 + } + if err := os.WriteFile(os.Getenv(authExecChildReportEnv), report, 0o600); err != nil { + return 99 + } + code, err := strconv.Atoi(os.Getenv(authExecChildExitEnv)) + if err != nil { + return 97 + } + return code +} + +// TestExecuteAuthExecCommand_ChildArgsAndExitCode runs a real child process +// through `auth exec` and verifies that arguments after "--" reach it verbatim +// (no shell interpretation, no Atmos flag parsing), that it runs with the +// authenticated identity's environment, and that its exit status propagates. +func TestExecuteAuthExecCommand_ChildArgsAndExitCode(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + + childArgs := []string{ + "two words", + `it's "quoted"`, + "$HOME and $(whoami) and `id`", + "line1\nline2", + "--identity=not-an-atmos-flag", + "", + } + + for _, tt := range []struct { + name string + exitCode int + }{ + {name: "success", exitCode: 0}, + {name: "failure exit code propagates", exitCode: 7}, + } { + t.Run(tt.name, func(t *testing.T) { + setupMockAuthFixture(t) + reportPath := filepath.Join(t.TempDir(), "child-report.json") + t.Setenv(authExecChildEnv, "1") + t.Setenv(authExecChildReportEnv, reportPath) + t.Setenv(authExecChildExitEnv, strconv.Itoa(tt.exitCode)) + + cmd := authExecCmd + resetAuthCmdFlags(t, cmd) + cmd.SetContext(context.Background()) + require.NoError(t, cmd.ParseFlags(append([]string{"--", executable}, childArgs...))) + + err := executeAuthExecCommand(cmd, cmd.Flags().Args()) + + if tt.exitCode == 0 { + require.NoError(t, err) + } else { + var exitErr errUtils.ExitCodeError + require.True(t, errors.As(err, &exitErr), "expected ExitCodeError, got %v", err) + assert.Equal(t, tt.exitCode, exitErr.Code) + assert.Equal(t, tt.exitCode, errUtils.GetExitCode(err)) + } + + raw, readErr := os.ReadFile(reportPath) + require.NoError(t, readErr, "the child process must have run") + var report authExecChildReport + require.NoError(t, json.Unmarshal(raw, &report)) + assert.Equal(t, childArgs, report.Args, "arguments after -- must reach the child verbatim") + require.Len(t, report.Args, len(childArgs)) + assert.Equal(t, childArgs[0], report.Args[0]) + assert.Equal(t, childArgs[len(childArgs)-1], report.Args[len(report.Args)-1]) + assert.Equal(t, "mock-identity", report.Identity, "the child must run as the resolved default identity") + }) + } +} diff --git a/cmd/auth/testmain_test.go b/cmd/auth/testmain_test.go index d511cd73c15..ac1cc3165ad 100644 --- a/cmd/auth/testmain_test.go +++ b/cmd/auth/testmain_test.go @@ -14,6 +14,11 @@ import ( // package so tests that exercise printWhoamiJSON, printWhoamiHuman, list // renderers, etc. don't panic with "data.InitWriter() must be called". func TestMain(m *testing.M) { + // Act as the child process of `auth exec` tests (see exec_child_process_test.go). + if os.Getenv(authExecChildEnv) == "1" { + os.Exit(runAuthExecChild()) + } + ioCtx, err := iolib.NewContext() if err != nil { // Tests cannot run without an IO context; fail loud. diff --git a/docs/fixes/2026-11-17-vendor-saml2aws-drop-go-jose-v3.md b/docs/fixes/2026-11-17-vendor-saml2aws-drop-go-jose-v3.md new file mode 100644 index 00000000000..4d4c449d858 --- /dev/null +++ b/docs/fixes/2026-11-17-vendor-saml2aws-drop-go-jose-v3.md @@ -0,0 +1,196 @@ +# Fix: Vendor `saml2aws` to drop `go-jose/v3` and fix the SAML browser driver + +**Date:** 2026-11-17 + +## Summary + +The `aws/saml` auth provider depended on `github.com/versent/saml2aws/v2` v2.36.19. That library is no longer +maintained, and through `github.com/playwright-community/playwright-go` v0.5700.1 it pulled +`github.com/go-jose/go-jose/v3` into the Atmos binary. go-jose v3 has an unfixed HIGH advisory +(CVE-2026-116587 / GHSA-mgcc-cww5-fp2q, CPU denial of service when parsing JWKs with RSA keys), so +vulnerability scanners reported it against Atmos. + +The library parts Atmos uses are now vendored (MIT, with attribution) into +`pkg/auth/providers/aws/saml2aws/`. The copy uses the current Playwright module, so `go-jose/v3` is no longer in +the module graph or the binary. The copy also fixes the browser driver's timeout panic and related bugs. + +## Context + +- **Upstream status:** the last saml2aws release was v2.36.19 (2025-03-13) and the last commit was on 2025-05-13. + The repo has 300 open issues and 66 open PRs, and + [Versent/saml2aws#1545](https://github.com/Versent/saml2aws/issues/1545) ("Still maintained?") has no reply. +- **Why a version bump could not fix it:** after v0.5700, playwright-go moved back to the + `github.com/mxschmitt/playwright-go` module path, and v0.6401.0 dropped go-jose (it uses `encoding/json`). + saml2aws still imports the old `playwright-community` path, and v0.5700.1 is the last release under it. + A `replace` from the old path to `mxschmitt/playwright-go` does not build, because the new module imports its own + `internal/` packages and Go does not allow that under an aliased path. +- **Reachability before the fix:** only `go-jose/v3/json` was linked, not the vulnerable JWK code. Module-level + scanners still flagged it, and arguing "not reachable" with each scanner was not a durable answer. +- **The other CVE in the same scan** (CVE-2026-116591, `klauspost/compress/zstd` <= 1.20.1) was already fixed on + `main` by #3688 (bump to 1.20.2). It is not part of this change. + +## Changes + +**Vendored package `pkg/auth/providers/aws/saml2aws/`** (see its `README.md` and `ATTRIBUTIONS.md`; upstream +`LICENSE.md` kept): + +- **Kept:** the root package (`NewSAMLClient`, assertion and role parsing), `cfg`, `creds`, the shared `provider` + HTTP client, the `Browser`, `GoogleApps`, `Okta` and `ADFS` drivers, and the helpers they use (`prompter`, + `page`, `cookiejar`, `dump`, `helper/credentials`). +- **Dropped:** the 15 IdP drivers Atmos never documented (AzureAD, ADFS2, Ping, PingNTLM, PingOne, JumpCloud, + OneLogin, Authentik, KeyCloak, Shibboleth, ShibbolethECP, F5APM, Akamai, Shell, NetIQ, Auth0), plus the + ini-file `ConfigManager` (`~/.saml2aws`), which Atmos never used. `NewSAMLClient` returns + `ErrUnsupportedProvider` with the list of supported drivers for any other value. +- **Playwright:** the browser driver moves to `github.com/mxschmitt/playwright-go` v0.6401.0. Its + `StorageState` call is updated for the new API. +- **Browser driver bug fixes** (each has a regression test): + - A timeout or error from `ExpectRequest` no longer dereferences a nil request. This was the panic that + `saml.go` previously documented as an upstream bug with no fix. + - A `PostData` error is returned instead of being swallowed. Upstream returned the wrong error variable, + which could report success with an empty assertion. + - The request callback and the waiting code no longer race on the captured data. + - An empty capture returns `ErrNoSAMLResponse` instead of an empty assertion. + - An invalid `browser_type` is rejected before Playwright is installed or started. + - A sign-in request that reached the `OnRequest` callback just before `ExpectRequest` started listening was + missed, so the user waited the full 5-minute timeout and failed. It is now used. + - The Playwright driver, browser and context are each released as soon as a later step fails. Upstream + leaked the node driver process when the browser failed to launch. + - `playwright install` progress goes to stderr instead of stdout, where it corrupted `eval $(atmos auth env)`. + Only the browser that will be launched is installed, not every Playwright browser. + - The storage-state path is built with `filepath.Join` and `homedir.Dir()` instead of a forward-slash + `fmt.Sprintf`. Its directory is created with `0700` permissions, and the file, which holds IdP session cookies + and which Playwright writes as `0644`, is tightened to `0600` after saving. +- **Other upstream bugs found while adding tests** (each marked `// Atmos fork:` with a regression test): + - ADFS: `checkResponse` called `log.Fatalf`, which exits the whole process, on an unnamed `` or a + `SAMLResponse` input with no value. It now skips unnamed inputs and returns an error. + - Prompter: the pinentry runner raced on its error result and closed the output pipe before all of it was + read. It now runs `Start`, then parses the output, then calls `Wait`. + - Okta: + - A Duo `FAILURE` and a missing Duo `sid` returned `errors.Wrap(nil, ...)`, which is `nil`, so they were + reported as success. + - FIDO fallback to the next key after a bad key handle never ran, because the search restarted at the + option that had just failed. + - Nil-response panics on a transport error with an existing session, and in the Duo endpoint-health + request. + - An index panic on a malformed Duo signature. + - GoogleApps: + - `challenge/skotp` URLs were handled as `challenge/sk` (U2F) because of the case order. + - Index panics on a form with no `action` and on a U2F page with no key handles. + - The captcha loop never used the legacy `.captcha-img` container (a `*goquery.Selection` is never nil) and + panicked on an empty container. A rejected new-style captcha answer was never retried, because the input is + `name="ca"` with no id. Retries are capped at 5. + - `mustFindInputByName` called `logger.Fatal` (process exit); `b64Safe` panicked on invalid base64. Both now + return errors. + - ADFS: the MFA loop had no limit. It now allows at most 5 one-time codes and about 5 minutes of Azure MFA + polling, then returns `ErrMFAAttemptsExceeded`. + - Shared HTTP client: `HttpAttemptsCount: "0"` (or an invalid value) made every request fail without being sent. + Attempts are clamped to at least 1, and a nil options value no longer panics. + - stdout: the iTerm captcha image (GoogleApps) and the Duo U2F touch prompts (Okta) were written to stdout, the + data channel, which corrupts output such as `eval $(atmos auth env)`. They go to stderr. + - TLS (code-scanning `missing-ssl-minversion`): every IdP transport (shared HTTP client, ADFS, Okta Duo + certifier) now sets an explicit TLS 1.2 minimum. TLS 1.3 is not required because many enterprise IdPs, + notably ADFS, still serve TLS 1.2 only, and ADFS relies on renegotiation, which TLS 1.3 removed. + - Okta Duo trusted-endpoint check: upstream skipped certificate verification for whatever `certifier_url` the + Duo page named. Verification is now skipped only for a loopback host, where the local certifier runs with a + self-signed certificate. + - Secrets in debug logs (code-scanning `clear-text logging`): with debug logging on, upstream logged the Okta + password (`loginDetails` printed with `%v`), the decoded SAML assertion (a bearer credential for AWS until it + expires), the Okta device token, and full request URLs whose query strings carry session tokens. The hidden + `DUMP_CONTENT` switch also dumped whole requests and responses (password form bodies, cookies, assertions). The + dump path and its package are removed, URLs are logged as scheme, host and path only (`provider.RedactURL`), + and secret values are replaced by their presence or length. + - Retry delay (code-scanning `incorrect integer conversion`): an unbounded `http_retry_delay` overflowed + `time.Duration`. It is parsed as 32 bits and capped at 5 minutes. + - CodeRabbit review round (details in the package `README.md`, "Later review fixes"): prompt failures (Ctrl+C, + no terminal) now abort login instead of sending an empty token or picking the first option; Okta push and Duo + polling stop after 5 minutes; SAML assertions are parsed by namespace URI rather than prefix; retried requests + resend their body; relative ADFS form actions and GoogleApps locale parameters are resolved correctly; the + browser session file is saved through a private temporary file; and several panics and leaked response + bodies are fixed. +- **Testability:** `getSAMLResponse` takes a narrow `samlPage` interface, mocked with `go.uber.org/mock`. + The poll and settle delays in Okta and ADFS are package variables, so tests do not sleep. + Tests that need a real browser moved to `browser_integration_test.go` and only run with + `RUN_PLAYWRIGHT_INTEGRATION=1`. + +**Atmos `aws/saml` provider (`pkg/auth/providers/aws/`):** + +- `saml.go` imports the vendored package. `Authenticate` rejects an unsupported `driver` value first, with + `ErrInvalidProviderConfig` and the list of supported drivers. The check is deliberately not in `Validate()`: + the auth manager validates every configured provider up front, so a stale driver on one unused SAML provider + would otherwise break authentication for every identity. +- **New `saml_browser_revision.go`, for a regression the Playwright bump would otherwise cause.** The old + "drivers installed" check accepted any non-empty browser directory. After the upgrade, a user with Chromium + installed for the old driver would have auto-download turned off, and the new driver would fail to launch. + `shouldDownloadBrowser` now checks for the exact revision of the browser that will be launched (Chromium by + default, or `browser_type: firefox|webkit`), named in the driver's `package/browsers.json`, including + per-platform `revisionOverrides`. It requires Playwright's `INSTALLATION_COMPLETE` marker so an interrupted + download does not count. Playwright-managed `browser_type` values (`chromium`, `firefox`, `webkit`) no longer + turn auto-download off; only system channels (`chrome*`, `msedge*`) and `browser_executable_path` do. It looks only where the driver itself looks: `PLAYWRIGHT_BROWSERS_PATH` (including `0`), + then `$XDG_CACHE_HOME` or `~/.cache` on Linux, `~/Library/Caches` on macOS, and `%LOCALAPPDATA%` on Windows. + `getDriver` still uses the broader check, so users who rely on auto-detection are not silently switched from + the `Browser` driver to an API driver. +- `saml_driver_preseed.go`: switched to the new Playwright module. It is kept because, unlike playwright-go's own + download, it verifies the npm tarball's `sha512` integrity. After pre-seeding it now applies playwright-go's + own `coreBundle.js` patch, which v0.6401 only applies on its own download path, so a pre-seeded driver no + longer runs unpatched. +- `SAML2AWS_AUTO_BROWSER_DOWNLOAD` was dead: nothing read it, but `setupBrowserAutomation` set or unset it + process-wide (clobbering a value the user exported) and `Environment()` exported it to subprocesses. Both are + removed, along with the unused `IDPAccount.DownloadBrowser` field, and the two auth PRDs that claimed exporting + it forces a download are corrected. The download decision reaches the driver through `LoginDetails`. +- Comments that described the upstream panic and the hardcoded upstream storage path were updated. + +**Repository:** + +- `go.mod`/`go.sum`: removed `github.com/versent/saml2aws/v2`, `github.com/playwright-community/playwright-go` + and `github.com/go-jose/go-jose/v3`. `github.com/mxschmitt/playwright-go` moved from v0.6100.0 to v0.6401.0. +- `NOTICE`: regenerated. It now lists the vendored package through its `LICENSE.md`, and drops the removed modules + and `go-ntlmssp`, which only a dropped driver used. +- `.gitignore`: the repo-wide `credentials` rule ignored the vendored `helper/credentials` package, so the first + push of this change was missing it and CI could not build. It is re-included with an exact-path exception, the + same way `pkg/auth/credentials/` already is. +- `.golangci.yml`: Atmos style and convention linters are relaxed for the vendored path. Correctness linters + still apply. +- `errors/errors.go`: added `ErrPlaywrightBrowserManifest`. +- Docs: `website/docs/cli/configuration/auth/providers.mdx` (an unsupported `driver` fails at login, and names + are case-sensitive) and `website/docs/cli/commands/auth/usage.mdx` (removed the reference to saml2aws). + +**Behavior change:** an `aws/saml` provider that sets `driver` to one of the 15 undocumented values now fails +with a clear error when that provider logs in, instead of working. Other providers and identities are not +affected. The documented drivers are unchanged, and `Browser` works with any IdP that ends +on the AWS SAML sign-in page. + +## Validation + +- `go build ./...`: passes. +- `go list -deps ./` (the `atmos` binary): no `go-jose/v3`, `playwright-community` or `versent` packages. + `go.mod` no longer lists `go-jose/v3`. +- `go vet ./pkg/auth/providers/aws/...`: passes. +- `go test -count=1 ./pkg/auth/providers/aws/`: passes, including the new driver-validation and + Chromium-revision tests and the updated tests that create fake browser installs. +- `go test -race -count=1 -cover ./pkg/auth/providers/aws/...`: passes. Coverage of the vendored packages: + - 100%: root, `cfg`, `dump`, `helper/credentials`, `page` + - `provider` 97.2%, `prompter` 96.6%, `provider/adfs` 95.8%, `cookiejar` 93.8% + - `provider/googleapps` 89.5%, `provider/okta` 86.8% + - `provider/browser` 69.1%. The rest needs a real browser and is covered by the opt-in integration tests. + - The Atmos `aws` provider package is at 84.0%. +- `go test -race -count=1 ./pkg/auth/... ./cmd/auth/... ./pkg/plugin/adapter/auth/...`: all 61 packages pass, + including the tests added during the pre-release auth review. `go vet` passes for linux, windows and darwin. +- `go mod tidy -diff`: clean. +- `go tool mage notice:generate`: regenerated `NOTICE` (CI checks it). +- `cd website && npm run build`: passes. +- `bash .claude/skills/fix-log/scripts/validate-fix-doc.sh` on this file: passes. +- **Not run:** + - `golangci-lint`, `gofmt` and `gofumpt` were not allowed in this session. Imports were regrouped by hand into + stdlib / third-party / atmos groups, but lint and format still need a run locally or in CI. + - Real-browser tests (`RUN_PLAYWRIGHT_INTEGRATION=1`) were not run because they download Chromium. + - No interactive SAML login against a real IdP was done. + +## Follow-ups + +- Before merging, run `atmos lint --changed` and do one interactive `aws/saml` login with the `Browser` driver. + Ideally the cache should hold an old Chromium revision, to confirm the auto-download. +- A pre-release review of the rest of Atmos Auth (code already merged to `main`, outside this change) found + bugs that are tracked in #3720 and will be fixed in a separate branch. Four of them are regressions new + since v1.234.1. +- None of the known issues in the code this change touches are left open: the upstream quirks found during review + (ADFS MFA loop, `logger.Fatal`, captcha selection and retry, `HttpAttemptsCount: "0"`) are fixed above. diff --git a/docs/prd/saml-browser-driver-integration.md b/docs/prd/saml-browser-driver-integration.md index 4d14c396a07..265f9aefe7e 100644 --- a/docs/prd/saml-browser-driver-integration.md +++ b/docs/prd/saml-browser-driver-integration.md @@ -36,9 +36,9 @@ Initial implementation had several issues: - Only recommended for specialized environments with driver pre-provisioning **LoginDetails as Source of Truth** -- saml2aws checks `LoginDetails.DownloadBrowser`, not `IDPAccount.DownloadBrowser` -- Atmos must set both fields to ensure configuration works -- Provider's `shouldDownloadBrowser()` determines value from config +- The browser driver checks `LoginDetails.DownloadBrowser` only +- Atmos's vendored saml2aws fork removed the unused `IDPAccount.DownloadBrowser` field +- Provider's `shouldDownloadBrowser()` determines the value from config and the installed browsers ### Implementation Details @@ -65,10 +65,18 @@ func (p *samlProvider) shouldDownloadBrowser() bool { } ``` -**Why both IDPAccount and LoginDetails?** -- `IDPAccount.DownloadBrowser`: Used for environment variable (`SAML2AWS_AUTO_BROWSER_DOWNLOAD`) -- `LoginDetails.DownloadBrowser`: Used by saml2aws authentication logic -- Both must be set to ensure downloads work +**Why only LoginDetails?** +- `LoginDetails.DownloadBrowser` is the only field the browser driver reads before running `playwright install` +- Upstream's `IDPAccount.DownloadBrowser` was never read by the library and was removed from the vendored fork +- `SAML2AWS_AUTO_BROWSER_DOWNLOAD` was only read by the saml2aws CLI flag parser, which Atmos does not use, + so Atmos neither sets it in its own process nor exports it to subprocesses + +**Which browser is checked?** +- Auto-detection checks the exact revision of the browser that will be launched, read from the driver's + `browsers.json` (`chromium-`, `firefox-` or `webkit-`, or + `__special-` when `revisionOverrides` has an entry for the host platform) +- `browser_type: chromium`, `firefox` and `webkit` are installed by Playwright, so auto-download still applies to them +- System channels (`chrome*`, `msedge*`) and `browser_executable_path` use the user's own browser and are never downloaded #### Cache Directory Management @@ -151,11 +159,9 @@ auth: download_browser_driver: false # Assumes drivers pre-installed ``` -**Environment Variable Override**: -```bash -export SAML2AWS_AUTO_BROWSER_DOWNLOAD=true -atmos auth login --identity my-identity -``` +**No Environment Variable Override**: + +`SAML2AWS_AUTO_BROWSER_DOWNLOAD` has no effect on Atmos. Use `download_browser_driver: true` to force a download. ### Testing Strategy diff --git a/errors/errors.go b/errors/errors.go index 7a989a94a6e..61b02e2d3d7 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -1142,6 +1142,7 @@ var ( ErrAwsUserKeyringReadFailed = errors.New("failed to read AWS user credentials from keyring") ErrAwsSAMLDecodeFailed = errors.New("aws saml decode failed") ErrPlaywrightDriverSeed = errors.New("failed to pre-seed the Playwright driver") + ErrPlaywrightBrowserManifest = errors.New("cannot read the Playwright browser manifest") ErrAwsMissingEnvVars = errors.New("missing required AWS environment variables") ErrIdentityNotAWS = errors.New("identity does not produce AWS credentials") ErrUnsupportedPlatform = errors.New("unsupported platform") diff --git a/go.mod b/go.mod index 9dac93c69cd..7d5657136cc 100644 --- a/go.mod +++ b/go.mod @@ -112,7 +112,6 @@ require ( github.com/otiai10/copy v1.14.1 github.com/pact-foundation/pact-go/v2 v2.5.1 github.com/pkg/errors v0.9.1 - github.com/playwright-community/playwright-go v0.5700.1 github.com/posthog/posthog-go v1.17.4 github.com/redis/go-redis/v9 v9.22.0 github.com/rhysd/actionlint v1.7.12 @@ -126,7 +125,6 @@ require ( github.com/stretchr/testify v1.12.1 github.com/terraform-docs/terraform-docs v0.24.0 github.com/tliron/glsp v0.2.2 - github.com/versent/saml2aws/v2 v2.36.19 github.com/xeipuuv/gojsonschema v1.2.0 github.com/yuin/goldmark v1.8.2 github.com/zalando/go-keyring v0.2.8 @@ -161,10 +159,9 @@ require ( cloud.google.com/go/monitoring v1.30.0 // indirect cuelang.org/go v0.17.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect - github.com/AlecAivazis/survey/v2 v2.3.7 // indirect + github.com/AlecAivazis/survey/v2 v2.3.7 github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirect - github.com/Azure/go-ntlmssp v0.1.1 // indirect github.com/BurntSushi/toml v1.6.0 // indirect github.com/CycloneDX/cyclonedx-go v0.11.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 // indirect @@ -182,7 +179,7 @@ require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/armon/go-metrics v0.4.1 // indirect github.com/arsham/rainbow v1.2.1 // indirect - github.com/avast/retry-go v3.0.0+incompatible // indirect + github.com/avast/retry-go v3.0.0+incompatible github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.19.1 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect @@ -199,7 +196,7 @@ require ( github.com/aymerick/douceur v0.2.0 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/bearsh/hid v1.6.0 // indirect - github.com/beevik/etree v1.6.0 // indirect + github.com/beevik/etree v1.6.0 github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/buger/jsonparser v1.2.0 // indirect @@ -252,7 +249,6 @@ require ( github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/go-git/go-billy/v5 v5.9.2 github.com/go-ini/ini v1.67.0 // indirect - github.com/go-jose/go-jose/v3 v3.0.5 // indirect github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-logfmt/logfmt v0.6.1 // indirect github.com/go-logr/logr v1.4.4 // indirect @@ -333,7 +329,7 @@ require ( github.com/lestrrat-go/option/v2 v2.0.0 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/magiconair/properties v1.8.10 // indirect - github.com/marshallbrekka/go-u2fhost v0.0.0-20210111072507-3ccdec8c8105 // indirect + github.com/marshallbrekka/go-u2fhost v0.0.0-20210111072507-3ccdec8c8105 github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-localereader v0.0.1 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d @@ -393,7 +389,7 @@ require ( github.com/tidwall/sjson v1.2.5 github.com/tliron/commonlog v0.2.21 // indirect github.com/tliron/go-kutil v0.4.0 // indirect - github.com/trimble-oss/go-webauthn-client v0.3.0 // indirect + github.com/trimble-oss/go-webauthn-client v0.3.0 github.com/ugorji/go/codec v1.3.1 // indirect github.com/ulikunitz/xz v0.5.15 // indirect github.com/valyala/fastjson v1.6.10 // indirect @@ -428,7 +424,7 @@ require ( golang.org/x/crypto v0.59.0 golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a // indirect golang.org/x/mod v0.42.0 - golang.org/x/net v0.62.0 // indirect + golang.org/x/net v0.62.0 golang.org/x/sys v0.50.0 golang.org/x/time v0.15.0 // indirect golang.org/x/tools v0.52.0 // indirect @@ -474,7 +470,7 @@ require ( github.com/hashicorp/go-plugin v1.7.0 github.com/magefile/mage v1.17.2 github.com/minamijoyo/hcledit v0.2.18 - github.com/mxschmitt/playwright-go v0.6100.0 + github.com/mxschmitt/playwright-go v0.6401.0 github.com/pb33f/ordered-map/v2 v2.3.1 github.com/secure-systems-lab/go-securesystemslib v0.11.0 github.com/shirou/gopsutil/v4 v4.26.3 diff --git a/go.sum b/go.sum index 27c67895927..921024933e9 100644 --- a/go.sum +++ b/go.sum @@ -102,8 +102,6 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0 h1:BM85pSYlVYQHdq00n github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0/go.mod h1:QYjP2cB7ZYtS/8jAbE0VSBZde/tjExqGjp+8JY6/+ts= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw= -github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU= @@ -597,8 +595,6 @@ github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= -github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ= -github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= @@ -761,7 +757,6 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= @@ -833,8 +828,6 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF2 github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= -github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE= -github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= github.com/hack-pad/hackpadfs v0.2.4 h1:7pmzQGR6JsGq/uB0JWxd3wTBi7I85f46CHGvcfrJsiE= @@ -1181,8 +1174,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mxschmitt/playwright-go v0.6100.0 h1:HYNnbGZsTHz8veJyDGe4fU1iPxfvXqzmwKchzuvGCsY= -github.com/mxschmitt/playwright-go v0.6100.0/go.mod h1:A7VtrS3j/c8ToGnSVUaOfNtQQVxi6JotUS0jeuus6r4= +github.com/mxschmitt/playwright-go v0.6401.0 h1:PQbHqgzMQiY6pq8YsBBM5AXYnOs9TnlyzNVcGOznYJ8= +github.com/mxschmitt/playwright-go v0.6401.0/go.mod h1:vLBP2yVO1gokUlb9ENA+YE3VQaVqf2A9BGxcb7aPjMI= github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A= github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= @@ -1253,8 +1246,6 @@ github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM= github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= -github.com/playwright-community/playwright-go v0.5700.1 h1:PNFb1byWqrTT720rEO0JL88C6Ju0EmUnR5deFLvtP/U= -github.com/playwright-community/playwright-go v0.5700.1/go.mod h1:MlSn1dZrx8rszbCxY6x3qK89ZesJUYVx21B2JnkoNF0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -1525,8 +1516,6 @@ github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADT github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= github.com/vektah/gqlparser/v2 v2.5.33 h1:lRp8aIeNUNbimf/axZd7ETg24q06hBtPaas+TcvI/7E= github.com/vektah/gqlparser/v2 v2.5.33/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts= -github.com/versent/saml2aws/v2 v2.36.19 h1:LrELOG9AA4migQQMfihmmJ++H8bGevElRNzoNA2XflY= -github.com/versent/saml2aws/v2 v2.36.19/go.mod h1:ti3sEknT847HYw3rY2MdQcpf8WzHCNTTsGjkGZW7a1w= github.com/virtuald/go-ordered-json v0.0.0-20170621173500-b18e6e673d74 h1:JwtAtbp7r/7QSyGz8mKUbYJBg2+6Cd7OjM8o/GNOcVo= github.com/virtuald/go-ordered-json v0.0.0-20170621173500-b18e6e673d74/go.mod h1:RmMWU37GKR2s6pgrIEB4ixgpVCt/cf7dnJv3fuH1J1c= github.com/wlynxg/chardet v1.0.5 h1:BNEolSEujJUtKwkaqNb0D6Ue+d7VTKTh5rXDyEdiipU= @@ -1678,7 +1667,6 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1694,7 +1682,6 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1715,8 +1702,6 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1733,7 +1718,6 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1772,17 +1756,11 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1793,8 +1771,6 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1811,7 +1787,6 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/pkg/auth/cloud/aws/ecr_token_test.go b/pkg/auth/cloud/aws/ecr_token_test.go new file mode 100644 index 00000000000..04e6c1debb9 --- /dev/null +++ b/pkg/auth/cloud/aws/ecr_token_test.go @@ -0,0 +1,145 @@ +package aws + +import ( + "context" + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/auth/types" +) + +// serveECRAuthorization points the ECR client at a fake endpoint that returns body +// for GetAuthorizationToken and records the signing region of the request. +func serveECRAuthorization(t *testing.T, body string) func() string { + t.Helper() + + // Keep the developer's shared AWS files and profile out of the SDK config load. + dir := t.TempDir() + t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "config")) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials")) + t.Setenv("AWS_PROFILE", "") + t.Setenv("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "") + t.Setenv("AWS_MAX_ATTEMPTS", "1") + // Inherited FIPS or dual-stack endpoint policies make the SDK reject the custom fake endpoint. + t.Setenv("AWS_USE_FIPS_ENDPOINT", "false") + t.Setenv("AWS_USE_DUALSTACK_ENDPOINT", "false") + + // The handler runs on the server goroutine, so the observed region is guarded by a mutex. + var mu sync.Mutex + signedRegion := "" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + assert.Equal(t, "AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken", r.Header.Get("X-Amz-Target")) + // Authorization: AWS4-HMAC-SHA256 Credential=AK///ecr/aws4_request, ... + if parts := strings.Split(r.Header.Get("Authorization"), "/"); len(parts) > 2 { + mu.Lock() + signedRegion = parts[2] + mu.Unlock() + } + w.Header().Set("Content-Type", "application/x-amz-json-1.1") + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + t.Setenv("AWS_ENDPOINT_URL_ECR", srv.URL) + return func() string { + mu.Lock() + defer mu.Unlock() + return signedRegion + } +} + +func TestGetAuthorizationToken(t *testing.T) { + token := base64.StdEncoding.EncodeToString([]byte("AWS:p@ss:with:colons")) + + tests := []struct { + name string + body string + credsRegion string + region string + wantRegion string + wantResult *ECRAuthResult + wantErrSubst string + }{ + { + name: "decodes token, strips scheme, and keeps expiry", + body: `{"authorizationData":[{"authorizationToken":"` + token + + `","expiresAt":1893553445,"proxyEndpoint":"https://123456789012.dkr.ecr.eu-west-1.amazonaws.com"}]}`, + credsRegion: "us-east-1", + region: "eu-west-1", + wantRegion: "eu-west-1", + wantResult: &ECRAuthResult{ + Username: "AWS", + Password: "p@ss:with:colons", + Registry: "123456789012.dkr.ecr.eu-west-1.amazonaws.com", + ExpiresAt: time.Unix(1893553445, 0), + }, + }, + { + name: "falls back to the credentials region", + body: `{"authorizationData":[{"authorizationToken":"` + token + `"}]}`, + credsRegion: "ap-southeast-2", + wantRegion: "ap-southeast-2", + wantResult: &ECRAuthResult{Username: "AWS", Password: "p@ss:with:colons"}, + }, + { + name: "no authorization data", + body: `{"authorizationData":[]}`, + region: "us-east-1", + wantErrSubst: "no authorization data returned", + }, + { + name: "token is not base64", + body: `{"authorizationData":[{"authorizationToken":"!!not-base64!!"}]}`, + region: "us-east-1", + wantErrSubst: "failed to decode token", + }, + { + name: "token has no password separator", + body: `{"authorizationData":[{"authorizationToken":"` + base64.StdEncoding.EncodeToString([]byte("AWS")) + `"}]}`, + region: "us-east-1", + wantErrSubst: "invalid token format", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + signedRegion := serveECRAuthorization(t, tt.body) + creds := &types.AWSCredentials{AccessKeyID: "AK", SecretAccessKey: "SK", SessionToken: "TK", Region: tt.credsRegion} + + result, err := GetAuthorizationToken(context.Background(), creds, "123456789012", tt.region) + + if tt.wantErrSubst != "" { + require.Error(t, err) + assert.ErrorIs(t, err, errUtils.ErrECRAuthFailed) + assert.ErrorContains(t, err, tt.wantErrSubst) + assert.Nil(t, result) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantRegion, signedRegion()) + assert.Equal(t, tt.wantResult.Username, result.Username) + assert.Equal(t, tt.wantResult.Password, result.Password) + assert.Equal(t, tt.wantResult.Registry, result.Registry) + assert.True(t, tt.wantResult.ExpiresAt.Equal(result.ExpiresAt), "expiresAt %s, want %s", result.ExpiresAt, tt.wantResult.ExpiresAt) + }) + } +} + +func TestGetAuthorizationToken_RejectsNonAWSCredentials(t *testing.T) { + result, err := GetAuthorizationToken(context.Background(), &types.OIDCCredentials{Token: "jwt"}, "123456789012", "us-east-1") + + require.Error(t, err) + assert.Nil(t, result) + assert.ErrorIs(t, err, errUtils.ErrECRAuthFailed) +} diff --git a/pkg/auth/cloud/kube/config_drift_test.go b/pkg/auth/cloud/kube/config_drift_test.go new file mode 100644 index 00000000000..794afd7a52b --- /dev/null +++ b/pkg/auth/cloud/kube/config_drift_test.go @@ -0,0 +1,119 @@ +package kube + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" +) + +// TestWriteClusterConfig_MergeRepairsDriftedAtmosEntry verifies that when the +// Atmos-managed entries in a kubeconfig were edited out-of-band (by hand or by +// another tool), the next login treats the file as changed and restores the exec +// plugin, rather than short-circuiting on a false "no-op" and leaving kubectl +// with credentials or routing Atmos did not configure. +func TestWriteClusterConfig_MergeRepairsDriftedAtmosEntry(t *testing.T) { + info := testClusterInfo() + userName := UserName(info) + contextName := "dev-eks" + + tests := []struct { + name string + drift func(cfg *clientcmdapi.Config) + }{ + {name: "static token added", drift: func(c *clientcmdapi.Config) { c.AuthInfos[userName].Token = "stolen-or-stale" }}, + {name: "impersonation added", drift: func(c *clientcmdapi.Config) { c.AuthInfos[userName].Impersonate = "system:admin" }}, + {name: "impersonation groups added", drift: func(c *clientcmdapi.Config) { + c.AuthInfos[userName].ImpersonateGroups = []string{"system:masters"} + }}, + {name: "impersonation extra added", drift: func(c *clientcmdapi.Config) { + c.AuthInfos[userName].ImpersonateUserExtra = map[string][]string{"scopes": {"all"}} + }}, + {name: "auth provider added", drift: func(c *clientcmdapi.Config) { + c.AuthInfos[userName].AuthProvider = &clientcmdapi.AuthProviderConfig{Name: "oidc", Config: map[string]string{"idp": "x"}} + }}, + {name: "exec env changed", drift: func(c *clientcmdapi.Config) { + c.AuthInfos[userName].Exec.Env = []clientcmdapi.ExecEnvVar{{Name: "ATMOS_IDENTITY", Value: "prod-admin"}} + }}, + {name: "exec args changed", drift: func(c *clientcmdapi.Config) { + c.AuthInfos[userName].Exec.Args = []string{"aws", "eks", "token", "--cluster-name", "other"} + }}, + {name: "exec command changed", drift: func(c *clientcmdapi.Config) { c.AuthInfos[userName].Exec.Command = "/tmp/evil" }}, + {name: "cluster TLS verification disabled", drift: func(c *clientcmdapi.Config) { + c.Clusters[info.ID].InsecureSkipTLSVerify = true + c.Clusters[info.ID].CertificateAuthorityData = nil + }}, + {name: "cluster proxy added", drift: func(c *clientcmdapi.Config) { c.Clusters[info.ID].ProxyURL = "http://proxy:3128" }}, + {name: "context namespace changed", drift: func(c *clientcmdapi.Config) { c.Contexts[contextName].Namespace = "kube-system" }}, + {name: "context points at another user", drift: func(c *clientcmdapi.Config) { c.Contexts[contextName].AuthInfo = "someone-else" }}, + {name: "current context switched away", drift: func(c *clientcmdapi.Config) { c.CurrentContext = "other" }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config") + mgr, err := NewKubeconfigManager(path, "") + require.NoError(t, err) + _, err = mgr.WriteClusterConfig(info, contextName, "merge") + require.NoError(t, err) + + // Simulate out-of-band edits. + cfg, err := clientcmd.LoadFromFile(path) + require.NoError(t, err) + tt.drift(cfg) + require.NoError(t, clientcmd.WriteToFile(*cfg, path)) + + changed, err := mgr.WriteClusterConfig(info, contextName, "merge") + require.NoError(t, err) + assert.True(t, changed, "drifted entry must be rewritten, not treated as a no-op") + + // The rewritten file must match exactly what Atmos builds. + got, err := clientcmd.LoadFromFile(path) + require.NoError(t, err) + want := BuildClusterConfig(info, contextName) + assert.False(t, mergeWouldChange(got, want), "rewritten kubeconfig must equal the Atmos-built entries") + assert.Equal(t, contextName, got.CurrentContext) + assert.Empty(t, got.AuthInfos[userName].Token) + assert.Nil(t, got.AuthInfos[userName].AuthProvider) + }) + } +} + +// TestWriteClusterConfig_MergePreservesThirdPartyAuthInfo verifies that merging +// the Atmos entry leaves unrelated users intact, including their tokens, +// impersonation and auth providers, so `atmos ... update-kubeconfig` never clobbers a user's +// existing kubectl credentials. +func TestWriteClusterConfig_MergePreservesThirdPartyAuthInfo(t *testing.T) { + path := filepath.Join(t.TempDir(), "config") + + existing := clientcmdapi.NewConfig() + existing.Clusters["kind-local"] = &clientcmdapi.Cluster{Server: "https://127.0.0.1:6443", InsecureSkipTLSVerify: true} + existing.AuthInfos["kind-user"] = &clientcmdapi.AuthInfo{ + Token: "kind-token", + Impersonate: "jane", + ImpersonateGroups: []string{"devs"}, + ImpersonateUserExtra: map[string][]string{"reason": {"debug"}}, + AuthProvider: &clientcmdapi.AuthProviderConfig{Name: "oidc", Config: map[string]string{"client-id": "abc"}}, + } + existing.Contexts["kind"] = &clientcmdapi.Context{Cluster: "kind-local", AuthInfo: "kind-user", Namespace: "apps"} + existing.CurrentContext = "kind" + require.NoError(t, clientcmd.WriteToFile(*existing, path)) + + mgr, err := NewKubeconfigManager(path, "") + require.NoError(t, err) + changed, err := mgr.WriteClusterConfig(testClusterInfo(), "dev-eks", "merge") + require.NoError(t, err) + assert.True(t, changed) + + got, err := clientcmd.LoadFromFile(path) + require.NoError(t, err) + assert.True(t, authInfosEqual(existing.AuthInfos["kind-user"], got.AuthInfos["kind-user"]), + "third-party auth info must be preserved field-for-field") + assert.True(t, clustersEqual(existing.Clusters["kind-local"], got.Clusters["kind-local"])) + assert.True(t, contextsEqual(existing.Contexts["kind"], got.Contexts["kind"])) + // Merge mode activates the new context, matching `aws eks update-kubeconfig`. + assert.Equal(t, "dev-eks", got.CurrentContext) +} diff --git a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md index 05d36180290..70f58deeecf 100644 --- a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md +++ b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md @@ -487,13 +487,13 @@ Atmos Auth provides a unified, cloud-agnostic authentication and authorization s 1. Engineer runs `atmos auth login -i prod-cross-account-admin` 2. System resolves identity chain: AWS SSO → Permission Set → Assume Role 3. **Step 1**: AWS SSO provider authenticates user via device flow - - Returns SSO session credentials with temporary access token + - Returns SSO session credentials with temporary access token 4. **Step 2**: Permission Set identity receives SSO credentials - - Uses SSO credentials to assume `IdentityManagersTeamAccess` permission set - - Returns permission set role credentials (AccessKeyID, SecretAccessKey, SessionToken) + - Uses SSO credentials to assume `IdentityManagersTeamAccess` permission set + - Returns permission set role credentials (AccessKeyID, SecretAccessKey, SessionToken) 5. **Step 3**: Assume Role identity receives permission set credentials - - Uses permission set credentials (not original SSO credentials) to assume cross-account role - - Returns final cross-account role credentials + - Uses permission set credentials (not original SSO credentials) to assume cross-account role + - Returns final cross-account role credentials 6. Engineer now has access to production cross-account resources **Identity Configuration Example**: @@ -694,39 +694,39 @@ For identity chains (e.g., AWS SSO → Permission Set → Assume Role): 1. **Chain Resolution**: Recursively resolve the provider source for the target identity - - `prod-admin` chains to `managers-base` identity - - `managers-base` chains to `company-sso` provider - - Source provider identified: `company-sso` + - `prod-admin` chains to `managers-base` identity + - `managers-base` chains to `company-sso` provider + - Source provider identified: `company-sso` 2. **Sequential Authentication**: Authenticate through the chain step by step - - **Step 1**: Authenticate with source provider (`company-sso`) - - Returns base credentials (SSO session tokens) - - **Step 2**: First identity (`managers-base`) authenticates using base credentials - - Permission Set identity receives SSO credentials - - Uses SSO credentials to assume permission set role - - Returns permission set credentials (AWS access keys) - - **Step 3**: Final identity (`prod-admin`) authenticates using previous credentials - - Assume Role identity receives permission set credentials - - Uses permission set credentials to assume cross-account role - - Returns final role credentials + - **Step 1**: Authenticate with source provider (`company-sso`) + - Returns base credentials (SSO session tokens) + - **Step 2**: First identity (`managers-base`) authenticates using base credentials + - Permission Set identity receives SSO credentials + - Uses SSO credentials to assume permission set role + - Returns permission set credentials (AWS access keys) + - **Step 3**: Final identity (`prod-admin`) authenticates using previous credentials + - Assume Role identity receives permission set credentials + - Uses permission set credentials to assume cross-account role + - Returns final role credentials 3. **Credential Transformation**: Each step transforms credentials for the next - - Provider credentials → Identity credentials → Final credentials - - Metadata (region, account, session info) preserved through chain - - Each identity validates incoming credentials are appropriate + - Provider credentials → Identity credentials → Final credentials + - Metadata (region, account, session info) preserved through chain + - Each identity validates incoming credentials are appropriate 4. **Error Handling**: Chain stops at first failure with clear error context - - Indicates which step in the chain failed - - Provides actionable error messages - - Maintains audit trail of successful steps + - Indicates which step in the chain failed + - Provides actionable error messages + - Maintains audit trail of successful steps 5. **Caching Strategy**: Cache credentials at each step for performance - - Provider credentials cached separately from identity credentials - - Each identity's credentials cached with appropriate expiration - - Cache keys include full chain context to avoid conflicts + - Provider credentials cached separately from identity credentials + - Each identity's credentials cached with appropriate expiration + - Cache keys include full chain context to avoid conflicts ### 4.3 Security Model @@ -836,22 +836,20 @@ providers: - `GoogleApps` - Google Workspace SAML - `Okta` - Okta SAML - `ADFS` - Active Directory Federation Services -- `ADFS2` - ADFS 2.0 -- `AzureAD` - Azure Active Directory -- `PingFed` - PingFederate -- `KeyCloak` - Keycloak -- `Auth0` - Auth0 -- `OneLogin` - OneLogin -- `Browser` - Generic browser-based SAML (auto-detected) +- `Browser` - Generic browser-based SAML (auto-detected); use it for any other IdP + (for example Azure AD, PingFederate, Keycloak, Auth0, OneLogin) + +The vendored SAML client supports only these four drivers. Other driver names are rejected +with an "unsupported SAML driver" error. **Environment Variables:** -- `SAML2AWS_AUTO_BROWSER_DOWNLOAD=true` - Auto-download Playwright browser drivers - `SAML_PASSWORD` - SAML password (if not provided in config) **Usage Notes:** - First run will download Playwright browser drivers automatically if `download_browser_driver: true` + (`SAML2AWS_AUTO_BROWSER_DOWNLOAD` is not read by Atmos and does not force a download) - Browser automation handles MFA challenges automatically - Supports headless browser operation for CI/CD environments - SAML assertions are cached for session duration to reduce authentication frequency @@ -1125,15 +1123,15 @@ identities: Atmos uses per-field precedence with deep merge: 1. **If YAML has complete credentials** (both `access_key_id` and `secret_access_key`): - - Use YAML entirely (including `mfa_arn` from YAML) - - Keyring is ignored + - Use YAML entirely (including `mfa_arn` from YAML) + - Keyring is ignored 2. **If YAML has no credentials** (both keys empty or omitted): - - Use keyring credentials (access keys + MFA ARN) - - **Override MFA ARN from YAML if present** (allows version-controlled MFA config) + - Use keyring credentials (access keys + MFA ARN) + - **Override MFA ARN from YAML if present** (allows version-controlled MFA config) 3. **If YAML has partial credentials** (only one key): - - Error: Both keys must be provided or both must be empty + - Error: Both keys must be provided or both must be empty This allows flexible configuration: - **Store sensitive credentials in keyring** (local, secure) @@ -1143,31 +1141,31 @@ This allows flexible configuration: **Authentication Flow with MFA:** 1. **Credential Resolution:** - - Atmos retrieves long-lived credentials (access key + secret) from YAML config or keychain - - MFA ARN is retrieved from YAML config, environment variable, or keychain + - Atmos retrieves long-lived credentials (access key + secret) from YAML config or keychain + - MFA ARN is retrieved from YAML config, environment variable, or keychain 2. **Interactive TOTP Prompt:** - - If MFA ARN is configured, Atmos displays an interactive form - - User enters 6-digit TOTP code from authenticator app (Google Authenticator, Authy, etc.) - - TOTP is validated (must be exactly 6 digits, cannot be empty) + - If MFA ARN is configured, Atmos displays an interactive form + - User enters 6-digit TOTP code from authenticator app (Google Authenticator, Authy, etc.) + - TOTP is validated (must be exactly 6 digits, cannot be empty) 3. **Session Token Generation:** - - Atmos calls AWS STS `GetSessionToken` with: - - Long-lived credentials (access key + secret) - - MFA device ARN (`SerialNumber` parameter) - - TOTP code (`TokenCode` parameter) - - Session duration (configurable, default: 12 hours) - - AWS validates MFA and returns temporary session credentials + - Atmos calls AWS STS `GetSessionToken` with: + - Long-lived credentials (access key + secret) + - MFA device ARN (`SerialNumber` parameter) + - TOTP code (`TokenCode` parameter) + - Session duration (configurable, default: 12 hours) + - AWS validates MFA and returns temporary session credentials 4. **Credential Storage:** - - Temporary session credentials (access key + secret + session token) are written to AWS files - - Long-lived credentials remain unchanged in keychain - - Session credentials are valid for configured duration + - Temporary session credentials (access key + secret + session token) are written to AWS files + - Long-lived credentials remain unchanged in keychain + - Session credentials are valid for configured duration 5. **Subsequent Operations:** - - All AWS API calls use temporary session credentials - - Session credentials expire after configured duration - - Re-authentication required after expiration (prompts for new TOTP) + - All AWS API calls use temporary session credentials + - Session credentials expire after configured duration + - Re-authentication required after expiration (prompts for new TOTP) **Session Duration Configuration:** @@ -1345,7 +1343,7 @@ components: **Component Auth Merging Rules**: 1. **Identity Property Overrides**: Component identity properties override global identity properties with same name - - Example: `managers.default: true` in component overrides `managers.default: false` in global config + - Example: `managers.default: true` in component overrides `managers.default: false` in global config 2. **New Identities**: New identities defined in components are added to available options 3. **Provider Overrides**: Component providers override global providers with same name 4. **Environment Variable Merging**: Component environment variables are merged with identity environment variables @@ -1502,9 +1500,9 @@ identities: 3. **Cache Check**: Check `aws-iam-identity-center/cplive-sso/managers` cache key 4. **If Valid**: Use cached credentials, skip authentication 5. **If Invalid**: - - Check `sso/cplive-sso/managers` for SSO tokens - - If SSO tokens valid, refresh permission set credentials - - If SSO tokens invalid, prompt for SSO authentication, then get permission set + - Check `sso/cplive-sso/managers` for SSO tokens + - If SSO tokens valid, refresh permission set credentials + - If SSO tokens invalid, prompt for SSO authentication, then get permission set #### Scenario 2: Complex Chain (SSO → Permission Set → Assume Role) @@ -1536,12 +1534,12 @@ identities: 1. **Target**: `sandbox-admin` identity 2. **Chain**: `cplive-sso` → `managers` → `sandbox-admin` 3. **Bottom-Up Validation**: - - Check `aws-assume-role/managers/sandbox-admin` (assume role credentials) - - If valid (>5min), use cached credentials ✅ - - If invalid, check `aws-iam-identity-center/cplive-sso/managers` (permission set credentials) - - If permission set valid, use it to refresh assume role credentials - - If permission set invalid, check `sso/cplive-sso/managers` (SSO tokens) - - Re-authenticate from first invalid point down to target + - Check `aws-assume-role/managers/sandbox-admin` (assume role credentials) + - If valid (>5min), use cached credentials ✅ + - If invalid, check `aws-iam-identity-center/cplive-sso/managers` (permission set credentials) + - If permission set valid, use it to refresh assume role credentials + - If permission set invalid, check `sso/cplive-sso/managers` (SSO tokens) + - Re-authenticate from first invalid point down to target #### Scenario 3: Deep Chain (SSO → Permission Set → Assume Role → Nested Assume Role) @@ -1571,10 +1569,10 @@ identities: 1. **Target**: `production-admin` identity 2. **Chain**: `cplive-sso` → `managers` → `cross-account-admin` → `production-admin` 3. **Optimization Strategy**: - - Check each level from bottom to top - - Find first valid cached credentials - - Re-authenticate only from first invalid point downward - - Cache all newly obtained credentials + - Check each level from bottom to top + - Find first valid cached credentials + - Re-authenticate only from first invalid point downward + - Cache all newly obtained credentials ### 5.2 Cache Key Strategy diff --git a/pkg/auth/identities/aws/permission_set_authenticate_test.go b/pkg/auth/identities/aws/permission_set_authenticate_test.go new file mode 100644 index 00000000000..15d5777fb4b --- /dev/null +++ b/pkg/auth/identities/aws/permission_set_authenticate_test.go @@ -0,0 +1,159 @@ +package aws + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + ssotypes "github.com/aws/aws-sdk-go-v2/service/sso/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/auth/types" + "github.com/cloudposse/atmos/pkg/schema" +) + +// Compile-time guard for the schema fields the permission-set tests rely on. +var _ = schema.Identity{Kind: "aws/permission-set", Principal: nil, Spec: nil} + +// fakeSSOPortal serves the two AWS SSO portal operations a permission-set login uses. +type fakeSSOPortal struct { + listCalls atomic.Int32 + credsCalls atomic.Int32 + // credsStatus, when non-zero, makes GetRoleCredentials fail with UnauthorizedException. + credsStatus int +} + +func (f *fakeSSOPortal) handler(t *testing.T) http.Handler { + t.Helper() + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "sso-bearer-token", r.Header.Get("x-amz-sso_bearer_token"), "the SSO access token is the bearer token") + w.Header().Set("Content-Type", "application/json") + + switch r.URL.Path { + case "/assignment/accounts": + f.listCalls.Add(1) + _, _ = w.Write([]byte(`{"accountList":[{"accountId":"111111111111","accountName":"staging"},{"accountId":"222222222222","accountName":"production"}]}`)) + case "/federation/credentials": + f.credsCalls.Add(1) + assert.Equal(t, "222222222222", r.URL.Query().Get("account_id")) + assert.Equal(t, "AdminAccess", r.URL.Query().Get("role_name")) + if f.credsStatus != 0 { + w.Header().Set("X-Amzn-ErrorType", "UnauthorizedException") + w.WriteHeader(f.credsStatus) + _, _ = w.Write([]byte(`{"message":"session expired"}`)) + return + } + // Expiration is milliseconds since the Unix epoch: 2030-01-02T03:04:05Z. + _, _ = w.Write([]byte(`{"roleCredentials":{"accessKeyId":"ASIAROLE","secretAccessKey":"role-secret","sessionToken":"role-session","expiration":1893553445000}}`)) + default: + t.Errorf("unexpected SSO portal request: %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + }) +} + +func newPortalPermissionSet(t *testing.T, endpoint string, account map[string]any) *permissionSetIdentity { + t.Helper() + identity, err := NewPermissionSetIdentity("prod-admin", &schema.Identity{ + Kind: "aws/permission-set", + Principal: map[string]any{ + "name": "AdminAccess", + "account": account, + }, + Spec: map[string]any{"endpoint_url": endpoint}, + }) + require.NoError(t, err) + ps, ok := identity.(*permissionSetIdentity) + require.True(t, ok) + return ps +} + +func TestPermissionSetIdentity_Authenticate_AgainstPortal(t *testing.T) { + ssoBase := &types.AWSCredentials{AccessKeyID: "sso-bearer-token", Region: "us-east-1"} + + tests := []struct { + name string + account map[string]any + wantListCalls int32 + }{ + { + name: "account id is used directly", + account: map[string]any{"id": "222222222222"}, + wantListCalls: 0, + }, + { + name: "account name is resolved through the portal", + account: map[string]any{"name": "production"}, + wantListCalls: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("ATMOS_XDG_CACHE_HOME", t.TempDir()) + portal := &fakeSSOPortal{} + srv := httptest.NewServer(portal.handler(t)) + t.Cleanup(srv.Close) + + ps := newPortalPermissionSet(t, srv.URL, tt.account) + creds, err := ps.Authenticate(context.Background(), ssoBase) + require.NoError(t, err) + + awsCreds, ok := creds.(*types.AWSCredentials) + require.True(t, ok) + assert.Equal(t, "ASIAROLE", awsCreds.AccessKeyID) + assert.Equal(t, "role-secret", awsCreds.SecretAccessKey) + assert.Equal(t, "role-session", awsCreds.SessionToken) + assert.Equal(t, "us-east-1", awsCreds.Region) + // The portal reports milliseconds; the credential must carry the matching wall-clock time. + want := time.Date(2030, time.January, 2, 3, 4, 5, 0, time.UTC) + got, err := time.Parse(time.RFC3339, awsCreds.Expiration) + require.NoError(t, err) + assert.True(t, want.Equal(got), "expiration %s, want %s", got, want) + + assert.Equal(t, tt.wantListCalls, portal.listCalls.Load()) + assert.Equal(t, int32(1), portal.credsCalls.Load()) + }) + } +} + +func TestPermissionSetIdentity_Authenticate_ReusesResolvedAccountID(t *testing.T) { + t.Setenv("ATMOS_XDG_CACHE_HOME", t.TempDir()) + portal := &fakeSSOPortal{} + srv := httptest.NewServer(portal.handler(t)) + t.Cleanup(srv.Close) + + ssoBase := &types.AWSCredentials{AccessKeyID: "sso-bearer-token", Region: "us-east-1"} + ps := newPortalPermissionSet(t, srv.URL, map[string]any{"name": "production"}) + + for range 2 { + _, err := ps.Authenticate(context.Background(), ssoBase) + require.NoError(t, err) + } + + // The account name is listed once per SSO session; later logins reuse the cached ID. + assert.Equal(t, int32(1), portal.listCalls.Load()) + assert.Equal(t, int32(2), portal.credsCalls.Load()) +} + +func TestPermissionSetIdentity_Authenticate_GetRoleCredentialsError(t *testing.T) { + t.Setenv("ATMOS_XDG_CACHE_HOME", t.TempDir()) + portal := &fakeSSOPortal{credsStatus: http.StatusUnauthorized} + srv := httptest.NewServer(portal.handler(t)) + t.Cleanup(srv.Close) + + ps := newPortalPermissionSet(t, srv.URL, map[string]any{"id": "222222222222"}) + creds, err := ps.Authenticate(context.Background(), &types.AWSCredentials{AccessKeyID: "sso-bearer-token", Region: "us-east-1"}) + + require.Error(t, err) + assert.Nil(t, creds) + assert.ErrorIs(t, err, errUtils.ErrAuthenticationFailed) + var unauthorized *ssotypes.UnauthorizedException + require.ErrorAs(t, err, &unauthorized, "the portal error must stay in the chain") + assert.Equal(t, "session expired", unauthorized.ErrorMessage()) +} diff --git a/pkg/auth/identities/gcp_service_account/prepare_environment_test.go b/pkg/auth/identities/gcp_service_account/prepare_environment_test.go new file mode 100644 index 00000000000..3015696a5f6 --- /dev/null +++ b/pkg/auth/identities/gcp_service_account/prepare_environment_test.go @@ -0,0 +1,112 @@ +package gcp_service_account + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + errUtils "github.com/cloudposse/atmos/errors" + gcpCloud "github.com/cloudposse/atmos/pkg/auth/cloud/gcp" + "github.com/cloudposse/atmos/pkg/auth/types" + "github.com/cloudposse/atmos/pkg/schema" +) + +// Compile-time guards for the schema/type fields these tests rely on. +var ( + _ = schema.IdentityVia{Provider: "gcp-adc"} + _ = types.GCPServiceAccountIdentityPrincipal{ServiceAccountEmail: "", ProjectID: ""} +) + +func newPrepareEnvIdentity(name, projectID string) *Identity { + return &Identity{ + name: name, + realm: "test-realm", + principal: &types.GCPServiceAccountIdentityPrincipal{ + ServiceAccountEmail: "deployer@email-project.iam.gserviceaccount.com", + ProjectID: projectID, + }, + config: &schema.Identity{Via: &schema.IdentityVia{Provider: "gcp-adc"}}, + } +} + +// writeIdentityADC persists an ADC file for the identity the same way PostAuthenticate does. +func writeIdentityADC(t *testing.T, identityName, token string, expiry time.Time) { + t.Helper() + _, err := gcpCloud.WriteADCFile("test-realm", "gcp-adc", identityName, &gcpCloud.AuthorizedUserContent{ + Type: "authorized_user", + AccessToken: token, + TokenExpiry: expiry.UTC().Format(time.RFC3339), + }) + require.NoError(t, err) +} + +func TestPrepareEnvironment_WithStoredCredentials(t *testing.T) { + tests := []struct { + name string + projectID string + wantProject string + }{ + {name: "principal project wins", projectID: "principal-project", wantProject: "principal-project"}, + {name: "project derived from service account email", projectID: "", wantProject: "email-project"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + id := newPrepareEnvIdentity("sa-identity", tt.projectID) + writeIdentityADC(t, "sa-identity", "ya29.stored-token", time.Now().Add(time.Hour)) + + input := map[string]string{"PATH": "/usr/bin"} + env, err := id.PrepareEnvironment(context.Background(), input) + require.NoError(t, err) + + // Token comes from the identity's own realm-scoped ADC file. + assert.Equal(t, "ya29.stored-token", env["GOOGLE_OAUTH_ACCESS_TOKEN"]) + // With an access token, the authorized_user ADC file (no refresh token) must not be + // advertised via GOOGLE_APPLICATION_CREDENTIALS. + assert.NotContains(t, env, "GOOGLE_APPLICATION_CREDENTIALS") + assert.Equal(t, tt.wantProject, env["GOOGLE_CLOUD_PROJECT"]) + assert.Equal(t, tt.wantProject, env["CLOUDSDK_CORE_PROJECT"]) + assert.Equal(t, "/usr/bin", env["PATH"]) + + // The gcloud config dir is isolated per realm, provider, and identity. + wantConfigDir, err := gcpCloud.GetConfigDir("test-realm", "gcp-adc", "sa-identity") + require.NoError(t, err) + assert.Equal(t, wantConfigDir, env["CLOUDSDK_CONFIG"]) + assert.True(t, filepath.IsAbs(env["CLOUDSDK_CONFIG"])) + + // The input map must not be mutated. + assert.Equal(t, map[string]string{"PATH": "/usr/bin"}, input) + }) + } +} + +func TestPrepareEnvironment_IdentitiesDoNotShareTokens(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + writeIdentityADC(t, "identity-a", "token-a", time.Now().Add(time.Hour)) + writeIdentityADC(t, "identity-b", "token-b", time.Now().Add(time.Hour)) + + envA, err := newPrepareEnvIdentity("identity-a", "p").PrepareEnvironment(context.Background(), nil) + require.NoError(t, err) + envB, err := newPrepareEnvIdentity("identity-b", "p").PrepareEnvironment(context.Background(), nil) + require.NoError(t, err) + + assert.Equal(t, "token-a", envA["GOOGLE_OAUTH_ACCESS_TOKEN"]) + assert.Equal(t, "token-b", envB["GOOGLE_OAUTH_ACCESS_TOKEN"]) + assert.NotEqual(t, envA["CLOUDSDK_CONFIG"], envB["CLOUDSDK_CONFIG"]) +} + +func TestPrepareEnvironment_ExpiredStoredCredentials(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + id := newPrepareEnvIdentity("expired-identity", "p") + writeIdentityADC(t, "expired-identity", "ya29.expired", time.Now().Add(-time.Minute)) + + env, err := id.PrepareEnvironment(context.Background(), map[string]string{}) + require.ErrorIs(t, err, errUtils.ErrAuthenticationFailed) + assert.Nil(t, env) + assert.Contains(t, err.Error(), "expired-identity") +} diff --git a/pkg/auth/integrations/aws/eks_kubeconfig_merge_test.go b/pkg/auth/integrations/aws/eks_kubeconfig_merge_test.go new file mode 100644 index 00000000000..4f3ac44c291 --- /dev/null +++ b/pkg/auth/integrations/aws/eks_kubeconfig_merge_test.go @@ -0,0 +1,180 @@ +package aws + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + + awsCloud "github.com/cloudposse/atmos/pkg/auth/cloud/aws" + "github.com/cloudposse/atmos/pkg/auth/cloud/kube" + "github.com/cloudposse/atmos/pkg/auth/types" + "github.com/cloudposse/atmos/pkg/schema" +) + +// stubEKSDescribe makes Execute describe a fixed cluster without AWS calls. +func stubEKSDescribe(t *testing.T, info *awsCloud.EKSClusterInfo) { + t.Helper() + origClientFactory, origDescribe := eksClientFactory, eksDescribeCluster + t.Cleanup(func() { + eksClientFactory = origClientFactory + eksDescribeCluster = origDescribe + }) + eksClientFactory = func(context.Context, types.ICredentials, string) (awsCloud.EKSClient, error) { + return nil, nil // Unused: DescribeCluster is stubbed too. + } + eksDescribeCluster = func(context.Context, awsCloud.EKSClient, string, string) (*awsCloud.EKSClusterInfo, error) { + return info, nil + } +} + +// userOwnedKubeconfig returns a kubeconfig with entries Atmos did not create. +func userOwnedKubeconfig() *clientcmdapi.Config { + cfg := clientcmdapi.NewConfig() + cfg.Clusters["minikube"] = &clientcmdapi.Cluster{Server: "https://127.0.0.1:8443"} + cfg.AuthInfos["minikube"] = &clientcmdapi.AuthInfo{Token: "user-token"} + cfg.Contexts["minikube"] = &clientcmdapi.Context{Cluster: "minikube", AuthInfo: "minikube", Namespace: "apps"} + cfg.CurrentContext = "minikube" + return cfg +} + +func TestEKSIntegration_ExecuteAndCleanup_PreserveUserEntries(t *testing.T) { + kubeconfigPath := filepath.Join(t.TempDir(), "kubeconfig") + writeKubeconfig(t, kubeconfigPath, userOwnedKubeconfig()) + + clusterARN := "arn:aws:eks:eu-west-1:123456789012:cluster/platform" + stubEKSDescribe(t, &awsCloud.EKSClusterInfo{ + Name: "platform", + Endpoint: "https://platform.eks.amazonaws.com", + CertificateAuthorityData: "dGVzdA==", + ARN: clusterARN, + Region: "eu-west-1", + }) + + integration := &EKSIntegration{ + name: "platform-eks", + identity: "platform-admin", + cluster: &schema.Cluster{ + Name: "platform", + Region: "eu-west-1", + Alias: "platform", + Kubeconfig: &schema.KubeconfigSettings{Path: kubeconfigPath, Update: "merge"}, + }, + } + workingDir, err := os.Getwd() + require.NoError(t, err) + + require.NoError(t, integration.Execute(t.Context(), nil)) + + merged, err := loadKubeconfig(kubeconfigPath) + require.NoError(t, err) + + // User-owned entries survive the merge untouched. + require.Contains(t, merged.Clusters, "minikube") + assert.Equal(t, "https://127.0.0.1:8443", merged.Clusters["minikube"].Server) + require.Contains(t, merged.AuthInfos, "minikube") + assert.Equal(t, "user-token", merged.AuthInfos["minikube"].Token) + require.Contains(t, merged.Contexts, "minikube") + assert.Equal(t, "apps", merged.Contexts["minikube"].Namespace) + + // The Atmos context points at the cluster ARN and an exec user that requests + // tokens for the right cluster, region, identity, and project directory. + require.Contains(t, merged.Contexts, "platform") + assert.Equal(t, "platform", merged.CurrentContext) + atmosCtx := merged.Contexts["platform"] + assert.Equal(t, clusterARN, atmosCtx.Cluster) + require.Contains(t, merged.AuthInfos, atmosCtx.AuthInfo) + exec := merged.AuthInfos[atmosCtx.AuthInfo].Exec + require.NotNil(t, exec) + assert.Equal(t, []string{ + "aws", "eks", "token", + "--cluster-name", "platform", + "--region", "eu-west-1", + "--identity=platform-admin", + }, exec.Args) + execEnv := map[string]string{} + for _, env := range exec.Env { + execEnv[env.Name] = env.Value + } + assert.Equal(t, "platform-admin", execEnv["ATMOS_IDENTITY"]) + assert.Equal(t, workingDir, execEnv["ATMOS_CHDIR"]) + assert.Equal(t, clientcmdapi.NeverExecInteractiveMode, exec.InteractiveMode) + + // Cleanup removes only what Atmos wrote. + require.NoError(t, integration.Cleanup(t.Context())) + + remaining, err := loadKubeconfig(kubeconfigPath) + require.NoError(t, err) + assert.NotContains(t, remaining.Clusters, clusterARN) + assert.NotContains(t, remaining.Contexts, "platform") + assert.NotContains(t, remaining.AuthInfos, atmosCtx.AuthInfo) + assert.Contains(t, remaining.Clusters, "minikube") + assert.Contains(t, remaining.AuthInfos, "minikube") + assert.Contains(t, remaining.Contexts, "minikube") + // The current context pointed at the removed Atmos context, so it is cleared. + assert.Empty(t, remaining.CurrentContext) +} + +func TestEKSIntegration_FindClusterARN_RequiresWholeClusterName(t *testing.T) { + tests := []struct { + name string + clusterName string + existing []string + wantARN string + wantErr bool + }{ + { + name: "exact cluster name matches", + clusterName: "prod", + existing: []string{"arn:aws:eks:us-east-1:123456789012:cluster/prod"}, + wantARN: "arn:aws:eks:us-east-1:123456789012:cluster/prod", + }, + { + name: "cluster whose name ends with the configured name does not match", + clusterName: "prod", + existing: []string{"arn:aws:eks:us-east-1:123456789012:cluster/my-prod"}, + wantErr: true, + }, + { + name: "cluster whose name starts with the configured name does not match", + clusterName: "prod", + existing: []string{"arn:aws:eks:us-east-1:123456789012:cluster/prod-blue"}, + wantErr: true, + }, + { + name: "empty kubeconfig has no match", + clusterName: "prod", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kubeconfigPath := filepath.Join(t.TempDir(), "kubeconfig") + cfg := clientcmdapi.NewConfig() + for _, arn := range tt.existing { + cfg.Clusters[arn] = &clientcmdapi.Cluster{Server: "https://example.eks.amazonaws.com"} + } + if len(tt.existing) > 0 { + writeKubeconfig(t, kubeconfigPath, cfg) + } + + mgr, err := kube.NewKubeconfigManager(kubeconfigPath, "") + require.NoError(t, err) + integration := &EKSIntegration{cluster: &schema.Cluster{Name: tt.clusterName, Region: "us-east-1"}} + + arn, err := integration.findClusterARN(mgr) + if tt.wantErr { + require.Error(t, err) + assert.Empty(t, arn) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantARN, arn) + }) + } +} diff --git a/pkg/auth/list/formatter_status_test.go b/pkg/auth/list/formatter_status_test.go new file mode 100644 index 00000000000..ffe0709f1fa --- /dev/null +++ b/pkg/auth/list/formatter_status_test.go @@ -0,0 +1,125 @@ +package list + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + authTypes "github.com/cloudposse/atmos/pkg/auth/types" +) + +// Compile-time guard so a WhoamiInfo field rename fails the build here. +var _ = authTypes.WhoamiInfo{Expiration: nil} + +const statusTestNow = "2026-01-01T12:00:00Z" + +// cachedCredentialsManager returns a mock whose cached credentials for "dev" +// expire `remaining` after statusTestNow; a nil remaining means no expiration. +func cachedCredentialsManager(t *testing.T, remaining *time.Duration, lookupErr error) *authTypes.MockAuthManager { + t.Helper() + now, err := time.Parse(time.RFC3339, statusTestNow) + require.NoError(t, err) + manager := authTypes.NewMockAuthManager(gomock.NewController(t)) + call := manager.EXPECT().GetCachedCredentials(gomock.Any(), "dev") + switch { + case lookupErr != nil: + call.Return(nil, lookupErr).AnyTimes() + case remaining == nil: + call.Return(&authTypes.WhoamiInfo{Identity: "dev"}, nil).AnyTimes() + default: + expiration := now.Add(*remaining) + call.Return(&authTypes.WhoamiInfo{Identity: "dev", Expiration: &expiration}, nil).AnyTimes() + } + return manager +} + +func durationPtr(d time.Duration) *time.Duration { return &d } + +// TestIdentityStatusAndExpirationAgree pins the status thresholds shared by the +// status dot and the expiration column, including both boundary instants. +func TestIdentityStatusAndExpirationAgree(t *testing.T) { + t.Setenv("ATMOS_TEST_NOW", statusTestNow) + + for _, tt := range []struct { + name string + remaining *time.Duration + lookupErr error + wantStatus authStatus + wantDuration string + }{ + {name: "no cached credentials", lookupErr: errors.New("not cached"), wantStatus: authStatusUnknown}, + {name: "credentials without expiration are valid", wantStatus: authStatusValid}, + {name: "expired one second ago", remaining: durationPtr(-time.Second), wantStatus: authStatusExpired, wantDuration: "expired"}, + {name: "expiring exactly now counts as expired", remaining: durationPtr(0), wantStatus: authStatusExpired, wantDuration: "expired"}, + {name: "one second left is expiring", remaining: durationPtr(time.Second), wantStatus: authStatusExpiring, wantDuration: "1s"}, + {name: "exactly at the threshold is expiring", remaining: durationPtr(expiringThreshold), wantStatus: authStatusExpiring, wantDuration: "15m"}, + {name: "just past the threshold is valid", remaining: durationPtr(expiringThreshold + time.Second), wantStatus: authStatusValid, wantDuration: "15m"}, + {name: "hours and minutes", remaining: durationPtr(2*time.Hour + 5*time.Minute), wantStatus: authStatusValid, wantDuration: "2h5m"}, + {name: "whole hours drop zero minutes", remaining: durationPtr(3 * time.Hour), wantStatus: authStatusValid, wantDuration: "3h"}, + } { + t.Run(tt.name, func(t *testing.T) { + manager := cachedCredentialsManager(t, tt.remaining, tt.lookupErr) + + assert.Equal(t, tt.wantStatus, getIdentityAuthStatus(manager, "dev")) + + duration, status := getExpirationInfo(manager, "dev") + assert.Equal(t, tt.wantStatus, status, "the expiration column must agree with the status dot") + assert.Equal(t, tt.wantDuration, duration) + + expiration := resolveIdentityExpiration(manager, "dev") + if tt.wantDuration == "" { + assert.Equal(t, emptyMarker, expiration) + } else { + assert.Contains(t, expiration, tt.wantDuration) + } + }) + } +} + +func TestIdentityStatusWithoutManager(t *testing.T) { + assert.Equal(t, authStatusUnknown, getIdentityAuthStatus(nil, "dev")) + duration, status := getExpirationInfo(nil, "dev") + assert.Empty(t, duration) + assert.Equal(t, authStatusUnknown, status) + assert.Equal(t, emptyMarker, resolveIdentityExpiration(nil, "dev")) +} + +func TestIdentityStatusNilWhoamiIsUnknown(t *testing.T) { + manager := authTypes.NewMockAuthManager(gomock.NewController(t)) + manager.EXPECT().GetCachedCredentials(gomock.Any(), "dev").Return(nil, nil).AnyTimes() + assert.Equal(t, authStatusUnknown, getIdentityAuthStatus(manager, "dev")) + duration, status := getExpirationInfo(manager, "dev") + assert.Empty(t, duration) + assert.Equal(t, authStatusUnknown, status) +} + +func TestFormatDurationRounding(t *testing.T) { + for _, tt := range []struct { + in time.Duration + want string + }{ + {-time.Minute, "expired"}, + {0, "expired"}, + {499 * time.Millisecond, "0s"}, + {30 * time.Second, "30s"}, + {59*time.Second + 600*time.Millisecond, "1m"}, + {45 * time.Minute, "45m"}, + {59*time.Minute + 59*time.Second + 600*time.Millisecond, "1h"}, + {90 * time.Minute, "1h30m"}, + {26 * time.Hour, "26h"}, + } { + assert.Equal(t, tt.want, formatDuration(tt.in), "formatDuration(%s)", tt.in) + } +} + +func TestFormatExpirationWithColorKeepsText(t *testing.T) { + assert.Empty(t, formatExpirationWithColor("", authStatusValid)) + assert.Equal(t, "5m", formatExpirationWithColor("5m", authStatusUnknown), "unknown status is left unstyled") + for _, status := range []authStatus{authStatusValid, authStatusExpiring, authStatusExpired} { + assert.Contains(t, formatExpirationWithColor("5m", status), "5m") + } +} diff --git a/pkg/auth/manager_operation_test.go b/pkg/auth/manager_operation_test.go new file mode 100644 index 00000000000..c69514cf8c7 --- /dev/null +++ b/pkg/auth/manager_operation_test.go @@ -0,0 +1,242 @@ +package auth + +import ( + "context" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + errUtils "github.com/cloudposse/atmos/errors" + authregistry "github.com/cloudposse/atmos/pkg/auth/registry" + "github.com/cloudposse/atmos/pkg/auth/types" + "github.com/cloudposse/atmos/pkg/schema" +) + +// Compile-time sentinels for the schema fields referenced by these tests. +var ( + _ = schema.AuthContext{Environment: map[string]string{}} + _ = schema.AuthConfig{IdentityCaseMap: map[string]string{}} +) + +// scopedOperationKind is a test-only identity kind registered per test so the +// isolated operation manager constructs a controllable gomock identity. +const scopedOperationKind = "scopedtest/operation" + +// registerScopedOperationIdentity registers scopedOperationKind for this test and +// returns a manager whose "store" identity uses it via the mock/aws provider. +func registerScopedOperationIdentity(t *testing.T, identity types.Identity) *manager { + t.Helper() + + unregister, err := authregistry.RegisterBatch(authregistry.Registration{ + Identities: map[string]authregistry.IdentityConfigConstructor{ + scopedOperationKind: func(string, *schema.Identity) (types.Identity, error) { return identity, nil }, + }, + }) + require.NoError(t, err) + t.Cleanup(unregister) + + parent := isolatedTestManager(t).(*manager) + parent.config.Identities["store"] = schema.Identity{Kind: scopedOperationKind, Via: &schema.IdentityVia{Provider: "mock"}} + return parent +} + +// expectScopedIdentityBasics allows the lifecycle calls the manager makes on every identity. +func expectScopedIdentityBasics(identity *types.MockIdentity) { + identity.EXPECT().Kind().Return(scopedOperationKind).AnyTimes() + identity.EXPECT().Validate().Return(nil).AnyTimes() + identity.EXPECT().SetRealm(gomock.Any()).AnyTimes() + expectNoStoredScopedCredentials(identity) +} + +// expectNoStoredScopedCredentials reports that the operation realm starts empty. +func expectNoStoredScopedCredentials(identity *types.MockIdentity) { + identity.EXPECT().LoadCredentials(gomock.Any()).Return(nil, assert.AnError).AnyTimes() + identity.EXPECT().GetProviderName().Return("mock", nil).AnyTimes() + identity.EXPECT().Environment().Return(map[string]string{}, nil).AnyTimes() +} + +func TestOperationCredentialStoreRedirectsOnlyTheOwnedTarget(t *testing.T) { + const parentRealm, operationRealm = "parent-realm", "operation-test" + tests := []struct { + name string + alias string + realm string + wantRealm string + }{ + {name: "target in parent realm", alias: "owned", realm: parentRealm, wantRealm: operationRealm}, + {name: "target legacy realm", alias: "owned", realm: "", wantRealm: operationRealm}, + {name: "ancestor in parent realm", alias: "ancestor", realm: parentRealm, wantRealm: parentRealm}, + {name: "ancestor legacy realm", alias: "ancestor", realm: "", wantRealm: ""}, + {name: "provider", alias: "root", realm: parentRealm, wantRealm: parentRealm}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + backend := types.NewMockCredentialStore(gomock.NewController(t)) + scoped := &operationCredentialStore{CredentialStore: backend, scope: &identityOperationScope{target: "owned", realm: operationRealm}} + creds := &types.AWSCredentials{AccessKeyID: "synthetic"} + + backend.EXPECT().Store(tt.alias, creds, tt.wantRealm).Return(nil) + backend.EXPECT().Retrieve(tt.alias, tt.wantRealm).Return(creds, nil) + backend.EXPECT().Delete(tt.alias, tt.wantRealm).Return(nil) + + require.NoError(t, scoped.Store(tt.alias, creds, tt.realm)) + got, err := scoped.Retrieve(tt.alias, tt.realm) + require.NoError(t, err) + assert.Same(t, creds, got) + require.NoError(t, scoped.Delete(tt.alias, tt.realm)) + }) + } +} + +func TestIdentityCredentialRealmSelectsOperationRealmOnlyForTarget(t *testing.T) { + m := &manager{} + m.realm.Value = "parent-realm" + assert.Equal(t, "parent-realm", m.identityCredentialRealm("owned"), "an unscoped manager always uses its realm") + + m.operationScope = &identityOperationScope{target: "owned", realm: "operation-test"} + assert.Equal(t, "operation-test", m.identityCredentialRealm("owned")) + assert.Equal(t, "parent-realm", m.identityCredentialRealm("ancestor")) +} + +func TestWithIsolatedIdentityConcurrentOperationsStayIsolated(t *testing.T) { + resetProcessCredentialCache() + t.Cleanup(resetProcessCredentialCache) + parent := isolatedTestManager(t).(*manager) + _, err := parent.Authenticate(t.Context(), "deployer") + require.NoError(t, err) + before := snapshotParent(parent) + + const workers = 8 + paths := make(chan string, workers) + errs := make(chan error, workers) + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + errs <- parent.WithIsolatedIdentity(t.Context(), "automation", func(_ context.Context, auth *schema.AuthContext) error { + if auth == nil || auth.AWS == nil { + return errUtils.ErrNilParam + } + if _, err := os.Stat(auth.AWS.CredentialsFile); err != nil { + return err + } + paths <- auth.AWS.CredentialsFile + return nil + }) + }() + } + wg.Wait() + close(errs) + close(paths) + for err := range errs { + require.NoError(t, err) + } + + seen := map[string]bool{} + for path := range paths { + require.False(t, seen[path], "each operation must own a private credentials file") + seen[path] = true + } + require.Len(t, seen, workers) + + processCredentialCache.Range(func(key, _ any) bool { + assert.NotContains(t, key.(string), "operation-", "operation cache entries must not outlive the operation") + return true + }) + assertParentUnchanged(t, parent, before) +} + +func TestWithIsolatedIdentityReleasesAfterOperationPanic(t *testing.T) { + ctrl := gomock.NewController(t) + identity := types.NewMockIdentity(ctrl) + expectScopedIdentityBasics(identity) + parent := registerScopedOperationIdentity(t, identity) + + identity.EXPECT().Authenticate(gomock.Any(), gomock.Any()).Return(&types.AWSCredentials{AccessKeyID: "synthetic"}, nil) + identity.EXPECT().PostAuthenticate(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, params *types.PostAuthenticateParams) error { + params.AuthContext.Environment = map[string]string{"VAULT_TOKEN": "synthetic"} + return nil + }) + identity.EXPECT().Logout(gomock.Any()).Return(nil).Times(1) + + require.PanicsWithValue(t, "operation failed", func() { + _ = parent.WithIsolatedIdentity(t.Context(), "store", func(context.Context, *schema.AuthContext) error { + panic("operation failed") + }) + }) +} + +func TestWithIsolatedIdentityReleasesAfterFailedAcquisition(t *testing.T) { + ctrl := gomock.NewController(t) + identity := types.NewMockIdentity(ctrl) + expectScopedIdentityBasics(identity) + parent := registerScopedOperationIdentity(t, identity) + + identity.EXPECT().Authenticate(gomock.Any(), gomock.Any()).Return(nil, assert.AnError) + // A server may already have minted a credential before reporting failure. + identity.EXPECT().Logout(gomock.Any()).Return(nil).Times(1) + + called := false + err := parent.WithIsolatedIdentity(t.Context(), "store", func(context.Context, *schema.AuthContext) error { + called = true + return nil + }) + require.ErrorIs(t, err, assert.AnError) + assert.False(t, called, "a failed acquisition must never dispatch the operation") +} + +func TestWithIsolatedIdentityCleanupOutlivesCallerCancellation(t *testing.T) { + ctrl := gomock.NewController(t) + identity := types.NewMockIdentity(ctrl) + expectScopedIdentityBasics(identity) + parent := registerScopedOperationIdentity(t, identity) + + identity.EXPECT().Authenticate(gomock.Any(), gomock.Any()).Return(&types.AWSCredentials{AccessKeyID: "synthetic"}, nil) + identity.EXPECT().PostAuthenticate(gomock.Any(), gomock.Any()).Return(nil) + identity.EXPECT().Logout(gomock.Any()).DoAndReturn(func(ctx context.Context) error { + require.NoError(t, ctx.Err(), "logout must run on a live cleanup context after caller cancellation") + deadline, ok := ctx.Deadline() + require.True(t, ok, "cleanup must stay bounded") + assert.LessOrEqual(t, time.Until(deadline), 30*time.Second) + return nil + }) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + err := parent.WithIsolatedIdentity(ctx, "store", func(opCtx context.Context, _ *schema.AuthContext) error { + cancel() + <-opCtx.Done() + return opCtx.Err() + }) + require.ErrorIs(t, err, context.Canceled) +} + +func TestWithIsolatedIdentityRealmScopesOnlyTarget(t *testing.T) { + ctrl := gomock.NewController(t) + identity := types.NewMockIdentity(ctrl) + identity.EXPECT().Kind().Return(scopedOperationKind).AnyTimes() + identity.EXPECT().Validate().Return(nil).AnyTimes() + var realms []string + identity.EXPECT().SetRealm(gomock.Any()).Do(func(realm string) { realms = append(realms, realm) }).AnyTimes() + expectNoStoredScopedCredentials(identity) + parent := registerScopedOperationIdentity(t, identity) + + identity.EXPECT().Authenticate(gomock.Any(), gomock.Any()).Return(&types.AWSCredentials{AccessKeyID: "synthetic"}, nil) + identity.EXPECT().PostAuthenticate(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, params *types.PostAuthenticateParams) error { + require.True(t, strings.HasPrefix(params.Realm, "operation-"), "target materializes into its operation realm, got %q", params.Realm) + require.NotEqual(t, parent.realm.Value, params.Realm) + return nil + }) + identity.EXPECT().Logout(gomock.Any()).Return(nil) + + require.NoError(t, parent.WithIsolatedIdentity(t.Context(), "store", func(context.Context, *schema.AuthContext) error { return nil })) + require.NotEmpty(t, realms) + assert.True(t, strings.HasPrefix(realms[len(realms)-1], "operation-"), "the last realm assigned to the target must be its operation realm") +} diff --git a/pkg/auth/providers/aws/saml.go b/pkg/auth/providers/aws/saml.go index 69f3c59e05e..562ee260490 100644 --- a/pkg/auth/providers/aws/saml.go +++ b/pkg/auth/providers/aws/saml.go @@ -16,12 +16,12 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sts" "github.com/spf13/viper" - "github.com/versent/saml2aws/v2" - "github.com/versent/saml2aws/v2/pkg/cfg" - "github.com/versent/saml2aws/v2/pkg/creds" errUtils "github.com/cloudposse/atmos/errors" awsCloud "github.com/cloudposse/atmos/pkg/auth/cloud/aws" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" "github.com/cloudposse/atmos/pkg/auth/types" "github.com/cloudposse/atmos/pkg/config/homedir" "github.com/cloudposse/atmos/pkg/duration" @@ -121,32 +121,19 @@ func (p *samlProvider) PreAuthenticate(manager types.AuthManager) error { // Authenticate performs SAML authentication using saml2aws. func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, error) { - samlDriver := p.getDriver() - downloadBrowser := p.shouldDownloadBrowser() + if err := p.validateDriver(); err != nil { + return nil, err + } - log.Info("Starting SAML authentication", "provider", p.name, "url", p.url, logFieldDriver, samlDriver) - log.Debug("SAML configuration", - logFieldDriver, samlDriver, - "download_browser", downloadBrowser, - "requires_drivers", samlDriver == "Browser") + samlDriver := p.getDriver() + p.logAuthenticationStart(samlDriver) if p.RoleToAssumeFromAssertion == "" { return nil, fmt.Errorf("%w: no role to assume for assertion, SAML provider must be part of a chain", errUtils.ErrInvalidAuthConfig) } - // Set up browser automation only for the Browser driver. - // Other drivers (GoogleApps, Okta, ADFS) use API/HTTP flows and don't need - // Playwright, XDG storage directories, or symlinks. - if samlDriver == "Browser" { - if err := p.setupBrowserAutomation(); err != nil { - return nil, err - } - // Pre-seed the Playwright driver from official registries: the download - // built into playwright-go/saml2aws points at a retired CDN and 404s. - // Best-effort — an already-installed driver keeps working offline. - if err := ensurePlaywrightDriver(); err != nil { - log.Warn("Could not pre-seed the Playwright driver; browser authentication may fail to download it", "error", err) - } + if err := p.prepareBrowserDriver(samlDriver); err != nil { + return nil, err } // Configure logrus to forward to Atmos logger instead of stdout. @@ -170,17 +157,9 @@ func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, er return nil, err } - decodedXML, err := base64.StdEncoding.DecodeString(assertionB64) + roles, err := rolesFromAssertion(assertionB64) if err != nil { - return nil, fmt.Errorf("%w: failed to decode assertion: %w", errUtils.ErrAwsSAMLDecodeFailed, err) - } - rolesStr, err := saml2aws.ExtractAwsRoles(decodedXML) - if err != nil { - return nil, fmt.Errorf("%w: extract AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) - } - roles, err := saml2aws.ParseAWSRoles(rolesStr) - if err != nil { - return nil, fmt.Errorf("%w: parse AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) + return nil, err } selectedRole := p.selectRole(roles) @@ -199,6 +178,53 @@ func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, er return awsCreds, nil } +// logAuthenticationStart logs the start of a SAML login and the effective driver settings. +func (p *samlProvider) logAuthenticationStart(samlDriver string) { + log.Info("Starting SAML authentication", "provider", p.name, "url", p.url, logFieldDriver, samlDriver) + log.Debug("SAML configuration", + logFieldDriver, samlDriver, + "download_browser", p.shouldDownloadBrowser(), + "requires_drivers", samlDriver == "Browser") +} + +// prepareBrowserDriver sets up browser automation, but only for the Browser driver. +// Other drivers (GoogleApps, Okta, ADFS) use API/HTTP flows and don't need +// Playwright, XDG storage directories, or symlinks. +func (p *samlProvider) prepareBrowserDriver(samlDriver string) error { + if samlDriver != "Browser" { + return nil + } + if err := p.setupBrowserAutomation(); err != nil { + return err + } + // Pre-seed the Playwright driver from official registries: the download + // built into playwright-go/saml2aws points at a retired CDN and 404s. + // Best-effort — an already-installed driver keeps working offline. + if err := ensurePlaywrightDriver(); err != nil { + log.Warn("Could not pre-seed the Playwright driver; browser authentication may fail to download it", "error", err) + } else if err := patchPlaywrightDriver(); err != nil { + log.Debug("Could not patch the Playwright driver", "error", err) + } + return nil +} + +// rolesFromAssertion decodes a base64 SAML assertion and returns the AWS roles it grants. +func rolesFromAssertion(assertionB64 string) ([]*saml2aws.AWSRole, error) { + decodedXML, err := base64.StdEncoding.DecodeString(assertionB64) + if err != nil { + return nil, fmt.Errorf("%w: failed to decode assertion: %w", errUtils.ErrAwsSAMLDecodeFailed, err) + } + rolesStr, err := saml2aws.ExtractAwsRoles(decodedXML) + if err != nil { + return nil, fmt.Errorf("%w: extract AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) + } + roles, err := saml2aws.ParseAWSRoles(rolesStr) + if err != nil { + return nil, fmt.Errorf("%w: parse AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) + } + return roles, nil +} + // createSAMLConfig creates the saml2aws configuration. func (p *samlProvider) createSAMLConfig() *cfg.IDPAccount { return &cfg.IDPAccount{ @@ -212,7 +238,6 @@ func (p *samlProvider) createSAMLConfig() *cfg.IDPAccount { SessionDuration: samlDefaultSessionSec, // 1 hour default. Profile: p.name, Region: p.region, - DownloadBrowser: p.shouldDownloadBrowser(), // Intelligently enable based on driver availability. BrowserType: p.config.BrowserType, BrowserExecutablePath: p.config.BrowserExecutablePath, Headless: false, // Force non-headless for interactive auth. @@ -237,13 +262,9 @@ func (p *samlProvider) createLoginDetails() *creds.LoginDetails { // authenticateAndGetAssertion authenticates and gets the SAML assertion. // -// IMPORTANT: This function calls saml2aws.SAMLClient.Authenticate() which may panic -// due to a bug in saml2aws browser provider (v2.36.19): -// - When browser timeout occurs, ExpectRequest() returns (nil, error) -// - The code then calls nil.PostData() causing a nil pointer dereference -// - Location: browser.go:191 in saml2aws -// - Workaround: Ensure browser authentication completes before timeout (default 5 minutes) -// - User should not close the browser window manually during authentication. +// Upstream saml2aws v2.36.19 panicked here when the browser flow timed out +// (nil request dereference in its browser provider). Atmos's vendored copy in +// pkg/auth/providers/aws/saml2aws returns an error instead. func (p *samlProvider) authenticateAndGetAssertion(samlClient saml2aws.SAMLClient, loginDetails *creds.LoginDetails) (string, error) { samlAssertion, err := samlClient.Authenticate(loginDetails) if err != nil { @@ -389,6 +410,21 @@ func (p *samlProvider) getDriver() string { return "Browser" } +// validateDriver rejects an explicit driver that the vendored saml2aws copy does not support. +// It runs when this provider authenticates, not in Validate: the auth manager validates every +// configured provider up front, so a stale driver on one unused SAML provider must not break +// authentication for every other identity. +func (p *samlProvider) validateDriver() error { + if p.config.Driver == "" { + return nil + } + if _, ok := saml2aws.MFAsByProvider[p.config.Driver]; ok { + return nil + } + return fmt.Errorf("%w: provider %q: unsupported SAML driver %q, supported drivers are %s", + errUtils.ErrInvalidProviderConfig, p.name, p.config.Driver, strings.Join(saml2aws.MFAsByProvider.Names(), ", ")) +} + // Validate validates the provider configuration. func (p *samlProvider) Validate() error { defer perf.Track(nil, "aws.samlProvider.Validate")() @@ -423,10 +459,8 @@ func (p *samlProvider) Environment() (map[string]string, error) { env["AWS_DEFAULT_REGION"] = p.region env["AWS_REGION"] = p.region - // Set saml2aws specific environment variables if needed. - if p.config.DownloadBrowserDriver { - env["SAML2AWS_AUTO_BROWSER_DOWNLOAD"] = "true" - } + // SAML2AWS_AUTO_BROWSER_DOWNLOAD is not exported: only the saml2aws CLI read it, and the vendored + // library installs browsers from LoginDetails.DownloadBrowser (see createLoginDetails). return env, nil } @@ -500,15 +534,36 @@ func (p *samlProvider) PrepareEnvironment(_ context.Context, environ map[string] // playwrightDriversInstalled checks if valid Playwright drivers are installed in standard locations. // Returns true if drivers are found, false if not found or home directory cannot be determined. func (p *samlProvider) playwrightDriversInstalled() bool { + playwrightPaths := p.playwrightBrowserPaths() + + for _, path := range playwrightPaths { + if p.hasValidPlaywrightDrivers(path) { + log.Debug("Found valid Playwright drivers", "path", path) + return true + } + } + + log.Debug("No valid Playwright drivers found", "checked_paths", playwrightPaths) + return false +} + +// playwrightBrowserPaths returns the directories where Playwright browsers may be installed. +func (p *samlProvider) playwrightBrowserPaths() []string { var playwrightPaths []string - // Check Atmos XDG cache directory first (allows users to consolidate all Atmos data). + // Check the directory the Playwright driver itself uses first (honors + // PLAYWRIGHT_BROWSERS_PATH, and XDG_CACHE_HOME on Linux). + if registryDir, err := playwrightRegistryDir(); err == nil { + playwrightPaths = append(playwrightPaths, registryDir) + } + + // Check Atmos XDG cache directory (allows users to consolidate all Atmos data). if xdgCacheDir, err := xdg.GetXDGCacheDir(playwrightCacheDir, playwrightCacheDirPermissions); err == nil { playwrightPaths = append(playwrightPaths, xdgCacheDir) } - // Check playwright-go's hardcoded cache locations. - // Note: playwright-go does NOT respect XDG_CACHE_HOME, it uses its own hardcoded paths. + // Check the home-based default browser locations of every OS. + // Note: these ignore XDG_CACHE_HOME; the registry directory above covers it on Linux. homeDir, err := homedir.Dir() if err == nil { playwrightPaths = append( @@ -532,15 +587,7 @@ func (p *samlProvider) playwrightDriversInstalled() bool { } } - for _, path := range playwrightPaths { - if p.hasValidPlaywrightDrivers(path) { - log.Debug("Found valid Playwright drivers", "path", path) - return true - } - } - - log.Debug("No valid Playwright drivers found", "checked_paths", playwrightPaths) - return false + return playwrightPaths } // hasPlaywrightDriversOrCanDownload checks if Playwright drivers are available or can be downloaded. @@ -580,6 +627,12 @@ func (p *samlProvider) hasValidPlaywrightDrivers(path string) bool { continue } + // Playwright keeps registry metadata (for example ".links") next to the browsers and creates it + // before any browser is downloaded, so an interrupted install must not count as an installed browser. + if strings.HasPrefix(entry.Name(), ".") { + continue + } + versionPath := filepath.Join(path, entry.Name()) versionEntries, err := os.ReadDir(versionPath) if err != nil { @@ -599,8 +652,10 @@ func (p *samlProvider) hasValidPlaywrightDrivers(path string) bool { // shouldDownloadBrowser determines if browser drivers should be auto-downloaded. // It checks if the user explicitly configured download_browser_driver, otherwise -// it intelligently enables auto-download for "Browser" driver if drivers aren't found -// and the user hasn't specified a custom browser. +// it enables auto-download for the "Browser" driver when the Playwright-managed browser +// that will be launched (Chromium by default, or the configured chromium, firefox or webkit +// browser_type) is not installed. A system browser channel (chrome*, msedge*) or a +// browser_executable_path is the user's own browser and is never downloaded. func (p *samlProvider) shouldDownloadBrowser() bool { // If user explicitly set download_browser_driver, respect their choice. if p.config.DownloadBrowserDriver { @@ -616,23 +671,32 @@ func (p *samlProvider) shouldDownloadBrowser() bool { return false } - // If user specified a custom browser type or executable path, don't auto-download. - // They're using their own browser installation. - if p.config.BrowserType != "" || p.config.BrowserExecutablePath != "" { - log.Debug("Custom browser configured, skipping auto-download", - "browser_type", p.config.BrowserType, + // A custom executable path is the user's own browser installation. + if p.config.BrowserExecutablePath != "" { + log.Debug("Custom browser executable configured, skipping auto-download", "browser_executable_path", p.config.BrowserExecutablePath) return false } - // Check if Playwright drivers are already installed. - if p.playwrightDriversInstalled() { - log.Debug("Found valid Playwright drivers, auto-download disabled") + // Only Chromium, Firefox and WebKit are installed by Playwright. System channels + // (chrome*, msedge*) use the browser installed on the system. + browserName, managed := playwrightManagedBrowser(p.config.BrowserType) + if !managed { + log.Debug("Browser type is not installed by Playwright, skipping auto-download", + "browser_type", p.config.BrowserType) return false } - // No valid drivers found and no custom browser configured, enable auto-download. - log.Debug("No valid Playwright drivers found, enabling auto-download for Browser driver") + // Check if the revision of the launched browser required by the bundled Playwright + // driver is installed. Any installed browser is not enough: after a Playwright upgrade + // the previous revision stays on disk but cannot be launched by the new driver, and + // an installed Chromium does not satisfy Firefox or WebKit. + if p.requiredBrowserInstalled(browserName) { + log.Debug("Required browser revision is installed, auto-download disabled", "browser", browserName) + return false + } + + log.Debug("Required browser revision not found, enabling auto-download for Browser driver", "browser", browserName) return true } @@ -654,15 +718,9 @@ func (p *samlProvider) setupBrowserAutomation() error { } } - // Set environment variables for browser automation. - // Clear/set explicitly on every call to avoid leaking state from a - // previous auth flow in the same process (e.g. MCP server, workflows). - if p.shouldDownloadBrowser() { - os.Setenv("SAML2AWS_AUTO_BROWSER_DOWNLOAD", "true") - log.Debug("Browser driver auto-download enabled", logFieldDriver, p.getDriver()) - } else { - _ = os.Unsetenv("SAML2AWS_AUTO_BROWSER_DOWNLOAD") - } + // Browser auto-download is passed to the vendored saml2aws library through + // LoginDetails.DownloadBrowser (see createLoginDetails). The process environment is + // not touched: SAML2AWS_AUTO_BROWSER_DOWNLOAD was only read by the saml2aws CLI. // Ensure the storage directory that saml2aws expects exists. // saml2aws hardcodes ~/.aws/saml2aws/storageState.json for browser state. @@ -713,11 +771,10 @@ func (p *samlProvider) validateBrowserExecutable() error { } // setupBrowserStorageDir ensures the directory that saml2aws uses for browser -// storage state exists. The path is hardcoded upstream as -// `~/.aws/saml2aws/storageState.json` (using fmt.Sprintf with forward slashes, -// which produces mixed-separator paths on Windows). We cannot redirect this -// path to an XDG location because saml2aws does not expose a configurable -// storage path. +// storage state exists. The path is `~/.aws/saml2aws/storageState.json` +// (see storageStatePath in the vendored saml2aws browser provider, which now +// builds it with filepath.Join). It is kept at the upstream location so existing +// browser sessions keep working after the move to the vendored copy. // // The fix: create `~/.aws/saml2aws/` as a plain directory using filepath.Join // (correct separators on all platforms) and os.MkdirAll (no privilege @@ -738,7 +795,7 @@ func (p *samlProvider) setupBrowserStorageDir() error { } // Create ~/.aws/saml2aws/ as a real directory (not a symlink). - // saml2aws hardcodes this path in pkg/provider/browser/browser.go:118. + // The vendored saml2aws browser provider reads and writes storage state here. saml2awsDir := filepath.Join(homeDir, awsDir, saml2awsSubdir) // Migrate legacy symlink left by previous Atmos versions. os.MkdirAll diff --git a/pkg/auth/providers/aws/saml2aws/ATTRIBUTIONS.md b/pkg/auth/providers/aws/saml2aws/ATTRIBUTIONS.md new file mode 100644 index 00000000000..f93a7983ca2 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/ATTRIBUTIONS.md @@ -0,0 +1,7 @@ +# Attributions + +This package is a vendored fork of [saml2aws](https://github.com/Versent/saml2aws) by [Versent](https://github.com/Versent), +copied from release [v2.36.19](https://github.com/Versent/saml2aws/releases/tag/v2.36.19). + +The original project is licensed under the MIT License. +For details, see the [LICENSE.md](./LICENSE.md) file. diff --git a/pkg/auth/providers/aws/saml2aws/LICENSE.md b/pkg/auth/providers/aws/saml2aws/LICENSE.md new file mode 100644 index 00000000000..b03abb9b4c6 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/LICENSE.md @@ -0,0 +1,11 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2024 Versent +-------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pkg/auth/providers/aws/saml2aws/README.md b/pkg/auth/providers/aws/saml2aws/README.md new file mode 100644 index 00000000000..d9014c5e75b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/README.md @@ -0,0 +1,103 @@ +# saml2aws (Atmos fork) + +This is Atmos's vendored fork of the library parts of [saml2aws](https://github.com/Versent/saml2aws) +v2.36.19. The `aws/saml` auth provider (`pkg/auth/providers/aws/saml.go`) uses it to sign in to a SAML +identity provider and read the AWS roles from the SAML assertion. + +## Why it is vendored + +- Upstream is no longer maintained. The last release was v2.36.19 (March 2025), the last commit was in + May 2025, and [Versent/saml2aws#1545](https://github.com/Versent/saml2aws/issues/1545) ("Still maintained?") has no reply. +- Upstream pins `github.com/playwright-community/playwright-go` v0.5700.1, the last release under that module path. + It pulls in `github.com/go-jose/go-jose/v3`, which has an unfixed HIGH advisory (CVE-2026-116587 / GHSA-mgcc-cww5-fp2q) + that vulnerability scanners report against the Atmos binary. +- The upstream browser provider panics when the sign-in times out. + +## What was kept + +| Path | Upstream path | Purpose | +|------|---------------|---------| +| `saml2aws.go`, `saml.go`, `aws_role.go` | repo root | `NewSAMLClient` dispatcher, assertion parsing, role parsing | +| `cfg/` | `pkg/cfg` | `IDPAccount` | +| `creds/` | `pkg/creds` | `LoginDetails` | +| `provider/` | `pkg/provider` | Shared HTTP client | +| `provider/browser/` | `pkg/provider/browser` | `Browser` driver (Playwright) | +| `provider/googleapps/` | `pkg/provider/googleapps` | `GoogleApps` driver | +| `provider/okta/` | `pkg/provider/okta` | `Okta` driver | +| `provider/adfs/` | `pkg/provider/adfs` | `ADFS` driver | +| `prompter/`, `page/`, `cookiejar/`, `dump/`, `helper/credentials/` | same names under `pkg/` or `helper/` | Shared helpers used by the drivers | +| `mocks/` | `mocks` | Upstream mockery mocks used by the copied Okta and GoogleApps tests | + +## Changes from upstream + +- **Drivers:** only `Browser`, `GoogleApps`, `Okta` and `ADFS` are kept, which are the drivers the Atmos docs list. + Any other driver fails with `ErrUnsupportedProvider`, and the Atmos provider rejects it when that provider logs in + (not during config validation, so one stale provider does not break other identities). +- **Playwright:** the browser driver uses `github.com/mxschmitt/playwright-go` v0.6401.0 (the project's current + module path). That release no longer depends on `go-jose`. +- **Browser driver fixes** (`provider/browser/browser.go`): + - A timeout or error from `ExpectRequest` no longer dereferences a nil request (panic). + - A `PostData` error is returned instead of being swallowed by returning the wrong variable. + - The request callback and the caller no longer race on the captured data. + - An empty capture returns `ErrNoSAMLResponse` instead of an empty assertion. + - A sign-in request that reaches the `OnRequest` callback just before `ExpectRequest` starts listening is + used instead of waiting for the full timeout and failing. + - An invalid `browser_type` is rejected before Playwright is installed or started. + - The Playwright driver, the browser and the browser context are each released as soon as a later step + fails. Upstream released them only after the page was created, so a failed launch leaked the driver process. + - `playwright install` writes its progress to stderr instead of stdout, and installs only the browser that + is launched (Chromium without the headless shell for a headed browser, or Firefox or WebKit) instead of + every Playwright browser. System browser channels (`chrome`, `msedge`, ...) keep upstream's behavior. + - The storage-state path is built with `filepath.Join` and the Atmos `homedir` package, and its parent + directory is created with `0700` permissions before saving. +- **`cfg`:** the ini-file `ConfigManager` (`~/.saml2aws`) was removed. Atmos builds `IDPAccount` from `atmos.yaml`. + The unused `IDPAccount.DownloadBrowser` field was removed: nothing in the library read it (only the saml2aws CLI + did, through `SAML2AWS_AUTO_BROWSER_DOWNLOAD`). The browser driver installs browsers when + `creds.LoginDetails.DownloadBrowser` is set. +- **GoogleApps driver fixes** (`provider/googleapps/`): + - The captcha loop used the legacy `.captcha-img` container only as dead code (a `*goquery.Selection` is never + nil), so it always looked for `div[data-auto-init='CaptchaInput']`. The legacy container is used when present, + the new one is the fallback, and a missing or empty container returns an error instead of panicking. + - `mustFindInputByName` called `logger.Fatal` (process exit) for an input without a value. It is now + `findInputByName` and returns an error. + - A rejected new-style captcha answer is asked again. Upstream re-checked only `#ca`, but that input is + `name="ca"` with no id, so the flow gave up and failed. Captcha retries are capped at 5. + - The iTerm inline captcha image is written to stderr instead of stdout. + - `b64Safe` returns an error instead of panicking on invalid base64, and the U2F device is closed on that error. +- **Okta driver:** the Duo U2F touch prompts are written to stderr instead of stdout. The Duo trusted-endpoint + check skips certificate verification only when `certifier_url` is a loopback host (the local certifier uses a + self-signed certificate); upstream skipped it for any URL the Duo page named. +- **TLS:** every IdP transport (`provider.NewDefaultTransport`, ADFS, the Okta Duo certifier) sets + `MinVersion: tls.VersionTLS12` (`provider.MinTLSVersion`). TLS 1.3 is not required because many enterprise IdPs, + notably ADFS, still serve TLS 1.2 only, and ADFS relies on renegotiation, which TLS 1.3 removed. +- **ADFS driver:** unnamed inputs and a `SAMLResponse` without a value no longer call `log.Fatalf`, and the MFA loop + is limited: at most 5 one-time codes and 300 Azure MFA approval polls, then `ErrMFAAttemptsExceeded` is returned + instead of looping forever. +- **`provider/http.go`:** an `http_attempts_count` of `0` is clamped to one attempt (retry-go v3 ran nothing and + returned an empty error), invalid attempt and delay values are logged at debug level, and a client created with + nil options sends the request once instead of panicking. +- **Later review fixes:** + - `aws_role.go` keeps commas inside role names (a comma separates ARNs only before another `arn:`). + - `saml.go` matches the Attribute elements by namespace URI instead of the Assertion's prefix. + - `cookiejar` no longer decodes the default cookie path twice. + - `page.Form` puts GET form fields in the URL query, and no longer panics when the document has no URL. + - The `prompter` methods return errors (Ctrl+C or a missing terminal stops authentication instead of choosing + the first option or sending an empty code), pinentry returns scanner errors, and selecting a default alias + resets an earlier pinentry choice. + - `provider/http.go` resends the request body on retries, binds retry waits to the request context, and closes + the body of a response rejected by the status validator. + - ADFS resolves every relative form action against the login page URL. + - Browser: the storage state is saved through a private temporary file, and a captured SAMLResponse is not + replaced by a later request without one. + - Google Apps: locale parameters are set in the query, challenge selection pages are followed at most 10 times + per attempt, the MFA response document has a URL, headings are matched with whitespace normalized, and + malformed `data-challenge-ui` values no longer panic. + - Okta: both MFA polling loops stop after `mfaPollTimeout`, a failed Duo health report cancels the status request, + the Duo callback response is closed, and the next FIDO device is searched for with the `Auto` setting. +- **Tests:** browser tests use `go.uber.org/mock` mocks of a narrow `samlPage` interface instead of a real browser. + Real-browser tests are in `browser_integration_test.go` and only run with `RUN_PLAYWRIGHT_INTEGRATION=1`. + +## Updating + +Upstream is unmaintained, so there is nothing to sync. Treat this package as Atmos code: fix bugs here and add tests. +Keep the `Atmos fork:` comments when changing upstream behavior so the differences stay easy to find. diff --git a/pkg/auth/providers/aws/saml2aws/aws_role.go b/pkg/auth/providers/aws/saml2aws/aws_role.go new file mode 100644 index 00000000000..28a8ee0aad3 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/aws_role.go @@ -0,0 +1,89 @@ +package saml2aws + +import ( + "fmt" + "regexp" + "strings" +) + +// AWSRole aws role attributes +type AWSRole struct { + RoleARN string + PrincipalARN string + Name string +} + +// ParseAWSRoles parses and splits the roles while also validating the contents +func ParseAWSRoles(roles []string) ([]*AWSRole, error) { + awsRoles := make([]*AWSRole, len(roles)) + + for i, role := range roles { + awsRole, err := parseRole(role) + if err != nil { + return nil, err + } + + awsRoles[i] = awsRole + } + + return awsRoles, nil +} + +// arnPattern matches a complete ARN: arn:::::. +var arnPattern = regexp.MustCompile(`^arn:[^:\n]*:[^:\n]*:[^:\n]*:[^:\n]*:[^\n]+$`) + +// arnSeparator is the comma that separates two ARNs in a role attribute value. +var arnSeparator = regexp.MustCompile(`,\s*arn:`) + +// splitRoleARNs splits a "," role attribute value into its ARNs. +// +// Atmos fork: upstream treated every comma as an ARN boundary, so a role name containing a comma +// (which IAM permits) was silently truncated. A comma only separates ARNs when the next ARN starts after it. +func splitRoleARNs(role string) []string { + role = strings.TrimSpace(role) + var parts []string + start := 0 + for _, loc := range arnSeparator.FindAllStringIndex(role, -1) { + parts = append(parts, role[start:loc[0]]) + // Skip the comma and any whitespace; the next ARN begins at "arn:". + start = loc[0] + strings.Index(role[loc[0]:], "arn:") + } + parts = append(parts, role[start:]) + + tokens := make([]string, 0, len(parts)) + for _, part := range parts { + if part = strings.TrimSpace(part); arnPattern.MatchString(part) { + tokens = append(tokens, part) + } + } + return tokens +} + +func parseRole(role string) (*AWSRole, error) { + tokens := splitRoleARNs(role) + + if len(tokens) != 2 { + return nil, fmt.Errorf("invalid role string only %d tokens", len(tokens)) + } + + awsRole := &AWSRole{} + + for _, token := range tokens { + if strings.Contains(token, ":saml-provider") { + awsRole.PrincipalARN = strings.TrimSpace(token) + } + if strings.Contains(token, ":role") { + awsRole.RoleARN = strings.TrimSpace(token) + } + } + + if awsRole.PrincipalARN == "" { + return nil, fmt.Errorf("unable to locate PrincipalARN in: %s", role) + } + + if awsRole.RoleARN == "" { + return nil, fmt.Errorf("unable to locate RoleARN in: %s", role) + } + + return awsRole, nil +} diff --git a/pkg/auth/providers/aws/saml2aws/aws_role_test.go b/pkg/auth/providers/aws/saml2aws/aws_role_test.go new file mode 100644 index 00000000000..08708ba4fca --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/aws_role_test.go @@ -0,0 +1,93 @@ +package saml2aws + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseRoles(t *testing.T) { + roles := []string{ + "arn:aws:iam::456456456456:saml-provider/example-idp,arn:aws:iam::456456456456:role/admin", + "arn:aws:iam::456456456456:role/admin,arn:aws:iam::456456456456:saml-provider/example-idp", + } + + awsRoles, err := ParseAWSRoles(roles) + + assert.Nil(t, err) + assert.Len(t, awsRoles, 2) + + for _, awsRole := range awsRoles { + assert.Equal(t, "arn:aws:iam::456456456456:saml-provider/example-idp", awsRole.PrincipalARN) + assert.Equal(t, "arn:aws:iam::456456456456:role/admin", awsRole.RoleARN) + } + + roles = []string{""} + awsRoles, err = ParseAWSRoles(roles) + + assert.NotNil(t, err) + assert.Nil(t, awsRoles) +} + +func TestParseAWSRolesErrors(t *testing.T) { + tests := []struct { + name string + role string + wantErr string + }{ + { + name: "single token", + role: "arn:aws:iam::123456789012:role/admin", + wantErr: "invalid role string only 1 tokens", + }, + { + name: "three tokens", + role: "arn:aws:iam::1:role/a,arn:aws:iam::1:saml-provider/b,arn:aws:iam::1:role/c", + wantErr: "invalid role string only 3 tokens", + }, + { + name: "missing principal", + role: "arn:aws:iam::123456789012:role/admin,arn:aws:iam::123456789012:role/other", + wantErr: "unable to locate PrincipalARN", + }, + { + name: "missing role", + role: "arn:aws:iam::123456789012:saml-provider/a,arn:aws:iam::123456789012:saml-provider/b", + wantErr: "unable to locate RoleARN", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + roles, err := ParseAWSRoles([]string{tt.role}) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), tt.wantErr) + } + assert.Nil(t, roles) + }) + } +} + +func TestParseAWSRolesGovCloudAndWhitespace(t *testing.T) { + roles, err := ParseAWSRoles([]string{ + " arn:aws-us-gov:iam::123456789012:role/path/admin , arn:aws-us-gov:iam::123456789012:saml-provider/idp ", + }) + if assert.NoError(t, err) && assert.Len(t, roles, 1) { + assert.Equal(t, "arn:aws-us-gov:iam::123456789012:role/path/admin", roles[0].RoleARN) + assert.Equal(t, "arn:aws-us-gov:iam::123456789012:saml-provider/idp", roles[0].PrincipalARN) + } +} + +// Regression: IAM permits commas in role names, so a comma only separates ARNs when another ARN follows. +func TestParseAWSRolesCommaInRoleName(t *testing.T) { + for _, role := range []string{ + "arn:aws:iam::123456789012:role/admin,ops,arn:aws:iam::123456789012:saml-provider/idp", + "arn:aws:iam::123456789012:saml-provider/idp,arn:aws:iam::123456789012:role/admin,ops", + } { + roles, err := ParseAWSRoles([]string{role}) + if assert.NoError(t, err) && assert.Len(t, roles, 1) { + assert.Equal(t, "arn:aws:iam::123456789012:role/admin,ops", roles[0].RoleARN) + assert.Equal(t, "arn:aws:iam::123456789012:saml-provider/idp", roles[0].PrincipalARN) + } + } +} diff --git a/pkg/auth/providers/aws/saml2aws/cfg/cfg.go b/pkg/auth/providers/aws/saml2aws/cfg/cfg.go new file mode 100644 index 00000000000..31c70b67382 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cfg/cfg.go @@ -0,0 +1,124 @@ +package cfg + +import ( + "errors" + "fmt" + "net/url" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/prompter" +) + +// Atmos fork: the ini-file ConfigManager (SaveIDPAccount/LoadIDPAccount, ~/.saml2aws) was removed. +// Atmos builds IDPAccount values from atmos.yaml and never reads or writes the saml2aws config file. + +const ( + // DefaultAmazonWebservicesURN URN used when authenticating to aws using SAML + // NOTE: This only needs to be changed to log into GovCloud + DefaultAmazonWebservicesURN = "urn:amazon:webservices" + + // DefaultSessionDuration this is the default session duration which can be overridden in the AWS console + // see https://aws.amazon.com/blogs/security/enable-federated-api-access-to-your-aws-resources-for-up-to-12-hours-using-iam-roles/ + DefaultSessionDuration = 3600 + + // DefaultProfile this is the default profile name used to save the credentials in the aws cli + DefaultProfile = "saml" +) + +// IDPAccount saml IDP account +// +// Atmos fork: upstream's DownloadBrowser field was removed. Nothing in the library read it +// (only the saml2aws CLI did, through SAML2AWS_AUTO_BROWSER_DOWNLOAD); the browser driver +// installs browsers when creds.LoginDetails.DownloadBrowser is set. +type IDPAccount struct { + Name string + URL string + Username string + Provider string + BrowserType string // used by 'Browser' Provider + BrowserExecutablePath string // used by 'Browser' Provider + BrowserAutoFill bool // used by 'Browser' Provider + MFA string + SkipVerify bool + Timeout int + AmazonWebservicesURN string + SessionDuration int + Profile string + RoleARN string + PolicyFile string + PolicyARNs string + Region string + HttpAttemptsCount string + HttpRetryDelay string + CredentialsFile string + SAMLCache bool + SAMLCacheFile string + TargetURL string + DisableRememberDevice bool // used by Okta + DisableSessions bool // used by Okta + BrowserDriverDir string // used by browser; hide from user if not set + Headless bool // used by browser + Prompter string +} + +func (ia IDPAccount) String() string { + var oktaCfg string + if ia.Provider == "Okta" { + oktaCfg = fmt.Sprintf(` + DisableSessions: %v + DisableRememberDevice: %v`, ia.DisableSessions, ia.DisableRememberDevice) + } + + return fmt.Sprintf(`account {%s + URL: %s + Username: %s + Provider: %s + MFA: %s + SkipVerify: %v + AmazonWebservicesURN: %s + SessionDuration: %d + Profile: %s + RoleARN: %s + Region: %s +}`, oktaCfg, ia.URL, ia.Username, ia.Provider, ia.MFA, ia.SkipVerify, ia.AmazonWebservicesURN, ia.SessionDuration, ia.Profile, ia.RoleARN, ia.Region) +} + +// Validate validate the required / expected fields are set +func (ia *IDPAccount) Validate() error { + if ia.URL == "" { + return errors.New("URL empty in idp account") + } + + _, err := url.Parse(ia.URL) + if err != nil { + return errors.New("URL parse failed") + } + + if ia.Provider == "" { + return errors.New("provider empty in idp account") + } + + if ia.Provider != "Browser" { + if ia.MFA == "" { + return errors.New("MFA empty in idp account") + } + } + + if ia.Profile == "" { + return errors.New("profile empty in idp account") + } + + if err := prompter.ValidateAndSetPrompter(ia.Prompter); err != nil { + return err + } + + return nil +} + +// NewIDPAccount Create an idp account and fill in any default fields with sane values +func NewIDPAccount() *IDPAccount { + return &IDPAccount{ + AmazonWebservicesURN: DefaultAmazonWebservicesURN, + SessionDuration: DefaultSessionDuration, + Profile: DefaultProfile, + } +} diff --git a/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go b/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go new file mode 100644 index 00000000000..7ad4d8b9811 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go @@ -0,0 +1,75 @@ +package cfg + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// Atmos fork: the upstream ConfigManager tests were removed with the ini-file ConfigManager. + +func TestIDPAccountString(t *testing.T) { + idpAccount := NewIDPAccount() + idpAccount.URL = "https://id.whatever.com/#/hash" + idpAccount.Provider = "Okta" + idpAccount.DisableRememberDevice = true + + s := idpAccount.String() + require.Contains(t, s, "urn:amazon:webservices\n") + require.Contains(t, s, "URL: https://id.whatever.com/#/hash\n") + require.Contains(t, s, "DisableSessions: false\n") + require.Contains(t, s, "DisableRememberDevice: true\n") +} + +func TestIDPAccountStringNonOkta(t *testing.T) { + idpAccount := NewIDPAccount() + idpAccount.Provider = "Browser" + + require.NotContains(t, idpAccount.String(), "DisableSessions") +} + +func TestNewIDPAccountDefaults(t *testing.T) { + idpAccount := NewIDPAccount() + + require.Equal(t, DefaultAmazonWebservicesURN, idpAccount.AmazonWebservicesURN) + require.Equal(t, DefaultSessionDuration, idpAccount.SessionDuration) + require.Equal(t, DefaultProfile, idpAccount.Profile) +} + +func TestIDPAccountValidate(t *testing.T) { + valid := func() *IDPAccount { + a := NewIDPAccount() + a.URL = "https://id.example.com" + a.Provider = "Okta" + a.MFA = "Auto" + return a + } + + tests := []struct { + name string + mutate func(a *IDPAccount) + wantErr string + }{ + {name: "valid", mutate: func(*IDPAccount) {}}, + {name: "browser does not need MFA", mutate: func(a *IDPAccount) { a.Provider = "Browser"; a.MFA = "" }}, + {name: "missing URL", mutate: func(a *IDPAccount) { a.URL = "" }, wantErr: "URL empty"}, + {name: "unparseable URL", mutate: func(a *IDPAccount) { a.URL = "://bad" }, wantErr: "URL parse failed"}, + {name: "missing provider", mutate: func(a *IDPAccount) { a.Provider = "" }, wantErr: "provider empty"}, + {name: "missing MFA", mutate: func(a *IDPAccount) { a.MFA = "" }, wantErr: "MFA empty"}, + {name: "missing profile", mutate: func(a *IDPAccount) { a.Profile = "" }, wantErr: "profile empty"}, + {name: "invalid prompter", mutate: func(a *IDPAccount) { a.Prompter = "nope" }, wantErr: "is not valid"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a := valid() + tt.mutate(a) + err := a.Validate() + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go new file mode 100644 index 00000000000..4bc8d680a3f --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go @@ -0,0 +1,494 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. +package cookiejar + +import ( + "errors" + "fmt" + "net" + "net/http" + "net/url" + "sort" + "strings" + "sync" + "time" +) + +// PublicSuffixList provides the public suffix of a domain. For example: +// - the public suffix of "example.com" is "com", +// - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and +// - the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us". +// +// Implementations of PublicSuffixList must be safe for concurrent use by +// multiple goroutines. +// +// An implementation that always returns "" is valid and may be useful for +// testing but it is not secure: it means that the HTTP server for foo.com can +// set a cookie for bar.com. +// +// A public suffix list implementation is in the package +// golang.org/x/net/publicsuffix. +type PublicSuffixList interface { + // PublicSuffix returns the public suffix of domain. + // + // TODO: specify which of the caller and callee is responsible for IP + // addresses, for leading and trailing dots, for case sensitivity, and + // for IDN/Punycode. + PublicSuffix(domain string) string + + // String returns a description of the source of this public suffix + // list. The description will typically contain something like a time + // stamp or version number. + String() string +} + +// Options are the options for creating a new Jar. +type Options struct { + // PublicSuffixList is the public suffix list that determines whether + // an HTTP server can set a cookie for a domain. + // + // A nil value is valid and may be useful for testing but it is not + // secure: it means that the HTTP server for foo.co.uk can set a cookie + // for bar.co.uk. + PublicSuffixList PublicSuffixList +} + +// Jar implements the http.CookieJar interface from the net/http package. +type Jar struct { + psList PublicSuffixList + + // mu locks the remaining fields. + mu sync.Mutex + + // entries is a set of entries, keyed by their eTLD+1 and subkeyed by + // their name/domain/path. + entries map[string]map[string]entry + + // nextSeqNum is the next sequence number assigned to a new cookie + // created SetCookies. + nextSeqNum uint64 +} + +// New returns a new cookie jar. A nil *Options is equivalent to a zero +// Options. +func New(o *Options) (*Jar, error) { + jar := &Jar{ + entries: make(map[string]map[string]entry), + } + if o != nil { + jar.psList = o.PublicSuffixList + } + return jar, nil +} + +// entry is the internal representation of a cookie. +// +// This struct type is not used outside of this package per se, but the exported +// fields are those of RFC 6265. +type entry struct { + Name string + Value string + Domain string + Path string + Secure bool + HttpOnly bool + Persistent bool + HostOnly bool + Expires time.Time + Creation time.Time + LastAccess time.Time + + // seqNum is a sequence number so that Cookies returns cookies in a + // deterministic order, even for cookies that have equal Path length and + // equal Creation time. This simplifies testing. + seqNum uint64 +} + +// id returns the domain;path;name triple of e as an id. +func (e *entry) id() string { + return fmt.Sprintf("%s;%s;%s", e.Domain, e.Path, e.Name) +} + +// shouldSend determines whether e's cookie qualifies to be included in a +// request to host/path. It is the caller's responsibility to check if the +// cookie is expired. +func (e *entry) shouldSend(https bool, host, path string) bool { + return e.domainMatch(host) && e.pathMatch(path) && (https || !e.Secure) +} + +// domainMatch implements "domain-match" of RFC 6265 section 5.1.3. +func (e *entry) domainMatch(host string) bool { + if e.Domain == host { + return true + } + return !e.HostOnly && hasDotSuffix(host, e.Domain) +} + +// pathMatch implements "path-match" according to RFC 6265 section 5.1.4. +func (e *entry) pathMatch(requestPath string) bool { + if requestPath == e.Path { + return true + } + if strings.HasPrefix(requestPath, e.Path) { + if e.Path[len(e.Path)-1] == '/' { + return true // The "/any/" matches "/any/path" case. + } else if requestPath[len(e.Path)] == '/' { + return true // The "/any" matches "/any/path" case. + } + } + return false +} + +// hasDotSuffix reports whether s ends in "."+suffix. +func hasDotSuffix(s, suffix string) bool { + return len(s) > len(suffix) && s[len(s)-len(suffix)-1] == '.' && s[len(s)-len(suffix):] == suffix +} + +// Cookies implements the Cookies method of the http.CookieJar interface. +// +// It returns an empty slice if the URL's scheme is not HTTP or HTTPS. +func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie) { + return j.cookies(u, time.Now()) +} + +// cookies is like Cookies but takes the current time as a parameter. +func (j *Jar) cookies(u *url.URL, now time.Time) (cookies []*http.Cookie) { + if u.Scheme != "http" && u.Scheme != "https" { + return cookies + } + host, err := canonicalHost(u.Host) + if err != nil { + return cookies + } + key := jarKey(host, j.psList) + + j.mu.Lock() + defer j.mu.Unlock() + + submap := j.entries[key] + if submap == nil { + return cookies + } + + https := u.Scheme == "https" + path := u.Path + if path == "" { + path = "/" + } + + modified := false + var selected []entry + for id, e := range submap { + if e.Persistent && !e.Expires.After(now) { + delete(submap, id) + modified = true + continue + } + if !e.shouldSend(https, host, path) { + continue + } + e.LastAccess = now + submap[id] = e + selected = append(selected, e) + modified = true + } + if modified { + if len(submap) == 0 { + delete(j.entries, key) + } else { + j.entries[key] = submap + } + } + + // sort according to RFC 6265 section 5.4 point 2: by longest + // path and then by earliest creation time. + sort.Slice(selected, func(i, j int) bool { + s := selected + if len(s[i].Path) != len(s[j].Path) { + return len(s[i].Path) > len(s[j].Path) + } + if !s[i].Creation.Equal(s[j].Creation) { + return s[i].Creation.Before(s[j].Creation) + } + return s[i].seqNum < s[j].seqNum + }) + for _, e := range selected { + cookies = append(cookies, &http.Cookie{Name: e.Name, Value: e.Value}) //nolint:gosec // Outgoing request cookies only carry name and value; attributes apply to Set-Cookie. + } + + return cookies +} + +// SetCookies implements the SetCookies method of the http.CookieJar interface. +// +// It does nothing if the URL's scheme is not HTTP or HTTPS. +func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { + j.setCookies(u, cookies, time.Now()) +} + +// setCookies is like SetCookies but takes the current time as parameter. +func (j *Jar) setCookies(u *url.URL, cookies []*http.Cookie, now time.Time) { + if len(cookies) == 0 { + return + } + if u.Scheme != "http" && u.Scheme != "https" { + return + } + host, err := canonicalHost(u.Host) + if err != nil { + return + } + key := jarKey(host, j.psList) + defPath := defaultPath(u.Path) + + j.mu.Lock() + defer j.mu.Unlock() + + submap := j.entries[key] + + modified := false + for _, cookie := range cookies { + e, remove, err := j.newEntry(cookie, now, defPath, host) + if err != nil { + continue + } + id := e.id() + if remove { + if submap != nil { + if _, ok := submap[id]; ok { + delete(submap, id) + modified = true + } + } + continue + } + if submap == nil { + submap = make(map[string]entry) + } + + if old, ok := submap[id]; ok { + e.Creation = old.Creation + e.seqNum = old.seqNum + } else { + e.Creation = now + e.seqNum = j.nextSeqNum + j.nextSeqNum++ + } + e.LastAccess = now + submap[id] = e + modified = true + } + + if modified { + if len(submap) == 0 { + delete(j.entries, key) + } else { + j.entries[key] = submap + } + } +} + +// canonicalHost strips port from host if present and returns the canonicalized +// host name. +func canonicalHost(host string) (string, error) { + var err error + host = strings.ToLower(host) + if hasPort(host) { + host, _, err = net.SplitHostPort(host) + if err != nil { + return "", err + } + } + host = strings.TrimSuffix(host, ".") + return toASCII(host) +} + +// hasPort reports whether host contains a port number. host may be a host +// name, an IPv4 or an IPv6 address. +func hasPort(host string) bool { + colons := strings.Count(host, ":") + if colons == 0 { + return false + } + if colons == 1 { + return true + } + return host[0] == '[' && strings.Contains(host, "]:") +} + +// jarKey returns the key to use for a jar. +func jarKey(host string, psl PublicSuffixList) string { + if isIP(host) { + return host + } + + var i int + if psl == nil { + i = strings.LastIndex(host, ".") + if i <= 0 { + return host + } + } else { + suffix := psl.PublicSuffix(host) + if suffix == host { + return host + } + i = len(host) - len(suffix) + if i <= 0 || host[i-1] != '.' { + // The provided public suffix list psl is broken. + // Storing cookies under host is a safe stopgap. + return host + } + // Only len(suffix) is used to determine the jar key from + // here on, so it is okay if psl.PublicSuffix("www.buggy.psl") + // returns "com" as the jar key is generated from host. + } + prevDot := strings.LastIndex(host[:i-1], ".") + return host[prevDot+1:] +} + +// isIP reports whether host is an IP address. +func isIP(host string) bool { + return net.ParseIP(host) != nil +} + +// defaultPath returns the directory part of an URL's path according to +// RFC 6265 section 5.1.4. +func defaultPath(path string) string { + if len(path) == 0 || path[0] != '/' { + return "/" // Path is empty or malformed. + } + + i := strings.LastIndex(path, "/") // Path starts with "/", so i != -1. + if i == 0 { + return "/" // Path has the form "/abc". + } + // Atmos fork: url.URL.Path is already decoded, so decoding it again corrupted paths that contain an + // escaped percent sign (for example "/a%2520b" is "/a%20b" in URL.Path, not "/a b"). + return path[:i] // Path is either of form "/abc/xyz" or "/abc/xyz/". +} + +// newEntry creates an entry from a http.Cookie c. now is the current time and +// is compared to c.Expires to determine deletion of c. defPath and host are the +// default-path and the canonical host name of the URL c was received from. +// +// remove records whether the jar should delete this cookie, as it has already +// expired with respect to now. In this case, e may be incomplete, but it will +// be valid to call e.id (which depends on e's Name, Domain and Path). +// +// A malformed c.Domain will result in an error. +func (j *Jar) newEntry(c *http.Cookie, now time.Time, defPath, host string) (e entry, remove bool, err error) { + e.Name = c.Name + + if c.Path == "" || c.Path[0] != '/' { + e.Path = defPath + } else if path, err := url.PathUnescape(c.Path); err == nil { + e.Path = path + } else { + e.Path = c.Path + } + + e.Domain, e.HostOnly, err = j.domainAndType(host, c.Domain) + if err != nil { + return e, false, err + } + + // MaxAge takes precedence over Expires. + if c.MaxAge < 0 { + return e, true, nil + } else if c.MaxAge > 0 { + e.Expires = now.Add(time.Duration(c.MaxAge) * time.Second) + e.Persistent = true + } else { + if c.Expires.IsZero() { + e.Expires = endOfTime + e.Persistent = false + } else { + if !c.Expires.After(now) { + return e, true, nil + } + e.Expires = c.Expires + e.Persistent = true + } + } + + e.Value = c.Value + e.Secure = c.Secure + e.HttpOnly = c.HttpOnly + + return e, false, nil +} + +var ( + errIllegalDomain = errors.New("cookiejar: illegal cookie domain attribute") + errMalformedDomain = errors.New("cookiejar: malformed cookie domain attribute") + errNoHostname = errors.New("cookiejar: no host name available (IP only)") +) + +// endOfTime is the time when session (non-persistent) cookies expire. +// This instant is representable in most date/time formats (not just +// Go's time.Time) and should be far enough in the future. +var endOfTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) + +// domainAndType determines the cookie's domain and hostOnly attribute. +func (j *Jar) domainAndType(host, domain string) (string, bool, error) { + if domain == "" { + // No domain attribute in the SetCookie header indicates a + // host cookie. + return host, true, nil + } + + if isIP(host) { + // According to RFC 6265 domain-matching includes not being + // an IP address. + // TODO: This might be relaxed as in common browsers. + return "", false, errNoHostname + } + + // From here on: If the cookie is valid, it is a domain cookie (with + // the one exception of a public suffix below). + // See RFC 6265 section 5.2.3. + if domain[0] == '.' { + domain = domain[1:] + } + + if len(domain) == 0 || domain[0] == '.' { + // Received either "Domain=." or "Domain=..some.thing", + // both are illegal. + return "", false, errMalformedDomain + } + domain = strings.ToLower(domain) + + if domain[len(domain)-1] == '.' { + // We received stuff like "Domain=www.example.com.". + // Browsers do handle such stuff (actually differently) but + // RFC 6265 seems to be clear here (e.g. section 4.1.2.3) in + // requiring a reject. 4.1.2.3 is not normative, but + // "Domain Matching" (5.1.3) and "Canonicalized Host Names" + // (5.1.2) are. + return "", false, errMalformedDomain + } + + // See RFC 6265 section 5.3 #5. + if j.psList != nil { + if ps := j.psList.PublicSuffix(domain); ps != "" && !hasDotSuffix(domain, ps) { + if host == domain { + // This is the one exception in which a cookie + // with a domain attribute is a host cookie. + return host, true, nil + } + return "", false, errIllegalDomain + } + } + + // The domain must domain-match host: www.mycompany.com cannot + // set cookies for .ourcompetitors.com. + if host != domain && !hasDotSuffix(host, domain) { + return "", false, errIllegalDomain + } + + return domain, false, nil +} diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go new file mode 100644 index 00000000000..ab7d2755768 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go @@ -0,0 +1,1380 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cookiejar + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + "testing" + "time" +) + +// tNow is the synthetic current time used as now during testing. +var tNow = time.Date(2013, 1, 1, 12, 0, 0, 0, time.UTC) + +// testPSL implements PublicSuffixList with just two rules: "co.uk" +// and the default rule "*". +// The implementation has two intentional bugs: +// +// PublicSuffix("www.buggy.psl") == "xy" +// PublicSuffix("www2.buggy.psl") == "com" +type testPSL struct{} + +func (testPSL) String() string { + return "testPSL" +} + +func (testPSL) PublicSuffix(d string) string { + if d == "co.uk" || strings.HasSuffix(d, ".co.uk") { + return "co.uk" + } + if d == "www.buggy.psl" { + return "xy" + } + if d == "www2.buggy.psl" { + return "com" + } + return d[strings.LastIndex(d, ".")+1:] +} + +// newTestJar creates an empty Jar with testPSL as the public suffix list. +func newTestJar() *Jar { + jar, err := New(&Options{PublicSuffixList: testPSL{}}) + if err != nil { + panic(err) + } + return jar +} + +var hasDotSuffixTests = [...]struct { + s, suffix string +}{ + {"", ""}, + {"", "."}, + {"", "x"}, + {".", ""}, + {".", "."}, + {".", ".."}, + {".", "x"}, + {".", "x."}, + {".", ".x"}, + {".", ".x."}, + {"x", ""}, + {"x", "."}, + {"x", ".."}, + {"x", "x"}, + {"x", "x."}, + {"x", ".x"}, + {"x", ".x."}, + {".x", ""}, + {".x", "."}, + {".x", ".."}, + {".x", "x"}, + {".x", "x."}, + {".x", ".x"}, + {".x", ".x."}, + {"x.", ""}, + {"x.", "."}, + {"x.", ".."}, + {"x.", "x"}, + {"x.", "x."}, + {"x.", ".x"}, + {"x.", ".x."}, + {"com", ""}, + {"com", "m"}, + {"com", "om"}, + {"com", "com"}, + {"com", ".com"}, + {"com", "x.com"}, + {"com", "xcom"}, + {"com", "xorg"}, + {"com", "org"}, + {"com", "rg"}, + {"foo.com", ""}, + {"foo.com", "m"}, + {"foo.com", "om"}, + {"foo.com", "com"}, + {"foo.com", ".com"}, + {"foo.com", "o.com"}, + {"foo.com", "oo.com"}, + {"foo.com", "foo.com"}, + {"foo.com", ".foo.com"}, + {"foo.com", "x.foo.com"}, + {"foo.com", "xfoo.com"}, + {"foo.com", "xfoo.org"}, + {"foo.com", "foo.org"}, + {"foo.com", "oo.org"}, + {"foo.com", "o.org"}, + {"foo.com", ".org"}, + {"foo.com", "org"}, + {"foo.com", "rg"}, +} + +func TestHasDotSuffix(t *testing.T) { + for _, tc := range hasDotSuffixTests { + got := hasDotSuffix(tc.s, tc.suffix) + want := strings.HasSuffix(tc.s, "."+tc.suffix) + if got != want { + t.Errorf("s=%q, suffix=%q: got %v, want %v", tc.s, tc.suffix, got, want) + } + } +} + +var canonicalHostTests = map[string]string{ + "www.example.com": "www.example.com", + "WWW.EXAMPLE.COM": "www.example.com", + "wWw.eXAmple.CoM": "www.example.com", + "www.example.com:80": "www.example.com", + "192.168.0.10": "192.168.0.10", + "192.168.0.5:8080": "192.168.0.5", + "2001:4860:0:2001::68": "2001:4860:0:2001::68", + "[2001:4860:0:::68]:8080": "2001:4860:0:::68", + "www.bücher.de": "www.xn--bcher-kva.de", + "www.example.com.": "www.example.com", + // TODO: Fix canonicalHost so that all of the following malformed + // domain names trigger an error. (This list is not exhaustive, e.g. + // malformed internationalized domain names are missing.) + ".": "", + "..": ".", + "...": "..", + ".net": ".net", + ".net.": ".net", + "a..": "a.", + "b.a..": "b.a.", + "weird.stuff...": "weird.stuff..", + "[bad.unmatched.bracket:": "error", +} + +func TestCanonicalHost(t *testing.T) { + for h, want := range canonicalHostTests { + got, err := canonicalHost(h) + if want == "error" { + if err == nil { + t.Errorf("%q: got %q and nil error, want non-nil", h, got) + } + continue + } + if err != nil { + t.Errorf("%q: %v", h, err) + continue + } + if got != want { + t.Errorf("%q: got %q, want %q", h, got, want) + continue + } + } +} + +var hasPortTests = map[string]bool{ + "www.example.com": false, + "www.example.com:80": true, + "127.0.0.1": false, + "127.0.0.1:8080": true, + "2001:4860:0:2001::68": false, + "[2001::0:::68]:80": true, +} + +func TestHasPort(t *testing.T) { + for host, want := range hasPortTests { + if got := hasPort(host); got != want { + t.Errorf("%q: got %t, want %t", host, got, want) + } + } +} + +var jarKeyTests = map[string]string{ + "foo.www.example.com": "example.com", + "www.example.com": "example.com", + "example.com": "example.com", + "com": "com", + "foo.www.bbc.co.uk": "bbc.co.uk", + "www.bbc.co.uk": "bbc.co.uk", + "bbc.co.uk": "bbc.co.uk", + "co.uk": "co.uk", + "uk": "uk", + "192.168.0.5": "192.168.0.5", + "www.buggy.psl": "www.buggy.psl", + "www2.buggy.psl": "buggy.psl", + // The following are actual outputs of canonicalHost for + // malformed inputs to canonicalHost (see above). + "": "", + ".": ".", + "..": ".", + ".net": ".net", + "a.": "a.", + "b.a.": "a.", + "weird.stuff..": ".", +} + +func TestJarKey(t *testing.T) { + for host, want := range jarKeyTests { + if got := jarKey(host, testPSL{}); got != want { + t.Errorf("%q: got %q, want %q", host, got, want) + } + } +} + +var jarKeyNilPSLTests = map[string]string{ + "foo.www.example.com": "example.com", + "www.example.com": "example.com", + "example.com": "example.com", + "com": "com", + "foo.www.bbc.co.uk": "co.uk", + "www.bbc.co.uk": "co.uk", + "bbc.co.uk": "co.uk", + "co.uk": "co.uk", + "uk": "uk", + "192.168.0.5": "192.168.0.5", + // The following are actual outputs of canonicalHost for + // malformed inputs to canonicalHost. + "": "", + ".": ".", + "..": "..", + ".net": ".net", + "a.": "a.", + "b.a.": "a.", + "weird.stuff..": "stuff..", +} + +func TestJarKeyNilPSL(t *testing.T) { + for host, want := range jarKeyNilPSLTests { + if got := jarKey(host, nil); got != want { + t.Errorf("%q: got %q, want %q", host, got, want) + } + } +} + +var isIPTests = map[string]bool{ + "127.0.0.1": true, + "1.2.3.4": true, + "2001:4860:0:2001::68": true, + "example.com": false, + "1.1.1.300": false, + "www.foo.bar.net": false, + "123.foo.bar.net": false, +} + +func TestIsIP(t *testing.T) { + for host, want := range isIPTests { + if got := isIP(host); got != want { + t.Errorf("%q: got %t, want %t", host, got, want) + } + } +} + +var defaultPathTests = map[string]string{ + "/": "/", + "/abc": "/", + "/abc/": "/abc", + "/abc/xyz": "/abc", + "/abc/xyz/": "/abc/xyz", + "/a/b/c.html": "/a/b", + "": "/", + "strange": "/", + "//": "/", + "/a//b": "/a/", + "/a/./b": "/a/.", + "/a/../b": "/a/..", +} + +func TestDefaultPath(t *testing.T) { + for path, want := range defaultPathTests { + if got := defaultPath(path); got != want { + t.Errorf("%q: got %q, want %q", path, got, want) + } + } +} + +var domainAndTypeTests = [...]struct { + host string // host Set-Cookie header was received from + domain string // domain attribute in Set-Cookie header + wantDomain string // expected domain of cookie + wantHostOnly bool // expected host-cookie flag + wantErr error // expected error +}{ + {"www.example.com", "", "www.example.com", true, nil}, + {"127.0.0.1", "", "127.0.0.1", true, nil}, + {"2001:4860:0:2001::68", "", "2001:4860:0:2001::68", true, nil}, + {"www.example.com", "example.com", "example.com", false, nil}, + {"www.example.com", ".example.com", "example.com", false, nil}, + {"www.example.com", "www.example.com", "www.example.com", false, nil}, + {"www.example.com", ".www.example.com", "www.example.com", false, nil}, + {"foo.sso.example.com", "sso.example.com", "sso.example.com", false, nil}, + {"bar.co.uk", "bar.co.uk", "bar.co.uk", false, nil}, + {"foo.bar.co.uk", ".bar.co.uk", "bar.co.uk", false, nil}, + {"127.0.0.1", "127.0.0.1", "", false, errNoHostname}, + {"2001:4860:0:2001::68", "2001:4860:0:2001::68", "2001:4860:0:2001::68", false, errNoHostname}, + {"www.example.com", ".", "", false, errMalformedDomain}, + {"www.example.com", "..", "", false, errMalformedDomain}, + {"www.example.com", "other.com", "", false, errIllegalDomain}, + {"www.example.com", "com", "", false, errIllegalDomain}, + {"www.example.com", ".com", "", false, errIllegalDomain}, + {"foo.bar.co.uk", ".co.uk", "", false, errIllegalDomain}, + {"127.www.0.0.1", "127.0.0.1", "", false, errIllegalDomain}, + {"com", "", "com", true, nil}, + {"com", "com", "com", true, nil}, + {"com", ".com", "com", true, nil}, + {"co.uk", "", "co.uk", true, nil}, + {"co.uk", "co.uk", "co.uk", true, nil}, + {"co.uk", ".co.uk", "co.uk", true, nil}, +} + +func TestDomainAndType(t *testing.T) { + jar := newTestJar() + for _, tc := range domainAndTypeTests { + domain, hostOnly, err := jar.domainAndType(tc.host, tc.domain) + if !errors.Is(err, tc.wantErr) { + t.Errorf("%q/%q: got %q error, want %q", + tc.host, tc.domain, err, tc.wantErr) + continue + } + if err != nil { + continue + } + if domain != tc.wantDomain || hostOnly != tc.wantHostOnly { + t.Errorf("%q/%q: got %q/%t want %q/%t", + tc.host, tc.domain, domain, hostOnly, + tc.wantDomain, tc.wantHostOnly) + } + } +} + +// expiresIn creates an expires attribute delta seconds from tNow. +func expiresIn(delta int) string { + t := tNow.Add(time.Duration(delta) * time.Second) + return "expires=" + t.Format(time.RFC1123) +} + +// mustParseURL parses s to an URL and panics on error. +func mustParseURL(s string) *url.URL { + u, err := url.Parse(s) + if err != nil || u.Scheme == "" || u.Host == "" { + panic(fmt.Sprintf("Unable to parse URL %s.", s)) + } + return u +} + +// jarTest encapsulates the following actions on a jar: +// 1. Perform SetCookies with fromURL and the cookies from setCookies. +// (Done at time tNow + 0 ms.) +// 2. Check that the entries in the jar matches content. +// (Done at time tNow + 1001 ms.) +// 3. For each query in tests: Check that Cookies with toURL yields the +// cookies in want. +// (Query n done at tNow + (n+2)*1001 ms.) +type jarTest struct { + description string // The description of what this test is supposed to test + fromURL string // The full URL of the request from which Set-Cookie headers where received + setCookies []string // All the cookies received from fromURL + content string // The whole (non-expired) content of the jar + queries []query // Queries to test the Jar.Cookies method +} + +// query contains one test of the cookies returned from Jar.Cookies. +type query struct { + toURL string // the URL in the Cookies call + want string // the expected list of cookies (order matters) +} + +// run runs the jarTest. +func (test jarTest) run(t *testing.T, jar *Jar) { + now := tNow + + // Populate jar with cookies. + setCookies := make([]*http.Cookie, len(test.setCookies)) + for i, cs := range test.setCookies { + cookies := (&http.Response{Header: http.Header{"Set-Cookie": {cs}}}).Cookies() + if len(cookies) != 1 { + panic(fmt.Sprintf("Wrong cookie line %q: %#v", cs, cookies)) + } + setCookies[i] = cookies[0] + } + jar.setCookies(mustParseURL(test.fromURL), setCookies, now) + now = now.Add(1001 * time.Millisecond) + + // Serialize non-expired entries in the form "name1=val1 name2=val2". + var cs []string + for _, submap := range jar.entries { + for _, cookie := range submap { + if !cookie.Expires.After(now) { + continue + } + cs = append(cs, cookie.Name+"="+cookie.Value) + } + } + sort.Strings(cs) + got := strings.Join(cs, " ") + + // Make sure jar content matches our expectations. + if got != test.content { + t.Errorf("Test %q Content\ngot %q\nwant %q", + test.description, got, test.content) + } + + // Test different calls to Cookies. + for i, query := range test.queries { + now = now.Add(1001 * time.Millisecond) + var s []string + for _, c := range jar.cookies(mustParseURL(query.toURL), now) { + s = append(s, c.Name+"="+c.Value) + } + if got := strings.Join(s, " "); got != query.want { + t.Errorf("Test %q #%d\ngot %q\nwant %q", test.description, i, got, query.want) + } + } +} + +// basicsTests contains fundamental tests. Each jarTest has to be performed on +// a fresh, empty Jar. +var basicsTests = [...]jarTest{ + { + "Retrieval of a plain host cookie.", + "http://www.host.test/", + []string{"A=a"}, + "A=a", + []query{ + {"http://www.host.test", "A=a"}, + {"http://www.host.test/", "A=a"}, + {"http://www.host.test/some/path", "A=a"}, + {"https://www.host.test", "A=a"}, + {"https://www.host.test/", "A=a"}, + {"https://www.host.test/some/path", "A=a"}, + {"ftp://www.host.test", ""}, + {"ftp://www.host.test/", ""}, + {"ftp://www.host.test/some/path", ""}, + {"http://www.other.org", ""}, + {"http://sibling.host.test", ""}, + {"http://deep.www.host.test", ""}, + }, + }, + { + "Secure cookies are not returned to http.", + "http://www.host.test/", + []string{"A=a; secure"}, + "A=a", + []query{ + {"http://www.host.test", ""}, + {"http://www.host.test/", ""}, + {"http://www.host.test/some/path", ""}, + {"https://www.host.test", "A=a"}, + {"https://www.host.test/", "A=a"}, + {"https://www.host.test/some/path", "A=a"}, + }, + }, + { + "Explicit path.", + "http://www.host.test/", + []string{"A=a; path=/some/path"}, + "A=a", + []query{ + {"http://www.host.test", ""}, + {"http://www.host.test/", ""}, + {"http://www.host.test/some", ""}, + {"http://www.host.test/some/", ""}, + {"http://www.host.test/some/path", "A=a"}, + {"http://www.host.test/some/paths", ""}, + {"http://www.host.test/some/path/foo", "A=a"}, + {"http://www.host.test/some/path/foo/", "A=a"}, + }, + }, + { + "Implicit path #1: path is a directory.", + "http://www.host.test/some/path/", + []string{"A=a"}, + "A=a", + []query{ + {"http://www.host.test", ""}, + {"http://www.host.test/", ""}, + {"http://www.host.test/some", ""}, + {"http://www.host.test/some/", ""}, + {"http://www.host.test/some/path", "A=a"}, + {"http://www.host.test/some/paths", ""}, + {"http://www.host.test/some/path/foo", "A=a"}, + {"http://www.host.test/some/path/foo/", "A=a"}, + }, + }, + { + "Implicit path #2: path is not a directory.", + "http://www.host.test/some/path/index.html", + []string{"A=a"}, + "A=a", + []query{ + {"http://www.host.test", ""}, + {"http://www.host.test/", ""}, + {"http://www.host.test/some", ""}, + {"http://www.host.test/some/", ""}, + {"http://www.host.test/some/path", "A=a"}, + {"http://www.host.test/some/paths", ""}, + {"http://www.host.test/some/path/foo", "A=a"}, + {"http://www.host.test/some/path/foo/", "A=a"}, + }, + }, + { + "Implicit path #3: no path in URL at all.", + "http://www.host.test", + []string{"A=a"}, + "A=a", + []query{ + {"http://www.host.test", "A=a"}, + {"http://www.host.test/", "A=a"}, + {"http://www.host.test/some/path", "A=a"}, + }, + }, + { + "Cookies are sorted by path length.", + "http://www.host.test/", + []string{ + "A=a; path=/foo/bar", + "B=b; path=/foo/bar/baz/qux", + "C=c; path=/foo/bar/baz", + "D=d; path=/foo", + }, + "A=a B=b C=c D=d", + []query{ + {"http://www.host.test/foo/bar/baz/qux", "B=b C=c A=a D=d"}, + {"http://www.host.test/foo/bar/baz/", "C=c A=a D=d"}, + {"http://www.host.test/foo/bar", "A=a D=d"}, + }, + }, + { + "Creation time determines sorting on same length paths.", + "http://www.host.test/", + []string{ + "A=a; path=/foo/bar", + "X=x; path=/foo/bar", + "Y=y; path=/foo/bar/baz/qux", + "B=b; path=/foo/bar/baz/qux", + "C=c; path=/foo/bar/baz", + "W=w; path=/foo/bar/baz", + "Z=z; path=/foo", + "D=d; path=/foo", + }, + "A=a B=b C=c D=d W=w X=x Y=y Z=z", + []query{ + {"http://www.host.test/foo/bar/baz/qux", "Y=y B=b C=c W=w A=a X=x Z=z D=d"}, + {"http://www.host.test/foo/bar/baz/", "C=c W=w A=a X=x Z=z D=d"}, + {"http://www.host.test/foo/bar", "A=a X=x Z=z D=d"}, + }, + }, + { + "Sorting of same-name cookies.", + "http://www.host.test/", + []string{ + "A=1; path=/", + "A=2; path=/path", + "A=3; path=/quux", + "A=4; path=/path/foo", + "A=5; domain=.host.test; path=/path", + "A=6; domain=.host.test; path=/quux", + "A=7; domain=.host.test; path=/path/foo", + }, + "A=1 A=2 A=3 A=4 A=5 A=6 A=7", + []query{ + {"http://www.host.test/path", "A=2 A=5 A=1"}, + {"http://www.host.test/path/foo", "A=4 A=7 A=2 A=5 A=1"}, + }, + }, + { + "Disallow domain cookie on public suffix.", + "http://www.bbc.co.uk", + []string{ + "a=1", + "b=2; domain=co.uk", + }, + "a=1", + []query{{"http://www.bbc.co.uk", "a=1"}}, + }, + { + "Host cookie on IP.", + "http://192.168.0.10", + []string{"a=1"}, + "a=1", + []query{{"http://192.168.0.10", "a=1"}}, + }, + { + "Port is ignored #1.", + "http://www.host.test/", + []string{"a=1"}, + "a=1", + []query{ + {"http://www.host.test", "a=1"}, + {"http://www.host.test:8080/", "a=1"}, + }, + }, + { + "Port is ignored #2.", + "http://www.host.test:8080/", + []string{"a=1"}, + "a=1", + []query{ + {"http://www.host.test", "a=1"}, + {"http://www.host.test:8080/", "a=1"}, + {"http://www.host.test:1234/", "a=1"}, + }, + }, +} + +func TestBasics(t *testing.T) { + for _, test := range basicsTests { + jar := newTestJar() + test.run(t, jar) + } +} + +// updateAndDeleteTests contains jarTests which must be performed on the same +// Jar. +var updateAndDeleteTests = [...]jarTest{ + { + "Set initial cookies.", + "http://www.host.test", + []string{ + "a=1", + "b=2; secure", + "c=3; httponly", + "d=4; secure; httponly", + }, + "a=1 b=2 c=3 d=4", + []query{ + {"http://www.host.test", "a=1 c=3"}, + {"https://www.host.test", "a=1 b=2 c=3 d=4"}, + }, + }, + { + "Update value via http.", + "http://www.host.test", + []string{ + "a=w", + "b=x; secure", + "c=y; httponly", + "d=z; secure; httponly", + }, + "a=w b=x c=y d=z", + []query{ + {"http://www.host.test", "a=w c=y"}, + {"https://www.host.test", "a=w b=x c=y d=z"}, + }, + }, + { + "Clear Secure flag from a http.", + "http://www.host.test/", + []string{ + "b=xx", + "d=zz; httponly", + }, + "a=w b=xx c=y d=zz", + []query{{"http://www.host.test", "a=w b=xx c=y d=zz"}}, + }, + { + "Delete all.", + "http://www.host.test/", + []string{ + "a=1; max-Age=-1", // delete via MaxAge + "b=2; " + expiresIn(-10), // delete via Expires + "c=2; max-age=-1; " + expiresIn(-10), // delete via both + "d=4; max-age=-1; " + expiresIn(10), + }, // MaxAge takes precedence + "", + []query{{"http://www.host.test", ""}}, + }, + { + "Refill #1.", + "http://www.host.test", + []string{ + "A=1", + "A=2; path=/foo", + "A=3; domain=.host.test", + "A=4; path=/foo; domain=.host.test", + }, + "A=1 A=2 A=3 A=4", + []query{{"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}}, + }, + { + "Refill #2.", + "http://www.google.com", + []string{ + "A=6", + "A=7; path=/foo", + "A=8; domain=.google.com", + "A=9; path=/foo; domain=.google.com", + }, + "A=1 A=2 A=3 A=4 A=6 A=7 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}, + {"http://www.google.com/foo", "A=7 A=9 A=6 A=8"}, + }, + }, + { + "Delete A7.", + "http://www.google.com", + []string{"A=; path=/foo; max-age=-1"}, + "A=1 A=2 A=3 A=4 A=6 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}, + {"http://www.google.com/foo", "A=9 A=6 A=8"}, + }, + }, + { + "Delete A4.", + "http://www.host.test", + []string{"A=; path=/foo; domain=host.test; max-age=-1"}, + "A=1 A=2 A=3 A=6 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=1 A=3"}, + {"http://www.google.com/foo", "A=9 A=6 A=8"}, + }, + }, + { + "Delete A6.", + "http://www.google.com", + []string{"A=; max-age=-1"}, + "A=1 A=2 A=3 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=1 A=3"}, + {"http://www.google.com/foo", "A=9 A=8"}, + }, + }, + { + "Delete A3.", + "http://www.host.test", + []string{"A=; domain=host.test; max-age=-1"}, + "A=1 A=2 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=1"}, + {"http://www.google.com/foo", "A=9 A=8"}, + }, + }, + { + "No cross-domain delete.", + "http://www.host.test", + []string{ + "A=; domain=google.com; max-age=-1", + "A=; path=/foo; domain=google.com; max-age=-1", + }, + "A=1 A=2 A=8 A=9", + []query{ + {"http://www.host.test/foo", "A=2 A=1"}, + {"http://www.google.com/foo", "A=9 A=8"}, + }, + }, + { + "Delete A8 and A9.", + "http://www.google.com", + []string{ + "A=; domain=google.com; max-age=-1", + "A=; path=/foo; domain=google.com; max-age=-1", + }, + "A=1 A=2", + []query{ + {"http://www.host.test/foo", "A=2 A=1"}, + {"http://www.google.com/foo", ""}, + }, + }, +} + +func TestUpdateAndDelete(t *testing.T) { + jar := newTestJar() + for _, test := range updateAndDeleteTests { + test.run(t, jar) + } +} + +func TestExpiration(t *testing.T) { + jar := newTestJar() + jarTest{ + "Expiration.", + "http://www.host.test", + []string{ + "a=1", + "b=2; max-age=3", + "c=3; " + expiresIn(3), + "d=4; max-age=5", + "e=5; " + expiresIn(5), + "f=6; max-age=100", + }, + "a=1 b=2 c=3 d=4 e=5 f=6", // executed at t0 + 1001 ms + []query{ + {"http://www.host.test", "a=1 b=2 c=3 d=4 e=5 f=6"}, // t0 + 2002 ms + {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 3003 ms + {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 4004 ms + {"http://www.host.test", "a=1 f=6"}, // t0 + 5005 ms + {"http://www.host.test", "a=1 f=6"}, // t0 + 6006 ms + }, + }.run(t, jar) +} + +// +// Tests derived from Chromium's cookie_store_unittest.h. +// + +// See http://src.chromium.org/viewvc/chrome/trunk/src/net/cookies/cookie_store_unittest.h?revision=159685&content-type=text/plain +// Some of the original tests are in a bad condition (e.g. +// DomainWithTrailingDotTest) or are not RFC 6265 conforming (e.g. +// TestNonDottedAndTLD #1 and #6) and have not been ported. + +// chromiumBasicsTests contains fundamental tests. Each jarTest has to be +// performed on a fresh, empty Jar. +var chromiumBasicsTests = [...]jarTest{ + { + "DomainWithTrailingDotTest.", + "http://www.google.com/", + []string{ + "a=1; domain=.www.google.com.", + "b=2; domain=.www.google.com..", + }, + "", + []query{ + {"http://www.google.com", ""}, + }, + }, + { + "ValidSubdomainTest #1.", + "http://a.b.c.d.com", + []string{ + "a=1; domain=.a.b.c.d.com", + "b=2; domain=.b.c.d.com", + "c=3; domain=.c.d.com", + "d=4; domain=.d.com", + }, + "a=1 b=2 c=3 d=4", + []query{ + {"http://a.b.c.d.com", "a=1 b=2 c=3 d=4"}, + {"http://b.c.d.com", "b=2 c=3 d=4"}, + {"http://c.d.com", "c=3 d=4"}, + {"http://d.com", "d=4"}, + }, + }, + { + "ValidSubdomainTest #2.", + "http://a.b.c.d.com", + []string{ + "a=1; domain=.a.b.c.d.com", + "b=2; domain=.b.c.d.com", + "c=3; domain=.c.d.com", + "d=4; domain=.d.com", + "X=bcd; domain=.b.c.d.com", + "X=cd; domain=.c.d.com", + }, + "X=bcd X=cd a=1 b=2 c=3 d=4", + []query{ + {"http://b.c.d.com", "b=2 c=3 d=4 X=bcd X=cd"}, + {"http://c.d.com", "c=3 d=4 X=cd"}, + }, + }, + { + "InvalidDomainTest #1.", + "http://foo.bar.com", + []string{ + "a=1; domain=.yo.foo.bar.com", + "b=2; domain=.foo.com", + "c=3; domain=.bar.foo.com", + "d=4; domain=.foo.bar.com.net", + "e=5; domain=ar.com", + "f=6; domain=.", + "g=7; domain=/", + "h=8; domain=http://foo.bar.com", + "i=9; domain=..foo.bar.com", + "j=10; domain=..bar.com", + "k=11; domain=.foo.bar.com?blah", + "l=12; domain=.foo.bar.com/blah", + "m=12; domain=.foo.bar.com:80", + "n=14; domain=.foo.bar.com:", + "o=15; domain=.foo.bar.com#sup", + }, + "", // Jar is empty. + []query{{"http://foo.bar.com", ""}}, + }, + { + "InvalidDomainTest #2.", + "http://foo.com.com", + []string{"a=1; domain=.foo.com.com.com"}, + "", + []query{{"http://foo.bar.com", ""}}, + }, + { + "DomainWithoutLeadingDotTest #1.", + "http://manage.hosted.filefront.com", + []string{"a=1; domain=filefront.com"}, + "a=1", + []query{{"http://www.filefront.com", "a=1"}}, + }, + { + "DomainWithoutLeadingDotTest #2.", + "http://www.google.com", + []string{"a=1; domain=www.google.com"}, + "a=1", + []query{ + {"http://www.google.com", "a=1"}, + {"http://sub.www.google.com", "a=1"}, + {"http://something-else.com", ""}, + }, + }, + { + "CaseInsensitiveDomainTest.", + "http://www.google.com", + []string{ + "a=1; domain=.GOOGLE.COM", + "b=2; domain=.www.gOOgLE.coM", + }, + "a=1 b=2", + []query{{"http://www.google.com", "a=1 b=2"}}, + }, + { + "TestIpAddress #1.", + "http://1.2.3.4/foo", + []string{"a=1; path=/"}, + "a=1", + []query{{"http://1.2.3.4/foo", "a=1"}}, + }, + { + "TestIpAddress #2.", + "http://1.2.3.4/foo", + []string{ + "a=1; domain=.1.2.3.4", + "b=2; domain=.3.4", + }, + "", + []query{{"http://1.2.3.4/foo", ""}}, + }, + { + "TestIpAddress #3.", + "http://1.2.3.4/foo", + []string{"a=1; domain=1.2.3.4"}, + "", + []query{{"http://1.2.3.4/foo", ""}}, + }, + { + "TestNonDottedAndTLD #2.", + "http://com./index.html", + []string{"a=1"}, + "a=1", + []query{ + {"http://com./index.html", "a=1"}, + {"http://no-cookies.com./index.html", ""}, + }, + }, + { + "TestNonDottedAndTLD #3.", + "http://a.b", + []string{ + "a=1; domain=.b", + "b=2; domain=b", + }, + "", + []query{{"http://bar.foo", ""}}, + }, + { + "TestNonDottedAndTLD #4.", + "http://google.com", + []string{ + "a=1; domain=.com", + "b=2; domain=com", + }, + "", + []query{{"http://google.com", ""}}, + }, + { + "TestNonDottedAndTLD #5.", + "http://google.co.uk", + []string{ + "a=1; domain=.co.uk", + "b=2; domain=.uk", + }, + "", + []query{ + {"http://google.co.uk", ""}, + {"http://else.co.com", ""}, + {"http://else.uk", ""}, + }, + }, + { + "TestHostEndsWithDot.", + "http://www.google.com", + []string{ + "a=1", + "b=2; domain=.www.google.com.", + }, + "a=1", + []query{{"http://www.google.com", "a=1"}}, + }, + { + "PathTest", + "http://www.google.izzle", + []string{"a=1; path=/wee"}, + "a=1", + []query{ + {"http://www.google.izzle/wee", "a=1"}, + {"http://www.google.izzle/wee/", "a=1"}, + {"http://www.google.izzle/wee/war", "a=1"}, + {"http://www.google.izzle/wee/war/more/more", "a=1"}, + {"http://www.google.izzle/weehee", ""}, + {"http://www.google.izzle/", ""}, + }, + }, +} + +func TestChromiumBasics(t *testing.T) { + for _, test := range chromiumBasicsTests { + jar := newTestJar() + test.run(t, jar) + } +} + +// chromiumDomainTests contains jarTests which must be executed all on the +// same Jar. +var chromiumDomainTests = [...]jarTest{ + { + "Fill #1.", + "http://www.google.izzle", + []string{"A=B"}, + "A=B", + []query{{"http://www.google.izzle", "A=B"}}, + }, + { + "Fill #2.", + "http://www.google.izzle", + []string{"C=D; domain=.google.izzle"}, + "A=B C=D", + []query{{"http://www.google.izzle", "A=B C=D"}}, + }, + { + "Verify A is a host cookie and not accessible from subdomain.", + "http://unused.nil", + []string{}, + "A=B C=D", + []query{{"http://foo.www.google.izzle", "C=D"}}, + }, + { + "Verify domain cookies are found on proper domain.", + "http://www.google.izzle", + []string{"E=F; domain=.www.google.izzle"}, + "A=B C=D E=F", + []query{{"http://www.google.izzle", "A=B C=D E=F"}}, + }, + { + "Leading dots in domain attributes are optional.", + "http://www.google.izzle", + []string{"G=H; domain=www.google.izzle"}, + "A=B C=D E=F G=H", + []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}}, + }, + { + "Verify domain enforcement works #1.", + "http://www.google.izzle", + []string{"K=L; domain=.bar.www.google.izzle"}, + "A=B C=D E=F G=H", + []query{{"http://bar.www.google.izzle", "C=D E=F G=H"}}, + }, + { + "Verify domain enforcement works #2.", + "http://unused.nil", + []string{}, + "A=B C=D E=F G=H", + []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}}, + }, +} + +func TestChromiumDomain(t *testing.T) { + jar := newTestJar() + for _, test := range chromiumDomainTests { + test.run(t, jar) + } +} + +// chromiumDeletionTests must be performed all on the same Jar. +var chromiumDeletionTests = [...]jarTest{ + { + "Create session cookie a1.", + "http://www.google.com", + []string{"a=1"}, + "a=1", + []query{{"http://www.google.com", "a=1"}}, + }, + { + "Delete sc a1 via MaxAge.", + "http://www.google.com", + []string{"a=1; max-age=-1"}, + "", + []query{{"http://www.google.com", ""}}, + }, + { + "Create session cookie b2.", + "http://www.google.com", + []string{"b=2"}, + "b=2", + []query{{"http://www.google.com", "b=2"}}, + }, + { + "Delete sc b2 via Expires.", + "http://www.google.com", + []string{"b=2; " + expiresIn(-10)}, + "", + []query{{"http://www.google.com", ""}}, + }, + { + "Create persistent cookie c3.", + "http://www.google.com", + []string{"c=3; max-age=3600"}, + "c=3", + []query{{"http://www.google.com", "c=3"}}, + }, + { + "Delete pc c3 via MaxAge.", + "http://www.google.com", + []string{"c=3; max-age=-1"}, + "", + []query{{"http://www.google.com", ""}}, + }, + { + "Create persistent cookie d4.", + "http://www.google.com", + []string{"d=4; max-age=3600"}, + "d=4", + []query{{"http://www.google.com", "d=4"}}, + }, + { + "Delete pc d4 via Expires.", + "http://www.google.com", + []string{"d=4; " + expiresIn(-10)}, + "", + []query{{"http://www.google.com", ""}}, + }, +} + +func TestChromiumDeletion(t *testing.T) { + jar := newTestJar() + for _, test := range chromiumDeletionTests { + test.run(t, jar) + } +} + +// domainHandlingTests tests and documents the rules for domain handling. +// Each test must be performed on an empty new Jar. +var domainHandlingTests = [...]jarTest{ + { + "Host cookie", + "http://www.host.test", + []string{"a=1"}, + "a=1", + []query{ + {"http://www.host.test", "a=1"}, + {"http://host.test", ""}, + {"http://bar.host.test", ""}, + {"http://foo.www.host.test", ""}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Domain cookie #1", + "http://www.host.test", + []string{"a=1; domain=host.test"}, + "a=1", + []query{ + {"http://www.host.test", "a=1"}, + {"http://host.test", "a=1"}, + {"http://bar.host.test", "a=1"}, + {"http://foo.www.host.test", "a=1"}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Domain cookie #2", + "http://www.host.test", + []string{"a=1; domain=.host.test"}, + "a=1", + []query{ + {"http://www.host.test", "a=1"}, + {"http://host.test", "a=1"}, + {"http://bar.host.test", "a=1"}, + {"http://foo.www.host.test", "a=1"}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Host cookie on IDNA domain #1", + "http://www.bücher.test", + []string{"a=1"}, + "a=1", + []query{ + {"http://www.bücher.test", "a=1"}, + {"http://www.xn--bcher-kva.test", "a=1"}, + {"http://bücher.test", ""}, + {"http://xn--bcher-kva.test", ""}, + {"http://bar.bücher.test", ""}, + {"http://bar.xn--bcher-kva.test", ""}, + {"http://foo.www.bücher.test", ""}, + {"http://foo.www.xn--bcher-kva.test", ""}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Host cookie on IDNA domain #2", + "http://www.xn--bcher-kva.test", + []string{"a=1"}, + "a=1", + []query{ + {"http://www.bücher.test", "a=1"}, + {"http://www.xn--bcher-kva.test", "a=1"}, + {"http://bücher.test", ""}, + {"http://xn--bcher-kva.test", ""}, + {"http://bar.bücher.test", ""}, + {"http://bar.xn--bcher-kva.test", ""}, + {"http://foo.www.bücher.test", ""}, + {"http://foo.www.xn--bcher-kva.test", ""}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Domain cookie on IDNA domain #1", + "http://www.bücher.test", + []string{"a=1; domain=xn--bcher-kva.test"}, + "a=1", + []query{ + {"http://www.bücher.test", "a=1"}, + {"http://www.xn--bcher-kva.test", "a=1"}, + {"http://bücher.test", "a=1"}, + {"http://xn--bcher-kva.test", "a=1"}, + {"http://bar.bücher.test", "a=1"}, + {"http://bar.xn--bcher-kva.test", "a=1"}, + {"http://foo.www.bücher.test", "a=1"}, + {"http://foo.www.xn--bcher-kva.test", "a=1"}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Domain cookie on IDNA domain #2", + "http://www.xn--bcher-kva.test", + []string{"a=1; domain=xn--bcher-kva.test"}, + "a=1", + []query{ + {"http://www.bücher.test", "a=1"}, + {"http://www.xn--bcher-kva.test", "a=1"}, + {"http://bücher.test", "a=1"}, + {"http://xn--bcher-kva.test", "a=1"}, + {"http://bar.bücher.test", "a=1"}, + {"http://bar.xn--bcher-kva.test", "a=1"}, + {"http://foo.www.bücher.test", "a=1"}, + {"http://foo.www.xn--bcher-kva.test", "a=1"}, + {"http://other.test", ""}, + {"http://test", ""}, + }, + }, + { + "Host cookie on TLD.", + "http://com", + []string{"a=1"}, + "a=1", + []query{ + {"http://com", "a=1"}, + {"http://any.com", ""}, + {"http://any.test", ""}, + }, + }, + { + "Domain cookie on TLD becomes a host cookie.", + "http://com", + []string{"a=1; domain=com"}, + "a=1", + []query{ + {"http://com", "a=1"}, + {"http://any.com", ""}, + {"http://any.test", ""}, + }, + }, + { + "Host cookie on public suffix.", + "http://co.uk", + []string{"a=1"}, + "a=1", + []query{ + {"http://co.uk", "a=1"}, + {"http://uk", ""}, + {"http://some.co.uk", ""}, + {"http://foo.some.co.uk", ""}, + {"http://any.uk", ""}, + }, + }, + { + "Domain cookie on public suffix is ignored.", + "http://some.co.uk", + []string{"a=1; domain=co.uk"}, + "", + []query{ + {"http://co.uk", ""}, + {"http://uk", ""}, + {"http://some.co.uk", ""}, + {"http://foo.some.co.uk", ""}, + {"http://any.uk", ""}, + }, + }, +} + +func TestDomainHandling(t *testing.T) { + for _, test := range domainHandlingTests { + jar := newTestJar() + test.run(t, jar) + } +} + +func TestIssue19384(t *testing.T) { + cookies := []*http.Cookie{{Name: "name", Value: "value"}} + for _, host := range []string{"", ".", "..", "..."} { + jar, _ := New(nil) + u := &url.URL{Scheme: "http", Host: host, Path: "/"} + if got := jar.Cookies(u); len(got) != 0 { + t.Errorf("host %q, got %v", host, got) + } + jar.SetCookies(u, cookies) + if got := jar.Cookies(u); len(got) != 1 || got[0].Value != "value" { + t.Errorf("host %q, got %v", host, got) + } + } +} + +func TestIssue26247(t *testing.T) { + cookies := []*http.Cookie{{Name: "name", Value: "value", Path: "/a%20path"}} + jar, _ := New(nil) + u := &url.URL{Scheme: "http", Host: "example.com"} + jar.SetCookies(u, cookies) + for _, path := range []string{"", "/", "/a", "/a/path", "/a/path/", "/a/path/here"} { + u.Path = path + if got := jar.Cookies(u); len(got) != 0 { + t.Errorf("path %q, got %v", path, got) + } + } + for _, path := range []string{"/a path", "/a path/", "/a path/here"} { + u.Path = path + if got := jar.Cookies(u); len(got) != 1 { + t.Errorf("path %q, got %v", path, got) + } + } +} + +// Regression: the default cookie path must not be percent-decoded a second time, or a cookie set +// without a Path is not returned for its originating URL. +func TestDefaultPathNotDoubleDecoded(t *testing.T) { + if got, want := defaultPath("/a%20b/login"), "/a%20b"; got != want { + t.Errorf("defaultPath: got %q, want %q", got, want) + } + + jar := newTestJar() + u, err := url.Parse("https://idp.example.com/a%2520b/login") + if err != nil { + t.Fatal(err) + } + jar.SetCookies(u, []*http.Cookie{{Name: "sid", Value: "1"}}) + if got := jar.Cookies(u); len(got) != 1 || got[0].Name != "sid" { + t.Errorf("Cookies(%v) = %v, want the sid cookie", u, got) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go b/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go new file mode 100644 index 00000000000..0b70e0fe45a --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go @@ -0,0 +1,159 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cookiejar + +// This file implements the Punycode algorithm from RFC 3492. + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +// These parameter values are specified in section 5. +// +// All computation is done with int32s, so that overflow behavior is identical +// regardless of whether int is 32-bit or 64-bit. +const ( + base int32 = 36 + damp int32 = 700 + initialBias int32 = 72 + initialN int32 = 128 + skew int32 = 38 + tmax int32 = 26 + tmin int32 = 1 +) + +// encode encodes a string as specified in section 6.3 and prepends prefix to +// the result. +// +// The "while h < length(input)" line in the specification becomes "for +// remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes. +func encode(prefix, s string) (string, error) { + output := make([]byte, len(prefix), len(prefix)+1+2*len(s)) + copy(output, prefix) + delta, n, bias := int32(0), initialN, initialBias + b, remaining := int32(0), int32(0) + for _, r := range s { + if r < utf8.RuneSelf { + b++ + output = append(output, byte(r)) //nolint:gosec // r < utf8.RuneSelf, so it fits in a byte. + } else { + remaining++ + } + } + h := b + if b > 0 { + output = append(output, '-') + } + for remaining != 0 { + m := int32(0x7fffffff) + for _, r := range s { + if m > r && r >= n { + m = r + } + } + delta += (m - n) * (h + 1) + if delta < 0 { + return "", fmt.Errorf("cookiejar: invalid label %q", s) + } + n = m + for _, r := range s { + if r < n { + delta++ + if delta < 0 { + return "", fmt.Errorf("cookiejar: invalid label %q", s) + } + continue + } + if r > n { + continue + } + q := delta + for k := base; ; k += base { + t := k - bias + if t < tmin { + t = tmin + } else if t > tmax { + t = tmax + } + if q < t { + break + } + output = append(output, encodeDigit(t+(q-t)%(base-t))) + q = (q - t) / (base - t) + } + output = append(output, encodeDigit(q)) + bias = adapt(delta, h+1, h == b) + delta = 0 + h++ + remaining-- + } + delta++ + n++ + } + return string(output), nil +} + +func encodeDigit(digit int32) byte { + switch { + case 0 <= digit && digit < 26: + return byte(digit + 'a') + case 26 <= digit && digit < 36: + return byte(digit + ('0' - 26)) + } + panic("cookiejar: internal error in punycode encoding") +} + +// adapt is the bias adaptation function specified in section 6.1. +func adapt(delta, numPoints int32, firstTime bool) int32 { + if firstTime { + delta /= damp + } else { + delta /= 2 + } + delta += delta / numPoints + k := int32(0) + for delta > ((base-tmin)*tmax)/2 { + delta /= base - tmin + k += base + } + return k + (base-tmin+1)*delta/(delta+skew) +} + +// Strictly speaking, the remaining code below deals with IDNA (RFC 5890 and +// friends) and not Punycode (RFC 3492) per se. + +// acePrefix is the ASCII Compatible Encoding prefix. +const acePrefix = "xn--" + +// toASCII converts a domain or domain label to its ASCII form. For example, +// toASCII("bücher.example.com") is "xn--bcher-kva.example.com", and +// toASCII("golang") is "golang". +func toASCII(s string) (string, error) { + if ascii(s) { + return s, nil + } + labels := strings.Split(s, ".") + for i, label := range labels { + if !ascii(label) { + a, err := encode(acePrefix, label) + if err != nil { + return "", err + } + labels[i] = a + } + } + return strings.Join(labels, "."), nil +} + +func ascii(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf { + return false + } + } + return true +} diff --git a/pkg/auth/providers/aws/saml2aws/creds/creds.go b/pkg/auth/providers/aws/saml2aws/creds/creds.go new file mode 100644 index 00000000000..9ab7d1d7452 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/creds/creds.go @@ -0,0 +1,17 @@ +package creds + +// LoginDetails used to authenticate +type LoginDetails struct { + ClientID string // used by OneLogin + ClientSecret string // used by OneLogin + DownloadBrowser bool // used by Browser + MFAIPAddress string // used by OneLogin + Username string + Password string + MFAToken string + DuoMFAOption string + URL string + StateToken string // used by Okta + OktaSessionCookie string // used by Okta + KCBroker string // used by KeyCloak +} diff --git a/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go new file mode 100644 index 00000000000..03c354c6db1 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go @@ -0,0 +1,62 @@ +package credentials + +import ( + "errors" +) + +var ( + // CurrentHelper the currently configured credentials helper + CurrentHelper Helper = &defaultHelper{} + + // ErrCredentialsNotFound returned when the credential can't be located in the native store. + ErrCredentialsNotFound = errors.New("credentials not found in native keychain") +) + +// Credentials holds the information shared between saml2aws and the credentials store. +type Credentials struct { + ServerURL string + Username string + Secret string +} + +// CredsLabel saml2aws credentials should be labeled as such in credentials stores that allow labelling. +// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain, +// Windows credentials manager and Linux libsecret. Default value is "saml2aws Credentials" +var CredsLabel = "saml2aws Credentials" + +// Helper is the interface a credentials store helper must implement. +type Helper interface { + // Add appends credentials to the store. + Add(*Credentials) error + // Delete removes credentials from the store. + Delete(serverURL string) error + // Get retrieves credentials from the store. + // It returns username and secret as strings. + Get(serverURL string) (string, string, error) + // SupportsCredentialStorage returns true or false if there is credential storage. + SupportsCredentialStorage() bool +} + +// IsErrCredentialsNotFound returns true if the error +// was caused by not having a set of credentials in a store. +func IsErrCredentialsNotFound(err error) bool { + return errors.Is(err, ErrCredentialsNotFound) +} + +type defaultHelper struct{} + +func (defaultHelper) Add(*Credentials) error { + return nil +} + +func (defaultHelper) Delete(serverURL string) error { + return nil +} + +func (defaultHelper) Get(serverURL string) (string, string, error) { + return "", "", ErrCredentialsNotFound +} + +func (defaultHelper) SupportsCredentialStorage() bool { + return false +} diff --git a/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials_test.go b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials_test.go new file mode 100644 index 00000000000..be3af96030b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials_test.go @@ -0,0 +1,204 @@ +package credentials + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +var errStore = errors.New("store failure") + +type storedSecret struct { + username string + secret string +} + +// fakeHelper is an in-memory credentials store. +type fakeHelper struct { + entries map[string]storedSecret + getErr map[string]error + added []*Credentials + addErr error + supports bool +} + +func (f *fakeHelper) Add(c *Credentials) error { + f.added = append(f.added, c) + return f.addErr +} + +func (f *fakeHelper) Delete(string) error { return nil } + +func (f *fakeHelper) Get(serverURL string) (string, string, error) { + if err, ok := f.getErr[serverURL]; ok { + return "", "", err + } + entry, ok := f.entries[serverURL] + if !ok { + return "", "", ErrCredentialsNotFound + } + return entry.username, entry.secret, nil +} + +func (f *fakeHelper) SupportsCredentialStorage() bool { return f.supports } + +// useHelper swaps CurrentHelper for the duration of a test. +func useHelper(t *testing.T, h Helper) { + t.Helper() + orig := CurrentHelper + CurrentHelper = h + t.Cleanup(func() { CurrentHelper = orig }) +} + +func TestDefaultHelper(t *testing.T) { + h := defaultHelper{} + + assert.NoError(t, h.Add(&Credentials{ServerURL: "https://idp.example.com"})) + assert.NoError(t, h.Delete("https://idp.example.com")) + assert.False(t, h.SupportsCredentialStorage()) + + user, secret, err := h.Get("https://idp.example.com") + assert.ErrorIs(t, err, ErrCredentialsNotFound) + assert.Empty(t, user) + assert.Empty(t, secret) +} + +func TestIsErrCredentialsNotFound(t *testing.T) { + assert.True(t, IsErrCredentialsNotFound(ErrCredentialsNotFound)) + assert.False(t, IsErrCredentialsNotFound(errStore)) + assert.False(t, IsErrCredentialsNotFound(nil)) +} + +func TestLookupCredentialsUsesDefaultHelper(t *testing.T) { + useHelper(t, &defaultHelper{}) + + err := LookupCredentials(&creds.LoginDetails{URL: "https://idp.example.com"}, "ADFS") + assert.True(t, IsErrCredentialsNotFound(err)) +} + +func TestLookupCredentials(t *testing.T) { + const idpURL = "https://idp.example.com" + + tests := []struct { + name string + provider string + helper *fakeHelper + wantErr error + wantUsername string + wantPassword string + wantCookie string + wantClientID string + wantClientSec string + }{ + { + name: "not found", + provider: "ADFS", + helper: &fakeHelper{}, + wantErr: ErrCredentialsNotFound, + }, + { + name: "store error", + provider: "ADFS", + helper: &fakeHelper{getErr: map[string]error{idpURL: errStore}}, + wantErr: errStore, + }, + { + name: "username and password", + provider: "ADFS", + helper: &fakeHelper{entries: map[string]storedSecret{idpURL: {"alice", "pw"}}}, + wantUsername: "alice", + wantPassword: "pw", + }, + { + name: "okta session cookie", + provider: "Okta", + helper: &fakeHelper{entries: map[string]storedSecret{ + idpURL: {"alice", "pw"}, + idpURL + "/sessionCookie": {"alice", "sid-123"}, + }}, + wantUsername: "alice", + wantPassword: "pw", + wantCookie: "sid-123", + }, + { + name: "okta without session cookie", + provider: "Okta", + helper: &fakeHelper{entries: map[string]storedSecret{idpURL: {"alice", "pw"}}}, + wantUsername: "alice", + wantPassword: "pw", + }, + { + name: "session cookie ignored for other providers", + provider: "ADFS", + helper: &fakeHelper{entries: map[string]storedSecret{ + idpURL: {"alice", "pw"}, + idpURL + "/sessionCookie": {"alice", "sid-123"}, + }}, + wantUsername: "alice", + wantPassword: "pw", + }, + { + // The OneLogin token key is built with path.Join, which collapses the "//" in the scheme. + name: "onelogin client credentials", + provider: "OneLogin", + helper: &fakeHelper{entries: map[string]storedSecret{ + idpURL: {"alice", "pw"}, + "https:/idp.example.com/auth/oauth2/v2/token": {"client-id", "client-secret"}, + }}, + wantUsername: "alice", + wantPassword: "pw", + wantClientID: "client-id", + wantClientSec: "client-secret", + }, + { + name: "onelogin client credentials missing", + provider: "OneLogin", + helper: &fakeHelper{entries: map[string]storedSecret{idpURL: {"alice", "pw"}}}, + wantErr: ErrCredentialsNotFound, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + useHelper(t, tt.helper) + ld := &creds.LoginDetails{URL: idpURL} + + err := LookupCredentials(ld, tt.provider) + if tt.wantErr != nil { + require.Error(t, err) + assert.ErrorIs(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantUsername, ld.Username) + assert.Equal(t, tt.wantPassword, ld.Password) + assert.Equal(t, tt.wantCookie, ld.OktaSessionCookie) + assert.Equal(t, tt.wantClientID, ld.ClientID) + assert.Equal(t, tt.wantClientSec, ld.ClientSecret) + }) + } +} + +func TestSaveCredentials(t *testing.T) { + h := &fakeHelper{} + useHelper(t, h) + + require.NoError(t, SaveCredentials("https://idp.example.com", "alice", "pw")) + require.Len(t, h.added, 1) + assert.Equal(t, &Credentials{ServerURL: "https://idp.example.com", Username: "alice", Secret: "pw"}, h.added[0]) + + h.addErr = errStore + assert.ErrorIs(t, SaveCredentials("https://idp.example.com", "alice", "pw"), errStore) +} + +func TestSupportsStorage(t *testing.T) { + useHelper(t, &fakeHelper{supports: true}) + assert.True(t, SupportsStorage()) + + useHelper(t, &fakeHelper{supports: false}) + assert.False(t, SupportsStorage()) +} diff --git a/pkg/auth/providers/aws/saml2aws/helper/credentials/saml.go b/pkg/auth/providers/aws/saml2aws/helper/credentials/saml.go new file mode 100644 index 00000000000..92d00585164 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/helper/credentials/saml.go @@ -0,0 +1,52 @@ +package credentials + +import ( + "path" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +// LookupCredentials lookup an existing set of credentials and validate it. +func LookupCredentials(loginDetails *creds.LoginDetails, provider string) error { + username, password, err := CurrentHelper.Get(loginDetails.URL) + if err != nil { + return err + } + + loginDetails.Username = username + loginDetails.Password = password + + // If the provider is Okta, check for existing Okta Session Cookie (sid) + if provider == "Okta" { + _, oktaSessionCookie, err := CurrentHelper.Get(loginDetails.URL + "/sessionCookie") + if err == nil { + loginDetails.OktaSessionCookie = oktaSessionCookie + } + } + + if provider == "OneLogin" { + id, secret, err := CurrentHelper.Get(path.Join(loginDetails.URL, "/auth/oauth2/v2/token")) + if err != nil { + return err + } + loginDetails.ClientID = id + loginDetails.ClientSecret = secret + } + return nil +} + +// SaveCredentials save the user credentials. +func SaveCredentials(url, username, password string) error { + creds := &Credentials{ + ServerURL: url, + Username: username, + Secret: password, + } + + return CurrentHelper.Add(creds) +} + +// SupportsStorage will return true or false if storage is supported. +func SupportsStorage() bool { + return CurrentHelper.SupportsCredentialStorage() +} diff --git a/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go b/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go new file mode 100644 index 00000000000..0e8d76220ad --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go @@ -0,0 +1,137 @@ +// Code generated by mockery v2.36.0. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// Prompter is an autogenerated mock type for the Prompter type +type Prompter struct { + mock.Mock +} + +// Choose provides a mock function with given fields: _a0, _a1. +// Atmos fork: returns (int, error); a missing error return value means nil. +func (_m *Prompter) Choose(_a0 string, _a1 []string) (int, error) { + ret := _m.Called(_a0, _a1) + + var r0 int + if rf, ok := ret.Get(0).(func(string, []string) int); ok { + r0 = rf(_a0, _a1) + } else { + r0 = ret.Get(0).(int) + } + + return r0, mockError(ret, 1) +} + +// ChooseWithDefault provides a mock function with given fields: _a0, _a1, _a2 +func (_m *Prompter) ChooseWithDefault(_a0 string, _a1 string, _a2 []string) (string, error) { + ret := _m.Called(_a0, _a1, _a2) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(string, string, []string) (string, error)); ok { + return rf(_a0, _a1, _a2) + } + if rf, ok := ret.Get(0).(func(string, string, []string) string); ok { + r0 = rf(_a0, _a1, _a2) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(string, string, []string) error); ok { + r1 = rf(_a0, _a1, _a2) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Display provides a mock function with given fields: _a0 +func (_m *Prompter) Display(_a0 string) { + _m.Called(_a0) +} + +// Password provides a mock function with given fields: _a0. +// Atmos fork: returns (string, error); a missing error return value means nil. +func (_m *Prompter) Password(_a0 string) (string, error) { + ret := _m.Called(_a0) + + var r0 string + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(string) + } + + return r0, mockError(ret, 1) +} + +// RequestSecurityCode provides a mock function with given fields: _a0. +// Atmos fork: returns (string, error); a missing error return value means nil. +func (_m *Prompter) RequestSecurityCode(_a0 string) (string, error) { + ret := _m.Called(_a0) + + var r0 string + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(string) + } + + return r0, mockError(ret, 1) +} + +// String provides a mock function with given fields: _a0, _a1. +// Atmos fork: returns (string, error); a missing error return value means nil. +func (_m *Prompter) String(_a0 string, _a1 string) (string, error) { + ret := _m.Called(_a0, _a1) + + var r0 string + if rf, ok := ret.Get(0).(func(string, string) string); ok { + r0 = rf(_a0, _a1) + } else { + r0 = ret.Get(0).(string) + } + + return r0, mockError(ret, 1) +} + +// StringRequired provides a mock function with given fields: _a0. +// Atmos fork: returns (string, error); a missing error return value means nil. +func (_m *Prompter) StringRequired(_a0 string) (string, error) { + ret := _m.Called(_a0) + + var r0 string + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(string) + } + + return r0, mockError(ret, 1) +} + +// mockError returns the error at index i of ret, or nil when the expectation did not set one. +func mockError(ret mock.Arguments, i int) error { + if len(ret) <= i { + return nil + } + return ret.Error(i) +} + +// NewPrompter creates a new instance of Prompter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPrompter(t interface { + mock.TestingT + Cleanup(func()) +}, +) *Prompter { + mock := &Prompter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/pkg/auth/providers/aws/saml2aws/mocks/U2FDevice.go b/pkg/auth/providers/aws/saml2aws/mocks/U2FDevice.go new file mode 100644 index 00000000000..a0b8c2dc2e0 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/mocks/U2FDevice.go @@ -0,0 +1,98 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +import u2fhost "github.com/marshallbrekka/go-u2fhost" + +// U2FDevice is an autogenerated mock type for the U2FDevice type +type U2FDevice struct { + mock.Mock +} + +// Authenticate provides a mock function with given fields: _a0 +func (_m *U2FDevice) Authenticate(_a0 *u2fhost.AuthenticateRequest) (*u2fhost.AuthenticateResponse, error) { + ret := _m.Called(_a0) + + var r0 *u2fhost.AuthenticateResponse + if rf, ok := ret.Get(0).(func(*u2fhost.AuthenticateRequest) *u2fhost.AuthenticateResponse); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*u2fhost.AuthenticateResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*u2fhost.AuthenticateRequest) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Close provides a mock function with given fields: +func (_m *U2FDevice) Close() { + _m.Called() +} + +// Open provides a mock function with given fields: +func (_m *U2FDevice) Open() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Register provides a mock function with given fields: _a0 +func (_m *U2FDevice) Register(_a0 *u2fhost.RegisterRequest) (*u2fhost.RegisterResponse, error) { + ret := _m.Called(_a0) + + var r0 *u2fhost.RegisterResponse + if rf, ok := ret.Get(0).(func(*u2fhost.RegisterRequest) *u2fhost.RegisterResponse); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*u2fhost.RegisterResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(*u2fhost.RegisterRequest) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Version provides a mock function with given fields: +func (_m *U2FDevice) Version() (string, error) { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} diff --git a/pkg/auth/providers/aws/saml2aws/page/example/multi-form.html b/pkg/auth/providers/aws/saml2aws/page/example/multi-form.html new file mode 100644 index 00000000000..da265087675 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/page/example/multi-form.html @@ -0,0 +1,20 @@ + + + + Example Login Page + + +
+ +
+
+ + + +
+
+ + +
+ + diff --git a/pkg/auth/providers/aws/saml2aws/page/form.go b/pkg/auth/providers/aws/saml2aws/page/form.go new file mode 100644 index 00000000000..ec434b8875f --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/page/form.go @@ -0,0 +1,139 @@ +package page + +import ( + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/PuerkitoBio/goquery" + "github.com/pkg/errors" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/provider" +) + +type Form struct { + URL string + Method string + Values *url.Values +} + +func (form *Form) BuildRequest() (*http.Request, error) { + // Atmos fork: a GET form submits its fields in the URL query; upstream always sent them in the body. + if strings.EqualFold(form.Method, http.MethodGet) { + target, err := url.Parse(form.URL) + if err != nil { + return nil, errors.Wrap(err, "error building request") + } + query := target.Query() + for name, vals := range *form.Values { + for _, val := range vals { + query.Add(name, val) + } + } + target.RawQuery = query.Encode() + req, err := http.NewRequest(http.MethodGet, target.String(), nil) + if err != nil { + return nil, errors.Wrap(err, "error building request") + } + return req, nil + } + + values := strings.NewReader(form.Values.Encode()) + req, err := http.NewRequest(form.Method, form.URL, values) + if err != nil { + return nil, errors.Wrap(err, "error building request") + } + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + return req, nil +} + +func (form *Form) Submit(client *provider.HTTPClient) (*http.Response, error) { + if req, err := form.BuildRequest(); err != nil { + return nil, errors.Wrap(err, "error building request") + } else if res, err := client.Do(req); err != nil { + return nil, errors.Wrap(err, "error submitting form") + } else { + return res, nil + } +} + +// If the document has multiple forms, the first form with an `action` attribute will be parsed. +// You can specify the exact form using a CSS filter. +func NewFormFromDocument(doc *goquery.Document, formFilter string) (*Form, error) { + form := Form{Method: "POST"} + + if formFilter == "" { + formFilter = "form[action]" + } + formSelection := doc.Find(formFilter).First() + if formSelection.Size() != 1 { + return nil, fmt.Errorf("could not find form") + } + + attrValue, ok := formSelection.Attr("action") + if ok { + action, err := resolveFormAction(attrValue, doc.Url) + if err != nil { + return nil, err + } + form.URL = action + } else if doc.Url != nil { + form.URL = doc.Url.String() + } else { + // Atmos fork: goquery leaves doc.Url nil for reader-based documents; upstream dereferenced it. + return nil, fmt.Errorf("form has no action and the document has no URL to fall back to") + } + + attrValue, ok = formSelection.Attr("method") + if ok { + form.Method = strings.ToUpper(attrValue) + } + + form.Values = &url.Values{} + formSelection.Find("input").Each(func(_ int, s *goquery.Selection) { + name, ok := s.Attr("name") + if !ok { + return + } + + val, ok := s.Attr("value") + if !ok { + return + } + + form.Values.Add(name, val) + }) + + return &form, nil +} + +// resolveFormAction resolves a form action against the document URL. +// Atmos fork: upstream stored a relative action verbatim, which cannot be requested because it has no scheme or host. +// Absolute actions are returned unchanged; a relative action needs a document URL to resolve against. +func resolveFormAction(action string, base *url.URL) (string, error) { + parsed, err := url.Parse(action) + if err != nil { + return "", errors.Wrap(err, "invalid form action") + } + if parsed.IsAbs() { + return action, nil + } + if base == nil { + return "", fmt.Errorf("form action %q is relative and the document has no URL to resolve it against", action) + } + return base.ResolveReference(parsed).String(), nil +} + +func NewFormFromResponse(res *http.Response, formFilter string) (*Form, error) { + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return nil, errors.Wrap(err, "failed to build document from response") + } + // Atmos fork: reader-based documents have no URL, so supply the request URL as the fallback form action. + if doc.Url == nil && res.Request != nil { + doc.Url = res.Request.URL + } + return NewFormFromDocument(doc, formFilter) +} diff --git a/pkg/auth/providers/aws/saml2aws/page/form_test.go b/pkg/auth/providers/aws/saml2aws/page/form_test.go new file mode 100644 index 00000000000..4208ff8d58b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/page/form_test.go @@ -0,0 +1,271 @@ +package page + +import ( + "bytes" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/PuerkitoBio/goquery" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/provider" +) + +var errRead = errors.New("read failure") + +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errRead } + +func TestNewFormFromDocument(t *testing.T) { + data, err := os.ReadFile(filepath.Join("example", "multi-form.html")) + require.Nil(t, err) + + doc, err := goquery.NewDocumentFromReader(bytes.NewReader(data)) + require.Nil(t, err) + doc.Url = &url.URL{Scheme: "https", Host: "idp.example.com", Path: "/start"} + + // assert the default behavior is to extract the first form with an action + form, err := NewFormFromDocument(doc, "") + require.Nil(t, err) + require.Equal(t, "https://idp.example.com/form_b", form.URL) + require.Equal(t, url.Values{"b1": []string{"rock"}, "b2": []string{"paper"}}, *form.Values) + + // assert we can provide a specific form filter + form, err = NewFormFromDocument(doc, "#c") + require.Nil(t, err) + require.Equal(t, "https://idp.example.com/form_c", form.URL) + require.Equal(t, url.Values{"c1": []string{"now"}}, *form.Values) +} + +func TestNewFormFromDocumentNoMatchingForm(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(`
`)) + require.NoError(t, err) + + // The default filter requires an action attribute. + _, err = NewFormFromDocument(doc, "") + require.Error(t, err) + + _, err = NewFormFromDocument(doc, "#missing") + require.Error(t, err) +} + +func TestNewFormFromDocumentDefaultsAndMethod(t *testing.T) { + docURL, err := url.Parse("https://idp.example.com/login?step=1") + require.NoError(t, err) + + tests := []struct { + name string + html string + wantURL string + wantMethod string + }{ + { + name: "no action falls back to document URL", + html: `
`, + wantURL: docURL.String(), + wantMethod: http.MethodPost, + }, + { + name: "method attribute is upper-cased", + html: `
`, + wantURL: "https://idp.example.com/next", + wantMethod: http.MethodGet, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(tt.html)) + require.NoError(t, err) + doc.Url = docURL + + form, err := NewFormFromDocument(doc, "#f") + require.NoError(t, err) + assert.Equal(t, tt.wantURL, form.URL) + assert.Equal(t, tt.wantMethod, form.Method) + assert.Equal(t, url.Values{"a": {"1"}}, *form.Values) + }) + } +} + +func TestNewFormFromDocumentSkipsInputsWithoutNameOrValue(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(`
+ + + + +
`)) + require.NoError(t, err) + doc.Url = &url.URL{Scheme: "https", Host: "idp.example.com"} + + form, err := NewFormFromDocument(doc, "") + require.NoError(t, err) + assert.Equal(t, url.Values{"keep": {"yes"}, "empty": {""}}, *form.Values) +} + +func TestNewFormFromResponse(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, "https://idp.example.com/login", nil) + require.NoError(t, err) + res := &http.Response{Body: io.NopCloser(strings.NewReader(`
`)), Request: req} + form, err := NewFormFromResponse(res, "") + require.NoError(t, err) + assert.Equal(t, "https://idp.example.com/go", form.URL) + assert.Equal(t, url.Values{"k": {"v"}}, *form.Values) + + res = &http.Response{Body: io.NopCloser(failingReader{})} + _, err = NewFormFromResponse(res, "") + require.Error(t, err) + assert.ErrorIs(t, err, errRead) +} + +func TestFormBuildRequest(t *testing.T) { + form := &Form{URL: "https://idp.example.com/submit", Method: http.MethodPost, Values: &url.Values{"user": {"alice"}}} + + req, err := form.BuildRequest() + require.NoError(t, err) + assert.Equal(t, http.MethodPost, req.Method) + assert.Equal(t, "https://idp.example.com/submit", req.URL.String()) + assert.Equal(t, "application/x-www-form-urlencoded", req.Header.Get("Content-Type")) + body, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.Equal(t, "user=alice", string(body)) + + form.Method = "BAD METHOD" + _, err = form.BuildRequest() + require.Error(t, err) +} + +func TestFormSubmit(t *testing.T) { + var gotForm url.Values + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.NoError(t, r.ParseForm()) + gotForm = r.PostForm + _, _ = w.Write([]byte("submitted")) + })) + defer ts.Close() + + client, err := provider.NewHTTPClient(http.DefaultTransport, &provider.HTTPClientOptions{}) + require.NoError(t, err) + + form := &Form{URL: ts.URL, Method: http.MethodPost, Values: &url.Values{"token": {"123"}}} + res, err := form.Submit(client) + require.NoError(t, err) + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + assert.Equal(t, "submitted", string(body)) + assert.Equal(t, url.Values{"token": {"123"}}, gotForm) + + // Invalid method fails while building the request. + badRes, err := (&Form{URL: ts.URL, Method: "BAD METHOD", Values: &url.Values{}}).Submit(client) + if badRes != nil { + _ = badRes.Body.Close() + } + require.Error(t, err) + assert.Contains(t, err.Error(), "error building request") + + // A server that is no longer listening fails while submitting. + ts.Close() + closedRes, err := form.Submit(client) + if closedRes != nil { + _ = closedRes.Body.Close() + } + require.Error(t, err) + assert.Contains(t, err.Error(), "error submitting form") +} + +// Regression: a GET form submits its fields in the URL query, not in the body. +func TestFormSubmitGetUsesQuery(t *testing.T) { + var gotQuery url.Values + var gotBody []byte + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotQuery = r.URL.Query() + gotBody, _ = io.ReadAll(r.Body) + _, _ = w.Write([]byte("ok")) + })) + defer ts.Close() + + client, err := provider.NewHTTPClient(http.DefaultTransport, &provider.HTTPClientOptions{}) + require.NoError(t, err) + + form := &Form{URL: ts.URL + "/go?keep=1", Method: http.MethodGet, Values: &url.Values{"token": {"123"}}} + res, err := form.Submit(client) + require.NoError(t, err) + defer res.Body.Close() + + assert.Equal(t, url.Values{"keep": {"1"}, "token": {"123"}}, gotQuery) + assert.Empty(t, gotBody) +} + +// Regression: a form without an action on a reader-based document must not panic on a nil document URL. +func TestNewFormFromResponseMissingDocumentURL(t *testing.T) { + const body = `
` + + res := &http.Response{Body: io.NopCloser(strings.NewReader(body))} + _, err := NewFormFromResponse(res, "#f") + require.Error(t, err) + + reqURL, perr := url.Parse("https://idp.example.com/login") + require.NoError(t, perr) + res = &http.Response{Body: io.NopCloser(strings.NewReader(body)), Request: &http.Request{URL: reqURL}} + form, err := NewFormFromResponse(res, "#f") + require.NoError(t, err) + assert.Equal(t, "https://idp.example.com/login", form.URL) +} + +// Regression: a relative form action was stored verbatim, so the request had no scheme or host. +func TestNewFormFromDocumentResolvesRelativeAction(t *testing.T) { + const html = `
` + newDoc := func(t *testing.T, base string) *goquery.Document { + t.Helper() + doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) + require.NoError(t, err) + if base != "" { + u, err := url.Parse(base) + require.NoError(t, err) + doc.Url = u + } + return doc + } + + t.Run("relative action resolves against the document URL", func(t *testing.T) { + form, err := NewFormFromDocument(newDoc(t, "https://idp.example.com/a/b?q=1"), "") + require.NoError(t, err) + assert.Equal(t, "https://idp.example.com/next", form.URL) + req, err := form.BuildRequest() + require.NoError(t, err) + assert.Equal(t, "idp.example.com", req.URL.Host) + }) + + t.Run("absolute action is unchanged", func(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(`
`)) + require.NoError(t, err) + doc.Url = &url.URL{Scheme: "https", Host: "idp.example.com", Path: "/a"} + form, err := NewFormFromDocument(doc, "") + require.NoError(t, err) + assert.Equal(t, "https://other.example.com/saml", form.URL) + }) + + t.Run("relative action without a document URL is an error", func(t *testing.T) { + _, err := NewFormFromDocument(newDoc(t, ""), "") + require.Error(t, err) + }) + + t.Run("response URL is used to resolve the action", func(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, "https://idp.example.com/login", nil) + require.NoError(t, err) + res := &http.Response{Body: io.NopCloser(strings.NewReader(html)), Request: req} + form, err := NewFormFromResponse(res, "") + require.NoError(t, err) + assert.Equal(t, "https://idp.example.com/next", form.URL) + }) +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go new file mode 100644 index 00000000000..e58f89e6267 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go @@ -0,0 +1,140 @@ +package prompter + +import ( + "bufio" + "fmt" + "io" + "os/exec" + "strings" +) + +const ( + defaultPinentryDialog string = "Security token [%s]" +) + +// PinentryRunner is the interface for pinentry to run itself +type PinentryRunner interface { + Run(string) (string, error) +} + +// RealPinentryRunner is the concrete implementation of PinentryRunner +type RealPinentryRunner struct { + PinentryBin string +} + +// PinentryPrompter is a concrete implementation of the Prompter interface. +// It uses the default Cli under the hood, except for RequestSecurityCode, where +// it uses any _pinentry_ binary to capture the security code. +// Its purpose is mainly to capture the TOTP code outside of the TTY, and thus +// making it possible to use TOTP with the credential process. +// https://github.com/Versent/saml2aws#using-saml2aws-as-credential-process +type PinentryPrompter struct { + Runner PinentryRunner + DefaultPrompter Prompter +} + +// NewPinentryPrompter is a factory for PinentryPrompter +func NewPinentryPrompter(bin string) *PinentryPrompter { + return &PinentryPrompter{Runner: NewRealPinentryRunner(bin), DefaultPrompter: NewCli()} +} + +// NewRealPinentryRunner is a factory for RealPinentryRunner +func NewRealPinentryRunner(bin string) *RealPinentryRunner { + return &RealPinentryRunner{PinentryBin: bin} +} + +// RequestSecurityCode for PinentryPrompter is creating a query for pinentry +// and sends it to the pinentry bin. +func (p *PinentryPrompter) RequestSecurityCode(pattern string) (string, error) { + commandTemplate := "SETPROMPT %s\nGETPIN\n" + prompt := fmt.Sprintf(defaultPinentryDialog, pattern) + command := fmt.Sprintf(commandTemplate, prompt) + output, err := p.Runner.Run(command) + if err != nil { + return "", err + } + return output, nil +} + +// ChooseWithDefault is running the default CLI ChooseWithDefault +func (p *PinentryPrompter) ChooseWithDefault(prompt string, def string, choices []string) (string, error) { + return p.DefaultPrompter.ChooseWithDefault(prompt, def, choices) +} + +// Choose is running the default CLI Choose +func (p *PinentryPrompter) Choose(pr string, options []string) (int, error) { + return p.DefaultPrompter.Choose(pr, options) +} + +// StringRequired is runniner the default Cli StringRequired +func (p *PinentryPrompter) StringRequired(pr string) (string, error) { + return p.DefaultPrompter.StringRequired(pr) +} + +// String is runniner the default Cli String +func (p *PinentryPrompter) String(pr string, defaultValue string) (string, error) { + return p.DefaultPrompter.String(pr, defaultValue) +} + +// Password is runniner the default Cli Password +func (p *PinentryPrompter) Password(pr string) (string, error) { + return p.DefaultPrompter.Password(pr) +} + +// Display is runniner the default Cli Display +func (p *PinentryPrompter) Display(pr string) { + p.DefaultPrompter.Display(pr) +} + +// Run wraps a pinentry run. It sends the query to pinentry via stdin and +// reads its stdout to determine the user PIN. +// Pinentry uses an Assuan protocol +func (r *RealPinentryRunner) Run(command string) (output string, err error) { + // Atmos fork: upstream ran cmd.Run() in a goroutine while parsing stdout here. Both + // goroutines wrote the named `err` result (a data race), and cmd.Run() waits for the + // process and closes the stdout pipe, which may happen before all output was read + // (os/exec forbids calling Wait before reads from StdoutPipe complete). Start the + // process, read its output, then Wait, sequentially. + cmd := exec.Command(r.PinentryBin, "--ttyname", "/dev/tty") //nolint:gosec // Binary is the configured pinentry program; arguments are fixed. + cmd.Stdin = strings.NewReader(command) + out, err := cmd.StdoutPipe() + if err != nil { + return "", err + } + if err := cmd.Start(); err != nil { + return "", err + } + + output, parseErr := ParseResults(out) + waitErr := cmd.Wait() + if parseErr != nil { + return "", parseErr + } + if waitErr != nil { + return "", waitErr + } + return output, nil +} + +// ParseResults parses the standard output of the pinentry command and determine the +// user input, or whether the program yielded any error +func ParseResults(pinEntryOutput io.Reader) (output string, err error) { + scanner := bufio.NewScanner(pinEntryOutput) + for scanner.Scan() { + line := scanner.Text() + // fmt.Println(line) + if strings.HasPrefix(line, "D ") { + output = line[2:] + } + if strings.HasPrefix(line, "ERR ") { + return "", fmt.Errorf("error while running pinentry: %s", line[4:]) + } + } + + // Atmos fork: upstream ignored scanner.Err(), so a read failure after "D " returned the code as a success. + if scanErr := scanner.Err(); scanErr != nil { + return "", fmt.Errorf("error while reading pinentry output: %w", scanErr) + } + + return output, err +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go b/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go new file mode 100644 index 00000000000..29d7040e79d --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go @@ -0,0 +1,229 @@ +package prompter + +import ( + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// creates a fake runner so we can perform unit tests +type FakePinentryRunner struct { + HasRun bool + FakeOutput string + FakePinentryOutput string + PassedInput string +} + +func (f *FakePinentryRunner) Run(cmd string) (string, error) { + f.PassedInput = cmd + f.HasRun = true + if f.FakeOutput != "" { + return f.FakeOutput, nil + } + if f.FakePinentryOutput != "" { + reader := strings.NewReader(f.FakePinentryOutput) + return ParseResults(reader) + } + return f.FakeOutput, nil +} + +// FakeDefaultPrompter is a Mock prompter +type FakeDefaultPrompter struct { + CalledRequestSecurityCode bool + CalledChoose bool + CalledChooseWithDefault bool + CalledString bool + CalledStringRequired bool + CalledPassword bool + CalledDisplay bool +} + +// all the functions to implement the Prompter interface +func (f *FakeDefaultPrompter) RequestSecurityCode(p string) (string, error) { + f.CalledRequestSecurityCode = true + return "", nil +} + +func (f *FakeDefaultPrompter) Choose(p string, option []string) (int, error) { + f.CalledChoose = true + return 0, nil +} + +func (f *FakeDefaultPrompter) ChooseWithDefault(p string, d string, c []string) (string, error) { + f.CalledChooseWithDefault = true + return "", nil +} + +func (f *FakeDefaultPrompter) String(p string, defaultValue string) (string, error) { + f.CalledString = true + return "", nil +} + +func (f *FakeDefaultPrompter) StringRequired(p string) (string, error) { + f.CalledStringRequired = true + return "", nil +} + +func (f *FakeDefaultPrompter) Password(p string) (string, error) { + f.CalledPassword = true + return "", nil +} + +func (f *FakeDefaultPrompter) Display(p string) { + f.CalledDisplay = true +} + +func TestValidateAndSetPrompterShouldFailWithWrongInput(t *testing.T) { + // backing up the current prompters for the other tests + oldPrompter := ActivePrompter + defer func() { ActivePrompter = oldPrompter }() + + errPrompts := []string{"abcde", "invalid", "prompt", " ", "pinentryfake"} + for _, errPrompt := range errPrompts { + err := ValidateAndSetPrompter(errPrompt) + assert.Error(t, err) + } +} + +func TestValidateAndSetPrompterShouldWorkWithInputForCli(t *testing.T) { + // backing up the current prompters for the other tests + oldPrompter := ActivePrompter + defer func() { ActivePrompter = oldPrompter }() + + errPrompts := []string{"", "default", "survey"} + for _, errPrompt := range errPrompts { + err := ValidateAndSetPrompter(errPrompt) + assert.NoError(t, err) + assert.IsType(t, ActivePrompter, NewCli()) + } +} + +// Regression: selecting a default alias after pinentry resets the active prompter, and an invalid +// value leaves the active prompter unchanged. +func TestValidateAndSetPrompterDefaultAliasesResetPinentry(t *testing.T) { + oldPrompter := ActivePrompter + defer func() { ActivePrompter = oldPrompter }() + + for _, alias := range []string{"", "default", "survey"} { + require.NoError(t, ValidateAndSetPrompter("pinentry")) + assert.IsType(t, &PinentryPrompter{}, ActivePrompter) + + require.NoError(t, ValidateAndSetPrompter(alias)) + assert.IsType(t, &CliPrompter{}, ActivePrompter) + } + + require.NoError(t, ValidateAndSetPrompter("pinentry")) + require.Error(t, ValidateAndSetPrompter("invalid")) + assert.IsType(t, &PinentryPrompter{}, ActivePrompter) +} + +// scannerErrReader returns data and then a read error. +type scannerErrReader struct{ done bool } + +func (r *scannerErrReader) Read(p []byte) (int, error) { + if r.done { + return 0, errors.New("read failed") + } + r.done = true + return copy(p, "D 123456\n"), nil +} + +// Regression: a reader failure after "D " must not return the code as a successful result. +func TestParseResultsReturnsScannerError(t *testing.T) { + output, err := ParseResults(&scannerErrReader{}) + require.Error(t, err) + assert.Empty(t, output) +} + +func TestValidateAndSetPrompterShouldWorkWithInputForPinentry(t *testing.T) { + // backing up the current prompters for the other tests + oldPrompter := ActivePrompter + defer func() { ActivePrompter = oldPrompter }() + + errPrompts := []string{"pinentry", "pinentry-tty", "pinentry-mac", "pinentry-gnome3"} + for _, errPrompt := range errPrompts { + err := ValidateAndSetPrompter(errPrompt) + assert.NoError(t, err) + assert.IsType(t, ActivePrompter, &PinentryPrompter{}) + } +} + +func TestChecksPinentryPrompterDefault(t *testing.T) { + p := &PinentryPrompter{} + fakeDefaultPrompter := &FakeDefaultPrompter{} + p.DefaultPrompter = fakeDefaultPrompter + + _, _ = p.Choose("random", []string{"1", "2"}) + assert.True(t, fakeDefaultPrompter.CalledChoose) + + _, _ = p.ChooseWithDefault("random", "random", []string{"1", "2"}) + assert.True(t, fakeDefaultPrompter.CalledChooseWithDefault) + + _, _ = p.String("random", "random") + assert.True(t, fakeDefaultPrompter.CalledString) + + _, _ = p.StringRequired("random") + assert.True(t, fakeDefaultPrompter.CalledStringRequired) + + _, _ = p.Password("random") + assert.True(t, fakeDefaultPrompter.CalledPassword) + + p.Display("random") + assert.True(t, fakeDefaultPrompter.CalledDisplay) +} + +func TestChecksPinentryPrompterCallsPinentryForRequestSecurityCode(t *testing.T) { + p := &PinentryPrompter{} + runner := &FakePinentryRunner{} + p.Runner = runner + runner.FakeOutput = "random_code" + pinentryOutput, err := p.RequestSecurityCode("000000") + + assert.NoError(t, err) + assert.True(t, runner.HasRun) + assert.Equal(t, pinentryOutput, "random_code") + assert.Equal(t, runner.PassedInput, "SETPROMPT Security token [000000]\nGETPIN\n") +} + +func TestChecksPinentryPrompterReturnsRightCodeGivenFakePinentryOutput(t *testing.T) { + p := &PinentryPrompter{} + runner := &FakePinentryRunner{} + p.Runner = runner + runner.FakePinentryOutput = "OK This line should get ignored\nOK This line should too\nD 654321\nOK Final\n" + pinentryOutput, err := p.RequestSecurityCode("000000") + + assert.NoError(t, err) + assert.True(t, runner.HasRun) + assert.Equal(t, pinentryOutput, "654321") +} + +func TestChecksPinentryPrompterReturnsNoCodeGivenErroneousFakePinentryOutput(t *testing.T) { + p := &PinentryPrompter{} + runner := &FakePinentryRunner{} + p.Runner = runner + runner.FakePinentryOutput = "OK This line should get ignored\nOK This line should too\nERR This is an error\nD 654321\nOK Final\n" + pinentryOutput, err := p.RequestSecurityCode("000000") + + assert.Error(t, err) + assert.True(t, runner.HasRun) + assert.Equal(t, pinentryOutput, "") +} + +func TestParseOutputShouldThrowError(t *testing.T) { + input := strings.NewReader("OK Ignore this line\nERR This is an error\nD This result should be ignored\nOK this is irrelevant\n") + output, err := ParseResults(input) + + assert.Error(t, err) + assert.Equal(t, output, "") +} + +func TestParseOutputShouldReturnCorrectOutput(t *testing.T) { + input := strings.NewReader("OK Ignore this line\nD THISISTHERETURN\nOK this is irrelevant\n") + output, err := ParseResults(input) + + assert.NoError(t, err) + assert.Equal(t, output, "THISISTHERETURN") +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/prompter.go b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go new file mode 100644 index 00000000000..6326861b55e --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go @@ -0,0 +1,88 @@ +package prompter + +import ( + "fmt" + "regexp" +) + +// ActivePrompter is by default the survey cli prompter +var ActivePrompter Prompter = NewCli() + +// Prompter handles prompting user for input +type Prompter interface { + // Atmos fork: the prompting methods return an error (for example when the user cancels with Ctrl+C + // or no terminal is available) so callers can stop instead of continuing with a zero value. + RequestSecurityCode(string) (string, error) + ChooseWithDefault(string, string, []string) (string, error) + Choose(string, []string) (int, error) + StringRequired(string) (string, error) + String(string, string) (string, error) + Password(string) (string, error) + Display(string) +} + +// SetPrompter configure an aternate prompter to the default one +func SetPrompter(prmpt Prompter) { + ActivePrompter = prmpt +} + +// ValidateAndSetPrompter validates the user configuration and will create +// a concrete prompter based on this configuration +func ValidateAndSetPrompter(prmptCfg string) error { + if prmptCfg == "" || prmptCfg == "survey" || prmptCfg == "default" { + // Atmos fork: reset to the survey prompter so an earlier pinentry selection does not stay active. + SetPrompter(NewCli()) + return nil + } + + // all pinentry programs will start with `pinentry` + re := regexp.MustCompile(`^pinentry(-.*)?$`) + if re.MatchString(prmptCfg) { + SetPrompter(NewPinentryPrompter(prmptCfg)) + return nil + } + + return fmt.Errorf("prompter %s is not valid", prmptCfg) +} + +// RequestSecurityCode request a security code to be entered by the user +func RequestSecurityCode(pattern string) (string, error) { + return ActivePrompter.RequestSecurityCode(pattern) +} + +// ChooseWithDefault given the choice return the option selected with a default +func ChooseWithDefault(pr string, defaultValue string, options []string) (string, error) { + // ensure the default is not empty and avoid bad input error + if defaultValue == "" { + if len(options) > 0 { + defaultValue = options[0] + } + } + + return ActivePrompter.ChooseWithDefault(pr, defaultValue, options) +} + +// Choose given the choice return the option selected +func Choose(pr string, options []string) (int, error) { + return ActivePrompter.Choose(pr, options) +} + +// StringRequired prompt for string which is required +func StringRequired(pr string) (string, error) { + return ActivePrompter.StringRequired(pr) +} + +// String prompt for string which is required +func String(pr string, defaultValue string) (string, error) { + return ActivePrompter.String(pr, defaultValue) +} + +// Password prompt for password which is required +func Password(pr string) (string, error) { + return ActivePrompter.Password(pr) +} + +// Display prompt, no user input required +func Display(pr string) { + ActivePrompter.Display(pr) +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go b/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go new file mode 100644 index 00000000000..d78105b03e7 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go @@ -0,0 +1,218 @@ +package prompter + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// recordingPrompter records the arguments it was called with. +type recordingPrompter struct { + calls []string + lastPrompt string + lastDefault string + lastOptions []string + chooseResult string +} + +func (r *recordingPrompter) RequestSecurityCode(pattern string) (string, error) { + r.calls = append(r.calls, "RequestSecurityCode") + r.lastPrompt = pattern + return "123456", nil +} + +func (r *recordingPrompter) ChooseWithDefault(pr, def string, options []string) (string, error) { + r.calls = append(r.calls, "ChooseWithDefault") + r.lastPrompt, r.lastDefault, r.lastOptions = pr, def, options + return r.chooseResult, nil +} + +func (r *recordingPrompter) Choose(pr string, options []string) (int, error) { + r.calls = append(r.calls, "Choose") + r.lastPrompt, r.lastOptions = pr, options + return len(options) - 1, nil +} + +func (r *recordingPrompter) StringRequired(pr string) (string, error) { + r.calls = append(r.calls, "StringRequired") + r.lastPrompt = pr + return "required", nil +} + +func (r *recordingPrompter) String(pr, def string) (string, error) { + r.calls = append(r.calls, "String") + r.lastPrompt, r.lastDefault = pr, def + return "value", nil +} + +func (r *recordingPrompter) Password(pr string) (string, error) { + r.calls = append(r.calls, "Password") + r.lastPrompt = pr + return "secret", nil +} + +func (r *recordingPrompter) Display(pr string) { + r.calls = append(r.calls, "Display") + r.lastPrompt = pr +} + +// useRecordingPrompter installs a recording prompter for the duration of a test. +func useRecordingPrompter(t *testing.T) *recordingPrompter { + t.Helper() + orig := ActivePrompter + rec := &recordingPrompter{chooseResult: "picked"} + SetPrompter(rec) + t.Cleanup(func() { SetPrompter(orig) }) + return rec +} + +func TestPackageFunctionsDelegateToActivePrompter(t *testing.T) { + rec := useRecordingPrompter(t) + + code, err := RequestSecurityCode("000000") + require.NoError(t, err) + assert.Equal(t, "123456", code) + assert.Equal(t, "000000", rec.lastPrompt) + + index, err := Choose("Pick", []string{"a", "b"}) + require.NoError(t, err) + assert.Equal(t, 1, index) + assert.Equal(t, []string{"a", "b"}, rec.lastOptions) + + required, err := StringRequired("Username") + require.NoError(t, err) + assert.Equal(t, "required", required) + assert.Equal(t, "Username", rec.lastPrompt) + + value, err := String("Region", "us-east-1") + require.NoError(t, err) + assert.Equal(t, "value", value) + assert.Equal(t, "us-east-1", rec.lastDefault) + + secret, err := Password("Password") + require.NoError(t, err) + assert.Equal(t, "secret", secret) + assert.Equal(t, "Password", rec.lastPrompt) + + Display("hello") + assert.Equal(t, "hello", rec.lastPrompt) + + assert.Equal(t, []string{"RequestSecurityCode", "Choose", "StringRequired", "String", "Password", "Display"}, rec.calls) +} + +func TestChooseWithDefault(t *testing.T) { + tests := []struct { + name string + def string + options []string + wantDefault string + }{ + {name: "explicit default kept", def: "b", options: []string{"a", "b"}, wantDefault: "b"}, + {name: "empty default uses first option", def: "", options: []string{"a", "b"}, wantDefault: "a"}, + {name: "empty default without options", def: "", options: nil, wantDefault: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := useRecordingPrompter(t) + + got, err := ChooseWithDefault("Pick a role", tt.def, tt.options) + require.NoError(t, err) + assert.Equal(t, "picked", got) + assert.Equal(t, "Pick a role", rec.lastPrompt) + assert.Equal(t, tt.wantDefault, rec.lastDefault) + assert.Equal(t, tt.options, rec.lastOptions) + }) + } +} + +func TestNewPinentryPrompter(t *testing.T) { + p := NewPinentryPrompter("pinentry-mac") + + runner, ok := p.Runner.(*RealPinentryRunner) + require.True(t, ok) + assert.Equal(t, "pinentry-mac", runner.PinentryBin) + assert.IsType(t, &CliPrompter{}, p.DefaultPrompter) +} + +func TestCliPrompterDisplay(t *testing.T) { + r, w, err := os.Pipe() + require.NoError(t, err) + origStderr := os.Stderr + os.Stderr = w + t.Cleanup(func() { os.Stderr = origStderr }) + + NewCli().Display("Open your authenticator app") + require.NoError(t, w.Close()) + os.Stderr = origStderr + + out, err := io.ReadAll(r) + require.NoError(t, err) + assert.Equal(t, "Open your authenticator app\n", string(out)) +} + +func TestRealPinentryRunner(t *testing.T) { + exe, err := os.Executable() + require.NoError(t, err) + + tests := []struct { + mode string + want string + wantErr string + }{ + {mode: "ok", want: "424242"}, + {mode: "cancel", wantErr: "Operation cancelled"}, + {mode: "crash", wantErr: "exit status 2"}, + } + + for _, tt := range tests { + t.Run(tt.mode, func(t *testing.T) { + t.Setenv(fakePinentryEnv, tt.mode) + + out, err := NewRealPinentryRunner(exe).Run(expectedPinentryInput) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + assert.Empty(t, out) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, out) + }) + } +} + +func TestPinentryPrompterEndToEnd(t *testing.T) { + exe, err := os.Executable() + require.NoError(t, err) + + tests := []struct { + mode string + want string + wantErr bool + }{ + {mode: "ok", want: "424242"}, + {mode: "cancel", want: "", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.mode, func(t *testing.T) { + t.Setenv(fakePinentryEnv, tt.mode) + got, err := NewPinentryPrompter(exe).RequestSecurityCode("000000") + assert.Equal(t, tt.wantErr, err != nil) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestRealPinentryRunnerMissingBinary(t *testing.T) { + missing := filepath.Join(t.TempDir(), "pinentry-does-not-exist") + + out, err := NewRealPinentryRunner(missing).Run(expectedPinentryInput) + require.Error(t, err) + assert.Empty(t, out) +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/survey.go b/pkg/auth/providers/aws/saml2aws/prompter/survey.go new file mode 100644 index 00000000000..77838502c1d --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey.go @@ -0,0 +1,127 @@ +package prompter + +import ( + "errors" + "fmt" + "os" + + survey "github.com/AlecAivazis/survey/v2" + survey_terminal "github.com/AlecAivazis/survey/v2/terminal" +) + +// outputWriter is where for all prompts will be printed. Defaults to os.Stder. +var outputWriter survey_terminal.FileWriter = os.Stderr + +// CliPrompter used to prompt for cli input +type CliPrompter struct{} + +// SetOutputWriter sets the output writer to use for all survey operations +func SetOutputWriter(writer survey_terminal.FileWriter) { + outputWriter = writer +} + +// stdioOption returns the IO option to use for survey functions +func stdioOption() survey.AskOpt { + return survey.WithStdio(os.Stdin, outputWriter, os.Stderr) +} + +// NewCli builds a new cli prompter +func NewCli() *CliPrompter { + return &CliPrompter{} +} + +// RequestSecurityCode request a security code to be entered by the user +func (cli *CliPrompter) RequestSecurityCode(pattern string) (string, error) { + token := "" + prompt := &survey.Input{ + Message: fmt.Sprintf("Security Token [%s]", pattern), + } + if err := survey.AskOne(prompt, &token, survey.WithValidator(survey.Required), stdioOption()); err != nil { + return "", err + } + return token, nil +} + +// ChooseWithDefault given the choice return the option selected with a default +func (cli *CliPrompter) ChooseWithDefault(pr string, defaultValue string, options []string) (string, error) { + selected := "" + prompt := &survey.Select{ + Message: pr, + Options: options, + Default: defaultValue, + } + // Atmos fork: propagate prompt failures (for example Ctrl+C) instead of discarding them. + if err := survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()); err != nil { + return "", err + } + + // return the selected element index + for i, option := range options { + if selected == option { + return options[i], nil + } + } + return "", errors.New("bad input") +} + +// Choose given the choice return the option selected +func (cli *CliPrompter) Choose(pr string, options []string) (int, error) { + selected := "" + prompt := &survey.Select{ + Message: pr, + Options: options, + } + // Atmos fork: propagate prompt failures instead of silently selecting the first option. + if err := survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()); err != nil { + return 0, err + } + + // return the selected element index + for i, option := range options { + if selected == option { + return i, nil + } + } + return 0, errors.New("bad input") +} + +// String prompt for string with a default +func (cli *CliPrompter) String(pr string, defaultValue string) (string, error) { + val := "" + prompt := &survey.Input{ + Message: pr, + Default: defaultValue, + } + if err := survey.AskOne(prompt, &val, stdioOption()); err != nil { + return "", err + } + return val, nil +} + +// StringRequired prompt for string which is required +func (cli *CliPrompter) StringRequired(pr string) (string, error) { + val := "" + prompt := &survey.Input{ + Message: pr, + } + if err := survey.AskOne(prompt, &val, survey.WithValidator(survey.Required), stdioOption()); err != nil { + return "", err + } + return val, nil +} + +// Password prompt for password which is required +func (cli *CliPrompter) Password(pr string) (string, error) { + val := "" + prompt := &survey.Password{ + Message: pr, + } + if err := survey.AskOne(prompt, &val, stdioOption()); err != nil { + return "", err + } + return val, nil +} + +func (cli *CliPrompter) Display(pr string) { + _, _ = os.Stderr.WriteString(pr + "\n") +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go b/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go new file mode 100644 index 00000000000..628ba731024 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go @@ -0,0 +1,65 @@ +package prompter + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// useNonInteractiveStdio points the survey prompts at a closed, non-terminal stdin and a +// temporary output file for the duration of a test. +func useNonInteractiveStdio(t *testing.T) { + t.Helper() + + r, w, err := os.Pipe() + require.NoError(t, err) + require.NoError(t, w.Close()) + + out, err := os.Create(filepath.Join(t.TempDir(), "prompts.txt")) + require.NoError(t, err) + + origStdin, origOutput := os.Stdin, outputWriter + os.Stdin = r + SetOutputWriter(out) + t.Cleanup(func() { + os.Stdin = origStdin + SetOutputWriter(origOutput) + _ = r.Close() + _ = out.Close() + }) +} + +// Without a terminal the survey prompts cannot collect input. They must return +// promptly with zero values rather than block or panic. +func TestCliPrompterWithoutTerminal(t *testing.T) { + useNonInteractiveStdio(t) + cli := NewCli() + + // Atmos fork: prompt failures are propagated, never turned into a default selection or an empty value. + code, err := cli.RequestSecurityCode("000000") + require.Error(t, err) + assert.Empty(t, code) + + value, err := cli.String("Region", "us-east-1") + require.Error(t, err) + assert.Empty(t, value) + + required, err := cli.StringRequired("Username") + require.Error(t, err) + assert.Empty(t, required) + + secret, err := cli.Password("Password") + require.Error(t, err) + assert.Empty(t, secret) + + index, err := cli.Choose("Pick", []string{"a", "b"}) + require.Error(t, err) + assert.Equal(t, 0, index) + + selected, err := cli.ChooseWithDefault("Pick", "b", []string{"a", "b"}) + require.Error(t, err) + assert.Empty(t, selected) +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/testmain_test.go b/pkg/auth/providers/aws/saml2aws/prompter/testmain_test.go new file mode 100644 index 00000000000..96811848509 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/testmain_test.go @@ -0,0 +1,50 @@ +package prompter + +import ( + "io" + "os" + "testing" +) + +// fakePinentryEnv selects a fake pinentry behavior when the test binary is re-executed +// as a pinentry program. This keeps the subprocess tests cross-platform. +const fakePinentryEnv = "_SAML2AWS_TEST_FAKE_PINENTRY" + +const expectedPinentryInput = "SETPROMPT Security token [000000]\nGETPIN\n" + +func TestMain(m *testing.M) { + if mode := os.Getenv(fakePinentryEnv); mode != "" { + os.Exit(runFakePinentry(mode)) + } + os.Exit(m.Run()) +} + +// runFakePinentry speaks a minimal subset of the Assuan protocol used by pinentry. +func runFakePinentry(mode string) int { + input, err := io.ReadAll(os.Stdin) + if err != nil { + return 3 + } + if len(os.Args) != 3 || os.Args[1] != "--ttyname" || os.Args[2] != "/dev/tty" { + _, _ = os.Stdout.WriteString("ERR 1 unexpected arguments\n") + return 0 + } + if string(input) != expectedPinentryInput { + _, _ = os.Stdout.WriteString("ERR 2 unexpected input\n") + return 0 + } + + switch mode { + case "ok": + _, _ = os.Stdout.WriteString("OK Pleased to meet you\nOK\nD 424242\nOK\n") + return 0 + case "cancel": + _, _ = os.Stdout.WriteString("OK Pleased to meet you\nOK\nERR 83886179 Operation cancelled\n") + return 0 + case "crash": + _, _ = os.Stdout.WriteString("OK Pleased to meet you\nOK\nD 424242\n") + return 2 + default: + return 4 + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go new file mode 100644 index 00000000000..1ed8fcbbf43 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go @@ -0,0 +1,349 @@ +package adfs + +import ( + "crypto/tls" + "fmt" + "log" + "net/http" + "net/url" + "strings" + "time" + + "github.com/PuerkitoBio/goquery" + "github.com/pkg/errors" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/prompter" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/provider" +) + +// Client wrapper around ADFS enabling authentication and retrieval of assertions +type Client struct { + provider.ValidateBase + + client *provider.HTTPClient + idpAccount *cfg.IDPAccount +} + +type AuthResponseType int + +const ( + UNKNOWN AuthResponseType = iota + SAML_RESPONSE + MFA_PROMPT + AZURE_MFA_WAIT + AZURE_MFA_SERVER_WAIT +) + +// Atmos fork: the Azure MFA poll interval is a package variable (upstream hard-coded +// time.Sleep(1 * time.Second)) so tests can shorten it. +var azureMFAPollInterval = 1 * time.Second + +// Atmos fork: upstream looped without a limit, so a server that kept returning an MFA page +// prompted for codes, or polled, forever. The limits below end the loop with ErrMFAAttemptsExceeded. +const ( + // maxMFAPromptAttempts is the number of one-time codes submitted before giving up. + maxMFAPromptAttempts = 5 + // maxAzureMFAPolls is the number of Azure MFA approval polls before giving up + // (about five minutes at the default one-second poll interval). + maxAzureMFAPolls = 300 +) + +// ErrMFAAttemptsExceeded is returned when the server keeps asking for MFA after the attempt limit. +var ErrMFAAttemptsExceeded = errors.New("too many MFA attempts") + +// New create a new ADFS client +func New(idpAccount *cfg.IDPAccount) (*Client, error) { + tr := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + // Atmos fork: explicit TLS 1.2 floor (upstream left MinVersion unset). Not TLS 1.3: + // renegotiation, which ADFS relies on, only exists up to TLS 1.2. + TLSClientConfig: &tls.Config{MinVersion: provider.MinTLSVersion, InsecureSkipVerify: idpAccount.SkipVerify, Renegotiation: tls.RenegotiateFreelyAsClient}, //nolint:gosec // Skipping verification is an explicit, user-configured opt-in (skip_verify). + } + + client, err := provider.NewHTTPClient(tr, provider.BuildHttpClientOpts(idpAccount)) + if err != nil { + return nil, errors.Wrap(err, "error building http client") + } + + return &Client{ + client: client, + idpAccount: idpAccount, + }, nil +} + +// Authenticate to ADFS and return the data from the body of the SAML assertion. +func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) { + var authSubmitURL string + var samlAssertion string + var instructions string + + awsURN := url.QueryEscape(ac.idpAccount.AmazonWebservicesURN) + + adfsURL := fmt.Sprintf("%s/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=%s", loginDetails.URL, awsURN) + + mfaToken := loginDetails.MFAToken + + doc, err := ac.get(adfsURL) + if err != nil { + return "", errors.Wrap(err, "failed to get adfs page") + } + + authForm := url.Values{} + + doc.Find("input").Each(func(i int, s *goquery.Selection) { + updateFormData(authForm, s, loginDetails) + }) + + doc.Find("form").Each(func(i int, s *goquery.Selection) { + action, ok := s.Attr("action") + if !ok { + return + } + authSubmitURL = action + }) + + // Trim whitespace and discard empty values from Kmsi field + if val, ok := authForm["Kmsi"]; ok { + var trimmedKmsi []string + var t string + for _, s := range val { + t = strings.TrimSpace(s) + if len(t) > 0 { + trimmedKmsi = append(trimmedKmsi, t) + } + } + authForm["Kmsi"] = trimmedKmsi + } + + if authSubmitURL == "" { + return samlAssertion, fmt.Errorf("unable to locate IDP authentication form submit URL") + } else { + // + // Atmos fork: resolve every action against the login page URL. Upstream resolved only actions that start + // with "/", so "?step=password" or "step=password" reached the HTTP client without a scheme. + // ResolveReference leaves absolute URLs unchanged. + // + parsedUrl, err := url.Parse(adfsURL) + if err != nil { + return "", errors.Wrap(err, "failed to parse ADFS URL") + } + parsedPath, err := url.Parse(authSubmitURL) + if err != nil { + return "", errors.Wrap(err, "failed to parse authSubmitURL fragment") + } + authSubmitURL = parsedUrl.ResolveReference(parsedPath).String() + } + + doc, err = ac.submit(authSubmitURL, authForm) + if err != nil { + return samlAssertion, errors.Wrap(err, "failed to submit adfs auth form") + } + + mfaPromptAttempts, azureMFAPolls := 0, 0 + for { + responseType, samlAssertion, err := checkResponse(doc) + + switch responseType { + case SAML_RESPONSE: + return samlAssertion, err + case MFA_PROMPT: + if mfaPromptAttempts >= maxMFAPromptAttempts { + return "", fmt.Errorf("%w: the server asked for a one-time code %d times", ErrMFAAttemptsExceeded, mfaPromptAttempts) + } + mfaPromptAttempts++ + otpForm := url.Values{} + if mfaToken == "" { + mfaToken, err = prompter.RequestSecurityCode("000000") + if err != nil { + return samlAssertion, errors.Wrap(err, "error reading the MFA code") + } + } + + doc.Find("input").Each(func(i int, s *goquery.Selection) { + updateOTPFormData(otpForm, s, mfaToken) + }) + doc, err = ac.submit(authSubmitURL, otpForm) + if err != nil { + return samlAssertion, errors.Wrap(err, "error retrieving mfa form results") + } + mfaToken = "" + case AZURE_MFA_SERVER_WAIT: + fallthrough + case AZURE_MFA_WAIT: + if azureMFAPolls >= maxAzureMFAPolls { + return "", fmt.Errorf("%w: no Azure MFA approval after %d polls", ErrMFAAttemptsExceeded, azureMFAPolls) + } + azureMFAPolls++ + azureForm := url.Values{} + doc.Find("input").Each(func(i int, s *goquery.Selection) { + updatePassthroughFormData(azureForm, s) + }) + sel := doc.Find("p#validEntropyNumber") + if sel.Index() != -1 { + if instructions != sel.Text() { + instructions = sel.Text() + log.Println("Open your Microsoft Authenticator app and tap the number you see below to sign in.") + log.Println(instructions) + } + } + sel = doc.Find("p#instructions") + if sel.Index() != -1 { + if instructions != sel.Text() { + instructions = sel.Text() + log.Println(instructions) + } + } + time.Sleep(azureMFAPollInterval) + doc, err = ac.submit(authSubmitURL, azureForm) + if err != nil { + return samlAssertion, errors.Wrap(err, "error retrieving mfa form results") + } + if responseType == AZURE_MFA_SERVER_WAIT { + sel := doc.Find("label#errorText") + if sel.Index() != -1 { + return samlAssertion, errors.New(sel.Text()) + } + } + case UNKNOWN: + return samlAssertion, errors.New("unable to classify response from auth server") + } + } +} + +func (ac *Client) get(url string) (*goquery.Document, error) { + res, err := ac.client.Get(url) + if err != nil { + return nil, errors.Wrap(err, "error retieving form") + } + defer res.Body.Close() + + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return nil, errors.Wrap(err, "failed to build document from response") + } + return doc, nil +} + +func (ac *Client) submit(url string, form url.Values) (*goquery.Document, error) { + req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode())) + if err != nil { + return nil, errors.Wrap(err, "error building request") + } + + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + res, err := ac.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "error submitting form") + } + defer res.Body.Close() + + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return nil, errors.Wrap(err, "failed to build document from response") + } + return doc, nil +} + +func checkResponse(doc *goquery.Document) (AuthResponseType, string, error) { + samlAssertion := "" + responseType := UNKNOWN + var checkErr error + + doc.Find("input").Each(func(i int, s *goquery.Selection) { + name, ok := s.Attr("name") + if !ok { + // Atmos fork: upstream called log.Fatalf here, terminating the whole process + // whenever the response page contained an unnamed (for example a + // submit button). Unnamed inputs carry no form data, so skip them. + return + } + if name == "SAMLResponse" { + val, ok := s.Attr("value") + if !ok { + // Atmos fork: upstream called log.Fatalf here; return an error instead. + checkErr = errors.New("unable to locate saml assertion value") + } + samlAssertion = val + responseType = SAML_RESPONSE + } + if name == "OathCode" { + responseType = MFA_PROMPT + } + if name == "AuthMethod" { + val, _ := s.Attr("value") + switch val { + case "VIPAuthenticationProviderWindowsAccountName", "VIPAuthenticationProviderUPN", "Defender AD FS Adapter": + responseType = MFA_PROMPT + case "AzureMfaAuthentication": + responseType = AZURE_MFA_WAIT + case "AzureMfaServerAuthentication": + responseType = AZURE_MFA_SERVER_WAIT + } + } + if name == "VerificationCode" { + responseType = MFA_PROMPT + } + }) + return responseType, samlAssertion, checkErr +} + +func updateFormData(authForm url.Values, s *goquery.Selection, user *creds.LoginDetails) { + name, ok := s.Attr("name") + if !ok { + return + } + + typeValue, typeFound := s.Attr("type") + hiddenAttr := typeFound && typeValue == "hidden" + + lname := strings.ToLower(name) + if strings.Contains(lname, "user") { + if !hiddenAttr { + authForm.Add(name, user.Username) + } + } else if strings.Contains(lname, "email") { + if !hiddenAttr { + authForm.Add(name, user.Username) + } + } else if strings.Contains(lname, "pass") { + if !hiddenAttr { + authForm.Add(name, user.Password) + } + } else { + updatePassthroughFormData(authForm, s) + } +} + +func updateOTPFormData(otpForm url.Values, s *goquery.Selection, token string) { + name, ok := s.Attr("name") + if !ok { + return + } + lname := strings.ToLower(name) + if strings.Contains(lname, "security_code") { + otpForm.Add(name, token) + } else if strings.Contains(lname, "verificationcode") { + otpForm.Add(name, token) + } else if strings.Contains(lname, "challengequestionanswer") { + otpForm.Add(name, token) + } else if strings.Contains(lname, "oathcode") { + otpForm.Add(name, token) + } else { + updatePassthroughFormData(otpForm, s) + } +} + +func updatePassthroughFormData(otpForm url.Values, s *goquery.Selection) { + name, ok := s.Attr("name") + if !ok { + return + } + val, ok := s.Attr("value") + if !ok { + return + } + otpForm.Add(name, val) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_mfa_limit_test.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_mfa_limit_test.go new file mode 100644 index 00000000000..14c266bebca --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_mfa_limit_test.go @@ -0,0 +1,76 @@ +package adfs + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/mocks" +) + +// Regression: a server that keeps returning the one-time-code page made Authenticate prompt and +// submit forever. It must give up after maxMFAPromptAttempts codes. +func TestAuthenticateMFAPromptAttemptLimit(t *testing.T) { + pr := &mocks.Prompter{} + pr.On("RequestSecurityCode", "000000").Return("999999") + usePrompter(t, pr) + + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{mfaPage(``)}, + repeatLast: true, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "111111")) + require.ErrorIs(t, err, ErrMFAAttemptsExceeded) + assert.Empty(t, assertion) + + // One login POST plus one POST per allowed code; the configured token counts as the first code. + posts := fake.postedForms() + require.Len(t, posts, 1+maxMFAPromptAttempts) + assert.Equal(t, []string{"111111"}, posts[1]["VerificationCode"]) + assert.Equal(t, []string{"999999"}, posts[maxMFAPromptAttempts]["VerificationCode"]) + pr.AssertNumberOfCalls(t, "RequestSecurityCode", maxMFAPromptAttempts-1) +} + +// Regression: a server that keeps returning the Azure MFA wait page was polled forever. +func TestAuthenticateAzureMFAPollLimit(t *testing.T) { + for _, method := range []string{"AzureMfaAuthentication", "AzureMfaServerAuthentication"} { + t.Run(method, func(t *testing.T) { + useFastAzurePolling(t) + captureLog(t) + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{azurePage(method, `

Approve the sign-in request.

`)}, + repeatLast: true, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + require.ErrorIs(t, err, ErrMFAAttemptsExceeded) + assert.Empty(t, assertion) + // One login POST plus one POST per allowed poll. + assert.Len(t, fake.postedForms(), 1+maxAzureMFAPolls) + }) + } +} + +// The limit only stops a server that never finishes: approval within the limit still succeeds. +func TestAuthenticateMFAPromptWithinLimit(t *testing.T) { + pr := &mocks.Prompter{} + pr.On("RequestSecurityCode", "000000").Return("999999") + usePrompter(t, pr) + + verification := mfaPage(``) + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{verification, verification, verification, verification, verification, samlResponsePage}, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "111111")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go new file mode 100644 index 00000000000..ec54070d1b8 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go @@ -0,0 +1,582 @@ +package adfs + +import ( + "bytes" + "fmt" + "log" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/PuerkitoBio/goquery" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/mocks" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/prompter" +) + +const ( + testSAMLAssertion = "PHNhbWxwOlJlc3BvbnNlPjwvc2FtbHA6UmVzcG9uc2U+" + testUsername = "alice@example.com" + testPassword = "s3cr3t" + // abortResponse instructs the fake server to drop the connection without replying. + abortResponse = "<>" +) + +// samlResponsePage mimics the auto-submitting page ADFS returns after a successful login. +var samlResponsePage = ` +
+ + +
` + +// loginPage mimics the ADFS forms-authentication page. +func loginPage(action string) string { + actionAttr := "" + if action != "" { + actionAttr = fmt.Sprintf(` action=%q`, action) + } + return ` +
+ + + + + + + +
` +} + +// fakeADFSMaxPosts stops a fake server that repeats its last response from looping forever. +const fakeADFSMaxPosts = 1000 + +// fakeADFS is an httptest handler that serves the login page on GET and replays canned +// responses, in order, for each POST it receives. +type fakeADFS struct { + t *testing.T + loginHTML string + responses []string + + // repeatLast serves the last response for every POST after the canned ones run out, + // up to fakeADFSMaxPosts, after which the connection is dropped. + repeatLast bool + + mu sync.Mutex + getQuery url.Values + posts []url.Values + paths []string +} + +func (f *fakeADFS) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + + if r.Method == http.MethodGet { + f.getQuery = r.URL.Query() + _, _ = w.Write([]byte(f.loginHTML)) + return + } + + if err := r.ParseForm(); err != nil { + f.t.Errorf("failed to parse posted form: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + idx := len(f.posts) + f.posts = append(f.posts, r.PostForm) + f.paths = append(f.paths, r.URL.RequestURI()) + + if f.repeatLast && idx >= len(f.responses) && len(f.responses) > 0 { + if idx >= fakeADFSMaxPosts { + panic(http.ErrAbortHandler) + } + idx = len(f.responses) - 1 + } + if idx >= len(f.responses) { + f.t.Errorf("unexpected POST #%d to %s", idx+1, r.URL) + w.WriteHeader(http.StatusInternalServerError) + return + } + if f.responses[idx] == abortResponse { + panic(http.ErrAbortHandler) + } + _, _ = w.Write([]byte(f.responses[idx])) +} + +func (f *fakeADFS) postedForms() []url.Values { + f.mu.Lock() + defer f.mu.Unlock() + return append([]url.Values(nil), f.posts...) +} + +// newTestServer starts a TLS server backed by the fake ADFS handler. +func newTestServer(t *testing.T, fake *fakeADFS) *httptest.Server { + t.Helper() + fake.t = t + ts := httptest.NewTLSServer(fake) + t.Cleanup(ts.Close) + return ts +} + +func newTestClient(t *testing.T) *Client { + t.Helper() + client, err := New(&cfg.IDPAccount{ + SkipVerify: true, + AmazonWebservicesURN: cfg.DefaultAmazonWebservicesURN, + }) + require.NoError(t, err) + return client +} + +func loginDetails(serverURL, mfaToken string) *creds.LoginDetails { + return &creds.LoginDetails{ + URL: serverURL, + Username: testUsername, + Password: testPassword, + MFAToken: mfaToken, + } +} + +func mfaPage(fields string) string { + return `
` + fields + + `
` +} + +func azurePage(authMethod, extra string) string { + return `
+ + +
` + extra + `` +} + +// useFastAzurePolling shortens the Azure MFA poll interval for the duration of a test. +func useFastAzurePolling(t *testing.T) { + t.Helper() + orig := azureMFAPollInterval + azureMFAPollInterval = time.Millisecond + t.Cleanup(func() { azureMFAPollInterval = orig }) +} + +// usePrompter swaps the active prompter for the duration of a test. +func usePrompter(t *testing.T, p prompter.Prompter) { + t.Helper() + orig := prompter.ActivePrompter + prompter.SetPrompter(p) + t.Cleanup(func() { prompter.SetPrompter(orig) }) +} + +// captureLog redirects the standard logger for the duration of a test. +func captureLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + origOut, origFlags := log.Writer(), log.Flags() + log.SetOutput(&buf) + log.SetFlags(0) + t.Cleanup(func() { + log.SetOutput(origOut) + log.SetFlags(origFlags) + }) + return &buf +} + +func TestAuthenticateSuccessRelativeAction(t *testing.T) { + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/?client-request-id=abc"), + responses: []string{samlResponsePage}, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + + // The IdP-initiated sign-on request targets the AWS relying party. + assert.Equal(t, cfg.DefaultAmazonWebservicesURN, fake.getQuery.Get("loginToRp")) + + // The relative action was resolved against the ADFS URL, preserving its query. + require.Len(t, fake.paths, 1) + assert.Equal(t, "/adfs/ls/?client-request-id=abc", fake.paths[0]) + + posts := fake.postedForms() + require.Len(t, posts, 1) + form := posts[0] + assert.Equal(t, []string{testUsername}, form["UserName"]) + assert.Equal(t, []string{testPassword}, form["Password"]) + assert.Equal(t, []string{"FormsAuthentication"}, form["AuthMethod"]) + // Kmsi values are trimmed and empty values discarded. + assert.Equal(t, []string{"true"}, form["Kmsi"]) + // Hidden inputs that look like credential fields are never sent. + _, hasHidden := form["UserNameHidden"] + assert.False(t, hasHidden) +} + +// Regression: relative actions that do not start with "/" are resolved against the login page URL. +func TestAuthenticateSuccessRelativeActionWithoutLeadingSlash(t *testing.T) { + for action, wantPath := range map[string]string{ + "?step=password": "/adfs/ls/IdpInitiatedSignOn.aspx?step=password", + "step=password": "/adfs/ls/step=password", + } { + fake := &fakeADFS{ + loginHTML: loginPage(action), + responses: []string{samlResponsePage}, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + require.NoError(t, err, action) + assert.Equal(t, testSAMLAssertion, assertion) + require.Len(t, fake.paths, 1) + assert.Equal(t, wantPath, fake.paths[0], action) + } +} + +func TestAuthenticateSuccessAbsoluteAction(t *testing.T) { + fake := &fakeADFS{responses: []string{samlResponsePage}} + ts := newTestServer(t, fake) + fake.loginHTML = loginPage(ts.URL + "/adfs/ls/absolute") + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + require.Len(t, fake.paths, 1) + assert.Equal(t, "/adfs/ls/absolute", fake.paths[0]) +} + +func TestAuthenticateErrors(t *testing.T) { + // A server that is closed immediately yields a URL nothing listens on. + closed := httptest.NewServer(http.NotFoundHandler()) + closedURL := closed.URL + closed.Close() + + tests := []struct { + name string + serverURL func(ts *httptest.Server) string + loginHTML func(ts *httptest.Server) string + responses []string + wantErr string + }{ + { + name: "login page unreachable", + serverURL: func(*httptest.Server) string { return closedURL }, + loginHTML: func(*httptest.Server) string { return "" }, + wantErr: "failed to get adfs page", + }, + { + name: "login page has no form action", + loginHTML: func(*httptest.Server) string { return loginPage("") }, + wantErr: "unable to locate IDP authentication form submit URL", + }, + { + name: "auth form submission fails", + loginHTML: func(*httptest.Server) string { return loginPage(closedURL + "/adfs/ls/") }, + wantErr: "failed to submit adfs auth form", + }, + { + name: "unclassifiable response", + loginHTML: func(*httptest.Server) string { return loginPage("/adfs/ls/") }, + // A failed login re-renders the forms-authentication page. + responses: []string{loginPage("/adfs/ls/")}, + wantErr: "unable to classify response from auth server", + }, + { + name: "SAMLResponse without value", + loginHTML: func(*httptest.Server) string { return loginPage("/adfs/ls/") }, + responses: []string{`
`}, + wantErr: "unable to locate saml assertion value", + }, + { + name: "mfa submission fails", + loginHTML: func(*httptest.Server) string { return loginPage("/adfs/ls/") }, + responses: []string{mfaPage(``), abortResponse}, + wantErr: "error retrieving mfa form results", + }, + { + name: "azure mfa poll fails", + loginHTML: func(*httptest.Server) string { return loginPage("/adfs/ls/") }, + responses: []string{azurePage("AzureMfaAuthentication", ""), abortResponse}, + wantErr: "error retrieving mfa form results", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + useFastAzurePolling(t) + fake := &fakeADFS{responses: tt.responses} + ts := newTestServer(t, fake) + fake.loginHTML = tt.loginHTML(ts) + serverURL := ts.URL + if tt.serverURL != nil { + serverURL = tt.serverURL(ts) + } + + assertion, err := newTestClient(t).Authenticate(loginDetails(serverURL, "123456")) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + assert.Empty(t, assertion) + }) + } +} + +func TestAuthenticateRejectsUntrustedCertificate(t *testing.T) { + fake := &fakeADFS{loginHTML: loginPage("/adfs/ls/"), responses: []string{samlResponsePage}} + ts := newTestServer(t, fake) + + client, err := New(&cfg.IDPAccount{SkipVerify: false}) + require.NoError(t, err) + + _, err = client.Authenticate(loginDetails(ts.URL, "")) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to get adfs page") + assert.Empty(t, fake.postedForms()) +} + +func TestAuthenticateMFAPrompt(t *testing.T) { + tests := []struct { + name string + fields string + tokenField string + }{ + { + name: "OathCode", + fields: ``, + tokenField: "OathCode", + }, + { + name: "VerificationCode", + fields: ``, + tokenField: "VerificationCode", + }, + { + name: "VIP account name", + fields: ` +`, + tokenField: "security_code", + }, + { + name: "VIP UPN", + fields: ` +`, + tokenField: "security_code", + }, + { + name: "Defender", + fields: ` +`, + tokenField: "ChallengeQuestionAnswer", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{mfaPage(tt.fields), samlResponsePage}, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "654321")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + + posts := fake.postedForms() + require.Len(t, posts, 2) + mfaForm := posts[1] + assert.Equal(t, []string{"654321"}, mfaForm[tt.tokenField]) + // Other inputs are passed through unchanged. + assert.Equal(t, []string{"ctx-123"}, mfaForm["Context"]) + // Credentials are not re-sent with the OTP form. + _, hasPassword := mfaForm["Password"] + assert.False(t, hasPassword) + }) + } +} + +func TestAuthenticateMFAPromptsWhenTokenMissingOrConsumed(t *testing.T) { + pr := &mocks.Prompter{} + pr.On("RequestSecurityCode", "000000").Return("999999").Once() + usePrompter(t, pr) + + verification := mfaPage(``) + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{verification, verification, samlResponsePage}, + } + ts := newTestServer(t, fake) + + // The configured token is used for the first challenge only; the second must be prompted for. + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "111111")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + + posts := fake.postedForms() + require.Len(t, posts, 3) + assert.Equal(t, []string{"111111"}, posts[1]["VerificationCode"]) + assert.Equal(t, []string{"999999"}, posts[2]["VerificationCode"]) + pr.AssertExpectations(t) +} + +func TestAuthenticateAzureMFAWait(t *testing.T) { + useFastAzurePolling(t) + logs := captureLog(t) + + waiting := azurePage("AzureMfaAuthentication", `

42

`) + fake := &fakeADFS{ + loginHTML: loginPage("/adfs/ls/"), + responses: []string{waiting, waiting, samlResponsePage}, + } + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + + posts := fake.postedForms() + require.Len(t, posts, 3) + for _, poll := range posts[1:] { + assert.Equal(t, []string{"AzureMfaAuthentication"}, poll["AuthMethod"]) + assert.Equal(t, []string{"azure-ctx"}, poll["Context"]) + } + // The number to tap is shown once even though the page was polled twice. + assert.Equal(t, 1, strings.Count(logs.String(), "Microsoft Authenticator")) + assert.Contains(t, logs.String(), "42") +} + +func TestAuthenticateAzureMFAServerWait(t *testing.T) { + waiting := azurePage("AzureMfaServerAuthentication", `

Approve the sign-in request.

`) + + tests := []struct { + name string + responses []string + wantErr string + }{ + { + name: "approved", + responses: []string{waiting, samlResponsePage}, + }, + { + name: "denied", + responses: []string{waiting, ``}, + wantErr: "The request was denied.", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + useFastAzurePolling(t) + logs := captureLog(t) + fake := &fakeADFS{loginHTML: loginPage("/adfs/ls/"), responses: tt.responses} + ts := newTestServer(t, fake) + + assertion, err := newTestClient(t).Authenticate(loginDetails(ts.URL, "")) + assert.Contains(t, logs.String(), "Approve the sign-in request.") + if tt.wantErr != "" { + require.Error(t, err) + assert.Equal(t, tt.wantErr, err.Error()) + assert.Empty(t, assertion) + return + } + require.NoError(t, err) + assert.Equal(t, testSAMLAssertion, assertion) + }) + } +} + +func TestCheckResponse(t *testing.T) { + tests := []struct { + name string + html string + wantType AuthResponseType + wantAssertion string + wantErr bool + }{ + {name: "empty page", html: ``, wantType: UNKNOWN}, + {name: "saml response", html: samlResponsePage, wantType: SAML_RESPONSE, wantAssertion: testSAMLAssertion}, + { + // Regression: upstream terminated the process via log.Fatalf on unnamed inputs. + name: "saml response with unnamed submit input", + html: `
`, + wantType: SAML_RESPONSE, + wantAssertion: "abc", + }, + { + // Regression: upstream terminated the process via log.Fatalf when the value was missing. + name: "saml response without value", + html: `
`, + wantType: SAML_RESPONSE, + wantErr: true, + }, + {name: "oath code", html: ``, wantType: MFA_PROMPT}, + {name: "verification code", html: ``, wantType: MFA_PROMPT}, + {name: "azure", html: ``, wantType: AZURE_MFA_WAIT}, + {name: "azure server", html: ``, wantType: AZURE_MFA_SERVER_WAIT}, + {name: "forms auth", html: ``, wantType: UNKNOWN}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(tt.html)) + require.NoError(t, err) + + gotType, gotAssertion, err := checkResponse(doc) + assert.Equal(t, tt.wantType, gotType) + assert.Equal(t, tt.wantAssertion, gotAssertion) + if tt.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestUpdateFormData(t *testing.T) { + user := &creds.LoginDetails{Username: "bob", Password: "pw"} + + tests := []struct { + name string + input string + want url.Values + }{ + {name: "username", input: ``, want: url.Values{"UserName": {"bob"}}}, + {name: "email", input: ``, want: url.Values{"EmailAddress": {"bob"}}}, + {name: "password", input: ``, want: url.Values{"Password": {"pw"}}}, + {name: "hidden username skipped", input: ``, want: url.Values{}}, + {name: "hidden email skipped", input: ``, want: url.Values{}}, + {name: "hidden password skipped", input: ``, want: url.Values{}}, + {name: "passthrough", input: ``, want: url.Values{"AuthMethod": {"Forms"}}}, + {name: "passthrough without value", input: ``, want: url.Values{}}, + {name: "unnamed", input: ``, want: url.Values{}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(tt.input)) + require.NoError(t, err) + + got := url.Values{} + doc.Find("input").Each(func(_ int, s *goquery.Selection) { + updateFormData(got, s, user) + }) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestUpdateOTPFormDataIgnoresUnnamedInputs(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(``)) + require.NoError(t, err) + + got := url.Values{} + doc.Find("input").Each(func(_ int, s *goquery.Selection) { + updateOTPFormData(got, s, "123456") + }) + assert.Empty(t, got) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_tls_test.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_tls_test.go new file mode 100644 index 00000000000..c3ffba467a5 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_tls_test.go @@ -0,0 +1,28 @@ +package adfs + +import ( + "crypto/tls" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" +) + +// Regression: upstream left MinVersion unset (code-scanning missing-ssl-minversion). ADFS keeps +// TLS renegotiation, which only exists up to TLS 1.2, so the floor is TLS 1.2, not TLS 1.3. +func TestNewSetsTLSFloorAndKeepsRenegotiation(t *testing.T) { + for _, skipVerify := range []bool{false, true} { + client, err := New(&cfg.IDPAccount{URL: "https://adfs.example.com", SkipVerify: skipVerify}) + require.NoError(t, err) + + transport, ok := client.client.Transport.(*http.Transport) + require.True(t, ok, "ADFS client must use an *http.Transport") + require.NotNil(t, transport.TLSClientConfig) + assert.Equal(t, uint16(tls.VersionTLS12), transport.TLSClientConfig.MinVersion) + assert.Equal(t, tls.RenegotiateFreelyAsClient, transport.TLSClientConfig.Renegotiation) + assert.Equal(t, skipVerify, transport.TLSClientConfig.InsecureSkipVerify) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/base_validate.go b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go new file mode 100644 index 00000000000..4c218a09dc3 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go @@ -0,0 +1,22 @@ +package provider + +import ( + "errors" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +type ValidateBase struct{} + +func (ac *ValidateBase) Validate(ld *creds.LoginDetails) error { + if ld.URL == "" { + return errors.New("empty URL") + } + if ld.Username == "" { + return errors.New("empty username") + } + if ld.Password == "" { + return errors.New("empty password") + } + return nil +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/base_validate_test.go b/pkg/auth/providers/aws/saml2aws/provider/base_validate_test.go new file mode 100644 index 00000000000..c8f4412d332 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/base_validate_test.go @@ -0,0 +1,39 @@ +package provider + +import ( + "testing" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +func TestLoginDetails_Validate(t *testing.T) { + type fields struct { + Username string + Password string + URL string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + // TODO: Add test cases. + {name: "hostname missing error", fields: fields{}, wantErr: true}, + {name: "username missing error", fields: fields{URL: "id.example.com"}, wantErr: true}, + {name: "password missing error", fields: fields{URL: "id.example.com", Username: "test"}, wantErr: true}, + {name: "ok", fields: fields{URL: "id.example.com", Username: "test", Password: "test"}, wantErr: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ld := &creds.LoginDetails{ + Username: tt.fields.Username, + Password: tt.fields.Password, + URL: tt.fields.URL, + } + providerstub := &ValidateBase{} + if err := providerstub.Validate(ld); (err != nil) != tt.wantErr { + t.Errorf("LoginDetails.Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go new file mode 100644 index 00000000000..0e7c3bb351b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go @@ -0,0 +1,470 @@ +package browser + +import ( + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + + "github.com/mxschmitt/playwright-go" + "github.com/sirupsen/logrus" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" + "github.com/cloudposse/atmos/pkg/config/homedir" +) + +//go:generate go run go.uber.org/mock/mockgen@v0.6.0 -source=$GOFILE -destination=mock_page_test.go -package=$GOPACKAGE +//go:generate go run go.uber.org/mock/mockgen@v0.6.0 -destination=mock_request_test.go -package=$GOPACKAGE github.com/mxschmitt/playwright-go Request,BrowserType,Browser + +var logger = logrus.WithField("provider", "browser") + +const DEFAULT_TIMEOUT float64 = 300000 + +// storageStateDirPerm is the permission for the directory holding the browser storage state, +// which contains IdP session cookies. +const storageStateDirPerm = 0o700 + +// storageStateFilePerm is the permission for the browser storage state file. +const storageStateFilePerm = 0o600 + +// ErrNoSAMLResponse is returned when the browser flow ends without capturing the AWS sign-in request. +var ErrNoSAMLResponse = errors.New("no SAML response captured from the AWS sign-in request") + +// errSAMLRequestCaptured ends an ExpectRequest wait when the OnRequest callback already captured the request. +var errSAMLRequestCaptured = errors.New("AWS sign-in request already captured") + +// samlPage is the subset of playwright.Page used to capture the SAML response. +// Atmos fork: narrowed from playwright.Page so the capture logic can be unit-tested with mocks. +type samlPage interface { + Goto(url string, options ...playwright.PageGotoOptions) (playwright.Response, error) + OnRequest(fn func(playwright.Request)) + ExpectRequest(urlOrPredicate any, cb func() error, options ...playwright.PageExpectRequestOptions) (playwright.Request, error) +} + +// storageStatePath returns the path of the persisted browser storage state. +// Atmos fork: built with filepath.Join and the Atmos homedir package instead of a +// forward-slash fmt.Sprintf, which produced mixed separators on Windows. +var storageStatePath = func() (string, error) { + userHomeDir, err := homedir.Dir() + if err != nil { + return "", err + } + return filepath.Join(userHomeDir, ".aws", "saml2aws", "storageState.json"), nil +} + +// Client client for browser based Identity Provider +type Client struct { + BrowserType string + BrowserExecutablePath string + Headless bool + // Setup alternative directory to download playwright browsers to + BrowserDriverDir string + Timeout int + BrowserAutoFill bool +} + +// New create new browser based client +func New(idpAccount *cfg.IDPAccount) (*Client, error) { + return &Client{ + Headless: idpAccount.Headless, + BrowserDriverDir: idpAccount.BrowserDriverDir, + BrowserType: strings.ToLower(idpAccount.BrowserType), + BrowserExecutablePath: idpAccount.BrowserExecutablePath, + Timeout: idpAccount.Timeout, + BrowserAutoFill: idpAccount.BrowserAutoFill, + }, nil +} + +// contains checks if a string is present in a slice +func contains(s []string, str string) bool { + for _, v := range s { + if v == str { + return true + } + } + + return false +} + +// validBrowserTypes are the browser channels Playwright can launch. +var validBrowserTypes = []string{"chromium", "firefox", "webkit", "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary"} + +// validateBrowserType rejects an unknown browser type. +// Atmos fork: runs before Playwright is installed or started, so a typo fails fast. +func (cl *Client) validateBrowserType() error { + if len(cl.BrowserType) > 0 && !contains(validBrowserTypes, cl.BrowserType) { + return fmt.Errorf("invalid browser-type: '%s', only %s are allowed", cl.BrowserType, validBrowserTypes) + } + return nil +} + +// Atmos fork: the Playwright entry points are package variables so tests can verify that +// every resource is released on each early return without starting a real driver. +var ( + installPlaywright = playwright.Install + runPlaywright = playwright.Run + stopPlaywright = func(pw *playwright.Playwright) error { return pw.Stop() } +) + +// runOptions returns the Playwright driver options used to install and run the driver. +// +// Atmos fork: upstream used zero-value RunOptions, so `playwright install` printed its +// download progress to stdout (corrupting the caller's data output, for example +// `eval $(atmos auth env)`) and downloaded every Playwright browser (Chromium, the Chromium +// headless shell, Firefox, WebKit and FFmpeg) although only one browser is launched. +func (cl *Client) runOptions() *playwright.RunOptions { + opts := &playwright.RunOptions{ + DriverDirectory: cl.BrowserDriverDir, + Stdout: os.Stderr, + } + switch cl.BrowserType { + case "", "chromium": + opts.Browsers = []string{"chromium"} + // Only the default headless Chromium launches the headless shell; a headed browser + // and the explicit "chromium" channel use the full Chromium build. + opts.NoInstallShell = cl.BrowserType != "" || !cl.Headless + case "firefox", "webkit": + opts.Browsers = []string{cl.BrowserType} + } + // Other browser types are channels of a browser installed on the system (Chrome, Edge); + // keep upstream's behavior of installing the default browsers for them. + return opts +} + +func (cl *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) { + if err := cl.validateBrowserType(); err != nil { + return "", err + } + + runOptions := cl.runOptions() + + // Optionally download browser drivers if specified + if loginDetails.DownloadBrowser { + err := installPlaywright(runOptions) + if err != nil { + return "", err + } + } + + pw, err := runPlaywright(runOptions) + if err != nil { + return "", err + } + // Atmos fork: upstream released Playwright, the browser and the context only in one + // defer registered after the page was created, so a failed Launch, storage-state lookup, + // NewContext or NewPage leaked the driver process (and the browser). Each resource is + // now released by its own defer as soon as it exists. Defers run in reverse order, which + // keeps upstream's shutdown order: save state, close context, close browser, stop driver. + defer func() { + if err := stopPlaywright(pw); err != nil { + logger.Info("Error when stopping pm", err) + } + }() + + // TODO: provide some overrides for this window + launchOptions := playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(cl.Headless), + } + + if cl.BrowserType != "" { + logger.Info(fmt.Sprintf("Setting browser type: %s", cl.BrowserType)) + launchOptions.Channel = playwright.String(cl.BrowserType) + } + + // Default browser is Chromium as it is widely supported for Identity providers, + // It can also be set to the other playwright browsers: Firefox and WebKit + browserType := pw.Chromium + switch cl.BrowserType { + case "firefox": + browserType = pw.Firefox + case "webkit": + browserType = pw.WebKit + } + + // You can set the path to a browser executable to run instead of the playwright-go bundled one. If `executablePath` + // is a relative path, then it is resolved relative to the current working directory. + // Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. see: + if len(cl.BrowserExecutablePath) > 0 { + logger.Info(fmt.Sprintf("Setting browser executable path: %s", cl.BrowserExecutablePath)) + launchOptions.ExecutablePath = &cl.BrowserExecutablePath + } + + // currently using the main browsers supported by Playwright: Chromium, Firefox or Webkit + // + // this is a sandboxed browser window so password managers and addons are separate + browser, err := browserType.Launch(launchOptions) + if err != nil { + return "", err + } + defer func() { + logger.Info("clean up browser") + if err := browser.Close(); err != nil { + logger.Info("Error when closing browser", err) + } + }() + + // create Context Optionsf + contextOptions := playwright.BrowserNewContextOptions{} + + // load saved storageState if present and add to contextOptions + statePath, err := storageStatePath() + if err != nil { + return "", err + } + if _, err := os.Stat(statePath); err == nil { + contextOptions.StorageStatePath = playwright.String(statePath) + } + + // Create new broswer context + context, err := browser.NewContext(contextOptions) + if err != nil { + return "", err + } + defer func() { + if err := context.Close(); err != nil { + logger.Info("Error when closing context", err) + } + }() + + page, err := context.NewPage() + if err != nil { + return "", err + } + + defer func() { + logger.Info("saving storage state") + if err := saveStorageState(context, statePath); err != nil { + logger.Info("Error saving storage state", err) + } + }() + + return getSAMLResponse(page, loginDetails, cl) +} + +// storageStateSaver is the subset of playwright.BrowserContext used to persist the storage state. +type storageStateSaver interface { + StorageState(path ...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) +} + +// saveStorageState writes the browser storage state (IdP session cookies) to statePath. +// Atmos fork: Playwright creates (os.Create, 0644) and writes the state file directly, so the cookies +// were world-readable until a later chmod, and a failed save could clobber the previous state. The state +// is saved to a private (0600) temporary file in a private (0700) directory and only moved over statePath +// after a successful save, so a failure leaves the previous state untouched. +func saveStorageState(saver storageStateSaver, statePath string) error { + dir := filepath.Dir(statePath) + if err := os.MkdirAll(dir, storageStateDirPerm); err != nil { + return err + } + // MkdirAll does not tighten an existing directory. + if err := os.Chmod(dir, storageStateDirPerm); err != nil { + return err + } + + tmp, err := os.CreateTemp(dir, filepath.Base(statePath)+".*.tmp") // Created with 0600. + if err != nil { + return err + } + tmpPath := tmp.Name() + if err := tmp.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + + if _, err := saver.StorageState(playwright.BrowserContextStorageStateOptions{Path: playwright.String(tmpPath)}); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := os.Chmod(tmpPath, storageStateFilePerm); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := os.Rename(tmpPath, statePath); err != nil { + _ = os.Remove(tmpPath) + return err + } + return nil +} + +// getSAMLResponse navigates to the IdP and captures the SAMLResponse posted to the AWS sign-in endpoint. +// +// Atmos fork fixes over upstream v2.36.19: +// - A timeout or error from ExpectRequest returned a nil request that was then dereferenced (panic). +// - A PostData error was swallowed because the wrong error variable was returned. +// - The request callback and the caller shared data without synchronization (data race). +// - An empty capture now fails with ErrNoSAMLResponse instead of returning an empty assertion. +// - A request the callback captured just before ExpectRequest started listening is used instead +// of waiting for the full timeout and failing. +var getSAMLResponse = func(page samlPage, loginDetails *creds.LoginDetails, client *Client) (string, error) { + var ( + mu sync.Mutex + data string + dataErr error + ) + + logger.WithField("URL", loginDetails.URL).Info("opening browser") + + signinRe, err := signinRegex() + if err != nil { + return "", err + } + + // record stores the request body. Atmos fork: a captured SAMLResponse is never replaced by a later + // request that carries none (for example a GET to the same URL, whose body is empty), which upstream + // overwrote and then waited for another request until the timeout. + record := func(postData string, postErr error) { + mu.Lock() + defer mu.Unlock() + if dataErr == nil && hasSAMLResponse(data) && (postErr != nil || !hasSAMLResponse(postData)) { + return + } + data, dataErr = postData, postErr + } + + page.OnRequest(func(request playwright.Request) { + if signinRe.MatchString(request.URL()) { + postData, postErr := request.PostData() + record(postData, postErr) + } + }) + if _, err := page.Goto(loginDetails.URL); err != nil { + return "", err + } + + if client.BrowserAutoFill { + if fullPage, ok := page.(playwright.Page); ok { + if err := autoFill(fullPage, loginDetails); err != nil { + logger.Error("error when auto filling", err) + } + } + } + + logger.Info("waiting ...") + capturedByCallback := func() bool { + mu.Lock() + defer mu.Unlock() + return data != "" + } + if !capturedByCallback() { + // Atmos fork: the sign-in request can reach the OnRequest callback after the check + // above but before ExpectRequest starts listening. ExpectRequest then never sees it + // and upstream waited for the full timeout and failed. The callback passed to + // ExpectRequest runs once the waiter listens and ends the wait when the request was + // already captured, and a failed wait still uses a request the callback captured. + r, err := page.ExpectRequest(signinRe, func() error { + if capturedByCallback() { + return errSAMLRequestCaptured + } + return nil + }, client.expectRequestTimeout()) + switch { + case (err != nil || r == nil) && capturedByCallback(): + // Use the request captured by the OnRequest callback. + case err != nil: + return "", fmt.Errorf("waiting for the AWS sign-in request: %w", err) + case r == nil: + return "", ErrNoSAMLResponse + default: + postData, postErr := r.PostData() + record(postData, postErr) + } + } + + mu.Lock() + captured, capturedErr := data, dataErr + mu.Unlock() + if capturedErr != nil { + return "", fmt.Errorf("reading the AWS sign-in request body: %w", capturedErr) + } + + values, err := url.ParseQuery(captured) + if err != nil { + return "", err + } + + samlResponse := values.Get("SAMLResponse") + if samlResponse == "" { + return "", ErrNoSAMLResponse + } + + return samlResponse, nil +} + +// hasSAMLResponse reports whether the request body carries a non-empty SAMLResponse form field. +func hasSAMLResponse(body string) bool { + values, err := url.ParseQuery(body) + return err == nil && values.Get("SAMLResponse") != "" +} + +var autoFill = func(page playwright.Page, loginDetails *creds.LoginDetails) error { + passwordField := page.Locator("input[type='password']") + err := passwordField.WaitFor(playwright.LocatorWaitForOptions{ + State: playwright.WaitForSelectorStateVisible, + }) + if err != nil { + return err + } + + err = passwordField.Fill(loginDetails.Password) + if err != nil { + return err + } + + keyboard := page.Keyboard() + + // move to username field which is above password field + err = keyboard.Press("Shift+Tab") + if err != nil { + return err + } + + err = keyboard.InsertText(loginDetails.Username) + if err != nil { + return err + } + + // Find the submit button or input of the form that the password field is in + submitLocator := page.Locator("form", playwright.PageLocatorOptions{ + Has: passwordField, + }).Locator("[type='submit']") + count, err := submitLocator.Count() + if err != nil { + return err + } + + // when submit locator exists, Click it + if count > 0 { + return submitLocator.Click() + } else { // Use javascript to submit the form when no submit input or button is found + _, err := page.Evaluate(`document.querySelector('input[type="password"]').form.submit()`, nil) + return err + } +} + +func signinRegex() (*regexp.Regexp, error) { + // https://docs.aws.amazon.com/general/latest/gr/signin-service.html + // https://docs.amazonaws.cn/en_us/aws/latest/userguide/endpoints-Ningxia.html + // https://docs.amazonaws.cn/en_us/aws/latest/userguide/endpoints-Beijing.html + return regexp.Compile(`https:\/\/((.*\.)?signin\.(aws\.amazon\.com|amazonaws-us-gov\.com|amazonaws\.cn))\/saml`) +} + +func (cl *Client) Validate(loginDetails *creds.LoginDetails) error { + if loginDetails.URL == "" { + return errors.New("empty URL") + } + + return nil +} + +func (cl *Client) expectRequestTimeout() playwright.PageExpectRequestOptions { + timeout := float64(cl.Timeout) + if timeout < 30000 { + timeout = DEFAULT_TIMEOUT + } + return playwright.PageExpectRequestOptions{Timeout: &timeout} +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser_integration_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_integration_test.go new file mode 100644 index 00000000000..4c9ad4cb9e5 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_integration_test.go @@ -0,0 +1,104 @@ +package browser + +import ( + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/mxschmitt/playwright-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +// These tests launch a real browser. They download the Playwright driver and Chromium +// (hundreds of MB), so they only run when RUN_PLAYWRIGHT_INTEGRATION=1 is set. + +func requirePlaywrightIntegration(t *testing.T) { + t.Helper() + if os.Getenv("RUN_PLAYWRIGHT_INTEGRATION") != "1" { + t.Skipf("Skipping real-browser test (set RUN_PLAYWRIGHT_INTEGRATION=1 to run)") + } + if testing.Short() { + t.Skipf("Skipping real-browser test in short mode") + } + if err := playwright.Install(&playwright.RunOptions{Browsers: []string{"chromium"}}); err != nil { + t.Skipf("Skipping real-browser test: could not install Playwright and Chromium: %v", err) + } +} + +func TestAuthenticateWithRealBrowser_Integration(t *testing.T) { + requirePlaywrightIntegration(t) + + original := getSAMLResponse + t.Cleanup(func() { getSAMLResponse = original }) + getSAMLResponse = func(samlPage, *creds.LoginDetails, *Client) (string, error) { + return testAssertion, nil + } + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("idp")) + })) + t.Cleanup(ts.Close) + + client := &Client{Headless: true} + got, err := client.Authenticate(&creds.LoginDetails{URL: ts.URL}) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +func TestAuthenticateInvalidBrowserExecutablePath_Integration(t *testing.T) { + requirePlaywrightIntegration(t) + + client := &Client{Headless: true, BrowserExecutablePath: "FAKEPATH"} + _, err := client.Authenticate(&creds.LoginDetails{URL: testIdPURL}) + require.ErrorContains(t, err, "FAKEPATH") +} + +func TestAutoFill_Integration(t *testing.T) { + requirePlaywrightIntegration(t) + + pw, err := playwright.Run() + require.NoError(t, err) + t.Cleanup(func() { _ = pw.Stop() }) + browser, err := pw.Chromium.Launch() + require.NoError(t, err) + t.Cleanup(func() { _ = browser.Close() }) + + for _, pageLocation := range []string{ + "example/loginpage.html", + "example/loginpage-button-submit.html", + "example/loginpage-without-submit.html", + } { + t.Run(pageLocation, func(t *testing.T) { + data, err := os.ReadFile(pageLocation) + require.NoError(t, err) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(data) + })) + t.Cleanup(ts.Close) + + context, err := browser.NewContext() + require.NoError(t, err) + t.Cleanup(func() { _ = context.Close() }) + page, err := context.NewPage() + require.NoError(t, err) + _, err = page.Goto(ts.URL) + require.NoError(t, err) + + loginDetails := &creds.LoginDetails{URL: ts.URL, Username: "golang", Password: "gopher"} + require.NoError(t, autoFill(page, loginDetails)) + + username, _ := page.Locator("input[name='username']").First().InputValue() + assert.Equal(t, "golang", username) + password, _ := page.Locator("input[type='password']").First().InputValue() + assert.Equal(t, "gopher", password) + + result, _ := page.Locator("div#result").Evaluate("el => el.innerText", nil) + assert.Equal(t, "golang:gopher", result) + }) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser_lifecycle_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_lifecycle_test.go new file mode 100644 index 00000000000..582351cebc5 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_lifecycle_test.go @@ -0,0 +1,150 @@ +package browser + +import ( + "os" + "testing" + + "github.com/mxschmitt/playwright-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +// fakePlaywright replaces the Playwright entry points with a driver whose Chromium is browserType. +// It returns a pointer to the number of times the driver was stopped. +func fakePlaywright(t *testing.T, browserType playwright.BrowserType) *int { + t.Helper() + originalInstall, originalRun, originalStop := installPlaywright, runPlaywright, stopPlaywright + t.Cleanup(func() { + installPlaywright, runPlaywright, stopPlaywright = originalInstall, originalRun, originalStop + }) + + stops := 0 + installPlaywright = func(...*playwright.RunOptions) error { + t.Fatal("install must not run when DownloadBrowser is false") + return nil + } + runPlaywright = func(...*playwright.RunOptions) (*playwright.Playwright, error) { + return &playwright.Playwright{Chromium: browserType}, nil + } + stopPlaywright = func(*playwright.Playwright) error { + stops++ + return nil + } + return &stops +} + +// Regression: upstream stopped the Playwright driver only in a defer registered after the +// page was created, so a failed browser launch left the driver process running. +func TestAuthenticateStopsPlaywrightWhenLaunchFails(t *testing.T) { + ctrl := gomock.NewController(t) + browserType := NewMockBrowserType(ctrl) + stops := fakePlaywright(t, browserType) + + browserType.EXPECT().Launch(gomock.Any()).Return(nil, errTest) + + _, err := (&Client{}).Authenticate(&creds.LoginDetails{URL: testIdPURL}) + require.ErrorIs(t, err, errTest) + assert.Equal(t, 1, *stops, "the Playwright driver must be stopped") +} + +// Regression: a failed context creation leaked both the browser and the driver. +func TestAuthenticateClosesBrowserWhenNewContextFails(t *testing.T) { + ctrl := gomock.NewController(t) + browserType := NewMockBrowserType(ctrl) + browser := NewMockBrowser(ctrl) + stops := fakePlaywright(t, browserType) + + browserType.EXPECT().Launch(gomock.Any()).Return(browser, nil) + browser.EXPECT().NewContext(gomock.Any()).Return(nil, errTest) + browser.EXPECT().Close().Return(nil) + + _, err := (&Client{}).Authenticate(&creds.LoginDetails{URL: testIdPURL}) + require.ErrorIs(t, err, errTest) + assert.Equal(t, 1, *stops, "the Playwright driver must be stopped") +} + +// Regression: a storage-state path failure leaked both the browser and the driver. +func TestAuthenticateClosesBrowserWhenStorageStatePathFails(t *testing.T) { + ctrl := gomock.NewController(t) + browserType := NewMockBrowserType(ctrl) + browser := NewMockBrowser(ctrl) + stops := fakePlaywright(t, browserType) + + original := storageStatePath + t.Cleanup(func() { storageStatePath = original }) + storageStatePath = func() (string, error) { return "", errTest } + + browserType.EXPECT().Launch(gomock.Any()).Return(browser, nil) + browser.EXPECT().Close().Return(nil) + + _, err := (&Client{}).Authenticate(&creds.LoginDetails{URL: testIdPURL}) + require.ErrorIs(t, err, errTest) + assert.Equal(t, 1, *stops, "the Playwright driver must be stopped") +} + +// A failed install never starts the driver. +func TestAuthenticateInstallFailureDoesNotStartPlaywright(t *testing.T) { + stops := fakePlaywright(t, nil) + installPlaywright = func(...*playwright.RunOptions) error { return errTest } + runPlaywright = func(...*playwright.RunOptions) (*playwright.Playwright, error) { + t.Fatal("Playwright must not start after a failed install") + return nil, nil + } + + _, err := (&Client{}).Authenticate(&creds.LoginDetails{URL: testIdPURL, DownloadBrowser: true}) + require.ErrorIs(t, err, errTest) + assert.Zero(t, *stops) +} + +// Install and Run receive the same options built by runOptions. +func TestAuthenticatePassesRunOptionsToInstallAndRun(t *testing.T) { + stops := fakePlaywright(t, nil) + var installed, ran *playwright.RunOptions + installPlaywright = func(opts ...*playwright.RunOptions) error { + installed = opts[0] + return nil + } + runPlaywright = func(opts ...*playwright.RunOptions) (*playwright.Playwright, error) { + ran = opts[0] + return nil, errTest + } + + client := &Client{BrowserDriverDir: t.TempDir()} + _, err := client.Authenticate(&creds.LoginDetails{URL: testIdPURL, DownloadBrowser: true}) + require.ErrorIs(t, err, errTest) + require.NotNil(t, installed) + assert.Same(t, installed, ran) + assert.Equal(t, client.BrowserDriverDir, installed.DriverDirectory) + assert.Zero(t, *stops, "a driver that failed to start has nothing to stop") +} + +// Regression: upstream installed with zero-value options, so the Playwright CLI wrote its +// download progress to stdout and downloaded every browser although only one is launched. +func TestRunOptions(t *testing.T) { + tests := []struct { + name string + client Client + wantBrowser []string + wantNoShell bool + }{ + {name: "default headed chromium", client: Client{}, wantBrowser: []string{"chromium"}, wantNoShell: true}, + {name: "default headless chromium needs the headless shell", client: Client{Headless: true}, wantBrowser: []string{"chromium"}}, + {name: "chromium channel uses the full build", client: Client{BrowserType: "chromium", Headless: true}, wantBrowser: []string{"chromium"}, wantNoShell: true}, + {name: "firefox", client: Client{BrowserType: "firefox"}, wantBrowser: []string{"firefox"}}, + {name: "webkit", client: Client{BrowserType: "webkit"}, wantBrowser: []string{"webkit"}}, + {name: "system browser channel keeps upstream defaults", client: Client{BrowserType: "msedge"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + opts := tt.client.runOptions() + assert.Same(t, os.Stderr, opts.Stdout, "install progress must not go to stdout") + assert.Equal(t, tt.wantBrowser, opts.Browsers) + assert.Equal(t, tt.wantNoShell, opts.NoInstallShell) + assert.False(t, opts.OnlyInstallShell) + }) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go new file mode 100644 index 00000000000..bf05a853965 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go @@ -0,0 +1,386 @@ +package browser + +import ( + "errors" + "net/url" + "path/filepath" + "testing" + + "github.com/mxschmitt/playwright-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +const ( + testIdPURL = "https://idp.example.com/login" + testSigninURL = "https://signin.aws.amazon.com/saml" + testAssertion = "PHNhbWxwOlJlc3BvbnNlPjwvc2FtbHA6UmVzcG9uc2U+" +) + +var errTest = errors.New("boom") + +func samlPostBody(assertion string) string { + params := url.Values{} + params.Add("RelayState", "state") + params.Add("SAMLResponse", assertion) + return params.Encode() +} + +func newTestClient(t *testing.T) *Client { + t.Helper() + client, err := New(&cfg.IDPAccount{Headless: true, Timeout: 100000}) + require.NoError(t, err) + return client +} + +func TestNew(t *testing.T) { + client, err := New(&cfg.IDPAccount{ + Headless: true, + BrowserDriverDir: "/drivers", + BrowserType: "Firefox", + BrowserExecutablePath: "/usr/bin/firefox", + Timeout: 42, + BrowserAutoFill: true, + }) + require.NoError(t, err) + assert.Equal(t, &Client{ + Headless: true, + BrowserDriverDir: "/drivers", + BrowserType: "firefox", + BrowserExecutablePath: "/usr/bin/firefox", + Timeout: 42, + BrowserAutoFill: true, + }, client) +} + +func TestValidate(t *testing.T) { + client := newTestClient(t) + + require.NoError(t, client.Validate(&creds.LoginDetails{URL: testIdPURL})) + require.ErrorContains(t, client.Validate(&creds.LoginDetails{}), "empty URL") +} + +func TestValidateBrowserType(t *testing.T) { + for _, browserType := range append([]string{""}, validBrowserTypes...) { + t.Run("valid "+browserType, func(t *testing.T) { + require.NoError(t, (&Client{BrowserType: browserType}).validateBrowserType()) + }) + } + + err := (&Client{BrowserType: "invalid"}).validateBrowserType() + require.ErrorContains(t, err, "invalid browser-type: 'invalid', only [chromium firefox webkit chrome chrome-beta chrome-dev chrome-canary msedge msedge-beta msedge-dev msedge-canary] are allowed") +} + +// An invalid browser type must fail before Playwright is installed or started. +func TestAuthenticateRejectsInvalidBrowserTypeBeforeStartingPlaywright(t *testing.T) { + client := &Client{BrowserType: "invalid", BrowserDriverDir: t.TempDir()} + + _, err := client.Authenticate(&creds.LoginDetails{URL: testIdPURL, DownloadBrowser: true}) + require.ErrorContains(t, err, "invalid browser-type") +} + +// Without an installed driver and without download, Run fails with a clear message (no network needed). +func TestAuthenticateWithoutDriverFails(t *testing.T) { + client := &Client{Headless: true, BrowserDriverDir: t.TempDir()} + + _, err := client.Authenticate(&creds.LoginDetails{URL: testIdPURL}) + require.ErrorContains(t, err, "please install the driver") +} + +func TestSigninRegex(t *testing.T) { + regex, err := signinRegex() + require.NoError(t, err) + + for _, u := range []string{ + "https://signin.aws.amazon.com/saml", + "https://us-east-1.signin.aws.amazon.com/saml", + "https://signin.amazonaws-us-gov.com/saml", + "https://signin.amazonaws.cn/saml", + } { + assert.True(t, regex.MatchString(u), u) + } + for _, u := range []string{"https://google.com/", "http://signin.aws.amazon.com/saml", "https://signin.aws.amazon.com/console"} { + assert.False(t, regex.MatchString(u), u) + } +} + +func TestExpectRequestOptions(t *testing.T) { + options := (&Client{Timeout: 100000}).expectRequestTimeout() + assert.InDelta(t, float64(100000), *options.Timeout, 0) +} + +func TestExpectRequestOptionsDefaultTimeout(t *testing.T) { + options := (&Client{Timeout: 1000}).expectRequestTimeout() + assert.InDelta(t, DEFAULT_TIMEOUT, *options.Timeout, 0) +} + +func TestStorageStatePath(t *testing.T) { + path, err := storageStatePath() + require.NoError(t, err) + assert.True(t, filepath.IsAbs(path), path) + assert.Equal(t, filepath.Join(".aws", "saml2aws", "storageState.json"), filepath.Join(filepath.Base(filepath.Dir(filepath.Dir(path))), filepath.Base(filepath.Dir(path)), filepath.Base(path))) +} + +// The SAML response is captured by ExpectRequest when the callback has not fired yet. +func TestGetSAMLResponseViaExpectRequest(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), client.expectRequestTimeout()).Return(req, nil) + req.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +// The SAML response is captured by the OnRequest callback, and ExpectRequest is not needed. +func TestGetSAMLResponseViaOnRequestCallback(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + var handler func(playwright.Request) + page.EXPECT().OnRequest(gomock.Any()).Do(func(fn func(playwright.Request)) { handler = fn }) + page.EXPECT().Goto(testIdPURL).DoAndReturn(func(string, ...playwright.PageGotoOptions) (playwright.Response, error) { + handler(req) + return nil, nil + }) + req.EXPECT().URL().Return(testSigninURL) + req.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +// Requests to other URLs are ignored by the callback. +func TestGetSAMLResponseCallbackIgnoresOtherURLs(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + other := NewMockRequest(ctrl) + signin := NewMockRequest(ctrl) + client := newTestClient(t) + + var handler func(playwright.Request) + page.EXPECT().OnRequest(gomock.Any()).Do(func(fn func(playwright.Request)) { handler = fn }) + page.EXPECT().Goto(testIdPURL).DoAndReturn(func(string, ...playwright.PageGotoOptions) (playwright.Response, error) { + handler(other) + return nil, nil + }) + other.EXPECT().URL().Return("https://idp.example.com/assets/app.js") + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(signin, nil) + signin.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +// Regression: upstream dereferenced the nil request after an ExpectRequest timeout and panicked. +func TestGetSAMLResponseExpectRequestTimeoutDoesNotPanic(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, errTest) + + var err error + require.NotPanics(t, func() { + _, err = getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + }) + require.ErrorIs(t, err, errTest) + assert.ErrorContains(t, err, "waiting for the AWS sign-in request") +} + +func TestGetSAMLResponseExpectRequestNilRequest(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) + + _, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.ErrorIs(t, err, ErrNoSAMLResponse) +} + +// Regression: upstream returned the wrong error variable, so a PostData failure was swallowed. +func TestGetSAMLResponsePostDataError(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(req, nil) + req.EXPECT().PostData().Return("", errTest) + + _, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.ErrorIs(t, err, errTest) +} + +func TestGetSAMLResponseGotoError(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, errTest) + + _, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.ErrorIs(t, err, errTest) +} + +func TestGetSAMLResponseMissingSAMLResponseField(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(req, nil) + req.EXPECT().PostData().Return("RelayState=state", nil) + + _, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.ErrorIs(t, err, ErrNoSAMLResponse) +} + +func TestGetSAMLResponseMalformedBody(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(req, nil) + req.EXPECT().PostData().Return("%zz", nil) + + _, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.Error(t, err) +} + +// Auto-fill only applies to a full playwright.Page; the narrow mock page is skipped without error. +func TestGetSAMLResponseAutoFillSkippedForNarrowPage(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + client.BrowserAutoFill = true + + original := autoFill + t.Cleanup(func() { autoFill = original }) + autoFill = func(playwright.Page, *creds.LoginDetails) error { + t.Fatal("autoFill must not be called for a page that is not a playwright.Page") + return nil + } + + page.EXPECT().OnRequest(gomock.Any()) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(req, nil) + req.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +func TestContains(t *testing.T) { + assert.True(t, contains([]string{"a", "b"}, "b")) + assert.False(t, contains([]string{"a", "b"}, "c")) + assert.False(t, contains(nil, "a")) +} + +// Regression: the sign-in request can reach the OnRequest callback after the "already +// captured" check but before ExpectRequest starts listening. ExpectRequest then never sees +// it and times out; upstream failed (or panicked) although the SAML response was captured. +func TestGetSAMLResponseUsesCallbackCaptureWhenExpectRequestMissesIt(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + var handler func(playwright.Request) + page.EXPECT().OnRequest(gomock.Any()).Do(func(fn func(playwright.Request)) { handler = fn }) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(any, func() error, ...playwright.PageExpectRequestOptions) (playwright.Request, error) { + handler(req) // Delivered to the OnRequest callback only. + return nil, errTest // The waiter never saw it and timed out. + }) + req.EXPECT().URL().Return(testSigninURL) + req.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +// Regression: a later request to the sign-in URL without a SAMLResponse (for example a GET) must not +// replace an assertion that was already captured. +func TestGetSAMLResponseKeepsCapturedAssertionOnLaterEmptyRequest(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + post := NewMockRequest(ctrl) + get := NewMockRequest(ctrl) + client := newTestClient(t) + + var handler func(playwright.Request) + page.EXPECT().OnRequest(gomock.Any()).Do(func(fn func(playwright.Request)) { handler = fn }) + page.EXPECT().Goto(testIdPURL).DoAndReturn(func(string, ...playwright.PageGotoOptions) (playwright.Response, error) { + handler(post) + handler(get) + return nil, nil + }) + post.EXPECT().URL().Return(testSigninURL) + post.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + get.EXPECT().URL().Return(testSigninURL) + get.EXPECT().PostData().Return("", nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} + +// The callback passed to ExpectRequest runs once the waiter listens. It lets the wait continue +// while nothing was captured, and ends it as soon as the OnRequest callback captured the request. +func TestGetSAMLResponseExpectRequestCallbackEndsWaitWhenCaptured(t *testing.T) { + ctrl := gomock.NewController(t) + page := NewMocksamlPage(ctrl) + req := NewMockRequest(ctrl) + client := newTestClient(t) + + var handler func(playwright.Request) + page.EXPECT().OnRequest(gomock.Any()).Do(func(fn func(playwright.Request)) { handler = fn }) + page.EXPECT().Goto(testIdPURL).Return(nil, nil) + page.EXPECT().ExpectRequest(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(_ any, cb func() error, _ ...playwright.PageExpectRequestOptions) (playwright.Request, error) { + require.NotNil(t, cb) + require.NoError(t, cb(), "nothing captured yet, keep waiting") + handler(req) + err := cb() + require.ErrorIs(t, err, errSAMLRequestCaptured) + return nil, err // playwright-go's RunAndWait returns the callback error. + }) + req.EXPECT().URL().Return(testSigninURL) + req.EXPECT().PostData().Return(samlPostBody(testAssertion), nil) + + got, err := getSAMLResponse(page, &creds.LoginDetails{URL: testIdPURL}, client) + require.NoError(t, err) + assert.Equal(t, testAssertion, got) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-button-submit.html b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-button-submit.html new file mode 100644 index 00000000000..979f798fc7a --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-button-submit.html @@ -0,0 +1,41 @@ + + + Fake Login Page + + +
+
+ + +
+ +
+ + +
+ +
+
+ + + + + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-without-submit.html b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-without-submit.html new file mode 100644 index 00000000000..e267347c6cd --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-without-submit.html @@ -0,0 +1,42 @@ + + + Fake Login Page + + +
+
+ + +
+ +
+ + +
+ + +
+ + + + + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage.html b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage.html new file mode 100644 index 00000000000..86c0f74b4a3 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage.html @@ -0,0 +1,41 @@ + + + Fake Login Page + + +
+
+ + +
+ +
+ + +
+ +
Login
+
+ + + + + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/mock_page_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/mock_page_test.go new file mode 100644 index 00000000000..890ca789f6b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/mock_page_test.go @@ -0,0 +1,136 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: browser.go +// +// Generated by this command: +// +// mockgen -source=browser.go -destination=mock_page_test.go -package=browser +// + +// Package browser is a generated GoMock package. +package browser + +import ( + reflect "reflect" + + playwright "github.com/mxschmitt/playwright-go" + gomock "go.uber.org/mock/gomock" +) + +// MocksamlPage is a mock of samlPage interface. +type MocksamlPage struct { + ctrl *gomock.Controller + recorder *MocksamlPageMockRecorder + isgomock struct{} +} + +// MocksamlPageMockRecorder is the mock recorder for MocksamlPage. +type MocksamlPageMockRecorder struct { + mock *MocksamlPage +} + +// NewMocksamlPage creates a new mock instance. +func NewMocksamlPage(ctrl *gomock.Controller) *MocksamlPage { + mock := &MocksamlPage{ctrl: ctrl} + mock.recorder = &MocksamlPageMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MocksamlPage) EXPECT() *MocksamlPageMockRecorder { + return m.recorder +} + +// ExpectRequest mocks base method. +func (m *MocksamlPage) ExpectRequest(urlOrPredicate any, cb func() error, options ...playwright.PageExpectRequestOptions) (playwright.Request, error) { + m.ctrl.T.Helper() + varargs := []any{urlOrPredicate, cb} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ExpectRequest", varargs...) + ret0, _ := ret[0].(playwright.Request) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ExpectRequest indicates an expected call of ExpectRequest. +func (mr *MocksamlPageMockRecorder) ExpectRequest(urlOrPredicate, cb any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{urlOrPredicate, cb}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExpectRequest", reflect.TypeOf((*MocksamlPage)(nil).ExpectRequest), varargs...) +} + +// Goto mocks base method. +func (m *MocksamlPage) Goto(url string, options ...playwright.PageGotoOptions) (playwright.Response, error) { + m.ctrl.T.Helper() + varargs := []any{url} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Goto", varargs...) + ret0, _ := ret[0].(playwright.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Goto indicates an expected call of Goto. +func (mr *MocksamlPageMockRecorder) Goto(url any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{url}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Goto", reflect.TypeOf((*MocksamlPage)(nil).Goto), varargs...) +} + +// OnRequest mocks base method. +func (m *MocksamlPage) OnRequest(fn func(playwright.Request)) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnRequest", fn) +} + +// OnRequest indicates an expected call of OnRequest. +func (mr *MocksamlPageMockRecorder) OnRequest(fn any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnRequest", reflect.TypeOf((*MocksamlPage)(nil).OnRequest), fn) +} + +// MockstorageStateSaver is a mock of storageStateSaver interface. +type MockstorageStateSaver struct { + ctrl *gomock.Controller + recorder *MockstorageStateSaverMockRecorder + isgomock struct{} +} + +// MockstorageStateSaverMockRecorder is the mock recorder for MockstorageStateSaver. +type MockstorageStateSaverMockRecorder struct { + mock *MockstorageStateSaver +} + +// NewMockstorageStateSaver creates a new mock instance. +func NewMockstorageStateSaver(ctrl *gomock.Controller) *MockstorageStateSaver { + mock := &MockstorageStateSaver{ctrl: ctrl} + mock.recorder = &MockstorageStateSaverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockstorageStateSaver) EXPECT() *MockstorageStateSaverMockRecorder { + return m.recorder +} + +// StorageState mocks base method. +func (m *MockstorageStateSaver) StorageState(path ...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range path { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "StorageState", varargs...) + ret0, _ := ret[0].(*playwright.StorageState) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StorageState indicates an expected call of StorageState. +func (mr *MockstorageStateSaverMockRecorder) StorageState(path ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StorageState", reflect.TypeOf((*MockstorageStateSaver)(nil).StorageState), path...) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/mock_request_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/mock_request_test.go new file mode 100644 index 00000000000..ef0c70fced9 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/mock_request_test.go @@ -0,0 +1,769 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/mxschmitt/playwright-go (interfaces: Request,BrowserType,Browser) +// +// Generated by this command: +// +// mockgen -destination=mock_request_test.go -package=browser github.com/mxschmitt/playwright-go Request,BrowserType,Browser +// + +// Package browser is a generated GoMock package. +package browser + +import ( + reflect "reflect" + + playwright "github.com/mxschmitt/playwright-go" + gomock "go.uber.org/mock/gomock" +) + +// MockRequest is a mock of Request interface. +type MockRequest struct { + ctrl *gomock.Controller + recorder *MockRequestMockRecorder + isgomock struct{} +} + +// MockRequestMockRecorder is the mock recorder for MockRequest. +type MockRequestMockRecorder struct { + mock *MockRequest +} + +// NewMockRequest creates a new mock instance. +func NewMockRequest(ctrl *gomock.Controller) *MockRequest { + mock := &MockRequest{ctrl: ctrl} + mock.recorder = &MockRequestMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRequest) EXPECT() *MockRequestMockRecorder { + return m.recorder +} + +// AllHeaders mocks base method. +func (m *MockRequest) AllHeaders() (map[string]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AllHeaders") + ret0, _ := ret[0].(map[string]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AllHeaders indicates an expected call of AllHeaders. +func (mr *MockRequestMockRecorder) AllHeaders() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllHeaders", reflect.TypeOf((*MockRequest)(nil).AllHeaders)) +} + +// ExistingResponse mocks base method. +func (m *MockRequest) ExistingResponse() (playwright.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExistingResponse") + ret0, _ := ret[0].(playwright.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ExistingResponse indicates an expected call of ExistingResponse. +func (mr *MockRequestMockRecorder) ExistingResponse() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExistingResponse", reflect.TypeOf((*MockRequest)(nil).ExistingResponse)) +} + +// Failure mocks base method. +func (m *MockRequest) Failure() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Failure") + ret0, _ := ret[0].(error) + return ret0 +} + +// Failure indicates an expected call of Failure. +func (mr *MockRequestMockRecorder) Failure() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Failure", reflect.TypeOf((*MockRequest)(nil).Failure)) +} + +// Frame mocks base method. +func (m *MockRequest) Frame() playwright.Frame { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Frame") + ret0, _ := ret[0].(playwright.Frame) + return ret0 +} + +// Frame indicates an expected call of Frame. +func (mr *MockRequestMockRecorder) Frame() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Frame", reflect.TypeOf((*MockRequest)(nil).Frame)) +} + +// HeaderValue mocks base method. +func (m *MockRequest) HeaderValue(name string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HeaderValue", name) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HeaderValue indicates an expected call of HeaderValue. +func (mr *MockRequestMockRecorder) HeaderValue(name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeaderValue", reflect.TypeOf((*MockRequest)(nil).HeaderValue), name) +} + +// Headers mocks base method. +func (m *MockRequest) Headers() map[string]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Headers") + ret0, _ := ret[0].(map[string]string) + return ret0 +} + +// Headers indicates an expected call of Headers. +func (mr *MockRequestMockRecorder) Headers() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Headers", reflect.TypeOf((*MockRequest)(nil).Headers)) +} + +// HeadersArray mocks base method. +func (m *MockRequest) HeadersArray() ([]playwright.NameValue, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HeadersArray") + ret0, _ := ret[0].([]playwright.NameValue) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HeadersArray indicates an expected call of HeadersArray. +func (mr *MockRequestMockRecorder) HeadersArray() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeadersArray", reflect.TypeOf((*MockRequest)(nil).HeadersArray)) +} + +// IsNavigationRequest mocks base method. +func (m *MockRequest) IsNavigationRequest() bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsNavigationRequest") + ret0, _ := ret[0].(bool) + return ret0 +} + +// IsNavigationRequest indicates an expected call of IsNavigationRequest. +func (mr *MockRequestMockRecorder) IsNavigationRequest() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNavigationRequest", reflect.TypeOf((*MockRequest)(nil).IsNavigationRequest)) +} + +// Method mocks base method. +func (m *MockRequest) Method() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Method") + ret0, _ := ret[0].(string) + return ret0 +} + +// Method indicates an expected call of Method. +func (mr *MockRequestMockRecorder) Method() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method", reflect.TypeOf((*MockRequest)(nil).Method)) +} + +// PostData mocks base method. +func (m *MockRequest) PostData() (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostData") + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PostData indicates an expected call of PostData. +func (mr *MockRequestMockRecorder) PostData() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostData", reflect.TypeOf((*MockRequest)(nil).PostData)) +} + +// PostDataBuffer mocks base method. +func (m *MockRequest) PostDataBuffer() ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostDataBuffer") + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PostDataBuffer indicates an expected call of PostDataBuffer. +func (mr *MockRequestMockRecorder) PostDataBuffer() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostDataBuffer", reflect.TypeOf((*MockRequest)(nil).PostDataBuffer)) +} + +// PostDataJSON mocks base method. +func (m *MockRequest) PostDataJSON(v any) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostDataJSON", v) + ret0, _ := ret[0].(error) + return ret0 +} + +// PostDataJSON indicates an expected call of PostDataJSON. +func (mr *MockRequestMockRecorder) PostDataJSON(v any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostDataJSON", reflect.TypeOf((*MockRequest)(nil).PostDataJSON), v) +} + +// RedirectedFrom mocks base method. +func (m *MockRequest) RedirectedFrom() playwright.Request { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RedirectedFrom") + ret0, _ := ret[0].(playwright.Request) + return ret0 +} + +// RedirectedFrom indicates an expected call of RedirectedFrom. +func (mr *MockRequestMockRecorder) RedirectedFrom() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RedirectedFrom", reflect.TypeOf((*MockRequest)(nil).RedirectedFrom)) +} + +// RedirectedTo mocks base method. +func (m *MockRequest) RedirectedTo() playwright.Request { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RedirectedTo") + ret0, _ := ret[0].(playwright.Request) + return ret0 +} + +// RedirectedTo indicates an expected call of RedirectedTo. +func (mr *MockRequestMockRecorder) RedirectedTo() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RedirectedTo", reflect.TypeOf((*MockRequest)(nil).RedirectedTo)) +} + +// ResourceType mocks base method. +func (m *MockRequest) ResourceType() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResourceType") + ret0, _ := ret[0].(string) + return ret0 +} + +// ResourceType indicates an expected call of ResourceType. +func (mr *MockRequestMockRecorder) ResourceType() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceType", reflect.TypeOf((*MockRequest)(nil).ResourceType)) +} + +// Response mocks base method. +func (m *MockRequest) Response() (playwright.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Response") + ret0, _ := ret[0].(playwright.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Response indicates an expected call of Response. +func (mr *MockRequestMockRecorder) Response() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Response", reflect.TypeOf((*MockRequest)(nil).Response)) +} + +// Sizes mocks base method. +func (m *MockRequest) Sizes() (*playwright.RequestSizesResult, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Sizes") + ret0, _ := ret[0].(*playwright.RequestSizesResult) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Sizes indicates an expected call of Sizes. +func (mr *MockRequestMockRecorder) Sizes() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sizes", reflect.TypeOf((*MockRequest)(nil).Sizes)) +} + +// Timing mocks base method. +func (m *MockRequest) Timing() *playwright.RequestTiming { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Timing") + ret0, _ := ret[0].(*playwright.RequestTiming) + return ret0 +} + +// Timing indicates an expected call of Timing. +func (mr *MockRequestMockRecorder) Timing() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Timing", reflect.TypeOf((*MockRequest)(nil).Timing)) +} + +// URL mocks base method. +func (m *MockRequest) URL() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "URL") + ret0, _ := ret[0].(string) + return ret0 +} + +// URL indicates an expected call of URL. +func (mr *MockRequestMockRecorder) URL() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "URL", reflect.TypeOf((*MockRequest)(nil).URL)) +} + +// MockBrowserType is a mock of BrowserType interface. +type MockBrowserType struct { + ctrl *gomock.Controller + recorder *MockBrowserTypeMockRecorder + isgomock struct{} +} + +// MockBrowserTypeMockRecorder is the mock recorder for MockBrowserType. +type MockBrowserTypeMockRecorder struct { + mock *MockBrowserType +} + +// NewMockBrowserType creates a new mock instance. +func NewMockBrowserType(ctrl *gomock.Controller) *MockBrowserType { + mock := &MockBrowserType{ctrl: ctrl} + mock.recorder = &MockBrowserTypeMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockBrowserType) EXPECT() *MockBrowserTypeMockRecorder { + return m.recorder +} + +// Connect mocks base method. +func (m *MockBrowserType) Connect(endpoint string, options ...playwright.BrowserTypeConnectOptions) (playwright.Browser, error) { + m.ctrl.T.Helper() + varargs := []any{endpoint} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Connect", varargs...) + ret0, _ := ret[0].(playwright.Browser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Connect indicates an expected call of Connect. +func (mr *MockBrowserTypeMockRecorder) Connect(endpoint any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{endpoint}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connect", reflect.TypeOf((*MockBrowserType)(nil).Connect), varargs...) +} + +// ConnectOverCDP mocks base method. +func (m *MockBrowserType) ConnectOverCDP(endpointURL string, options ...playwright.BrowserTypeConnectOverCDPOptions) (playwright.Browser, error) { + m.ctrl.T.Helper() + varargs := []any{endpointURL} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ConnectOverCDP", varargs...) + ret0, _ := ret[0].(playwright.Browser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ConnectOverCDP indicates an expected call of ConnectOverCDP. +func (mr *MockBrowserTypeMockRecorder) ConnectOverCDP(endpointURL any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{endpointURL}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectOverCDP", reflect.TypeOf((*MockBrowserType)(nil).ConnectOverCDP), varargs...) +} + +// ExecutablePath mocks base method. +func (m *MockBrowserType) ExecutablePath() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExecutablePath") + ret0, _ := ret[0].(string) + return ret0 +} + +// ExecutablePath indicates an expected call of ExecutablePath. +func (mr *MockBrowserTypeMockRecorder) ExecutablePath() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecutablePath", reflect.TypeOf((*MockBrowserType)(nil).ExecutablePath)) +} + +// Launch mocks base method. +func (m *MockBrowserType) Launch(options ...playwright.BrowserTypeLaunchOptions) (playwright.Browser, error) { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Launch", varargs...) + ret0, _ := ret[0].(playwright.Browser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Launch indicates an expected call of Launch. +func (mr *MockBrowserTypeMockRecorder) Launch(options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Launch", reflect.TypeOf((*MockBrowserType)(nil).Launch), options...) +} + +// LaunchPersistentContext mocks base method. +func (m *MockBrowserType) LaunchPersistentContext(userDataDir string, options ...playwright.BrowserTypeLaunchPersistentContextOptions) (playwright.BrowserContext, error) { + m.ctrl.T.Helper() + varargs := []any{userDataDir} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "LaunchPersistentContext", varargs...) + ret0, _ := ret[0].(playwright.BrowserContext) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// LaunchPersistentContext indicates an expected call of LaunchPersistentContext. +func (mr *MockBrowserTypeMockRecorder) LaunchPersistentContext(userDataDir any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{userDataDir}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LaunchPersistentContext", reflect.TypeOf((*MockBrowserType)(nil).LaunchPersistentContext), varargs...) +} + +// Name mocks base method. +func (m *MockBrowserType) Name() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Name") + ret0, _ := ret[0].(string) + return ret0 +} + +// Name indicates an expected call of Name. +func (mr *MockBrowserTypeMockRecorder) Name() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockBrowserType)(nil).Name)) +} + +// MockBrowser is a mock of Browser interface. +type MockBrowser struct { + ctrl *gomock.Controller + recorder *MockBrowserMockRecorder + isgomock struct{} +} + +// MockBrowserMockRecorder is the mock recorder for MockBrowser. +type MockBrowserMockRecorder struct { + mock *MockBrowser +} + +// NewMockBrowser creates a new mock instance. +func NewMockBrowser(ctrl *gomock.Controller) *MockBrowser { + mock := &MockBrowser{ctrl: ctrl} + mock.recorder = &MockBrowserMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockBrowser) EXPECT() *MockBrowserMockRecorder { + return m.recorder +} + +// Bind mocks base method. +func (m *MockBrowser) Bind(title string, options ...playwright.BrowserBindOptions) (*playwright.Bind, error) { + m.ctrl.T.Helper() + varargs := []any{title} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Bind", varargs...) + ret0, _ := ret[0].(*playwright.Bind) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Bind indicates an expected call of Bind. +func (mr *MockBrowserMockRecorder) Bind(title any, options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{title}, options...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bind", reflect.TypeOf((*MockBrowser)(nil).Bind), varargs...) +} + +// BrowserType mocks base method. +func (m *MockBrowser) BrowserType() playwright.BrowserType { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BrowserType") + ret0, _ := ret[0].(playwright.BrowserType) + return ret0 +} + +// BrowserType indicates an expected call of BrowserType. +func (mr *MockBrowserMockRecorder) BrowserType() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BrowserType", reflect.TypeOf((*MockBrowser)(nil).BrowserType)) +} + +// Close mocks base method. +func (m *MockBrowser) Close(options ...playwright.BrowserCloseOptions) error { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Close", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *MockBrowserMockRecorder) Close(options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockBrowser)(nil).Close), options...) +} + +// Contexts mocks base method. +func (m *MockBrowser) Contexts() []playwright.BrowserContext { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Contexts") + ret0, _ := ret[0].([]playwright.BrowserContext) + return ret0 +} + +// Contexts indicates an expected call of Contexts. +func (mr *MockBrowserMockRecorder) Contexts() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Contexts", reflect.TypeOf((*MockBrowser)(nil).Contexts)) +} + +// Emit mocks base method. +func (m *MockBrowser) Emit(name string, payload ...any) bool { + m.ctrl.T.Helper() + varargs := []any{name} + for _, a := range payload { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Emit", varargs...) + ret0, _ := ret[0].(bool) + return ret0 +} + +// Emit indicates an expected call of Emit. +func (mr *MockBrowserMockRecorder) Emit(name any, payload ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{name}, payload...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Emit", reflect.TypeOf((*MockBrowser)(nil).Emit), varargs...) +} + +// IsConnected mocks base method. +func (m *MockBrowser) IsConnected() bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsConnected") + ret0, _ := ret[0].(bool) + return ret0 +} + +// IsConnected indicates an expected call of IsConnected. +func (mr *MockBrowserMockRecorder) IsConnected() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsConnected", reflect.TypeOf((*MockBrowser)(nil).IsConnected)) +} + +// ListenerCount mocks base method. +func (m *MockBrowser) ListenerCount(name string) int { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListenerCount", name) + ret0, _ := ret[0].(int) + return ret0 +} + +// ListenerCount indicates an expected call of ListenerCount. +func (mr *MockBrowserMockRecorder) ListenerCount(name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListenerCount", reflect.TypeOf((*MockBrowser)(nil).ListenerCount), name) +} + +// NewBrowserCDPSession mocks base method. +func (m *MockBrowser) NewBrowserCDPSession() (playwright.CDPSession, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "NewBrowserCDPSession") + ret0, _ := ret[0].(playwright.CDPSession) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// NewBrowserCDPSession indicates an expected call of NewBrowserCDPSession. +func (mr *MockBrowserMockRecorder) NewBrowserCDPSession() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBrowserCDPSession", reflect.TypeOf((*MockBrowser)(nil).NewBrowserCDPSession)) +} + +// NewContext mocks base method. +func (m *MockBrowser) NewContext(options ...playwright.BrowserNewContextOptions) (playwright.BrowserContext, error) { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "NewContext", varargs...) + ret0, _ := ret[0].(playwright.BrowserContext) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// NewContext indicates an expected call of NewContext. +func (mr *MockBrowserMockRecorder) NewContext(options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewContext", reflect.TypeOf((*MockBrowser)(nil).NewContext), options...) +} + +// NewPage mocks base method. +func (m *MockBrowser) NewPage(options ...playwright.BrowserNewPageOptions) (playwright.Page, error) { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "NewPage", varargs...) + ret0, _ := ret[0].(playwright.Page) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// NewPage indicates an expected call of NewPage. +func (mr *MockBrowserMockRecorder) NewPage(options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewPage", reflect.TypeOf((*MockBrowser)(nil).NewPage), options...) +} + +// On mocks base method. +func (m *MockBrowser) On(name string, handler any) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "On", name, handler) +} + +// On indicates an expected call of On. +func (mr *MockBrowserMockRecorder) On(name, handler any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "On", reflect.TypeOf((*MockBrowser)(nil).On), name, handler) +} + +// OnContext mocks base method. +func (m *MockBrowser) OnContext(fn func(playwright.BrowserContext)) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnContext", fn) +} + +// OnContext indicates an expected call of OnContext. +func (mr *MockBrowserMockRecorder) OnContext(fn any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnContext", reflect.TypeOf((*MockBrowser)(nil).OnContext), fn) +} + +// OnDisconnected mocks base method. +func (m *MockBrowser) OnDisconnected(fn func(playwright.Browser)) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnDisconnected", fn) +} + +// OnDisconnected indicates an expected call of OnDisconnected. +func (mr *MockBrowserMockRecorder) OnDisconnected(fn any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnDisconnected", reflect.TypeOf((*MockBrowser)(nil).OnDisconnected), fn) +} + +// Once mocks base method. +func (m *MockBrowser) Once(name string, handler any) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Once", name, handler) +} + +// Once indicates an expected call of Once. +func (mr *MockBrowserMockRecorder) Once(name, handler any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Once", reflect.TypeOf((*MockBrowser)(nil).Once), name, handler) +} + +// RemoveListener mocks base method. +func (m *MockBrowser) RemoveListener(name string, handler any) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RemoveListener", name, handler) +} + +// RemoveListener indicates an expected call of RemoveListener. +func (mr *MockBrowserMockRecorder) RemoveListener(name, handler any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveListener", reflect.TypeOf((*MockBrowser)(nil).RemoveListener), name, handler) +} + +// RemoveListeners mocks base method. +func (m *MockBrowser) RemoveListeners(name string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RemoveListeners", name) +} + +// RemoveListeners indicates an expected call of RemoveListeners. +func (mr *MockBrowserMockRecorder) RemoveListeners(name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveListeners", reflect.TypeOf((*MockBrowser)(nil).RemoveListeners), name) +} + +// StartTracing mocks base method. +func (m *MockBrowser) StartTracing(options ...playwright.BrowserStartTracingOptions) error { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range options { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "StartTracing", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// StartTracing indicates an expected call of StartTracing. +func (mr *MockBrowserMockRecorder) StartTracing(options ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartTracing", reflect.TypeOf((*MockBrowser)(nil).StartTracing), options...) +} + +// StopTracing mocks base method. +func (m *MockBrowser) StopTracing() ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StopTracing") + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StopTracing indicates an expected call of StopTracing. +func (mr *MockBrowserMockRecorder) StopTracing() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopTracing", reflect.TypeOf((*MockBrowser)(nil).StopTracing)) +} + +// Unbind mocks base method. +func (m *MockBrowser) Unbind() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Unbind") + ret0, _ := ret[0].(error) + return ret0 +} + +// Unbind indicates an expected call of Unbind. +func (mr *MockBrowserMockRecorder) Unbind() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unbind", reflect.TypeOf((*MockBrowser)(nil).Unbind)) +} + +// Version mocks base method. +func (m *MockBrowser) Version() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Version") + ret0, _ := ret[0].(string) + return ret0 +} + +// Version indicates an expected call of Version. +func (mr *MockBrowserMockRecorder) Version() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*MockBrowser)(nil).Version)) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go new file mode 100644 index 00000000000..95a44d3d1be --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go @@ -0,0 +1,125 @@ +package browser + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/mxschmitt/playwright-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" +) + +// writeStateLikePlaywright writes the state file the way Playwright does (world-readable). +func writeStateLikePlaywright(t *testing.T) func(...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) { + t.Helper() + return func(opts ...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) { + require.Len(t, opts, 1) + require.NotNil(t, opts[0].Path) + require.NoError(t, os.WriteFile(*opts[0].Path, []byte(`{"cookies":[]}`), 0o644)) + return &playwright.StorageState{}, nil + } +} + +// The storage state holds IdP session cookies, so it must not stay world-readable. +func TestSaveStorageStateRestrictsPermissions(t *testing.T) { + ctrl := gomock.NewController(t) + saver := NewMockstorageStateSaver(ctrl) + statePath := filepath.Join(t.TempDir(), ".aws", "saml2aws", "storageState.json") + + saver.EXPECT().StorageState(gomock.Any()).DoAndReturn(writeStateLikePlaywright(t)) + + require.NoError(t, saveStorageState(saver, statePath)) + + data, err := os.ReadFile(statePath) + require.NoError(t, err) + assert.JSONEq(t, `{"cookies":[]}`, string(data)) + + if runtime.GOOS == "windows" { + return // Unix permission bits are not meaningful on Windows. + } + fileInfo, err := os.Stat(statePath) + require.NoError(t, err) + assert.Equal(t, os.FileMode(storageStateFilePerm), fileInfo.Mode().Perm()) + dirInfo, err := os.Stat(filepath.Dir(statePath)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(storageStateDirPerm), dirInfo.Mode().Perm()) +} + +func TestSaveStorageStateReturnsSaveError(t *testing.T) { + ctrl := gomock.NewController(t) + saver := NewMockstorageStateSaver(ctrl) + statePath := filepath.Join(t.TempDir(), "storageState.json") + + saver.EXPECT().StorageState(gomock.Any()).Return(nil, errTest) + + require.ErrorIs(t, saveStorageState(saver, statePath), errTest) + _, err := os.Stat(statePath) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestSaveStorageStateReturnsMkdirError(t *testing.T) { + ctrl := gomock.NewController(t) + saver := NewMockstorageStateSaver(ctrl) // No StorageState call is expected. + + // A regular file where the parent directory should be makes MkdirAll fail on every OS. + blocker := filepath.Join(t.TempDir(), "blocker") + require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600)) + + require.Error(t, saveStorageState(saver, filepath.Join(blocker, "storageState.json"))) +} + +// Regression: the state is written to a private temporary file, so it is never world-readable, even when +// the destination file or directory already exists with wide permissions. +func TestSaveStorageStateNeverWorldReadable(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skipf("Unix permission bits are not meaningful on Windows.") + } + ctrl := gomock.NewController(t) + saver := NewMockstorageStateSaver(ctrl) + dir := t.TempDir() + require.NoError(t, os.Chmod(dir, 0o755)) + statePath := filepath.Join(dir, "storageState.json") + require.NoError(t, os.WriteFile(statePath, []byte(`{"old":true}`), 0o644)) + + saver.EXPECT().StorageState(gomock.Any()).DoAndReturn(func(opts ...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) { + // While Playwright writes, the target is a private file in a private directory. + info, err := os.Stat(*opts[0].Path) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + dirInfo, err := os.Stat(dir) + require.NoError(t, err) + assert.Equal(t, os.FileMode(storageStateDirPerm), dirInfo.Mode().Perm()) + return writeStateLikePlaywright(t)(opts...) + }) + + require.NoError(t, saveStorageState(saver, statePath)) + info, err := os.Stat(statePath) + require.NoError(t, err) + assert.Equal(t, os.FileMode(storageStateFilePerm), info.Mode().Perm()) +} + +// A failed save keeps the previous state and leaves no temporary file behind. +func TestSaveStorageStateFailurePreservesPreviousState(t *testing.T) { + ctrl := gomock.NewController(t) + saver := NewMockstorageStateSaver(ctrl) + dir := t.TempDir() + statePath := filepath.Join(dir, "storageState.json") + require.NoError(t, os.WriteFile(statePath, []byte(`{"old":true}`), 0o600)) + + saver.EXPECT().StorageState(gomock.Any()).DoAndReturn(func(opts ...playwright.BrowserContextStorageStateOptions) (*playwright.StorageState, error) { + require.NoError(t, os.WriteFile(*opts[0].Path, []byte("partial"), 0o600)) + return nil, errTest + }) + + require.ErrorIs(t, saveStorageState(saver, statePath), errTest) + + data, err := os.ReadFile(statePath) + require.NoError(t, err) + assert.JSONEq(t, `{"old":true}`, string(data)) + entries, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Len(t, entries, 1) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/captcha.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/captcha.html new file mode 100644 index 00000000000..07e0e05579f --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/captcha.html @@ -0,0 +1,102 @@ + + + + Sign in - Google Accounts + + +
+
+
+
+
Google
+
+
+
+

Sign in

+

Use your Google Account

+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+

+

Forgot email?

+ +
+ CAPTCHA image of text used to distinguish humans from robots + + +
+
+
+
+ +
+
+
+
+ +
+ Please enter the characters you see in the image above +
+
+
+
+ +
+ + + + + + + +
+
+
+ +
+

Not your computer? Use a private browsing window to sign in. Learn more about using Guest mode

+
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+ + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-extra-number.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-extra-number.html new file mode 100644 index 00000000000..67dcbc6b51c --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-extra-number.html @@ -0,0 +1,96 @@ + + + + + + Google Accounts + + + +
+
+
+
+
+
+
+
+
+

2-Step Verification

+

This extra step shows it’s really you trying to sign in

+
+
+
+
Open the Gmail app on Nicholas’s iPhone
Google sent a notification to your Nicholas’s iPhone. Open the Gmail app, tap Yes on the prompt, then tap 89 on your phone to verify it’s you.
89

After you’ve finished on your phone, press the button below.

Don’t ask again on this device
+
+
+
+
+
+
+
nick@example.comUse a different account
+
+
+
+ +
+
+
+
+
+ + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-prompt.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-prompt.html new file mode 100644 index 00000000000..ad7bf502ec1 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-prompt.html @@ -0,0 +1,126 @@ + + + + + + Google Accounts + + + +
+
+
+
+
+
+
+
+
+
+

2-Step Verification

+
+
+

This extra step shows it’s really you trying to sign in

+
+
+
+
+
+
+ + + + + + + + + + Didn't get the prompt? + +
+
+
+
+
+ + + + + + + + + + +
+
+ +
Unlock your Google Pixel 2
+
+
Google sent a notification to your Google Pixel 2. Tap + Yes on the notification to continue. +
+ +
+
+
+
+ + + +
+ + Don't ask again on this computer + +
+
+
+
+
+
+
+
+
+ + + + + + + + + +
+
+
+ mark@wolfe.id.au + Use a different account +
+
+
+ + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms-send.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms-send.html new file mode 100644 index 00000000000..2d2d747e3fd --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms-send.html @@ -0,0 +1,350 @@ + + + + +
+
+
+
+
+
+
+
+
+
+
+

2-Step Verification

+
+
+

This extra step shows it’s really you trying to sign in

+
+
+
+
+
+ + + + + + + + + + + + + + + +
+ +
+ Get a verification code by text message at: + + (•••) •••-••XX + +
+ +
+ + + Don’t ask again on this device + + +
+
+
+
+
+
+
+ + + + + + + + + + + + + + +
+
+
+ + edw@defang.io + + + Use a different account + +
+
+
+
+ +
+ + + + +
+
+
+
+ diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html new file mode 100644 index 00000000000..0a67c70a610 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html @@ -0,0 +1,371 @@ + + + + +
+
+
+
+
+
+
+
+
+
+
+

+ 2-Step Verification +

+
+
+

+ This extra step shows it’s really you trying to sign in +

+
+
+
+
+
+ + + + + + + + + + + + + + + +
+ +
+ Enter a verification code +
+
+ A text message with a verification code was just sent to + + (•••) •••-••XX + +
+
+
+ G- +
+ +
+ + + Enter a code + + + +
+ + + Don’t ask again on this device + + +
+
+
+
+
+
+
+ + + + + + + + + + + + + + +
+
+
+ + edw@defang.io + + + Use a different account + +
+
+
+
+ +
+ + + + +
+
+
+
+ + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html new file mode 100644 index 00000000000..b69d2f7393c --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html @@ -0,0 +1,102 @@ + + + + + + Google Accounts + + + +
+
+
+
+
+
+
+
+
+
+

2-Step Verification

+
+
+

This extra step shows it’s really you trying to sign in

+
+
+
+
+
+ + + + + + + + + + +
+ +
Enter a verification code
+
Get a verification code from the + Google Authenticator app
+
+ +
+ +
+ + Don't ask again on this computer + +
+
+
+
+
+
+
+ + + + + + + + + +
+
+
+ mark@wolfe.id.au + Use a different account +
+
+
+
+ +
+
+
+ + + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-1.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-1.html new file mode 100644 index 00000000000..e8771fd7f63 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-1.html @@ -0,0 +1,115 @@ + + + + + + + + + + Google Accounts + + +
+
+
+
+
+
+
+
+
+
+

One account. All of Google.

+

Sign in with your Google Account

+
+
+
+
+ + + + + + + + + + + + + + + +
+
+ + test-id1@example.com +
+ +
+ + +
+ +
+ + Stay signed in + +
+
+
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+

Sign in with a different account

+

One Google Account for everything Google

+
+
+
+
+
+
+ +
+ + + +
+
+
+
+ + +
diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-2.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-2.html new file mode 100644 index 00000000000..046c73c1ee9 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-2.html @@ -0,0 +1,115 @@ + + + + + + + + + + Google Accounts + + +
+
+
+
+
+
+
+
+
+
+

One account. All of Google.

+

Sign in with your Google Account

+
+
+
+
+ + + + + + + + + + + + + + + +
+
+ + test-id2@example.com +
+ +
+ + +
+ +
+ + Stay signed in + +
+
+
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+

Sign in with a different account

+

One Google Account for everything Google

+
+
+
+
+
+
+ +
+ + + +
+
+
+
+ + +
diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-3.html b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-3.html new file mode 100644 index 00000000000..3591d59fcdb --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-3.html @@ -0,0 +1,93 @@ + + + + + + + + + + + Sign in - Google Accounts + + +
+
+
+
+
+ Google +
+
+
+
+

Welcome

+

+ +
+
+
+ +
+ + + + +
+
+
+
+ +
+
+
+
+
+
+ + +
+
+ +
+
+
+
+ +
+
+ +
+
+
+ +
+
+
+
+
+
+ + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go new file mode 100644 index 00000000000..0d79e1e00e4 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -0,0 +1,956 @@ +package googleapps + +import ( + "bufio" + "bytes" + b64 "encoding/base64" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "strings" + + "github.com/PuerkitoBio/goquery" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/prompter" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/provider" +) + +var logger = logrus.WithField("provider", "googleapps") + +// errInputValueNotFound is returned when a form input exists but has no value attribute. +var errInputValueNotFound = errors.New("unable to locate field value") + +// errCaptchaImageNotFound is returned when a captcha is requested but its image cannot be found. +var errCaptchaImageNotFound = errors.New("captcha image not found but requested") + +// errCaptchaAttemptsExceeded is returned when Google keeps asking for a captcha. +var errCaptchaAttemptsExceeded = errors.New("captcha still requested after the maximum number of attempts") + +// errMFATransitionsExceeded is returned when Google keeps sending the user back to a challenge selection page. +var errMFATransitionsExceeded = errors.New("2-step verification did not complete after the maximum number of challenge transitions") + +// maxMFATransitions bounds how many challenge selection pages one authentication attempt follows. +const maxMFATransitions = 10 + +// maxCaptchaAttempts bounds how many captcha answers are submitted before giving up. +const maxCaptchaAttempts = 5 + +// captchaInputIDs are the element ids that mark a page asking for a captcha. +var captchaInputIDs = []string{ + "logincaptcha", + "identifier-captcha-input", + "captchaimg", +} + +// findCaptcha returns the captcha element on the page and the name of the form field to answer it in. +// It returns an empty selection when the page does not ask for a captcha. +func findCaptcha(doc *goquery.Document) (*goquery.Selection, string) { + for _, id := range captchaInputIDs { + if found := doc.Find("#" + id); found.Length() > 0 { + return found, id + } + } + // Atmos fork: the new-style captcha input has `name="ca"` and no id. + if found := doc.Find("input[name='ca']"); found.Length() > 0 { + return found, "ca" + } + return doc.Find("#" + captchaInputIDs[0]), "" +} + +// Atmos fork: the U2F device finder is created through a package variable so tests can +// inject a mock device instead of requiring attached hardware. +var newU2FDeviceFinder = func() DeviceFinder { return &U2FDeviceFinder{} } + +// Client wrapper around Google Apps. +type Client struct { + provider.ValidateBase + + client *provider.HTTPClient + + // mfaTransitions counts the challenge selection pages followed during the current authentication attempt. + // Atmos fork: upstream followed them recursively without a limit. + mfaTransitions int +} + +// New create a new Google Apps Client +func New(idpAccount *cfg.IDPAccount) (*Client, error) { + tr := provider.NewDefaultTransport(idpAccount.SkipVerify) + + client, err := provider.NewHTTPClient(tr, provider.BuildHttpClientOpts(idpAccount)) + if err != nil { + return nil, errors.Wrap(err, "error building http client") + } + + return &Client{ + client: client, + }, nil +} + +// Authenticate logs into Google Apps and returns a SAML response +func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) { + kc.mfaTransitions = 0 + + // Get the first page + authURL, authForm, err := kc.loadFirstPage(loginDetails) + if err != nil { + return "", errors.Wrap(err, "error loading first page") + } + + // Google supports only JavaScript-enabled clients + authForm.Set("bgresponse", "js_enabled") + + authForm.Set("Email", loginDetails.Username) + + // Post email address w/o password, then Get the password-input page + passwordURL, passwordForm, err := kc.loadLoginPage(withLocale(authURL), withLocale(loginDetails.URL), authForm) + if err != nil { + // if failed, try with "identifier" + authForm.Set("Email", "") // Clear previous key + authForm.Set("identifier", loginDetails.Username) + passwordURL, passwordForm, err = kc.loadLoginPage(withLocale(authURL), withLocale(loginDetails.URL), authForm) + if err != nil { + return "", errors.Wrap(err, "error loading login page") + } + } + + logger.Debugf("loginURL: %s", provider.RedactRawURL(passwordURL)) + + passwordForm.Set("Passwd", loginDetails.Password) + passwordForm.Set("TrustDevice", "on") + + referingURL := passwordURL + + responseDoc, err := kc.loadChallengePage(withLocale(passwordURL), referingURL, passwordForm, loginDetails) + if err != nil { + return "", errors.Wrap(err, "error loading challenge page") + } + + captchaFound, captchaInputId := findCaptcha(responseDoc) + + for attempt := 0; captchaFound != nil && captchaFound.Length() > 0; attempt++ { + if attempt >= maxCaptchaAttempts { + return "", errCaptchaAttemptsExceeded + } + // Atmos fork: upstream checked `captchaImgDiv != nil`, which is always true for a + // *goquery.Selection, so the legacy .captcha-img markup was never used, and it indexed + // Children().Nodes[0] without a length check, which panicked when the container was + // missing or empty. The new-style container is now only a fallback, and a missing image + // returns an error. + captchaImgDiv := responseDoc.Find(".captcha-img") + if captchaImgDiv.Length() == 0 { + captchaImgDiv = responseDoc.Find("div[data-auto-init='CaptchaInput']") + captchaInputId = "ca" + } + captchaImg := captchaImgDiv.Children().First() + if captchaImg.Length() == 0 { + return "", errCaptchaImageNotFound + } + captchaPictureSrc, found := captchaImg.Attr("src") + + if !found { + return "", errCaptchaImageNotFound + } + + captchaPictureURL, err := generateFullURLIfRelative(captchaPictureSrc, passwordURL) + if err != nil { + return "", errors.Wrap(err, "error generating captcha image URL") + } + + captcha, err := kc.tryDisplayCaptcha(captchaPictureURL) + if err != nil { + return "", err + } + + captchaForm, captchaURL, err := extractInputsByFormID(responseDoc, "gaia_loginform", "challenge") + if err != nil { + return "", errors.Wrap(err, "error extracting captcha") + } + + logger.Debugf("captchaURL: %s", provider.RedactRawURL(captchaURL)) + + _, captchaV1 := captchaForm["Passwd"] + if captchaV1 { + captchaForm.Set("Passwd", loginDetails.Password) + } + captchaForm.Set(captchaInputId, captcha) + + responseDoc, err = kc.loadChallengePage(withLocale(captchaURL), captchaURL, captchaForm, loginDetails) + if err != nil { + return "", errors.Wrap(err, "error loading challenge page") + } + + // Atmos fork: upstream re-checked only `#`, but the new-style captcha input + // is `name="ca"` with no id, so a rejected answer was never retried and the flow failed + // looking for a SAMLResponse on the captcha page. Re-run the same detection instead. + captchaFound, captchaInputId = findCaptcha(responseDoc) + } + + // New Captcha proceeds back to password page + passworddBeingRequested := responseDoc.Find("#password") + if passworddBeingRequested != nil && passworddBeingRequested.Length() > 0 { + loginForm, loginURL, err := extractInputsByFormID(responseDoc, "challenge") + if err != nil { + return "", errors.Wrap(err, "error parsing password page after captcha") + } + + loginForm.Set("Passwd", loginDetails.Password) + + responseDoc, err = kc.loadChallengePage(withLocale(loginURL), loginURL, loginForm, loginDetails) + if err != nil { + return "", errors.Wrap(err, "error loading challenge page") + } + } + + samlAssertion, err := findInputByName(responseDoc, "SAMLResponse") + if err != nil { + return "", err + } + if samlAssertion == "" { + if responseDoc.Selection.Find("#passwordError").Text() != "" { + return "", errors.New("Password error") + } + + if err := isMissing2StepSetup(responseDoc); err != nil { + return "", err + } + + return "", errors.New("page is missing saml assertion") + } + + return samlAssertion, nil +} + +func isMissing2StepSetup(responseDoc *goquery.Document) error { + if responseDoc.Selection.Find("section.aN1Vld ").Text() != "" { + return errors.New("Because of your organization settings, you must set-up 2-Step Verification in your account") + } + return nil +} + +func (kc *Client) tryDisplayCaptcha(captchaPictureURL string) (string, error) { + // TODO: check for user flag for easy captcha presentation + + if os.Getenv("TERM_PROGRAM") == "iTerm.app" { + // Use iTerm to show the image if available + return kc.iTermCaptchaPrompt(captchaPictureURL) + } else { + return simpleCaptchaPrompt(captchaPictureURL) + } +} + +func (kc *Client) iTermCaptchaPrompt(captchaPictureURL string) (string, error) { + log.Printf("Detected iTerm, displaying URL: %s\n", captchaPictureURL) + imgResp, err := kc.client.Get(captchaPictureURL) + if err != nil { + return "", errors.Wrap(err, "unable to fetch captcha image") + } + defer imgResp.Body.Close() + var buf bytes.Buffer + b64Encoder := b64.NewEncoder(b64.StdEncoding, &buf) + _, _ = io.Copy(b64Encoder, imgResp.Body) + _ = b64Encoder.Close() + + // Atmos fork: upstream printed the inline image to stdout, which is the caller's data + // channel (for example `eval $(atmos auth env)`). It is written to stderr, where the + // prompts are shown and which is still the terminal. + if os.Getenv("TERM") == "screen" { + log.Println("Detected tmux, using specific workaround...") + fmt.Fprintf(os.Stderr, "\033Ptmux;\033\033]1337;File=width=40;preserveAspectRatio=1;inline=1;:%s\a\033\\\n", buf.String()) + } else { + fmt.Fprintf(os.Stderr, "\033]1337;File=width=40;preserveAspectRatio=1;inline=1;:%s\a\n", buf.String()) + } + return prompter.String("Captcha", "") +} + +func simpleCaptchaPrompt(captchaPictureURL string) (string, error) { + log.Println("Open this link in a browser:\n", captchaPictureURL) + return prompter.String("Captcha", "") +} + +// withLocale returns rawURL with hl=en and loc=US set in its query. +// +// Atmos fork: upstream concatenated "?hl=en&loc=US" (or "&hl=en&loc=US") onto the URL, which appended the +// parameters to the value of the last existing query parameter when the URL already had a query string. +// The other query parameters are kept byte for byte, and any existing hl or loc parameter is replaced. +func withLocale(rawURL string) string { + base, fragment, hasFragment := strings.Cut(rawURL, "#") + base, query, _ := strings.Cut(base, "?") + + var kept []string + for _, pair := range strings.Split(query, "&") { + name, _, _ := strings.Cut(pair, "=") + if pair == "" || name == "hl" || name == "loc" { + continue + } + kept = append(kept, pair) + } + kept = append(kept, "hl=en", "loc=US") + + result := base + "?" + strings.Join(kept, "&") + if hasFragment { + result += "#" + fragment + } + return result +} + +func (kc *Client) loadFirstPage(loginDetails *creds.LoginDetails) (string, url.Values, error) { + firstPageURL := withLocale(loginDetails.URL) + + req, err := http.NewRequest("GET", firstPageURL, nil) + if err != nil { + return "", nil, errors.Wrap(err, "error retrieving login form from idp") + } + + res, err := kc.client.Do(req) + if err != nil { + return "", nil, errors.Wrap(err, "failed to make request to login form") + } + defer res.Body.Close() + + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return "", nil, errors.Wrap(err, "error parsing first page html document") + } + + doc.Url, err = url.Parse(firstPageURL) + if err != nil { + return "", url.Values{}, errors.Wrap(err, "failed to define URL for html doc") + } + + authForm, submitURL, err := extractInputsByFormID(doc, "gaia_loginform", "challenge") + if err != nil { + return "", nil, errors.Wrap(err, "failed to build login form data") + } + + return submitURL, authForm, err +} + +func (kc *Client) loadLoginPage(submitURL string, referer string, authForm url.Values) (string, url.Values, error) { + req, err := http.NewRequest("POST", submitURL, strings.NewReader(authForm.Encode())) + if err != nil { + return "", nil, errors.Wrap(err, "error retrieving login form") + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept-Language", "en-US") + req.Header.Set("Content-Language", "en-US") + req.Header.Set("Referer", referer) + + res, err := kc.client.Do(req) + if err != nil { + return "", nil, errors.Wrap(err, "failed to make request to login form") + } + defer res.Body.Close() + + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return "", nil, errors.Wrap(err, "error parsing login page html document") + } + + doc.Url, err = url.Parse(submitURL) + if err != nil { + return "", url.Values{}, errors.Wrap(err, "failed to define URL for html doc") + } + + loginForm, loginURL, err := extractInputsByFormID(doc, "gaia_loginform", "challenge") + if err != nil { + return "", nil, errors.Wrap(err, "failed to build login form data") + } + + return loginURL, loginForm, err +} + +func (kc *Client) loadChallengePage(submitURL string, referer string, authForm url.Values, loginDetails *creds.LoginDetails) (*goquery.Document, error) { + authForm.Set("bgresponse", "js_enabled") + + req, err := http.NewRequest("POST", submitURL, strings.NewReader(authForm.Encode())) + if err != nil { + return nil, errors.Wrap(err, "error retrieving login form") + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept-Language", "en-US") + req.Header.Set("Content-Language", "en-US") + req.Header.Set("Referer", referer) + + res, err := kc.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "failed to make request to login form") + } + defer res.Body.Close() + + doc, err := goquery.NewDocumentFromReader(res.Body) + if err != nil { + return nil, errors.Wrap(err, "error parsing login page html document") + } + + doc.Url, err = url.Parse(submitURL) + if err != nil { + return nil, errors.Wrap(err, "failed to define URL for html doc") + } + + errMsg := mustFindErrorMsg(doc) + + if errMsg != "" { + return nil, errors.New("Invalid username or password") + } + + secondFactorHeader := "This extra step shows it’s really you trying to sign in" + secondFactorHeader2 := "This extra step shows that it’s really you trying to sign in" + secondFactorHeader3 := "2-Step Verification" + secondFactorHeaderJp := "2 段階認証プロセス" + + // have we been asked for 2-Step Verification + if extractNodeText(doc, "h2", secondFactorHeader) != "" || + extractNodeText(doc, "h2", secondFactorHeader2) != "" || + extractNodeText(doc, "h1", secondFactorHeader3) != "" || + extractNodeText(doc, "h1", secondFactorHeaderJp) != "" { + + responseForm, secondActionURL, err := extractInputsByFormID(doc, "challenge") + if err != nil { + return nil, errors.Wrap(err, "unable to extract challenge form") + } + + logger.Debugf("secondActionURL: %s", provider.RedactRawURL(secondActionURL)) + + switch { + case strings.Contains(secondActionURL, "challenge/totp"): // handle TOTP challenge + + token := loginDetails.MFAToken + if token == "" { + var err error + if token, err = prompter.RequestSecurityCode("000000"); err != nil { + return nil, errors.Wrap(err, "failed to read the TOTP code") + } + } + + responseForm.Set("Pin", token) + responseForm.Set("TrustDevice", "on") // Don't ask again on this computer + + return kc.loadResponsePage(secondActionURL, submitURL, responseForm) + case strings.Contains(secondActionURL, "challenge/ipp"): // handle SMS challenge + + if extractNodeText(doc, "button", "Send text message") != "" { + responseForm.Set("SendMethod", "SMS") // extractInputsByFormID does not extract the name and value from