From eaea51b84afddd3f1be5f6705162b2948bbf1c78 Mon Sep 17 00:00:00 2001 From: aknysh Date: Tue, 17 Nov 2026 20:11:53 -0500 Subject: [PATCH 1/7] fix(auth): vendor saml2aws to drop go-jose/v3 and fix the SAML browser driver saml2aws is unmaintained, and through playwright-community/playwright-go v0.5700.1 it pulled github.com/go-jose/go-jose/v3 (unfixed HIGH advisory GHSA-mgcc-cww5-fp2q / CVE-2026-116587) into the Atmos binary. A version bump was not possible because playwright-go moved back to the github.com/mxschmitt/playwright-go module path. - Vendor the library parts of saml2aws v2.36.19 (MIT, with attribution) into pkg/auth/providers/aws/saml2aws, keeping the documented Browser, GoogleApps, Okta and ADFS drivers. - Port the browser driver to mxschmitt/playwright-go v0.6401.0; go-jose/v3, saml2aws and playwright-community leave go.mod and the binary. - Fix upstream bugs: browser timeout panic, swallowed errors, data races, process exits (log.Fatal) on malformed pages, unbounded ADFS MFA and captcha loops, stdout writes on login paths, leaked Playwright processes, and a world-readable session-cookie file. - Download the exact browser revision the new driver needs, so an upgrade with an older Chromium in the cache does not break login. - Reject an unsupported SAML driver when that provider logs in, not during config validation, so one stale provider cannot break other identities. - Add tests across the vendored packages and the auth subsystem. Co-Authored-By: Claude Opus 5.5 --- .golangci.yml | 23 + NOTICE | 24 +- cmd/auth/exec_child_process_test.go | 108 ++ cmd/auth/testmain_test.go | 5 + ...6-11-17-vendor-saml2aws-drop-go-jose-v3.md | 173 ++ docs/prd/saml-browser-driver-integration.md | 30 +- errors/errors.go | 1 + go.mod | 18 +- go.sum | 29 +- pkg/auth/cloud/aws/ecr_token_test.go | 133 ++ pkg/auth/cloud/kube/config_drift_test.go | 119 ++ pkg/auth/docs/PRD/PRD-Atmos-Auth.md | 2 +- .../aws/permission_set_authenticate_test.go | 159 ++ .../prepare_environment_test.go | 112 ++ .../aws/eks_kubeconfig_merge_test.go | 180 ++ pkg/auth/list/formatter_status_test.go | 125 ++ pkg/auth/manager_operation_test.go | 242 +++ pkg/auth/providers/aws/saml.go | 139 +- .../providers/aws/saml2aws/ATTRIBUTIONS.md | 7 + pkg/auth/providers/aws/saml2aws/LICENSE.md | 11 + pkg/auth/providers/aws/saml2aws/README.md | 80 + pkg/auth/providers/aws/saml2aws/aws_role.go | 60 + .../providers/aws/saml2aws/aws_role_test.go | 81 + pkg/auth/providers/aws/saml2aws/cfg/cfg.go | 124 ++ .../providers/aws/saml2aws/cfg/cfg_test.go | 75 + .../providers/aws/saml2aws/cookiejar/jar.go | 495 +++++ .../aws/saml2aws/cookiejar/jar_test.go | 1342 +++++++++++++ .../aws/saml2aws/cookiejar/punycode.go | 159 ++ .../providers/aws/saml2aws/creds/creds.go | 17 + pkg/auth/providers/aws/saml2aws/dump/dump.go | 34 + .../providers/aws/saml2aws/dump/dump_test.go | 126 ++ .../providers/aws/saml2aws/mocks/Prompter.go | 123 ++ .../providers/aws/saml2aws/mocks/U2FDevice.go | 98 + .../aws/saml2aws/page/example/multi-form.html | 20 + pkg/auth/providers/aws/saml2aws/page/form.go | 91 + .../providers/aws/saml2aws/page/form_test.go | 174 ++ .../aws/saml2aws/prompter/pinentry.go | 135 ++ .../aws/saml2aws/prompter/pinentry_test.go | 188 ++ .../aws/saml2aws/prompter/prompter.go | 87 + .../aws/saml2aws/prompter/prompter_test.go | 205 ++ .../providers/aws/saml2aws/prompter/survey.go | 114 ++ .../aws/saml2aws/prompter/survey_test.go | 50 + .../aws/saml2aws/prompter/testmain_test.go | 50 + .../aws/saml2aws/provider/adfs/adfs.go | 348 ++++ .../provider/adfs/adfs_mfa_limit_test.go | 76 + .../aws/saml2aws/provider/adfs/adfs_test.go | 562 ++++++ .../aws/saml2aws/provider/base_validate.go | 23 + .../saml2aws/provider/base_validate_test.go | 39 + .../aws/saml2aws/provider/browser/browser.go | 430 +++++ .../browser/browser_integration_test.go | 104 ++ .../browser/browser_lifecycle_test.go | 150 ++ .../saml2aws/provider/browser/browser_test.go | 360 ++++ .../example/loginpage-button-submit.html | 41 + .../example/loginpage-without-submit.html | 42 + .../provider/browser/example/loginpage.html | 41 + .../provider/browser/mock_page_test.go | 136 ++ .../provider/browser/mock_request_test.go | 769 ++++++++ .../provider/browser/storage_state_test.go | 72 + .../provider/googleapps/example/captcha.html | 102 + .../example/challenge-extra-number.html | 96 + .../googleapps/example/challenge-prompt.html | 126 ++ .../example/challenge-sms-send.html | 350 ++++ .../googleapps/example/challenge-sms.html | 371 ++++ .../googleapps/example/challenge-totp.html | 102 + .../example/form-password-challengeid-1.html | 115 ++ .../example/form-password-challengeid-2.html | 115 ++ .../example/form-password-challengeid-3.html | 93 + .../provider/googleapps/googleapps.go | 873 +++++++++ .../googleapps/googleapps_challenge_test.go | 331 ++++ .../googleapps/googleapps_flow_test.go | 349 ++++ .../googleapps/googleapps_helpers_test.go | 257 +++ .../googleapps/googleapps_robustness_test.go | 133 ++ .../provider/googleapps/googleapps_test.go | 289 +++ .../aws/saml2aws/provider/googleapps/u2f.go | 159 ++ .../saml2aws/provider/googleapps/u2f_test.go | 173 ++ .../providers/aws/saml2aws/provider/http.go | 224 +++ .../saml2aws/provider/http_attempts_test.go | 70 + .../aws/saml2aws/provider/http_test.go | 348 ++++ .../aws/saml2aws/provider/okta/okta.go | 1656 +++++++++++++++++ .../provider/okta/okta_auth_flow_test.go | 442 +++++ .../provider/okta/okta_duo_flow_test.go | 391 ++++ .../saml2aws/provider/okta/okta_duo_u2f.go | 113 ++ .../provider/okta/okta_duo_u2f_output_test.go | 69 + .../provider/okta/okta_duo_u2f_test.go | 96 + .../provider/okta/okta_helpers_test.go | 217 +++ .../provider/okta/okta_mfa_flow_test.go | 385 ++++ .../provider/okta/okta_session_test.go | 176 ++ .../aws/saml2aws/provider/okta/okta_test.go | 1007 ++++++++++ .../saml2aws/provider/okta/okta_webauthn.go | 182 ++ .../provider/okta/okta_webauthn_test.go | 163 ++ pkg/auth/providers/aws/saml2aws/saml.go | 183 ++ pkg/auth/providers/aws/saml2aws/saml2aws.go | 103 + .../providers/aws/saml2aws/saml2aws_test.go | 80 + pkg/auth/providers/aws/saml2aws/saml_test.go | 361 ++++ .../aws/saml2aws/testdata/assertion.xml | 57 + .../testdata/assertion_invalid_date.xml | 57 + .../testdata/assertion_no_destination.xml | 57 + .../aws/saml2aws/testdata/notxml.xml | 1 + .../aws/saml_browser_autodownload_test.go | 175 ++ .../providers/aws/saml_browser_platform.go | 179 ++ .../aws/saml_browser_platform_darwin.go | 22 + .../aws/saml_browser_platform_other.go | 15 + .../aws/saml_browser_platform_test.go | 131 ++ .../providers/aws/saml_browser_revision.go | 195 ++ .../aws/saml_browser_revision_test.go | 303 +++ .../saml_driver_download_integration_test.go | 58 +- .../providers/aws/saml_driver_patch_test.go | 105 ++ pkg/auth/providers/aws/saml_driver_preseed.go | 37 +- pkg/auth/providers/aws/saml_storage_test.go | 14 +- pkg/auth/providers/aws/saml_test.go | 163 +- pkg/auth/providers/aws/saml_testmain_test.go | 20 + pkg/auth/providers/aws/sso_token_flow_test.go | 324 ++++ .../providers/azure/device_code_paths_test.go | 82 + pkg/auth/validation/validator_test.go | 18 + .../adapter/auth/interactions_e2e_test.go | 128 ++ pkg/plugin/adapter/auth/main_test.go | 3 + website/docs/cli/commands/auth/usage.mdx | 2 +- .../docs/cli/configuration/auth/providers.mdx | 2 +- 118 files changed, 20939 insertions(+), 270 deletions(-) create mode 100644 cmd/auth/exec_child_process_test.go create mode 100644 docs/fixes/2026-11-17-vendor-saml2aws-drop-go-jose-v3.md create mode 100644 pkg/auth/cloud/aws/ecr_token_test.go create mode 100644 pkg/auth/cloud/kube/config_drift_test.go create mode 100644 pkg/auth/identities/aws/permission_set_authenticate_test.go create mode 100644 pkg/auth/identities/gcp_service_account/prepare_environment_test.go create mode 100644 pkg/auth/integrations/aws/eks_kubeconfig_merge_test.go create mode 100644 pkg/auth/list/formatter_status_test.go create mode 100644 pkg/auth/manager_operation_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/ATTRIBUTIONS.md create mode 100644 pkg/auth/providers/aws/saml2aws/LICENSE.md create mode 100644 pkg/auth/providers/aws/saml2aws/README.md create mode 100644 pkg/auth/providers/aws/saml2aws/aws_role.go create mode 100644 pkg/auth/providers/aws/saml2aws/aws_role_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/cfg/cfg.go create mode 100644 pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/cookiejar/jar.go create mode 100644 pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go create mode 100644 pkg/auth/providers/aws/saml2aws/creds/creds.go create mode 100644 pkg/auth/providers/aws/saml2aws/dump/dump.go create mode 100644 pkg/auth/providers/aws/saml2aws/dump/dump_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/mocks/Prompter.go create mode 100644 pkg/auth/providers/aws/saml2aws/mocks/U2FDevice.go create mode 100644 pkg/auth/providers/aws/saml2aws/page/example/multi-form.html create mode 100644 pkg/auth/providers/aws/saml2aws/page/form.go create mode 100644 pkg/auth/providers/aws/saml2aws/page/form_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/pinentry.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/prompter.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/survey.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/survey_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/prompter/testmain_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_mfa_limit_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/base_validate.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/base_validate_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/browser.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/browser_integration_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/browser_lifecycle_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-button-submit.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage-without-submit.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/example/loginpage.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/mock_page_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/mock_request_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/captcha.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-extra-number.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-prompt.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms-send.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-1.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-2.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/example/form-password-challengeid-3.html create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_flow_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_helpers_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_robustness_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/http.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/http_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_auth_flow_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_flow_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_output_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_helpers_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_mfa_flow_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_session_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/saml.go create mode 100644 pkg/auth/providers/aws/saml2aws/saml2aws.go create mode 100644 pkg/auth/providers/aws/saml2aws/saml2aws_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/saml_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/testdata/assertion.xml create mode 100644 pkg/auth/providers/aws/saml2aws/testdata/assertion_invalid_date.xml create mode 100644 pkg/auth/providers/aws/saml2aws/testdata/assertion_no_destination.xml create mode 100644 pkg/auth/providers/aws/saml2aws/testdata/notxml.xml create mode 100644 pkg/auth/providers/aws/saml_browser_autodownload_test.go create mode 100644 pkg/auth/providers/aws/saml_browser_platform.go create mode 100644 pkg/auth/providers/aws/saml_browser_platform_darwin.go create mode 100644 pkg/auth/providers/aws/saml_browser_platform_other.go create mode 100644 pkg/auth/providers/aws/saml_browser_platform_test.go create mode 100644 pkg/auth/providers/aws/saml_browser_revision.go create mode 100644 pkg/auth/providers/aws/saml_browser_revision_test.go create mode 100644 pkg/auth/providers/aws/saml_driver_patch_test.go create mode 100644 pkg/auth/providers/aws/saml_testmain_test.go create mode 100644 pkg/auth/providers/aws/sso_token_flow_test.go create mode 100644 pkg/auth/providers/azure/device_code_paths_test.go create mode 100644 pkg/plugin/adapter/auth/interactions_e2e_test.go 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..731aa34cc7f --- /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 ( + // authExecChildEnv turns the test binary into the child process `auth exec` runs. + authExecChildEnv = "_ATMOS_TEST_AUTH_EXEC_CHILD" + // authExecChildReportEnv names the file the child writes its observations to. + authExecChildReportEnv = "_ATMOS_TEST_AUTH_EXEC_REPORT" + // authExecChildExitEnv is the 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..c2755763d2a --- /dev/null +++ b/docs/fixes/2026-11-17-vendor-saml2aws-drop-go-jose-v3.md @@ -0,0 +1,173 @@ +# 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. +- **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. +- `.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..fb6e20f1670 --- /dev/null +++ b/pkg/auth/cloud/aws/ecr_token_test.go @@ -0,0 +1,133 @@ +package aws + +import ( + "context" + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "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) *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") + + signedRegion := new(string) + 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 { + *signedRegion = parts[2] + } + 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 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..18d0dfee0e7 --- /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 (with tokens, impersonation and auth +// providers) intact, 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..d0baadf5016 100644 --- a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md +++ b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md @@ -846,12 +846,12 @@ providers: **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 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..1e120f6f7e9 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,6 +121,10 @@ func (p *samlProvider) PreAuthenticate(manager types.AuthManager) error { // Authenticate performs SAML authentication using saml2aws. func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, error) { + if err := p.validateDriver(); err != nil { + return nil, err + } + samlDriver := p.getDriver() downloadBrowser := p.shouldDownloadBrowser() @@ -146,6 +150,8 @@ func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, er // 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) } } @@ -212,7 +218,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 +242,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 +390,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 +439,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 +514,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 +567,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. @@ -599,8 +626,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 +645,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 +692,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 +745,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 +769,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..2e475bcd88e --- /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. \ No newline at end of file diff --git a/pkg/auth/providers/aws/saml2aws/README.md b/pkg/auth/providers/aws/saml2aws/README.md new file mode 100644 index 00000000000..783054a5c55 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/README.md @@ -0,0 +1,80 @@ +# 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. +- **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. +- **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..60ff2246b6d --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/aws_role.go @@ -0,0 +1,60 @@ +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 +} + +func parseRole(role string) (*AWSRole, error) { + r, _ := regexp.Compile("arn:([^:\n]*):([^:\n]*):([^:\n]*):([^:\n]*):(([^:/\n]*)[:/])?([^:,\n]*)") + tokens := r.FindAllString(role, -1) + + 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..582e32c145f --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/aws_role_test.go @@ -0,0 +1,81 @@ +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) + } +} 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..da19ca97460 --- /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..5248e86b3ac --- /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..2c3b569f8fa --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go @@ -0,0 +1,495 @@ +// 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}) + } + + 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". + } + if s, err := url.PathUnescape(path[:i]); err == nil { + return s + } + 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..5262d215432 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go @@ -0,0 +1,1342 @@ +// 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 ( + "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 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) + } + } +} 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..a9cc666e8c9 --- /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)) + } 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/dump/dump.go b/pkg/auth/providers/aws/saml2aws/dump/dump.go new file mode 100644 index 00000000000..da97f0fc9d8 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/dump/dump.go @@ -0,0 +1,34 @@ +package dump + +import ( + "net/http" + "net/http/httputil" + "os" +) + +// RequestString helper method to dump the http request +func RequestString(req *http.Request) string { + data, err := httputil.DumpRequestOut(req, ContentEnable()) + + if err != nil { + return "" + } + + return string(data) +} + +// ResponseString helper method to dump the http response +func ResponseString(res *http.Response) string { + data, err := httputil.DumpResponse(res, ContentEnable()) + + if err != nil { + return "" + } + + return string(data) +} + +// ContentEnable enable dumping of request / response content +func ContentEnable() bool { + return os.Getenv("DUMP_CONTENT") == "true" +} diff --git a/pkg/auth/providers/aws/saml2aws/dump/dump_test.go b/pkg/auth/providers/aws/saml2aws/dump/dump_test.go new file mode 100644 index 00000000000..59bee88b600 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/dump/dump_test.go @@ -0,0 +1,126 @@ +package dump + +import ( + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errors.New("read failure") } + +func TestContentEnable(t *testing.T) { + tests := []struct { + value string + want bool + }{ + {value: "true", want: true}, + {value: "TRUE", want: false}, + {value: "1", want: false}, + {value: "", want: false}, + } + + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Setenv("DUMP_CONTENT", tt.value) + assert.Equal(t, tt.want, ContentEnable()) + }) + } +} + +func TestRequestString(t *testing.T) { + tests := []struct { + name string + dump string + wantBody bool + }{ + {name: "headers and body", dump: "true", wantBody: true}, + {name: "headers only", dump: "false", wantBody: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("DUMP_CONTENT", tt.dump) + req, err := http.NewRequest(http.MethodPost, "https://idp.example.com/login", strings.NewReader("user=alice")) + require.NoError(t, err) + + out := RequestString(req) + assert.Contains(t, out, "POST /login HTTP/1.1") + assert.Contains(t, out, "Host: idp.example.com") + if tt.wantBody { + assert.Contains(t, out, "user=alice") + } else { + assert.NotContains(t, out, "user=alice") + } + }) + } +} + +func TestRequestStringError(t *testing.T) { + t.Setenv("DUMP_CONTENT", "true") + req, err := http.NewRequest(http.MethodGet, "ftp://idp.example.com/login", nil) + require.NoError(t, err) + + assert.Empty(t, RequestString(req)) +} + +func TestResponseString(t *testing.T) { + tests := []struct { + name string + dump string + wantBody bool + }{ + {name: "headers and body", dump: "true", wantBody: true}, + {name: "headers only", dump: "false", wantBody: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("DUMP_CONTENT", tt.dump) + res := &http.Response{ + Status: "200 OK", + StatusCode: http.StatusOK, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: http.Header{"X-Test": {"yes"}}, + Body: io.NopCloser(strings.NewReader("ok")), + ContentLength: int64(len("ok")), + } + + out := ResponseString(res) + assert.Contains(t, out, "HTTP/1.1 200 OK") + assert.Contains(t, out, "X-Test: yes") + if tt.wantBody { + assert.Contains(t, out, "ok") + // The body is restored so callers can still read it. + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + assert.Equal(t, "ok", string(body)) + } else { + assert.NotContains(t, out, "ok") + } + }) + } +} + +func TestResponseStringError(t *testing.T) { + t.Setenv("DUMP_CONTENT", "true") + res := &http.Response{ + Status: "200 OK", + StatusCode: http.StatusOK, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: http.Header{}, + Body: io.NopCloser(failingReader{}), + } + + assert.Empty(t, ResponseString(res)) +} 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..ff4baf1a250 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go @@ -0,0 +1,123 @@ +// 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 +func (_m *Prompter) Choose(_a0 string, _a1 []string) int { + 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 +} + +// 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 +func (_m *Prompter) Password(_a0 string) string { + 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 +} + +// RequestSecurityCode provides a mock function with given fields: _a0 +func (_m *Prompter) RequestSecurityCode(_a0 string) string { + 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 +} + +// String provides a mock function with given fields: _a0, _a1 +func (_m *Prompter) String(_a0 string, _a1 string) string { + 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 +} + +// StringRequired provides a mock function with given fields: _a0 +func (_m *Prompter) StringRequired(_a0 string) string { + 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 +} + +// 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..c1a73d25b91 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/page/form.go @@ -0,0 +1,91 @@ +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) { + 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 { + form.URL = attrValue + } else { + form.URL = doc.Url.String() + } + + 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 +} + +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") + } + 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..9888dbedd42 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/page/form_test.go @@ -0,0 +1,174 @@ +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) + + // assert the default behavior is to extract the first form with an action + form, err := NewFormFromDocument(doc, "") + require.Nil(t, err) + require.Equal(t, "/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, "/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: "/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) + + form, err := NewFormFromDocument(doc, "") + require.NoError(t, err) + assert.Equal(t, url.Values{"keep": {"yes"}, "empty": {""}}, *form.Values) +} + +func TestNewFormFromResponse(t *testing.T) { + res := &http.Response{Body: io.NopCloser(strings.NewReader(`
`))} + form, err := NewFormFromResponse(res, "") + require.NoError(t, err) + assert.Equal(t, "/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. + _, err = (&Form{URL: ts.URL, Method: "BAD METHOD", Values: &url.Values{}}).Submit(client) + require.Error(t, err) + assert.Contains(t, err.Error(), "error building request") + + // A server that is no longer listening fails while submitting. + ts.Close() + _, err = form.Submit(client) + require.Error(t, err) + assert.Contains(t, err.Error(), "error submitting form") +} 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..b2f22307fb9 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go @@ -0,0 +1,135 @@ +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) (output string) { + commandTemplate := "SETPROMPT %s\nGETPIN\n" + prompt := fmt.Sprintf(defaultPinentryDialog, pattern) + command := fmt.Sprintf(commandTemplate, prompt) + if output, err := p.Runner.Run(command); err != nil { + return "" + } else { + return output + } +} + +// 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 { + return p.DefaultPrompter.Choose(pr, options) +} + +// StringRequired is runniner the default Cli StringRequired +func (p *PinentryPrompter) StringRequired(pr string) string { + return p.DefaultPrompter.StringRequired(pr) +} + +// String is runniner the default Cli String +func (p *PinentryPrompter) String(pr string, defaultValue string) string { + return p.DefaultPrompter.String(pr, defaultValue) +} + +// Password is runniner the default Cli Password +func (p *PinentryPrompter) Password(pr string) string { + 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") + 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 wheter 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:]) + } + } + + 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..7c4dfecec36 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go @@ -0,0 +1,188 @@ +package prompter + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// 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 { + f.CalledRequestSecurityCode = true + return "" +} +func (f *FakeDefaultPrompter) Choose(p string, option []string) int { + f.CalledChoose = true + return 0 +} +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 { + f.CalledString = true + return "" +} +func (f *FakeDefaultPrompter) StringRequired(p string) string { + f.CalledStringRequired = true + return "" +} +func (f *FakeDefaultPrompter) Password(p string) string { + f.CalledPassword = true + return "" +} +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()) + } + +} +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 := p.RequestSecurityCode("000000") + + 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 := p.RequestSecurityCode("000000") + + 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 := p.RequestSecurityCode("000000") + + 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..2637c03b637 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go @@ -0,0 +1,87 @@ +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 { + RequestSecurityCode(string) string + ChooseWithDefault(string, string, []string) (string, error) + Choose(string, []string) int + StringRequired(string) string + String(string, string) string + Password(string) string + 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" { + // nothing to do; the default prompter is the survey one. + 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 { + 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 { + return ActivePrompter.Choose(pr, options) +} + +// StringRequired prompt for string which is required +func StringRequired(pr string) string { + return ActivePrompter.StringRequired(pr) +} + +// String prompt for string which is required +func String(pr string, defaultValue string) string { + return ActivePrompter.String(pr, defaultValue) +} + +// Password prompt for password which is required +func Password(pr string) string { + 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..98ad0f20130 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go @@ -0,0 +1,205 @@ +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 { + r.calls = append(r.calls, "RequestSecurityCode") + r.lastPrompt = pattern + return "123456" +} + +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 { + r.calls = append(r.calls, "Choose") + r.lastPrompt, r.lastOptions = pr, options + return len(options) - 1 +} + +func (r *recordingPrompter) StringRequired(pr string) string { + r.calls = append(r.calls, "StringRequired") + r.lastPrompt = pr + return "required" +} + +func (r *recordingPrompter) String(pr, def string) string { + r.calls = append(r.calls, "String") + r.lastPrompt, r.lastDefault = pr, def + return "value" +} + +func (r *recordingPrompter) Password(pr string) string { + r.calls = append(r.calls, "Password") + r.lastPrompt = pr + return "secret" +} + +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) + + assert.Equal(t, "123456", RequestSecurityCode("000000")) + assert.Equal(t, "000000", rec.lastPrompt) + + assert.Equal(t, 1, Choose("Pick", []string{"a", "b"})) + assert.Equal(t, []string{"a", "b"}, rec.lastOptions) + + assert.Equal(t, "required", StringRequired("Username")) + assert.Equal(t, "Username", rec.lastPrompt) + + assert.Equal(t, "value", String("Region", "us-east-1")) + assert.Equal(t, "us-east-1", rec.lastDefault) + + assert.Equal(t, "secret", Password("Password")) + 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 + }{ + {mode: "ok", want: "424242"}, + {mode: "cancel", want: ""}, + } + + for _, tt := range tests { + t.Run(tt.mode, func(t *testing.T) { + t.Setenv(fakePinentryEnv, tt.mode) + assert.Equal(t, tt.want, NewPinentryPrompter(exe).RequestSecurityCode("000000")) + }) + } +} + +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..2ef5d223d9f --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey.go @@ -0,0 +1,114 @@ +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 { + token := "" + prompt := &survey.Input{ + Message: fmt.Sprintf("Security Token [%s]", pattern), + } + _ = survey.AskOne(prompt, &token, survey.WithValidator(survey.Required), stdioOption()) + return token +} + +// 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, + } + _ = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()) + + // 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 { + selected := "" + prompt := &survey.Select{ + Message: pr, + Options: options, + } + _ = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()) + + // return the selected element index + for i, option := range options { + if selected == option { + return i + } + } + return 0 +} + +// String prompt for string with a default +func (cli *CliPrompter) String(pr string, defaultValue string) string { + val := "" + prompt := &survey.Input{ + Message: pr, + Default: defaultValue, + } + _ = survey.AskOne(prompt, &val, stdioOption()) + return val +} + +// StringRequired prompt for string which is required +func (cli *CliPrompter) StringRequired(pr string) string { + val := "" + prompt := &survey.Input{ + Message: pr, + } + _ = survey.AskOne(prompt, &val, survey.WithValidator(survey.Required), stdioOption()) + return val +} + +// Password prompt for password which is required +func (cli *CliPrompter) Password(pr string) string { + val := "" + prompt := &survey.Password{ + Message: pr, + } + _ = survey.AskOne(prompt, &val, stdioOption()) + return val +} + +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..1a928ab455d --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go @@ -0,0 +1,50 @@ +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() + + assert.Empty(t, cli.RequestSecurityCode("000000")) + assert.Empty(t, cli.String("Region", "us-east-1")) + assert.Empty(t, cli.StringRequired("Username")) + assert.Empty(t, cli.Password("Password")) + assert.Equal(t, 0, cli.Choose("Pick", []string{"a", "b"})) + + 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..2cace6f026b --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go @@ -0,0 +1,348 @@ +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, + TLSClientConfig: &tls.Config{InsecureSkipVerify: idpAccount.SkipVerify, Renegotiation: tls.RenegotiateFreelyAsClient}, + } + + 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 if strings.HasPrefix(authSubmitURL, "/") { + // + // The server returned a relative URL. Make it absolute. + // + 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 = prompter.RequestSecurityCode("000000") + } + + 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..0dd9b5aeea1 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go @@ -0,0 +1,562 @@ +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) +} + +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/base_validate.go b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go new file mode 100644 index 00000000000..324b590f43a --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go @@ -0,0 +1,23 @@ +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..c8d3adfcbb5 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go @@ -0,0 +1,430 @@ +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 + if cl.BrowserType == "firefox" { + browserType = pw.Firefox + } else if cl.BrowserType == "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 the file with 0644 permissions, so the directory is created +// with 0700 and the file is tightened to 0600 after saving. +func saveStorageState(saver storageStateSaver, statePath string) error { + if err := os.MkdirAll(filepath.Dir(statePath), storageStateDirPerm); err != nil { + return err + } + if _, err := saver.StorageState(playwright.BrowserContextStorageStateOptions{Path: playwright.String(statePath)}); err != nil { + return err + } + return os.Chmod(statePath, storageStateFilePerm) +} + +// 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 + } + + page.OnRequest(func(request playwright.Request) { + if signinRe.MatchString(request.URL()) { + postData, postErr := request.PostData() + mu.Lock() + data, dataErr = postData, postErr + mu.Unlock() + } + }) + 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() + mu.Lock() + data, dataErr = postData, postErr + mu.Unlock() + } + } + + 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 +} + +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..e39a646c9c8 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go @@ -0,0 +1,360 @@ +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) +} + +// 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..ab46b2260f5 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go @@ -0,0 +1,72 @@ +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"))) +} 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..419acfa510c --- /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 +
+
+
+ + + \ No newline at end of file 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..ac45efe1485 --- /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 + +
+
+
+
+ +
+ + + + +
+
+
+
+ \ No newline at end of file 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..f69d1464574 --- /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 + +
+
+
+
+ +
+ + + + +
+
+
+
+ + + \ No newline at end of file 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..6a589adc55c --- /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 +
+
+
+
+ +
+
+
+ + + \ No newline at end of file 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..a7bc14a658d --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -0,0 +1,873 @@ +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") + +// 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 +} + +// 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) { + + // 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(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", 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(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", authForm) + + if err != nil { + return "", errors.Wrap(err, "error loading login page") + } + } + + logger.Debugf("loginURL: %s", passwordURL) + + passwordForm.Set("Passwd", loginDetails.Password) + passwordForm.Set("TrustDevice", "on") + + referingURL := passwordURL + + responseDoc, err := kc.loadChallengePage(passwordURL+"?hl=en&loc=US", 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", captchaURL) + + _, captchaV1 := captchaForm["Passwd"] + if captchaV1 { + captchaForm.Set("Passwd", loginDetails.Password) + } + captchaForm.Set(captchaInputId, captcha) + + responseDoc, err = kc.loadChallengePage(captchaURL+"?hl=en&loc=US", 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(loginURL+"?hl=en&loc=US", 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), nil + } +} + +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") + } + 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", ""), nil +} + +func simpleCaptchaPrompt(captchaPictureURL string) string { + log.Println("Open this link in a browser:\n", captchaPictureURL) + return prompter.String("Captcha", "") +} + +func (kc *Client) loadFirstPage(loginDetails *creds.LoginDetails) (string, url.Values, error) { + firstPageURL := loginDetails.URL + "&hl=en&loc=US" + + 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") + } + + 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") + } + + 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") + } + + 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", secondActionURL) + + switch { + case strings.Contains(secondActionURL, "challenge/totp"): // handle TOTP challenge + + var token = loginDetails.MFAToken + if token == "" { + token = prompter.RequestSecurityCode("000000") + } + + 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
- \ No newline at end of file + 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 index ac45efe1485..2d2d747e3fd 100644 --- 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 @@ -347,4 +347,4 @@

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

- \ No newline at end of file + 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 index f69d1464574..0a67c70a610 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-sms.html @@ -368,4 +368,4 @@

- \ No newline at end of file + 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 index 6a589adc55c..b69d2f7393c 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/example/challenge-totp.html @@ -99,4 +99,4 @@

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

- \ No newline at end of file + diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go index a7bc14a658d..b680ed315c4 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -72,7 +72,6 @@ type Client struct { // 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)) @@ -87,7 +86,6 @@ func New(idpAccount *cfg.IDPAccount) (*Client, error) { // Authenticate logs into Google Apps and returns a SAML response func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) { - // Get the first page authURL, authForm, err := kc.loadFirstPage(loginDetails) if err != nil { @@ -102,11 +100,10 @@ func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) // Post email address w/o password, then Get the password-input page passwordURL, passwordForm, err := kc.loadLoginPage(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", authForm) if err != nil { - //if failed, try with "identifier" + // if failed, try with "identifier" authForm.Set("Email", "") // Clear previous key authForm.Set("identifier", loginDetails.Username) passwordURL, passwordForm, err = kc.loadLoginPage(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", authForm) - if err != nil { return "", errors.Wrap(err, "error loading login page") } @@ -297,7 +294,6 @@ func (kc *Client) loadFirstPage(loginDetails *creds.LoginDetails) (string, url.V } 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") @@ -332,7 +328,6 @@ func (kc *Client) loadLoginPage(submitURL string, referer string, authForm url.V } 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())) @@ -387,7 +382,7 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u switch { case strings.Contains(secondActionURL, "challenge/totp"): // handle TOTP challenge - var token = loginDetails.MFAToken + token := loginDetails.MFAToken if token == "" { token = prompter.RequestSecurityCode("000000") } @@ -418,7 +413,7 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u logger.Debugf("After sms request secondActionURL: %s", secondActionURL) } - var token = prompter.StringRequired("Enter SMS token: G-") + token := prompter.StringRequired("Enter SMS token: G-") responseForm.Set("Pin", token) responseForm.Set("TrustDevice", "on") // Don't ask again on this computer @@ -429,7 +424,7 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u // "challenge/sk" first, which also matches skotp URLs and made this case unreachable. case strings.Contains(secondActionURL, "challenge/skotp"): // handle one-time HOTP challenge log.Println("Get a one-time code by visiting https://g.co/sc on another device where you can use your security key") - var token = prompter.RequestSecurityCode("000 000") + token := prompter.RequestSecurityCode("000 000") responseForm.Set("Pin", token) responseForm.Set("TrustDevice", "on") // Don't ask again on this computer @@ -509,11 +504,9 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u } return doc, nil - } func (kc *Client) skipChallengePage(doc *goquery.Document, submitURL string, secondActionURL string, loginDetails *creds.LoginDetails) (*goquery.Document, error) { - skipResponseForm, skipActionURL, err := extractInputsByFormQuery(doc, `[action$="skip"]`) if err != nil { return nil, errors.Wrap(err, "unable to extract skip form") @@ -527,7 +520,6 @@ func (kc *Client) skipChallengePage(doc *goquery.Document, submitURL string, sec } func (kc *Client) loadAlternateChallengePage(submitURL string, referer string, authForm url.Values, loginDetails *creds.LoginDetails) (*goquery.Document, error) { - req, err := http.NewRequest("POST", submitURL, strings.NewReader(authForm.Encode())) if err != nil { return nil, errors.Wrap(err, "error retrieving login form") @@ -591,7 +583,6 @@ func (kc *Client) loadChallengeEntryPage(doc *goquery.Document, submitURL string } func (kc *Client) postJSON(submitURL string, values map[string]string, referer string) (*http.Response, error) { - data, _ := json.Marshal(values) req, err := http.NewRequest("POST", submitURL, bytes.NewReader(data)) @@ -613,7 +604,6 @@ func (kc *Client) postJSON(submitURL string, values map[string]string, referer s } func (kc *Client) loadResponsePage(submitURL string, referer string, responseForm url.Values) (*goquery.Document, error) { - req, err := http.NewRequest("POST", submitURL, strings.NewReader(responseForm.Encode())) if err != nil { return nil, errors.Wrap(err, "error retrieving response page") @@ -667,7 +657,6 @@ func mustFindErrorMsg(doc *goquery.Document) string { var fieldValue string doc.Find(".error-msg").Each(func(i int, s *goquery.Selection) { fieldValue = s.Text() - }) return fieldValue } @@ -703,7 +692,7 @@ func extractInputsByFormQuery(doc *goquery.Document, formQuery string) (url.Valu currentURL := doc.Url.String() - //get action url + // get action url foundForms := doc.Find(query) if len(foundForms.Nodes) == 0 { return formData, "", fmt.Errorf("could not find form with query %q", query) @@ -742,7 +731,6 @@ func extractInputsByFormQuery(doc *goquery.Document, formQuery string) (url.Valu } func extractNodeText(doc *goquery.Document, tag, txt string) string { - var res string doc.Find(tag).Each(func(i int, s *goquery.Selection) { @@ -755,7 +743,6 @@ func extractNodeText(doc *goquery.Document, tag, txt string) string { } func extractDataAttributes(doc *goquery.Document, query string, attrsToSelect []string) map[string]string { - dataAttrs := make(map[string]string) doc.Find(query).Each(func(_ int, sel *goquery.Selection) { diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go index 33524bae031..7fe47436148 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go @@ -105,8 +105,8 @@ func TestChallenge_PhonePrompt(t *testing.T) { t.Run("waits for the Google app approval", func(t *testing.T) { f := newFakeGoogle(t, map[string]pageHandler{ - pathStart: static(fixture(t, "challenge-prompt.html")), - awaitPath: static(`{}`), + pathStart: static(fixture(t, "challenge-prompt.html")), + awaitPath: static(`{}`), "/signin/challenge/az/5": static(samlPage), }) kc, rt := newClient(t, f.ts.URL) diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_test.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_test.go index 4cf260085ed..0434cd24816 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_test.go @@ -58,6 +58,7 @@ func TestExtractInputsByFormQuery(t *testing.T) { require.Equal(t, "http://example.com/test", actionURL2) require.Equal(t, "test error message", form2.Get("pass")) } + func TestExtractErrorMsg(t *testing.T) { html := `test error message` @@ -179,7 +180,6 @@ func TestPasswordFormChallengeId3(t *testing.T) { } func TestChallengePage(t *testing.T) { - data, err := os.ReadFile("example/challenge-totp.html") require.Nil(t, err) diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go index 867e5e32e72..e6c6b5fe7fd 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go @@ -16,9 +16,7 @@ const ( retryDelay = 200 * time.Millisecond ) -var ( - errNoDeviceFound = fmt.Errorf("no U2F devices found. device might not be plugged in") -) +var errNoDeviceFound = fmt.Errorf("no U2F devices found. device might not be plugged in") // U2FClient represents a challenge and the device used to respond type U2FClient struct { diff --git a/pkg/auth/providers/aws/saml2aws/provider/http.go b/pkg/auth/providers/aws/saml2aws/provider/http.go index bf868610168..e5e3f5af265 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http.go @@ -33,7 +33,7 @@ const ( ) type HTTPClientOptions struct { - IsWithRetries bool //http retry feature switch + IsWithRetries bool // http retry feature switch AttemptsCount uint RetryDelay time.Duration } @@ -97,7 +97,6 @@ func atLeastOneAttempt(attempts uint) uint { // NewHTTPClient configure the default http client used by the providers func NewHTTPClient(tr http.RoundTripper, opts *HTTPClientOptions) (*HTTPClient, error) { - options := &cookiejar.Options{ PublicSuffixList: publicsuffix.List, } @@ -114,7 +113,6 @@ func NewHTTPClient(tr http.RoundTripper, opts *HTTPClientOptions) (*HTTPClient, // Do do the request func (hc *HTTPClient) Do(req *http.Request) (*http.Response, error) { - req.Header.Set("User-Agent", fmt.Sprintf("saml2aws/1.0 (%s %s) Versent", runtime.GOOS, runtime.GOARCH)) var resp *http.Response @@ -168,7 +166,6 @@ func (hc *HTTPClient) doWithRetry(req *http.Request) (*http.Response, error) { }), ) return resp, err - } // DisableFollowRedirect disable redirects @@ -194,7 +191,6 @@ func SuccessOrRedirectResponseValidator(req *http.Request, resp *http.Response) // SuccessOrRedirectOrUnauthorizedResponseValidator also allows 401 func SuccessOrRedirectOrUnauthorizedResponseValidator(req *http.Request, resp *http.Response) error { - validatorResponse := SuccessOrRedirectResponseValidator(req, resp) if validatorResponse == nil || resp.StatusCode == 401 { @@ -205,7 +201,6 @@ func SuccessOrRedirectOrUnauthorizedResponseValidator(req *http.Request, resp *h } func (hc *HTTPClient) logHTTPRequest(req *http.Request) { - if dump.ContentEnable() { log.Println(dump.RequestString(req)) return @@ -218,7 +213,6 @@ func (hc *HTTPClient) logHTTPRequest(req *http.Request) { } func (hc *HTTPClient) logHTTPResponse(resp *http.Response) { - if dump.ContentEnable() { log.Println(dump.ResponseString(resp)) return diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go index 9c31470b1de..12cc0127ef6 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go @@ -63,19 +63,17 @@ var ( newU2FDeviceFinder = func() DeviceFinder { return new(U2FDeviceFinder) } ) -var ( - supportedMfaOptions = map[string]string{ - IdentifierDuoMfa: "DUO MFA authentication", - IdentifierSmsMfa: "SMS MFA authentication", - IdentifierEmailMfa: "EMAIL MFA authentication", - IdentifierPushMfa: "PUSH MFA authentication", - IdentifierTotpMfa: "TOTP MFA authentication", - IdentifierOktaTotpMfa: "Okta MFA authentication", - IdentifierSymantecTotpMfa: "Symantec VIP MFA authentication", - IdentifierFIDOWebAuthn: "FIDO WebAuthn MFA authentication", - IdentifierYubiMfa: "YUBICO TOKEN:HARDWARE", - } -) +var supportedMfaOptions = map[string]string{ + IdentifierDuoMfa: "DUO MFA authentication", + IdentifierSmsMfa: "SMS MFA authentication", + IdentifierEmailMfa: "EMAIL MFA authentication", + IdentifierPushMfa: "PUSH MFA authentication", + IdentifierTotpMfa: "TOTP MFA authentication", + IdentifierOktaTotpMfa: "Okta MFA authentication", + IdentifierSymantecTotpMfa: "Symantec VIP MFA authentication", + IdentifierFIDOWebAuthn: "FIDO WebAuthn MFA authentication", + IdentifierYubiMfa: "YUBICO TOKEN:HARDWARE", +} // Client is a wrapper representing a Okta SAML client type Client struct { @@ -121,7 +119,6 @@ type mfaChallengeContext struct { // New creates a new Okta client func New(idpAccount *cfg.IDPAccount) (*Client, error) { - tr := provider.NewDefaultTransport(idpAccount.SkipVerify) client, err := provider.NewHTTPClient(tr, provider.BuildHttpClientOpts(idpAccount)) @@ -177,7 +174,7 @@ func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken s oktaOrgHost := oktaURL.Host - //authenticate via okta api + // authenticate via okta api sessionReq := SessionRequst{SessionToken: sessionToken} sessionReqBody := new(bytes.Buffer) err = json.NewEncoder(sessionReqBody).Encode(sessionReq) @@ -361,7 +358,7 @@ func (oc *Client) authWithSession(loginDetails *creds.LoginDetails) (string, err // cookie value // This function is not currently used and but can be used in the future func (oc *Client) getDeviceTokenFromOkta(loginDetails *creds.LoginDetails) (string, error) { - //dummy request to set device token cookie ("dt") + // dummy request to set device token cookie ("dt") req, err := http.NewRequest("GET", loginDetails.URL, nil) if err != nil { return "", errors.Wrap(err, "error building device token request") @@ -385,7 +382,6 @@ func (oc *Client) getDeviceTokenFromOkta(loginDetails *creds.LoginDetails) (stri // this func can be uplifted in the future to set custom device tokens or used with // getDeviceTokenFromOkta function func (oc *Client) setDeviceTokenCookie(loginDetails *creds.LoginDetails) error { - // getDeviceTokenFromOkta is not used but doing this to keep the function code // uncommented (avoid linting issues) if false { @@ -417,14 +413,13 @@ func (oc *Client) setDeviceTokenCookie(loginDetails *creds.LoginDetails) error { // primaryAuth creates the Okta Primary Authentication request // returns the authStatus, sessionToken, http response and a error func (oc *Client) primaryAuth(loginDetails *creds.LoginDetails) (string, string, string, error) { - oktaURL, err := url.Parse(loginDetails.URL) if err != nil { return "", "", "", errors.Wrap(err, "error building oktaURL") } oktaOrgHost := oktaURL.Host - //authenticate via okta api + // authenticate via okta api authReq := AuthRequest{Username: loginDetails.Username, Password: loginDetails.Password} if loginDetails.StateToken != "" { authReq = AuthRequest{StateToken: loginDetails.StateToken} @@ -465,7 +460,6 @@ func (oc *Client) primaryAuth(loginDetails *creds.LoginDetails) (string, string, // Authenticate logs into Okta and returns a SAML response func (oc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) { - // Set Okta device token err := oc.setDeviceTokenCookie(loginDetails) if err != nil { @@ -510,7 +504,7 @@ func (oc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) // if user disabled sessions, default to using standard login WITHOUT sessions if oc.disableSessions { - //now call saml endpoint + // now call saml endpoint oktaSessionRedirectURL := fmt.Sprintf("https://%s/login/sessionCookieRedirect", oktaOrgHost) req, err := http.NewRequest("GET", oktaSessionRedirectURL, nil) @@ -600,7 +594,6 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c return "", err } return oc.follow(ctx, req, loginDetails) - } func (oc *Client) getStateToken(req *http.Request, loginDetails *creds.LoginDetails) (string, error) { @@ -644,7 +637,6 @@ func getStateTokenFromOktaPageBody(responseBody string) (string, error) { } return "", errors.New("cannot find state token") - } func parseMfaIdentifer(json string, arrayPosition int) (string, string, string) { @@ -684,7 +676,8 @@ func docIsFormRedirectToTarget(doc *goquery.Document, target string) bool { url := fmt.Sprintf("form[action=\"%s\"]", target) urls = []string{url} } else { - urls = []string{"form[action=\"https://signin.aws.amazon.com/saml\"]", + urls = []string{ + "form[action=\"https://signin.aws.amazon.com/saml\"]", "form[action=\"https://signin.amazonaws-us-gov.com/saml\"]", "form[action=\"https://signin.amazonaws.cn/saml\"]", } @@ -795,7 +788,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } else { mfaOptions = append(mfaOptions, fmt.Sprintf("%s - %s", val, id)) } - } else { mfaOptions = append(mfaOptions, "UNSUPPORTED: "+identifier) } @@ -834,7 +826,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, case IdentifierYubiMfa: return gjson.Get(challengeContext.challengeResponseBody, "sessionToken").String(), nil case IdentifierSmsMfa, IdentifierEmailMfa, IdentifierTotpMfa, IdentifierOktaTotpMfa, IdentifierSymantecTotpMfa: - var verifyCode = loginDetails.MFAToken + verifyCode := loginDetails.MFAToken if verifyCode == "" { verifyCode = prompter.RequestSecurityCode("000000") } @@ -916,8 +908,8 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if len(duoSignatures) < 2 { return "", errors.New("invalid duo verification signature") } - //duoSignatures[0] = TX - //duoSignatures[1] = APP + // duoSignatures[0] = TX + // duoSignatures[1] = APP duoCallback := gjson.Get(challengeContext.challengeResponseBody, "_embedded.factor._embedded.verification._links.complete.href").String() // initiate duo mfa to get sid @@ -958,7 +950,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, // At this point, if device trust is enabled we need to go on that tangent doc, err := goquery.NewDocumentFromReader(res.Body) - if err != nil { return "", errors.Wrap(err, "error parsing document") } @@ -973,10 +964,8 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, origUrl := req.URL.String() duoEndpointHost := "127.0.0.1:53100" doc, err = verifyEndpointHealth(oc, doc, origUrl, duoEndpointHost, duoHost, duoSubmitURL, q) - if err != nil { return "", errors.Wrap(err, "couldn't validate endpoint health") - } } @@ -988,7 +977,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } duoSID = html.UnescapeString(duoSID) - var duoMfaOptions = []string{} + duoMfaOptions := []string{} var token string webauthnOption := doc.Find("option[name=\"webauthn\"]") @@ -1024,7 +1013,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } if duoMfaOptions[duoMfaOption] == "Passcode" { - //get users DUO MFA Token + // get users DUO MFA Token token = prompter.StringRequired("Enter passcode") } @@ -1111,14 +1100,13 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if duoRestStatusCode == "u2f_sent" { appId := gjson.Get(resp, "response.u2f_sign_request.0.appId").String() - //appId := "api-23a9854b.duosecurity.com" + // appId := "api-23a9854b.duosecurity.com" version := gjson.Get(resp, "response.u2f_sign_request.0.version").String() challengeNonce := gjson.Get(resp, "response.u2f_sign_request.0.challenge").String() keyHandle := gjson.Get(resp, "response.u2f_sign_request.0.keyHandle").String() sessionId := gjson.Get(resp, "response.u2f_sign_request.0.sessionId").String() u2fClient, err := NewDUOU2FClient(challengeNonce, appId, version, keyHandle, sessionId, newU2FDeviceFinder()) - if err != nil { return "", err } @@ -1207,7 +1195,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } if duoTxResult != "SUCCESS" { - //poll as this is likely a push request + // poll as this is likely a push request for { time.Sleep(duoPollInterval) @@ -1361,7 +1349,6 @@ func extractSessionToken(r io.Reader) (string, error) { } func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallengeContext, mfaOption int, stateToken string, mfaOptions []string, resp string) (string, error) { - var signedAssertion *SignedAssertion challengeResponseBody := challengeContext.challengeResponseBody lastMfaOption := mfaOption @@ -1495,7 +1482,6 @@ func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSub oc.client.Transport = customTransport req, err := http.NewRequest("GET", duoCertifierURL, nil) - if err != nil { return nil, errors.Wrap(err, "error building cert validation request") } @@ -1509,14 +1495,12 @@ func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSub duoCertURL := fmt.Sprintf("%s?sid=%s&certs_txid=%s&type=AJAX", certUrl, url.QueryEscape(sid), txid) req, err = http.NewRequest("GET", duoCertURL, nil) - if err != nil { return nil, errors.Wrap(err, "error building cert validation request ") } req.Header.Add("Referer", "https://"+duoHost) res, err = oc.client.Do(req) - if err != nil { return nil, errors.Wrap(err, "error retrieving cert validation response") } @@ -1567,7 +1551,6 @@ func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSub } func verifyEndpointHealth(oc *Client, doc *goquery.Document, origURL string, duoEndpointHost string, duoHost string, duoSubmitURL string, postQuery url.Values) (*goquery.Document, error) { - txid, _ := doc.Find("input[name=\"txid\"]").Attr("value") sid, _ := doc.Find("input[name=\"sid\"]").Attr("value") ehServiceUrl, _ := doc.Find("input[name=\"eh_service_url\"]").Attr("value") @@ -1592,7 +1575,6 @@ func verifyEndpointHealth(oc *Client, doc *goquery.Document, origURL string, duo _, err := oc.client.Do(req) if err != nil { return nil, errors.Wrapf(err, "failed to query alive URL %s", duoAliveUrl) - } duoCheckEndpointAppURL := fmt.Sprintf("https://%s/frame/check_endpoint_app_status", duoHost) diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go index 479b4259274..87c965b546b 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go @@ -75,7 +75,6 @@ func TestGetStateTokenFromOktaPageBody(t *testing.T) { assert.NotNil(t, err) assert.Equal(t, test.err.Error(), err.Error()) } - }) } } @@ -270,7 +269,6 @@ func TestVerifyMfa(t *testing.T) { } func TestVerifyMfa_Email(t *testing.T) { - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/verify": @@ -427,7 +425,8 @@ func setupTestDuoHttpServer(t *testing.T, duoFactor string) *httptest.Server { assert.Equal(t, url.Values{ "parent": {"https://host-from-argument/signin/verify/duo/web"}, "tx": {"TX|blah_tx_blah"}, - "v": {"2.8"}}, + "v": {"2.8"}, + }, query) assert.Nil(t, err) @@ -449,7 +448,8 @@ func setupTestDuoHttpServer(t *testing.T, duoFactor string) *httptest.Server { "react_support_error_message": {""}, "screen_resolution_height": {"1692"}, "screen_resolution_width": {"3008"}, - "tx": {"TX|blah_tx_blah"}}, + "tx": {"TX|blah_tx_blah"}, + }, query) assert.Nil(t, err) @@ -677,7 +677,6 @@ func TestSetDeviceTokenCookie(t *testing.T) { } assert.NotEqual(t, actualDT, "") assert.Equal(t, expectedDT, actualDT) - } func TestOktaCfgFlagsDefaultState(t *testing.T) { @@ -711,7 +710,6 @@ func TestOktaCfgFlagsCustomState(t *testing.T) { assert.True(t, oc.disableSessions, fmt.Errorf("DisableSessions was set to true so disableSessions should be true")) assert.False(t, oc.rememberDevice, fmt.Errorf("DisablDisableSessionseRememberDevice was set to true, so rememberDevice should be false")) - } func TestOktaParseMfaIdentifer(t *testing.T) { @@ -774,7 +772,6 @@ func TestOktaParseMfaIdentifer(t *testing.T) { } func TestGetStateToken(t *testing.T) { - persistedCookie := &http.Cookie{Name: "TestCookie", Value: "test"} svr := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Contains(t, r.Cookies(), persistedCookie) @@ -841,6 +838,7 @@ func (s *testServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { h, s.handlers = s.handlers[0], s.handlers[1:] h(w, r) } + func TestVerifyTrustedCert(t *testing.T) { host := "" @@ -875,7 +873,6 @@ func TestVerifyTrustedCert(t *testing.T) { assert.Equal(t, "0dcfcbe4-5e20-47a3-9037-cb1d1bf4ad5b", r.Form.Get("certs_txid")) assert.Equal(t, fmt.Sprintf("https://%s/certs-url", host), r.Form.Get("certs_url")) assert.Equal(t, fmt.Sprintf("https://%s/certifier-url", host), r.Form.Get("certifier_url")) - }, } @@ -944,7 +941,6 @@ func TestVerifyEndpointHealth(t *testing.T) { assert.Equal(t, "0dcfcbe4-5e20-47a3-9037-cb1d1bf4ad5b", r.URL.Query().Get("txid")) assert.Equal(t, "HAlorymR7ZuV2CxZz9T10jABE4jzkWFBJYLEnlF4nUwCqQ=|1683218343|2a46eb852b3ef9f662304cee03d008daed6d71f6", r.URL.Query().Get("sid")) assert.Equal(t, "XMLHttpRequest", r.Header.Get("X-Requested-With")) - }, "/submit": func(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go index 5da67c0ac53..cda9e6f1459 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go @@ -16,9 +16,7 @@ const ( RetryDelayMS = 200 * time.Millisecond ) -var ( - errNoDeviceFound = fmt.Errorf("no U2F devices found. device might not be plugged in") -) +var errNoDeviceFound = fmt.Errorf("no U2F devices found. device might not be plugged in") // FidoClient represents a challenge and the device used to respond type FidoClient struct { @@ -133,7 +131,6 @@ func (d *FidoClient) ChallengeU2F() (*SignedAssertion, error) { } } } - } // U2FDeviceFinder returns a U2F device diff --git a/pkg/auth/providers/aws/saml2aws/saml.go b/pkg/auth/providers/aws/saml2aws/saml.go index 282aedd8690..70b330647c7 100644 --- a/pkg/auth/providers/aws/saml2aws/saml.go +++ b/pkg/auth/providers/aws/saml2aws/saml.go @@ -39,7 +39,6 @@ func (e ErrMissingElement) Error() string { // ExtractSessionDuration this will attempt to extract a session duration from the assertion // see https://aws.amazon.com/SAML/Attributes/SessionDuration func ExtractSessionDuration(data []byte) (int64, error) { - doc := etree.NewDocument() if err := doc.ReadFromBytes(data); err != nil { return 0, err @@ -52,7 +51,7 @@ func ExtractSessionDuration(data []byte) (int64, error) { // log.Printf("tag: %s", assertionElement.Tag) - //Get the actual assertion attributes + // Get the actual assertion attributes attributeStatement := assertionElement.FindElement(childPath(assertionElement.Space, attributeStatementTag)) if attributeStatement == nil { return 0, ErrMissingElement{Tag: attributeStatementTag} @@ -77,7 +76,6 @@ func ExtractSessionDuration(data []byte) (int64, error) { // This is necessary to support AWS instances with custom endpoints such as GovCloud and AWS China without requiring // hardcoded endpoints on the saml2aws side. func ExtractDestinationURL(data []byte) (string, error) { - doc := etree.NewDocument() if err := doc.ReadFromBytes(data); err != nil { return "", err @@ -135,7 +133,6 @@ func ExtractMFATokenExpiryTime(data []byte) (time.Time, error) { // ExtractAwsRoles given an assertion document extract the aws roles func ExtractAwsRoles(data []byte) ([]string, error) { - awsroles := []string{} doc := etree.NewDocument() @@ -152,7 +149,7 @@ func ExtractAwsRoles(data []byte) ([]string, error) { // log.Printf("tag: %s", assertionElement.Tag) - //Get the actual assertion attributes + // Get the actual assertion attributes attributeStatement := assertionElement.FindElement(childPath(assertionElement.Space, attributeStatementTag)) if attributeStatement == nil { return nil, ErrMissingElement{Tag: attributeStatementTag} @@ -178,6 +175,6 @@ func childPath(space, tag string) string { if space == "" { return "./" + tag } - //log.Printf("query = %s", "./"+space+":"+tag) + // log.Printf("query = %s", "./"+space+":"+tag) return "./" + space + ":" + tag } diff --git a/pkg/auth/providers/aws/saml2aws/testdata/assertion.xml b/pkg/auth/providers/aws/saml2aws/testdata/assertion.xml index f22b940f0e2..af2860281ca 100644 --- a/pkg/auth/providers/aws/saml2aws/testdata/assertion.xml +++ b/pkg/auth/providers/aws/saml2aws/testdata/assertion.xml @@ -54,4 +54,4 @@ - \ No newline at end of file + diff --git a/pkg/auth/providers/aws/saml2aws/testdata/assertion_no_destination.xml b/pkg/auth/providers/aws/saml2aws/testdata/assertion_no_destination.xml index ee0056142d8..e4d26fff033 100644 --- a/pkg/auth/providers/aws/saml2aws/testdata/assertion_no_destination.xml +++ b/pkg/auth/providers/aws/saml2aws/testdata/assertion_no_destination.xml @@ -54,4 +54,4 @@ - \ No newline at end of file + diff --git a/pkg/auth/providers/aws/saml2aws/testdata/notxml.xml b/pkg/auth/providers/aws/saml2aws/testdata/notxml.xml index 66c441f4ee5..be108529a22 100644 --- a/pkg/auth/providers/aws/saml2aws/testdata/notxml.xml +++ b/pkg/auth/providers/aws/saml2aws/testdata/notxml.xml @@ -1 +1 @@ -??? \ No newline at end of file +??? diff --git a/pkg/auth/providers/aws/saml_browser_platform.go b/pkg/auth/providers/aws/saml_browser_platform.go index df675edc26b..e151fa57063 100644 --- a/pkg/auth/providers/aws/saml_browser_platform.go +++ b/pkg/auth/providers/aws/saml_browser_platform.go @@ -176,4 +176,3 @@ func leadingInt(s string) (int, bool) { } return n, true } - From a3c25bbca26d6bf7bde9099fbba42c5fdf0d1369 Mon Sep 17 00:00:00 2001 From: aknysh Date: Tue, 17 Nov 2026 20:49:20 -0500 Subject: [PATCH 4/7] fix(auth): address code scanning and CodeRabbit review on vendored saml2aws Code scanning: - Stop logging secrets at debug level: the Okta password (loginDetails %v), the decoded SAML assertion, the Okta device token, and full request URLs whose query strings carry session tokens. Remove the hidden DUMP_CONTENT request/response dump and its package; log URLs as scheme, host and path. - Parse http_retry_delay as 32 bits and cap it at 5 minutes (overflow). CodeRabbit: - Propagate prompt failures (Ctrl+C, no terminal) instead of sending an empty token or choosing the first option. - Bound Okta push and Duo polling (5 minutes) and GoogleApps challenge transitions; cancel the Duo endpoint-health status request on failure. - Parse SAML assertions by namespace URI, not prefix; split role pairs only at ",arn:". - Resend the request body on retry, bind retry waits to the request context, and close rejected and unused response bodies. - Resolve relative ADFS form actions and set GoogleApps locale parameters in the query; fix several nil and index panics. - Save the browser session file through a private temporary file. - Ignore Playwright registry metadata when detecting installed browsers, and honor INIT_CWD and the npm config forms of PLAYWRIGHT_BROWSERS_PATH. Co-Authored-By: Claude Opus 5.5 --- ...6-11-17-vendor-saml2aws-drop-go-jose-v3.md | 14 ++ pkg/auth/cloud/aws/ecr_token_test.go | 22 ++- pkg/auth/docs/PRD/PRD-Atmos-Auth.md | 12 +- pkg/auth/providers/aws/saml.go | 6 + pkg/auth/providers/aws/saml2aws/README.md | 18 +++ pkg/auth/providers/aws/saml2aws/aws_role.go | 33 ++++- .../providers/aws/saml2aws/aws_role_test.go | 14 ++ .../providers/aws/saml2aws/cookiejar/jar.go | 5 +- .../aws/saml2aws/cookiejar/jar_test.go | 18 +++ pkg/auth/providers/aws/saml2aws/dump/dump.go | 32 ----- .../providers/aws/saml2aws/dump/dump_test.go | 126 ------------------ .../providers/aws/saml2aws/mocks/Prompter.go | 43 +++--- pkg/auth/providers/aws/saml2aws/page/form.go | 29 +++- .../providers/aws/saml2aws/page/form_test.go | 39 ++++++ .../aws/saml2aws/prompter/pinentry.go | 23 ++-- .../aws/saml2aws/prompter/pinentry_test.go | 76 ++++++++--- .../aws/saml2aws/prompter/prompter.go | 25 ++-- .../aws/saml2aws/prompter/prompter_test.go | 51 ++++--- .../providers/aws/saml2aws/prompter/survey.go | 48 ++++--- .../aws/saml2aws/prompter/survey_test.go | 25 +++- .../aws/saml2aws/provider/adfs/adfs.go | 11 +- .../aws/saml2aws/provider/adfs/adfs_test.go | 20 +++ .../aws/saml2aws/provider/browser/browser.go | 63 +++++++-- .../saml2aws/provider/browser/browser_test.go | 26 ++++ .../provider/browser/storage_state_test.go | 53 ++++++++ .../provider/googleapps/googleapps.go | 112 +++++++++++++--- .../googleapps/googleapps_robustness_test.go | 67 ++++++++++ .../providers/aws/saml2aws/provider/http.go | 42 +++--- .../saml2aws/provider/http_attempts_test.go | 72 ++++++++++ .../aws/saml2aws/provider/http_test.go | 91 +++++++++---- .../aws/saml2aws/provider/okta/okta.go | 87 ++++++++++-- .../provider/okta/okta_duo_flow_test.go | 69 ++++++++++ .../provider/okta/okta_log_redaction_test.go | 68 ++++++++++ .../provider/okta/okta_mfa_flow_test.go | 92 +++++++++++++ .../providers/aws/saml2aws/provider/redact.go | 24 ++++ pkg/auth/providers/aws/saml2aws/saml.go | 40 ++++-- pkg/auth/providers/aws/saml2aws/saml_test.go | 50 +++++++ .../providers/aws/saml_browser_revision.go | 25 +++- .../aws/saml_browser_revision_test.go | 35 +++++ .../aws/saml_driver_detection_test.go | 12 ++ pkg/auth/providers/aws/sso_token_flow_test.go | 8 +- 41 files changed, 1356 insertions(+), 370 deletions(-) delete mode 100644 pkg/auth/providers/aws/saml2aws/dump/dump.go delete mode 100644 pkg/auth/providers/aws/saml2aws/dump/dump_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_log_redaction_test.go create mode 100644 pkg/auth/providers/aws/saml2aws/provider/redact.go 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 index d31de5dd9a7..4d4c449d858 100644 --- 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 @@ -93,6 +93,20 @@ the module graph or the binary. The copy also fixes the browser driver's timeout - 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 diff --git a/pkg/auth/cloud/aws/ecr_token_test.go b/pkg/auth/cloud/aws/ecr_token_test.go index fb6e20f1670..04e6c1debb9 100644 --- a/pkg/auth/cloud/aws/ecr_token_test.go +++ b/pkg/auth/cloud/aws/ecr_token_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "path/filepath" "strings" + "sync" "testing" "time" @@ -20,7 +21,7 @@ import ( // 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) *string { +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. @@ -30,21 +31,32 @@ func serveECRAuthorization(t *testing.T, body string) *string { 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") - signedRegion := new(string) + // 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 { - *signedRegion = 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 signedRegion + return func() string { + mu.Lock() + defer mu.Unlock() + return signedRegion + } } func TestGetAuthorizationToken(t *testing.T) { @@ -115,7 +127,7 @@ func TestGetAuthorizationToken(t *testing.T) { return } require.NoError(t, err) - assert.Equal(t, tt.wantRegion, *signedRegion) + 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) diff --git a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md index d0baadf5016..35b525563c5 100644 --- a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md +++ b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md @@ -836,13 +836,11 @@ 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:** diff --git a/pkg/auth/providers/aws/saml.go b/pkg/auth/providers/aws/saml.go index a7ba1e00f6b..562ee260490 100644 --- a/pkg/auth/providers/aws/saml.go +++ b/pkg/auth/providers/aws/saml.go @@ -627,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 { diff --git a/pkg/auth/providers/aws/saml2aws/README.md b/pkg/auth/providers/aws/saml2aws/README.md index 73137160fc4..d9014c5e75b 100644 --- a/pkg/auth/providers/aws/saml2aws/README.md +++ b/pkg/auth/providers/aws/saml2aws/README.md @@ -76,6 +76,24 @@ identity provider and read the AWS roles from the SAML assertion. - **`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`. diff --git a/pkg/auth/providers/aws/saml2aws/aws_role.go b/pkg/auth/providers/aws/saml2aws/aws_role.go index 60ff2246b6d..719ca1b650d 100644 --- a/pkg/auth/providers/aws/saml2aws/aws_role.go +++ b/pkg/auth/providers/aws/saml2aws/aws_role.go @@ -29,9 +29,38 @@ func ParseAWSRoles(roles []string) ([]*AWSRole, error) { 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) { - r, _ := regexp.Compile("arn:([^:\n]*):([^:\n]*):([^:\n]*):([^:\n]*):(([^:/\n]*)[:/])?([^:,\n]*)") - tokens := r.FindAllString(role, -1) + tokens := splitRoleARNs(role) if len(tokens) != 2 { return nil, fmt.Errorf("Invalid role string only %d tokens", len(tokens)) diff --git a/pkg/auth/providers/aws/saml2aws/aws_role_test.go b/pkg/auth/providers/aws/saml2aws/aws_role_test.go index dd48073dcb2..8ff0db9bb6a 100644 --- a/pkg/auth/providers/aws/saml2aws/aws_role_test.go +++ b/pkg/auth/providers/aws/saml2aws/aws_role_test.go @@ -77,3 +77,17 @@ func TestParseAWSRolesGovCloudAndWhitespace(t *testing.T) { 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/cookiejar/jar.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go index 2c3b569f8fa..d2bb8ee4f14 100644 --- a/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go @@ -366,9 +366,8 @@ func defaultPath(path string) string { if i == 0 { return "/" // Path has the form "/abc". } - if s, err := url.PathUnescape(path[:i]); err == nil { - return s - } + // 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/". } diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go index e0a720f92d4..0fa88ae42ec 100644 --- a/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go @@ -1359,3 +1359,21 @@ func TestIssue26247(t *testing.T) { } } } + +// 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/dump/dump.go b/pkg/auth/providers/aws/saml2aws/dump/dump.go deleted file mode 100644 index 607e336e6c3..00000000000 --- a/pkg/auth/providers/aws/saml2aws/dump/dump.go +++ /dev/null @@ -1,32 +0,0 @@ -package dump - -import ( - "net/http" - "net/http/httputil" - "os" -) - -// RequestString helper method to dump the http request -func RequestString(req *http.Request) string { - data, err := httputil.DumpRequestOut(req, ContentEnable()) - if err != nil { - return "" - } - - return string(data) -} - -// ResponseString helper method to dump the http response -func ResponseString(res *http.Response) string { - data, err := httputil.DumpResponse(res, ContentEnable()) - if err != nil { - return "" - } - - return string(data) -} - -// ContentEnable enable dumping of request / response content -func ContentEnable() bool { - return os.Getenv("DUMP_CONTENT") == "true" -} diff --git a/pkg/auth/providers/aws/saml2aws/dump/dump_test.go b/pkg/auth/providers/aws/saml2aws/dump/dump_test.go deleted file mode 100644 index 59bee88b600..00000000000 --- a/pkg/auth/providers/aws/saml2aws/dump/dump_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package dump - -import ( - "errors" - "io" - "net/http" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type failingReader struct{} - -func (failingReader) Read([]byte) (int, error) { return 0, errors.New("read failure") } - -func TestContentEnable(t *testing.T) { - tests := []struct { - value string - want bool - }{ - {value: "true", want: true}, - {value: "TRUE", want: false}, - {value: "1", want: false}, - {value: "", want: false}, - } - - for _, tt := range tests { - t.Run(tt.value, func(t *testing.T) { - t.Setenv("DUMP_CONTENT", tt.value) - assert.Equal(t, tt.want, ContentEnable()) - }) - } -} - -func TestRequestString(t *testing.T) { - tests := []struct { - name string - dump string - wantBody bool - }{ - {name: "headers and body", dump: "true", wantBody: true}, - {name: "headers only", dump: "false", wantBody: false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Setenv("DUMP_CONTENT", tt.dump) - req, err := http.NewRequest(http.MethodPost, "https://idp.example.com/login", strings.NewReader("user=alice")) - require.NoError(t, err) - - out := RequestString(req) - assert.Contains(t, out, "POST /login HTTP/1.1") - assert.Contains(t, out, "Host: idp.example.com") - if tt.wantBody { - assert.Contains(t, out, "user=alice") - } else { - assert.NotContains(t, out, "user=alice") - } - }) - } -} - -func TestRequestStringError(t *testing.T) { - t.Setenv("DUMP_CONTENT", "true") - req, err := http.NewRequest(http.MethodGet, "ftp://idp.example.com/login", nil) - require.NoError(t, err) - - assert.Empty(t, RequestString(req)) -} - -func TestResponseString(t *testing.T) { - tests := []struct { - name string - dump string - wantBody bool - }{ - {name: "headers and body", dump: "true", wantBody: true}, - {name: "headers only", dump: "false", wantBody: false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Setenv("DUMP_CONTENT", tt.dump) - res := &http.Response{ - Status: "200 OK", - StatusCode: http.StatusOK, - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - Header: http.Header{"X-Test": {"yes"}}, - Body: io.NopCloser(strings.NewReader("ok")), - ContentLength: int64(len("ok")), - } - - out := ResponseString(res) - assert.Contains(t, out, "HTTP/1.1 200 OK") - assert.Contains(t, out, "X-Test: yes") - if tt.wantBody { - assert.Contains(t, out, "ok") - // The body is restored so callers can still read it. - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - assert.Equal(t, "ok", string(body)) - } else { - assert.NotContains(t, out, "ok") - } - }) - } -} - -func TestResponseStringError(t *testing.T) { - t.Setenv("DUMP_CONTENT", "true") - res := &http.Response{ - Status: "200 OK", - StatusCode: http.StatusOK, - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - Header: http.Header{}, - Body: io.NopCloser(failingReader{}), - } - - assert.Empty(t, ResponseString(res)) -} diff --git a/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go b/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go index b9e1a205ce6..0e8d76220ad 100644 --- a/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go +++ b/pkg/auth/providers/aws/saml2aws/mocks/Prompter.go @@ -9,8 +9,9 @@ type Prompter struct { mock.Mock } -// Choose provides a mock function with given fields: _a0, _a1 -func (_m *Prompter) Choose(_a0 string, _a1 []string) int { +// 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 @@ -20,7 +21,7 @@ func (_m *Prompter) Choose(_a0 string, _a1 []string) int { r0 = ret.Get(0).(int) } - return r0 + return r0, mockError(ret, 1) } // ChooseWithDefault provides a mock function with given fields: _a0, _a1, _a2 @@ -52,8 +53,9 @@ func (_m *Prompter) Display(_a0 string) { _m.Called(_a0) } -// Password provides a mock function with given fields: _a0 -func (_m *Prompter) Password(_a0 string) string { +// 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 @@ -63,11 +65,12 @@ func (_m *Prompter) Password(_a0 string) string { r0 = ret.Get(0).(string) } - return r0 + return r0, mockError(ret, 1) } -// RequestSecurityCode provides a mock function with given fields: _a0 -func (_m *Prompter) RequestSecurityCode(_a0 string) string { +// 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 @@ -77,11 +80,12 @@ func (_m *Prompter) RequestSecurityCode(_a0 string) string { r0 = ret.Get(0).(string) } - return r0 + return r0, mockError(ret, 1) } -// String provides a mock function with given fields: _a0, _a1 -func (_m *Prompter) String(_a0 string, _a1 string) string { +// 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 @@ -91,11 +95,12 @@ func (_m *Prompter) String(_a0 string, _a1 string) string { r0 = ret.Get(0).(string) } - return r0 + return r0, mockError(ret, 1) } -// StringRequired provides a mock function with given fields: _a0 -func (_m *Prompter) StringRequired(_a0 string) string { +// 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 @@ -105,7 +110,15 @@ func (_m *Prompter) StringRequired(_a0 string) string { r0 = ret.Get(0).(string) } - return r0 + 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. diff --git a/pkg/auth/providers/aws/saml2aws/page/form.go b/pkg/auth/providers/aws/saml2aws/page/form.go index c1a73d25b91..5a315f7ff62 100644 --- a/pkg/auth/providers/aws/saml2aws/page/form.go +++ b/pkg/auth/providers/aws/saml2aws/page/form.go @@ -19,6 +19,26 @@ type Form struct { } 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 { @@ -55,8 +75,11 @@ func NewFormFromDocument(doc *goquery.Document, formFilter string) (*Form, error attrValue, ok := formSelection.Attr("action") if ok { form.URL = attrValue - } else { + } 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") @@ -87,5 +110,9 @@ func NewFormFromResponse(res *http.Response, formFilter string) (*Form, error) { 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 index 9888dbedd42..659d5f832e7 100644 --- a/pkg/auth/providers/aws/saml2aws/page/form_test.go +++ b/pkg/auth/providers/aws/saml2aws/page/form_test.go @@ -172,3 +172,42 @@ func TestFormSubmit(t *testing.T) { 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) +} diff --git a/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go index b2f22307fb9..68330784cdd 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go @@ -45,15 +45,15 @@ func NewRealPinentryRunner(bin string) *RealPinentryRunner { // RequestSecurityCode for PinentryPrompter is creating a query for pinentry // and sends it to the pinentry bin. -func (p *PinentryPrompter) RequestSecurityCode(pattern string) (output string) { +func (p *PinentryPrompter) RequestSecurityCode(pattern string) (string, error) { commandTemplate := "SETPROMPT %s\nGETPIN\n" prompt := fmt.Sprintf(defaultPinentryDialog, pattern) command := fmt.Sprintf(commandTemplate, prompt) - if output, err := p.Runner.Run(command); err != nil { - return "" - } else { - return output + output, err := p.Runner.Run(command) + if err != nil { + return "", err } + return output, nil } // ChooseWithDefault is running the default CLI ChooseWithDefault @@ -62,22 +62,22 @@ func (p *PinentryPrompter) ChooseWithDefault(prompt string, def string, choices } // Choose is running the default CLI Choose -func (p *PinentryPrompter) Choose(pr string, options []string) int { +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 { +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 { +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 { +func (p *PinentryPrompter) Password(pr string) (string, error) { return p.DefaultPrompter.Password(pr) } @@ -131,5 +131,10 @@ func ParseResults(pinEntryOutput io.Reader) (output string, err error) { } } + // 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 index ee4f8d6276d..29d7040e79d 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry_test.go @@ -1,10 +1,12 @@ 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 @@ -40,14 +42,14 @@ type FakeDefaultPrompter struct { } // all the functions to implement the Prompter interface -func (f *FakeDefaultPrompter) RequestSecurityCode(p string) string { +func (f *FakeDefaultPrompter) RequestSecurityCode(p string) (string, error) { f.CalledRequestSecurityCode = true - return "" + return "", nil } -func (f *FakeDefaultPrompter) Choose(p string, option []string) int { +func (f *FakeDefaultPrompter) Choose(p string, option []string) (int, error) { f.CalledChoose = true - return 0 + return 0, nil } func (f *FakeDefaultPrompter) ChooseWithDefault(p string, d string, c []string) (string, error) { @@ -55,19 +57,19 @@ func (f *FakeDefaultPrompter) ChooseWithDefault(p string, d string, c []string) return "", nil } -func (f *FakeDefaultPrompter) String(p string, defaultValue string) string { +func (f *FakeDefaultPrompter) String(p string, defaultValue string) (string, error) { f.CalledString = true - return "" + return "", nil } -func (f *FakeDefaultPrompter) StringRequired(p string) string { +func (f *FakeDefaultPrompter) StringRequired(p string) (string, error) { f.CalledStringRequired = true - return "" + return "", nil } -func (f *FakeDefaultPrompter) Password(p string) string { +func (f *FakeDefaultPrompter) Password(p string) (string, error) { f.CalledPassword = true - return "" + return "", nil } func (f *FakeDefaultPrompter) Display(p string) { @@ -99,6 +101,43 @@ func TestValidateAndSetPrompterShouldWorkWithInputForCli(t *testing.T) { } } +// 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 @@ -117,19 +156,19 @@ func TestChecksPinentryPrompterDefault(t *testing.T) { fakeDefaultPrompter := &FakeDefaultPrompter{} p.DefaultPrompter = fakeDefaultPrompter - _ = p.Choose("random", []string{"1", "2"}) + _, _ = 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") + _, _ = p.String("random", "random") assert.True(t, fakeDefaultPrompter.CalledString) - _ = p.StringRequired("random") + _, _ = p.StringRequired("random") assert.True(t, fakeDefaultPrompter.CalledStringRequired) - _ = p.Password("random") + _, _ = p.Password("random") assert.True(t, fakeDefaultPrompter.CalledPassword) p.Display("random") @@ -141,8 +180,9 @@ func TestChecksPinentryPrompterCallsPinentryForRequestSecurityCode(t *testing.T) runner := &FakePinentryRunner{} p.Runner = runner runner.FakeOutput = "random_code" - pinentryOutput := p.RequestSecurityCode("000000") + 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") @@ -153,8 +193,9 @@ func TestChecksPinentryPrompterReturnsRightCodeGivenFakePinentryOutput(t *testin runner := &FakePinentryRunner{} p.Runner = runner runner.FakePinentryOutput = "OK This line should get ignored\nOK This line should too\nD 654321\nOK Final\n" - pinentryOutput := p.RequestSecurityCode("000000") + pinentryOutput, err := p.RequestSecurityCode("000000") + assert.NoError(t, err) assert.True(t, runner.HasRun) assert.Equal(t, pinentryOutput, "654321") } @@ -164,8 +205,9 @@ func TestChecksPinentryPrompterReturnsNoCodeGivenErroneousFakePinentryOutput(t * 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 := p.RequestSecurityCode("000000") + pinentryOutput, err := p.RequestSecurityCode("000000") + assert.Error(t, err) assert.True(t, runner.HasRun) assert.Equal(t, pinentryOutput, "") } diff --git a/pkg/auth/providers/aws/saml2aws/prompter/prompter.go b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go index 8f935ae91f7..4f6fd93c60f 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/prompter.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go @@ -10,12 +10,14 @@ var ActivePrompter Prompter = NewCli() // Prompter handles prompting user for input type Prompter interface { - RequestSecurityCode(string) string + // 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 - StringRequired(string) string - String(string, string) string - Password(string) string + Choose(string, []string) (int, error) + StringRequired(string) (string, error) + String(string, string) (string, error) + Password(string) (string, error) Display(string) } @@ -28,7 +30,8 @@ func SetPrompter(prmpt Prompter) { // a concrete prompter based on this configuration func ValidateAndSetPrompter(prmptCfg string) error { if prmptCfg == "" || prmptCfg == "survey" || prmptCfg == "default" { - // nothing to do; the default prompter is the survey one. + // Atmos fork: reset to the survey prompter so an earlier pinentry selection does not stay active. + SetPrompter(NewCli()) return nil } @@ -43,7 +46,7 @@ func ValidateAndSetPrompter(prmptCfg string) error { } // RequestSecurityCode request a security code to be entered by the user -func RequestSecurityCode(pattern string) string { +func RequestSecurityCode(pattern string) (string, error) { return ActivePrompter.RequestSecurityCode(pattern) } @@ -60,22 +63,22 @@ func ChooseWithDefault(pr string, defaultValue string, options []string) (string } // Choose given the choice return the option selected -func Choose(pr string, options []string) int { +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 { +func StringRequired(pr string) (string, error) { return ActivePrompter.StringRequired(pr) } // String prompt for string which is required -func String(pr string, defaultValue string) string { +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 { +func Password(pr string) (string, error) { return ActivePrompter.Password(pr) } diff --git a/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go b/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go index 98ad0f20130..d78105b03e7 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter_test.go @@ -19,10 +19,10 @@ type recordingPrompter struct { chooseResult string } -func (r *recordingPrompter) RequestSecurityCode(pattern string) string { +func (r *recordingPrompter) RequestSecurityCode(pattern string) (string, error) { r.calls = append(r.calls, "RequestSecurityCode") r.lastPrompt = pattern - return "123456" + return "123456", nil } func (r *recordingPrompter) ChooseWithDefault(pr, def string, options []string) (string, error) { @@ -31,28 +31,28 @@ func (r *recordingPrompter) ChooseWithDefault(pr, def string, options []string) return r.chooseResult, nil } -func (r *recordingPrompter) Choose(pr string, options []string) int { +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 + return len(options) - 1, nil } -func (r *recordingPrompter) StringRequired(pr string) string { +func (r *recordingPrompter) StringRequired(pr string) (string, error) { r.calls = append(r.calls, "StringRequired") r.lastPrompt = pr - return "required" + return "required", nil } -func (r *recordingPrompter) String(pr, def string) string { +func (r *recordingPrompter) String(pr, def string) (string, error) { r.calls = append(r.calls, "String") r.lastPrompt, r.lastDefault = pr, def - return "value" + return "value", nil } -func (r *recordingPrompter) Password(pr string) string { +func (r *recordingPrompter) Password(pr string) (string, error) { r.calls = append(r.calls, "Password") r.lastPrompt = pr - return "secret" + return "secret", nil } func (r *recordingPrompter) Display(pr string) { @@ -73,19 +73,29 @@ func useRecordingPrompter(t *testing.T) *recordingPrompter { func TestPackageFunctionsDelegateToActivePrompter(t *testing.T) { rec := useRecordingPrompter(t) - assert.Equal(t, "123456", RequestSecurityCode("000000")) + code, err := RequestSecurityCode("000000") + require.NoError(t, err) + assert.Equal(t, "123456", code) assert.Equal(t, "000000", rec.lastPrompt) - assert.Equal(t, 1, Choose("Pick", []string{"a", "b"})) + index, err := Choose("Pick", []string{"a", "b"}) + require.NoError(t, err) + assert.Equal(t, 1, index) assert.Equal(t, []string{"a", "b"}, rec.lastOptions) - assert.Equal(t, "required", StringRequired("Username")) + required, err := StringRequired("Username") + require.NoError(t, err) + assert.Equal(t, "required", required) assert.Equal(t, "Username", rec.lastPrompt) - assert.Equal(t, "value", String("Region", "us-east-1")) + value, err := String("Region", "us-east-1") + require.NoError(t, err) + assert.Equal(t, "value", value) assert.Equal(t, "us-east-1", rec.lastDefault) - assert.Equal(t, "secret", Password("Password")) + secret, err := Password("Password") + require.NoError(t, err) + assert.Equal(t, "secret", secret) assert.Equal(t, "Password", rec.lastPrompt) Display("hello") @@ -181,17 +191,20 @@ func TestPinentryPrompterEndToEnd(t *testing.T) { require.NoError(t, err) tests := []struct { - mode string - want string + mode string + want string + wantErr bool }{ {mode: "ok", want: "424242"}, - {mode: "cancel", want: ""}, + {mode: "cancel", want: "", wantErr: true}, } for _, tt := range tests { t.Run(tt.mode, func(t *testing.T) { t.Setenv(fakePinentryEnv, tt.mode) - assert.Equal(t, tt.want, NewPinentryPrompter(exe).RequestSecurityCode("000000")) + got, err := NewPinentryPrompter(exe).RequestSecurityCode("000000") + assert.Equal(t, tt.wantErr, err != nil) + assert.Equal(t, tt.want, got) }) } } diff --git a/pkg/auth/providers/aws/saml2aws/prompter/survey.go b/pkg/auth/providers/aws/saml2aws/prompter/survey.go index 719a98c31cf..77838502c1d 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/survey.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey.go @@ -31,13 +31,15 @@ func NewCli() *CliPrompter { } // RequestSecurityCode request a security code to be entered by the user -func (cli *CliPrompter) RequestSecurityCode(pattern string) string { +func (cli *CliPrompter) RequestSecurityCode(pattern string) (string, error) { token := "" prompt := &survey.Input{ Message: fmt.Sprintf("Security Token [%s]", pattern), } - _ = survey.AskOne(prompt, &token, survey.WithValidator(survey.Required), stdioOption()) - return token + 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 @@ -48,7 +50,10 @@ func (cli *CliPrompter) ChooseWithDefault(pr string, defaultValue string, option Options: options, Default: defaultValue, } - _ = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()) + // 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 { @@ -60,52 +65,61 @@ func (cli *CliPrompter) ChooseWithDefault(pr string, defaultValue string, option } // Choose given the choice return the option selected -func (cli *CliPrompter) Choose(pr string, options []string) int { +func (cli *CliPrompter) Choose(pr string, options []string) (int, error) { selected := "" prompt := &survey.Select{ Message: pr, Options: options, } - _ = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stdioOption()) + // 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 + return i, nil } } - return 0 + return 0, errors.New("bad input") } // String prompt for string with a default -func (cli *CliPrompter) String(pr string, defaultValue string) string { +func (cli *CliPrompter) String(pr string, defaultValue string) (string, error) { val := "" prompt := &survey.Input{ Message: pr, Default: defaultValue, } - _ = survey.AskOne(prompt, &val, stdioOption()) - return val + 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 { +func (cli *CliPrompter) StringRequired(pr string) (string, error) { val := "" prompt := &survey.Input{ Message: pr, } - _ = survey.AskOne(prompt, &val, survey.WithValidator(survey.Required), stdioOption()) - return val + 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 { +func (cli *CliPrompter) Password(pr string) (string, error) { val := "" prompt := &survey.Password{ Message: pr, } - _ = survey.AskOne(prompt, &val, stdioOption()) - return val + if err := survey.AskOne(prompt, &val, stdioOption()); err != nil { + return "", err + } + return val, nil } func (cli *CliPrompter) Display(pr string) { diff --git a/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go b/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go index 1a928ab455d..628ba731024 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/survey_test.go @@ -38,11 +38,26 @@ func TestCliPrompterWithoutTerminal(t *testing.T) { useNonInteractiveStdio(t) cli := NewCli() - assert.Empty(t, cli.RequestSecurityCode("000000")) - assert.Empty(t, cli.String("Region", "us-east-1")) - assert.Empty(t, cli.StringRequired("Username")) - assert.Empty(t, cli.Password("Password")) - assert.Equal(t, 0, cli.Choose("Pick", []string{"a", "b"})) + // 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) diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go index 05f2c7c767d..1c80314f608 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go @@ -119,9 +119,11 @@ func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) if authSubmitURL == "" { return samlAssertion, fmt.Errorf("unable to locate IDP authentication form submit URL") - } else if strings.HasPrefix(authSubmitURL, "/") { + } else { // - // The server returned a relative URL. Make it absolute. + // 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 { @@ -153,7 +155,10 @@ func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) mfaPromptAttempts++ otpForm := url.Values{} if mfaToken == "" { - mfaToken = prompter.RequestSecurityCode("000000") + 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) { diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go index 0dd9b5aeea1..ec54070d1b8 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs_test.go @@ -218,6 +218,26 @@ func TestAuthenticateSuccessRelativeAction(t *testing.T) { 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) diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go index efff8b544cd..87e5093b98f 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go @@ -251,16 +251,43 @@ type storageStateSaver interface { } // saveStorageState writes the browser storage state (IdP session cookies) to statePath. -// Atmos fork: Playwright creates the file with 0644 permissions, so the directory is created -// with 0700 and the file is tightened to 0600 after saving. +// 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 { - if err := os.MkdirAll(filepath.Dir(statePath), storageStateDirPerm); err != nil { + dir := filepath.Dir(statePath) + if err := os.MkdirAll(dir, storageStateDirPerm); err != nil { return err } - if _, err := saver.StorageState(playwright.BrowserContextStorageStateOptions{Path: playwright.String(statePath)}); err != nil { + // MkdirAll does not tighten an existing directory. + if err := os.Chmod(dir, storageStateDirPerm); err != nil { return err } - return os.Chmod(statePath, storageStateFilePerm) + + 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. @@ -286,12 +313,22 @@ var getSAMLResponse = func(page samlPage, loginDetails *creds.LoginDetails, clie 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() - mu.Lock() - data, dataErr = postData, postErr - mu.Unlock() + record(postData, postErr) } }) if _, err := page.Goto(loginDetails.URL); err != nil { @@ -333,9 +370,7 @@ var getSAMLResponse = func(page samlPage, loginDetails *creds.LoginDetails, clie return "", ErrNoSAMLResponse default: postData, postErr := r.PostData() - mu.Lock() - data, dataErr = postData, postErr - mu.Unlock() + record(postData, postErr) } } @@ -359,6 +394,12 @@ var getSAMLResponse = func(page samlPage, loginDetails *creds.LoginDetails, clie 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{ diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go index e39a646c9c8..bf05a853965 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser_test.go @@ -331,6 +331,32 @@ func TestGetSAMLResponseUsesCallbackCaptureWhenExpectRequestMissesIt(t *testing. 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) { 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 index ab46b2260f5..95a44d3d1be 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/storage_state_test.go @@ -70,3 +70,56 @@ func TestSaveStorageStateReturnsMkdirError(t *testing.T) { 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/googleapps.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go index b680ed315c4..853345df0a8 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -34,6 +34,12 @@ 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 @@ -68,6 +74,10 @@ 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 @@ -86,6 +96,8 @@ func New(idpAccount *cfg.IDPAccount) (*Client, error) { // 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 { @@ -98,25 +110,25 @@ func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) authForm.Set("Email", loginDetails.Username) // Post email address w/o password, then Get the password-input page - passwordURL, passwordForm, err := kc.loadLoginPage(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", authForm) + 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(authURL+"?hl=en&loc=US", loginDetails.URL+"&hl=en&loc=US", authForm) + 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", passwordURL) + logger.Debugf("loginURL: %s", provider.RedactRawURL(passwordURL)) passwordForm.Set("Passwd", loginDetails.Password) passwordForm.Set("TrustDevice", "on") referingURL := passwordURL - responseDoc, err := kc.loadChallengePage(passwordURL+"?hl=en&loc=US", referingURL, passwordForm, loginDetails) + responseDoc, err := kc.loadChallengePage(withLocale(passwordURL), referingURL, passwordForm, loginDetails) if err != nil { return "", errors.Wrap(err, "error loading challenge page") } @@ -162,7 +174,7 @@ func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) return "", errors.Wrap(err, "error extracting captcha") } - logger.Debugf("captchaURL: %s", captchaURL) + logger.Debugf("captchaURL: %s", provider.RedactRawURL(captchaURL)) _, captchaV1 := captchaForm["Passwd"] if captchaV1 { @@ -170,7 +182,7 @@ func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) } captchaForm.Set(captchaInputId, captcha) - responseDoc, err = kc.loadChallengePage(captchaURL+"?hl=en&loc=US", captchaURL, captchaForm, loginDetails) + responseDoc, err = kc.loadChallengePage(withLocale(captchaURL), captchaURL, captchaForm, loginDetails) if err != nil { return "", errors.Wrap(err, "error loading challenge page") } @@ -191,7 +203,7 @@ func (kc *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) loginForm.Set("Passwd", loginDetails.Password) - responseDoc, err = kc.loadChallengePage(loginURL+"?hl=en&loc=US", loginURL, loginForm, loginDetails) + responseDoc, err = kc.loadChallengePage(withLocale(loginURL), loginURL, loginForm, loginDetails) if err != nil { return "", errors.Wrap(err, "error loading challenge page") } @@ -230,7 +242,7 @@ func (kc *Client) tryDisplayCaptcha(captchaPictureURL string) (string, error) { // Use iTerm to show the image if available return kc.iTermCaptchaPrompt(captchaPictureURL) } else { - return simpleCaptchaPrompt(captchaPictureURL), nil + return simpleCaptchaPrompt(captchaPictureURL) } } @@ -254,16 +266,42 @@ func (kc *Client) iTermCaptchaPrompt(captchaPictureURL string) (string, error) { } else { fmt.Fprintf(os.Stderr, "\033]1337;File=width=40;preserveAspectRatio=1;inline=1;:%s\a\n", buf.String()) } - return prompter.String("Captcha", ""), nil + return prompter.String("Captcha", "") } -func simpleCaptchaPrompt(captchaPictureURL string) string { +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 := loginDetails.URL + "&hl=en&loc=US" + firstPageURL := withLocale(loginDetails.URL) req, err := http.NewRequest("GET", firstPageURL, nil) if err != nil { @@ -377,14 +415,17 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u return nil, errors.Wrap(err, "unable to extract challenge form") } - logger.Debugf("secondActionURL: %s", secondActionURL) + logger.Debugf("secondActionURL: %s", provider.RedactRawURL(secondActionURL)) switch { case strings.Contains(secondActionURL, "challenge/totp"): // handle TOTP challenge token := loginDetails.MFAToken if token == "" { - token = prompter.RequestSecurityCode("000000") + 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) @@ -410,10 +451,13 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u return nil, errors.Wrap(err, "unable to extract challenge form") } - logger.Debugf("After sms request secondActionURL: %s", secondActionURL) + logger.Debugf("After sms request secondActionURL: %s", provider.RedactRawURL(secondActionURL)) } - token := prompter.StringRequired("Enter SMS token: G-") + token, err := prompter.StringRequired("Enter SMS token: G-") + if err != nil { + return nil, errors.Wrap(err, "failed to read the SMS token") + } responseForm.Set("Pin", token) responseForm.Set("TrustDevice", "on") // Don't ask again on this computer @@ -424,7 +468,10 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u // "challenge/sk" first, which also matches skotp URLs and made this case unreachable. case strings.Contains(secondActionURL, "challenge/skotp"): // handle one-time HOTP challenge log.Println("Get a one-time code by visiting https://g.co/sc on another device where you can use your security key") - token := prompter.RequestSecurityCode("000 000") + token, err := prompter.RequestSecurityCode("000 000") + if err != nil { + return nil, errors.Wrap(err, "failed to read the one-time code") + } responseForm.Set("Pin", token) responseForm.Set("TrustDevice", "on") // Don't ask again on this computer @@ -469,10 +516,12 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u log.Println("Open the Google App, and tap 'Yes' on the prompt to sign in") - _, err := kc.postJSON(fmt.Sprintf("https://content.googleapis.com/cryptauth/v1/authzen/awaittx?alt=json&key=%s", dataAttrs["data-api-key"]), waitValues, submitURL) + waitRes, err := kc.postJSON(fmt.Sprintf("https://content.googleapis.com/cryptauth/v1/authzen/awaittx?alt=json&key=%s", dataAttrs["data-api-key"]), waitValues, submitURL) if err != nil { return nil, errors.Wrap(err, "unable to extract post wait tx form") } + // Atmos fork: the response body was never closed, which prevents connection reuse. + _ = waitRes.Body.Close() // responseForm.Set("Pin", token) responseForm.Set("TrustDevice", "on") // Don't ask again on this computer @@ -549,6 +598,13 @@ func (kc *Client) loadAlternateChallengePage(submitURL string, referer string, a } func (kc *Client) loadChallengeEntryPage(doc *goquery.Document, submitURL string, loginDetails *creds.LoginDetails) (*goquery.Document, error) { + // Atmos fork: every challenge cycle (including the skip and alternate-factor paths) passes through here, + // so one budget bounds the recursion that upstream left unlimited. + kc.mfaTransitions++ + if kc.mfaTransitions > maxMFATransitions { + return nil, errMFATransitionsExceeded + } + var challengeEntry string doc.Find("form[data-challengeentry]").EachWithBreak(func(i int, s *goquery.Selection) bool { @@ -624,6 +680,14 @@ func (kc *Client) loadResponsePage(submitURL string, referer string, responseFor return nil, errors.Wrap(err, "error parsing login page html document") } + // Atmos fork: NewDocumentFromReader leaves doc.Url nil, and later steps (for example a captcha + // in the MFA response) dereference it. Use the final request URL, falling back to the submit URL. + if res.Request != nil && res.Request.URL != nil { + doc.Url = res.Request.URL + } else if doc.Url, err = url.Parse(submitURL); err != nil { + return nil, errors.Wrap(err, "failed to define URL for html doc") + } + return doc, nil } @@ -730,12 +794,18 @@ func extractInputsByFormQuery(doc *goquery.Document, formQuery string) (url.Valu return formData, actionURL, nil } +// normalizeSpace trims s and collapses every run of whitespace into a single space. +func normalizeSpace(s string) string { + return strings.Join(strings.Fields(s), " ") +} + func extractNodeText(doc *goquery.Document, tag, txt string) string { var res string doc.Find(tag).Each(func(i int, s *goquery.Selection) { - if s.Text() == txt { - res = s.Text() + // Atmos fork: compare with whitespace normalized, because headings are often wrapped in newlines and indentation. + if normalizeSpace(s.Text()) == normalizeSpace(txt) { + res = normalizeSpace(s.Text()) } }) @@ -765,6 +835,10 @@ func extractKeyHandles(doc *goquery.Document, challengeTxt string) (string, []st if ok { firstIdx := strings.Index(val, "{") lastIdx := strings.LastIndex(val, "}") + // Atmos fork: upstream sliced with unchecked indexes and panicked on values without a JSON object, such as "[]". + if firstIdx < 0 || lastIdx < firstIdx { + return + } obj := []byte(val[firstIdx : lastIdx+1]) _ = json.Unmarshal(obj, &result) // ignore the error and continue // Key handles diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_robustness_test.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_robustness_test.go index c977ec309b8..8228548dc17 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_robustness_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_robustness_test.go @@ -2,6 +2,7 @@ package googleapps import ( "fmt" + "net/url" "testing" u2fhost "github.com/marshallbrekka/go-u2fhost" @@ -9,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/mocks" ) @@ -131,3 +133,68 @@ func TestB64Safe(t *testing.T) { _, err = b64Safe("not base64!") require.Error(t, err) } + +// Regression: the locale parameters are added to the query instead of being appended to the value of +// the last existing parameter. +func TestWithLocale(t *testing.T) { + tests := []struct{ in, want string }{ + {"https://idp.example.com/pw", "https://idp.example.com/pw?hl=en&loc=US"}, + {"https://idp.example.com/pw?a=1&b=2", "https://idp.example.com/pw?a=1&b=2&hl=en&loc=US"}, + {"https://idp.example.com/pw?TL=abc%2Bdef", "https://idp.example.com/pw?TL=abc%2Bdef&hl=en&loc=US"}, + {"https://idp.example.com/pw?hl=fr&a=1&loc=CA", "https://idp.example.com/pw?a=1&hl=en&loc=US"}, + {"https://idp.example.com/pw?a=1#frag", "https://idp.example.com/pw?a=1&hl=en&loc=US#frag"}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, withLocale(tt.in), tt.in) + } +} + +// Regression: a challenge selection page that keeps returning the same selection page must end with an +// error instead of recursing forever. +func TestLoadChallengeEntryPageTransitionsAreBounded(t *testing.T) { + chooser := `

To sign in to your Google Account, choose a task from the list below.

` + + `
` + + `` + f := newFakeGoogle(t, map[string]pageHandler{ + "/start": static(chooser), + "/signin/challenge/totp/2": static(chooser), + }) + kc := &Client{client: mustHTTPClient(t)} + + _, err := kc.loadChallengePage(f.ts.URL+"/start", f.ts.URL, url.Values{}, &creds.LoginDetails{}) + require.ErrorIs(t, err, errMFATransitionsExceeded) + assert.Equal(t, maxMFATransitions, f.count("/signin/challenge/totp/2")) +} + +// Regression: the MFA response document needs a URL, or a captcha on it panics in extractInputsByFormQuery. +func TestLoadResponsePageSetsDocumentURL(t *testing.T) { + f := newFakeGoogle(t, map[string]pageHandler{"/resp": static(`
`)}) + kc := &Client{client: mustHTTPClient(t)} + + doc, err := kc.loadResponsePage(f.ts.URL+"/resp", f.ts.URL, url.Values{}) + require.NoError(t, err) + require.NotNil(t, doc.Url) + assert.Equal(t, f.ts.URL+"/resp", doc.Url.String()) + + _, actionURL, err := extractInputsByFormQuery(doc, "#f") + require.NoError(t, err) + assert.Equal(t, f.ts.URL+"/next", actionURL) +} + +// Regression: headings wrapped in whitespace (as in challenge-sms.html) still match. +func TestExtractNodeTextNormalizesWhitespace(t *testing.T) { + doc := mustDoc(t, "

\n Send text\n message\n

Inline

", "https://accounts.google.com/") + assert.Equal(t, "Send text message", extractNodeText(doc, "h2", "Send text message")) + assert.Equal(t, "Inline", extractNodeText(doc, "h1", "Inline")) + assert.Empty(t, extractNodeText(doc, "h2", "Other")) +} + +// Regression: a data-challenge-ui value without a JSON object must not panic. +func TestExtractKeyHandlesMalformedChallengeUI(t *testing.T) { + for _, value := range []string{"[]", "", "}{", "no braces"} { + doc := mustDoc(t, `
`, "https://accounts.google.com/") + appID, handles := extractKeyHandles(doc, testChallenge) + assert.Empty(t, appID, value) + assert.Empty(t, handles, value) + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/http.go b/pkg/auth/providers/aws/saml2aws/provider/http.go index e5e3f5af265..746577c1a8b 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http.go @@ -3,7 +3,6 @@ package provider import ( "crypto/tls" "fmt" - "log" "net" "net/http" "runtime" @@ -17,7 +16,6 @@ import ( "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cookiejar" - "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/dump" ) // HTTPClient saml2aws http client which extends the existing client @@ -30,6 +28,8 @@ type HTTPClient struct { const ( DefaultAttemptsCount = 1 DefaultRetryDelay = time.Duration(1) * time.Second + // MaxRetryDelay caps the configured delay between HTTP retries. + MaxRetryDelay = 5 * time.Minute ) type HTTPClientOptions struct { @@ -76,7 +76,10 @@ func BuildHttpClientOpts(account *cfg.IDPAccount) *HTTPClientOptions { opts.AttemptsCount = DefaultAttemptsCount } - delay, delayErr := strconv.ParseUint(account.HttpRetryDelay, 10, 0) + // Atmos fork: upstream parsed an unbounded integer and multiplied it into a time.Duration, + // which overflows for large values. Parse at most 32 bits (no overflow when multiplied by + // time.Second) and cap the delay at MaxRetryDelay. + delay, delayErr := strconv.ParseUint(account.HttpRetryDelay, 10, 32) if delayErr != nil { if account.HttpRetryDelay != "" { logrus.WithField("http_retry_delay", account.HttpRetryDelay). @@ -84,7 +87,7 @@ func BuildHttpClientOpts(account *cfg.IDPAccount) *HTTPClientOptions { } opts.RetryDelay = DefaultRetryDelay } else { - opts.RetryDelay = time.Duration(delay) * time.Second + opts.RetryDelay = min(time.Duration(delay)*time.Second, MaxRetryDelay) } return opts @@ -133,6 +136,9 @@ func (hc *HTTPClient) Do(req *http.Request) (*http.Response, error) { if hc.CheckResponseStatus != nil { err = hc.CheckResponseStatus(req, resp) if err != nil { + // Atmos fork: callers discard the response when the status check fails, so its body + // was never closed. The status line stays available on the returned response. + _ = resp.Body.Close() return resp, err } } @@ -144,8 +150,19 @@ func (hc *HTTPClient) Do(req *http.Request) (*http.Response, error) { func (hc *HTTPClient) doWithRetry(req *http.Request) (*http.Response, error) { var resp *http.Response + attempted := false err := retry.Do( func() error { + // Atmos fork: a failed attempt may have consumed the request body, so later attempts + // send a fresh copy. Upstream resent the consumed body. + if attempted && req.GetBody != nil { + body, bodyErr := req.GetBody() + if bodyErr != nil { + return retry.Unrecoverable(bodyErr) + } + req.Body = body + } + attempted = true hc.logHTTPRequest(req) clientResp, err := hc.Client.Do(req) if err != nil { @@ -157,6 +174,8 @@ func (hc *HTTPClient) doWithRetry(req *http.Request) (*http.Response, error) { // Atmos fork: options built without BuildHttpClientOpts are clamped too. retry.Attempts(atLeastOneAttempt(hc.Options.AttemptsCount)), retry.Delay(hc.Options.RetryDelay), + // Atmos fork: cancelling the request also stops the retry waits. + retry.Context(req.Context()), retry.OnRetry( func(n uint, err error) { logrus. @@ -200,24 +219,17 @@ func SuccessOrRedirectOrUnauthorizedResponseValidator(req *http.Request, resp *h return validatorResponse } +// Atmos fork: upstream's DUMP_CONTENT switch dumped full requests and responses, including +// password form bodies, session cookies and SAML assertions, to the terminal. It was removed, +// and request URLs are logged without their query string, which can carry session tokens. func (hc *HTTPClient) logHTTPRequest(req *http.Request) { - if dump.ContentEnable() { - log.Println(dump.RequestString(req)) - return - } - logrus.WithField("http", "client").WithFields(logrus.Fields{ - "URL": req.URL.String(), + "URL": RedactURL(req.URL), "method": req.Method, }).Debug("HTTP Req") } func (hc *HTTPClient) logHTTPResponse(resp *http.Response) { - if dump.ContentEnable() { - log.Println(dump.ResponseString(resp)) - return - } - logrus.WithField("http", "client").WithFields(logrus.Fields{ "Status": resp.Status, }).Debug("HTTP Res") diff --git a/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go b/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go index 8151384d42e..f09f5b7ac83 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go @@ -1,8 +1,12 @@ package provider import ( + "context" + "errors" + "io" "net/http" "net/http/httptest" + "strings" "sync/atomic" "testing" "time" @@ -68,3 +72,71 @@ func TestClientDo_NilOptions(t *testing.T) { require.NoError(t, err) _ = resp.Body.Close() } + +// bodyConsumingTransport reads the whole request body on every attempt, fails the first attempts, +// and then answers 200. +type bodyConsumingTransport struct { + failures int + bodies []string +} + +func (b *bodyConsumingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + data, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + b.bodies = append(b.bodies, string(data)) + if len(b.bodies) <= b.failures { + return nil, errors.New("transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Body: io.NopCloser(strings.NewReader("ok")), Request: req}, nil +} + +// Regression: a retried POST sends the original body again, not the body the failed attempt consumed. +func TestClientDoWithRetry_ResendsRequestBody(t *testing.T) { + tr := &bodyConsumingTransport{failures: 1} + hc, err := NewHTTPClient(tr, &HTTPClientOptions{IsWithRetries: true, AttemptsCount: 3, RetryDelay: time.Millisecond}) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodPost, "https://idp.example.com/login", strings.NewReader("user=alice&pass=s3cret")) + require.NoError(t, err) + resp, err := hc.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + + assert.Equal(t, []string{"user=alice&pass=s3cret", "user=alice&pass=s3cret"}, tr.bodies) +} + +// Bodyless requests stay retryable. +func TestClientDoWithRetry_BodylessRequestStillRetried(t *testing.T) { + tr := &flakyTransport{failures: 1, next: http.DefaultTransport} + ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer ts.Close() + hc, err := NewHTTPClient(tr, &HTTPClientOptions{IsWithRetries: true, AttemptsCount: 2, RetryDelay: time.Millisecond}) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, ts.URL, nil) + require.NoError(t, err) + resp, err := hc.Do(req) + require.NoError(t, err) + _ = resp.Body.Close() + assert.Equal(t, int32(2), tr.calls.Load()) +} + +// Regression: cancelling the request context stops the retry backoff instead of waiting it out. +func TestClientDoWithRetry_StopsOnCancelledContext(t *testing.T) { + tr := &flakyTransport{failures: 10, next: http.DefaultTransport} + hc, err := NewHTTPClient(tr, &HTTPClientOptions{IsWithRetries: true, AttemptsCount: 5, RetryDelay: time.Minute}) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://idp.example.com/", nil) + require.NoError(t, err) + + start := time.Now() + _, err = hc.Do(req) + require.Error(t, err) + assert.Less(t, time.Since(start), 10*time.Second) + assert.Equal(t, int32(1), tr.calls.Load()) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/http_test.go b/pkg/auth/providers/aws/saml2aws/provider/http_test.go index 38c078185ba..4a68b817910 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -82,6 +83,11 @@ func TestClientDoResponseCheck(t *testing.T) { res, err := hc.Do(req) require.Error(t, err) require.Equal(t, 400, res.StatusCode) + + // Regression: the rejected response's body is closed, since callers discard the response on error. + _, readErr := res.Body.Read(make([]byte, 1)) + require.Error(t, readErr) + assert.NotErrorIs(t, readErr, io.EOF) } var errTransport = errors.New("transport failure") @@ -139,6 +145,9 @@ func TestBuildHttpClientOpts(t *testing.T) { {name: "explicit values", attempts: "3", delay: "5", wantRetries: true, wantCount: 3, wantDelay: 5 * time.Second}, {name: "invalid values fall back", attempts: "many", delay: "soon", wantRetries: false, wantCount: DefaultAttemptsCount, wantDelay: DefaultRetryDelay}, {name: "negative values fall back", attempts: "-1", delay: "-2", wantRetries: false, wantCount: DefaultAttemptsCount, wantDelay: DefaultRetryDelay}, + // Regression (code-scanning: incorrect integer conversion): a huge delay overflowed time.Duration. + {name: "delay is capped", attempts: "2", delay: "4000000000", wantRetries: true, wantCount: 2, wantDelay: MaxRetryDelay}, + {name: "delay beyond 32 bits falls back", attempts: "2", delay: "18446744073709551615", wantRetries: true, wantCount: 2, wantDelay: DefaultRetryDelay}, } for _, tt := range tests { @@ -305,47 +314,81 @@ func TestResponseValidators(t *testing.T) { } } -func TestClientDoDumpsContent(t *testing.T) { +// Regression: upstream's DUMP_CONTENT switch printed full requests and responses (password form +// bodies, session cookies, SAML assertions), and the debug log printed full URLs, whose query +// strings can carry session tokens. Neither may reach the logs. +func TestClientDoDoesNotLogSecrets(t *testing.T) { + const ( + secretBody = "Passwd=hunter2" + secretQuery = "sessionToken=secret-session-token" + secretReply = "SAMLResponse=secret-assertion" + ) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = w.Write([]byte("response-body")) + _, _ = w.Write([]byte(secretReply)) })) defer ts.Close() - tests := []struct { - name string - dump string - wantDump bool - }{ - {name: "enabled", dump: "true", wantDump: true}, - {name: "disabled", dump: "false", wantDump: false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Setenv("DUMP_CONTENT", tt.dump) - logs := captureLog(t) + for _, dumpContent := range []string{"true", ""} { + t.Run("DUMP_CONTENT="+dumpContent, func(t *testing.T) { + t.Setenv("DUMP_CONTENT", dumpContent) + stdLog := captureLog(t) + logrusLog := captureLogrus(t) hc, err := NewHTTPClient(http.DefaultTransport, &HTTPClientOptions{}) require.NoError(t, err) - req, err := http.NewRequest(http.MethodPost, ts.URL+"/submit", strings.NewReader("request-body")) + req, err := http.NewRequest(http.MethodPost, ts.URL+"/submit?"+secretQuery, strings.NewReader(secretBody)) require.NoError(t, err) res, err := hc.Do(req) require.NoError(t, err) defer res.Body.Close() - // The response body must remain readable after it has been dumped. + // The response body is untouched for the caller. body, err := io.ReadAll(res.Body) require.NoError(t, err) - assert.Equal(t, "response-body", string(body)) + assert.Equal(t, secretReply, string(body)) - if tt.wantDump { - assert.Contains(t, logs.String(), "POST /submit HTTP/1.1") - assert.Contains(t, logs.String(), "request-body") - assert.Contains(t, logs.String(), "response-body") - } else { - assert.Empty(t, logs.String()) + logs := stdLog.String() + logrusLog.String() + assert.Contains(t, logs, "/submit", "the request is still logged at debug level") + for _, secret := range []string{"hunter2", "secret-session-token", "secret-assertion"} { + assert.NotContains(t, logs, secret) } }) } } + +// captureLogrus captures the global logrus output at debug level for the test. +func captureLogrus(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + origOut, origLevel := logrus.StandardLogger().Out, logrus.GetLevel() + logrus.SetOutput(&buf) + logrus.SetLevel(logrus.DebugLevel) + t.Cleanup(func() { + logrus.SetOutput(origOut) + logrus.SetLevel(origLevel) + }) + return &buf +} + +func TestRedactURL(t *testing.T) { + tests := []struct { + raw string + want string + }{ + {raw: "https://idp.example.com/login", want: "https://idp.example.com/login"}, + {raw: "https://idp.example.com/login/sessionCookieRedirect?token=secret&redirectUrl=x", want: "https://idp.example.com/login/sessionCookieRedirect"}, + {raw: "https://user:pass@idp.example.com/path#otp=123456", want: "https://idp.example.com/path"}, + {raw: "/relative/path?code=1", want: "/relative/path"}, + {raw: "", want: ""}, + {raw: "http://[::1:bad", want: "[unparseable URL]"}, + } + + for _, tt := range tests { + t.Run(tt.raw, func(t *testing.T) { + assert.Equal(t, tt.want, RedactRawURL(tt.raw)) + }) + } + + assert.Empty(t, RedactURL(nil)) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go index 12cc0127ef6..b0baf42dc32 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go @@ -49,6 +49,9 @@ const ( var logger = logrus.WithField("provider", "okta") +// errMFAPollTimeout is returned when an MFA push is still pending after mfaPollTimeout. +var errMFAPollTimeout = errors.New("timed out waiting for the MFA push to be approved") + // Atmos fork: the polling/settle delays and the U2F device finder factory are package // variables (instead of inline literals) so tests can shorten the delays and inject a // mock device without real sleeps or attached hardware. Production values are unchanged. @@ -57,6 +60,11 @@ var ( pushPollInterval = 3 * time.Second // duoPollInterval is the delay between Duo push status checks. duoPollInterval = 3 * time.Second + // mfaPollTimeout bounds how long the Okta Verify push and Duo push polling loops wait for a terminal answer. + // Atmos fork: upstream polled without a limit when the IdP kept answering with a non-terminal result. + mfaPollTimeout = 5 * time.Minute + // endpointHealthTimeout bounds the Duo endpoint health requests. + endpointHealthTimeout = 60 * time.Second // endpointHealthSettleDelay is the delay before re-submitting the Duo auth form after an endpoint health report. endpointHealthSettleDelay = 2 * time.Second // newU2FDeviceFinder returns the DeviceFinder used for Duo U2F and Okta FIDO challenges. @@ -163,7 +171,9 @@ type ctxKey string func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken string) (string, string, error) { logger.Debug("create session func called") if loginDetails == nil || sessionToken == "" { - logger.Debugf("unable to create an Okta session, nil input | loginDetails: %v | sessionToken: %s", loginDetails, sessionToken) + // Atmos fork: upstream logged loginDetails with %v, which includes the password, and the + // session token. Log only whether each input is present. + logger.Debugf("unable to create an Okta session, nil input | loginDetails set: %t | sessionToken set: %t", loginDetails != nil, sessionToken != "") return "", "", fmt.Errorf("unable to create an okta session, nil input") } @@ -386,7 +396,7 @@ func (oc *Client) setDeviceTokenCookie(loginDetails *creds.LoginDetails) error { // uncommented (avoid linting issues) if false { dt, _ := oc.getDeviceTokenFromOkta(loginDetails) - logger.Debugf("getDeviceTokenFromOkta is not yet implemented: dt: %s", dt) + logger.Debugf("getDeviceTokenFromOkta is not yet implemented: device token set: %t", dt != "") } oktaURL, err := url.Parse(loginDetails.URL) @@ -562,7 +572,9 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c if err != nil { return "", errors.Wrap(err, "failed to decode saml-response") } - logger.WithField("type", "saml-response").WithField("saml-response", string(decodedSamlResponse)).Debug("doc detect") + // Atmos fork: upstream logged the full decoded SAML response. The assertion is a bearer + // credential (it can be exchanged for AWS credentials until it expires), so only its size is logged. + logger.WithField("type", "saml-response").WithField("saml-response-bytes", len(decodedSamlResponse)).Debug("doc detect") return samlResponse, nil } } else if docIsFormSamlRequest(doc) { @@ -737,7 +749,10 @@ func getMfaChallengeContext(oc *Client, mfaOption int, resp string) (*mfaChallen // yay switch mfa := mfaIdentifer; mfa { case IdentifierYubiMfa: - verifyCode := prompter.Password("Press the button on your yubikey") + verifyCode, promptErr := prompter.Password("Press the button on your yubikey") + if promptErr != nil { + return nil, errors.Wrap(promptErr, "error reading the yubikey code") + } verifyReq.PassCode = verifyCode } @@ -804,7 +819,10 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } // If multiple MFA of the same type are found, we prompt the user to pick which one to use if len(mfaOptionsMatches) > 1 { - matchOptionIndex := prompter.Choose(fmt.Sprintf("Multiple %s MFA options found. Select which MFA option to use", oc.mfa), mfaOptionsMatches) + matchOptionIndex, promptErr := prompter.Choose(fmt.Sprintf("Multiple %s MFA options found. Select which MFA option to use", oc.mfa), mfaOptionsMatches) + if promptErr != nil { + return "", errors.Wrap(promptErr, "error selecting the MFA option") + } for i := range mfaOptions { if mfaOptions[i] == mfaOptionsMatches[matchOptionIndex] { mfaOption = i @@ -814,7 +832,10 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, mfaOption = findMfaOption(oc.mfa, mfaOptions, 0) } } else if len(mfaOptions) > 1 { - mfaOption = prompter.Choose("Select which MFA option to use", mfaOptions) + var promptErr error + if mfaOption, promptErr = prompter.Choose("Select which MFA option to use", mfaOptions); promptErr != nil { + return "", errors.Wrap(promptErr, "error selecting the MFA option") + } } challengeContext, err := getMfaChallengeContext(oc, mfaOption, resp) @@ -828,7 +849,10 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, case IdentifierSmsMfa, IdentifierEmailMfa, IdentifierTotpMfa, IdentifierOktaTotpMfa, IdentifierSymantecTotpMfa: verifyCode := loginDetails.MFAToken if verifyCode == "" { - verifyCode = prompter.RequestSecurityCode("000000") + var promptErr error + if verifyCode, promptErr = prompter.RequestSecurityCode("000000"); promptErr != nil { + return "", errors.Wrap(promptErr, "error reading the MFA code") + } } tokenReq := VerifyRequest{StateToken: stateToken, PassCode: verifyCode, RememberDevice: strconv.FormatBool(oc.rememberDevice)} tokenBody := new(bytes.Buffer) @@ -858,6 +882,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, // loop until success, error, or timeout body := challengeContext.challengeResponseBody + pushDeadline := time.Now().Add(mfaPollTimeout) for { // on 'success' status if gjson.Get(body, "status").String() == "SUCCESS" { @@ -870,6 +895,9 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, switch gjson.Get(body, "factorResult").String() { case "WAITING": + if time.Now().After(pushDeadline) { + return "", errMFAPollTimeout + } time.Sleep(pushPollInterval) logger.Debug("Waiting for user to authorize login") updatedContext, err := getMfaChallengeContext(oc, mfaOption, resp) @@ -1005,7 +1033,10 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } } } else { - duoMfaOption = prompter.Choose("Select a DUO MFA Option", duoMfaOptions) + var promptErr error + if duoMfaOption, promptErr = prompter.Choose("Select a DUO MFA Option", duoMfaOptions); promptErr != nil { + return "", errors.Wrap(promptErr, "error selecting the DUO MFA option") + } } if duoMfaOption == -1 { @@ -1014,7 +1045,10 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if duoMfaOptions[duoMfaOption] == "Passcode" { // get users DUO MFA Token - token = prompter.StringRequired("Enter passcode") + var promptErr error + if token, promptErr = prompter.StringRequired("Enter passcode"); promptErr != nil { + return "", errors.Wrap(promptErr, "error reading the DUO passcode") + } } // send mfa auth request @@ -1196,7 +1230,11 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if duoTxResult != "SUCCESS" { // poll as this is likely a push request + duoDeadline := time.Now().Add(mfaPollTimeout) for { + if time.Now().After(duoDeadline) { + return "", errMFAPollTimeout + } time.Sleep(duoPollInterval) req, err = http.NewRequest("POST", duoSubmitURL, strings.NewReader(duoForm.Encode())) @@ -1286,10 +1324,13 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = oc.client.Do(req) // TODO: check result + // Atmos fork: the callback response was never closed, which prevents connection reuse. + callbackRes, err := oc.client.Do(req) // TODO: check result if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + _, _ = io.Copy(io.Discard, callbackRes.Body) + _ = callbackRes.Body.Close() // extract okta session token @@ -1386,7 +1427,13 @@ func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallenge // Atmos fork: search from the option after the one that just failed. Upstream passed // lastMfaOption, and findMfaOption is inclusive of its start index, so it always returned // the failed option again and the "try the next FIDO device" fallback never ran. - nextMfaOption := findMfaOption(oc.mfa, mfaOptions, lastMfaOption+1) + // Atmos fork: with the "Auto" setting no option label starts with "AUTO", so the search + // never found a later FIDO option. Search for the FIDO label itself in that case. + fidoPrefix := oc.mfa + if strings.EqualFold(oc.mfa, "AUTO") { + fidoPrefix = strings.ToUpper(supportedMfaOptions[IdentifierFIDOWebAuthn]) + } + nextMfaOption := findMfaOption(fidoPrefix, mfaOptions, lastMfaOption+1) if nextMfaOption <= lastMfaOption { return "", errors.Wrap(err, "tried all MFA options") } @@ -1572,10 +1619,11 @@ func verifyEndpointHealth(oc *Client, doc *goquery.Document, origURL string, duo req.Header.Add("Referer", "https://"+duoHost+"/") req.Header.Add("Origin", "https://"+duoHost) - _, err := oc.client.Do(req) + aliveRes, err := oc.client.Do(req) if err != nil { return nil, errors.Wrapf(err, "failed to query alive URL %s", duoAliveUrl) } + _ = aliveRes.Body.Close() duoCheckEndpointAppURL := fmt.Sprintf("https://%s/frame/check_endpoint_app_status", duoHost) req, _ = http.NewRequest("GET", duoCheckEndpointAppURL, nil) @@ -1590,6 +1638,12 @@ func verifyEndpointHealth(oc *Client, doc *goquery.Document, origURL string, duo req.Header.Add("Referer", origURL) req.Header.Add("X-Requested-With", "XMLHttpRequest") + // Atmos fork: the status request blocks until the report is queried, so it gets a cancellable, bounded + // context. If the report fails, the status request is cancelled instead of blocking forever. + ctx, cancel := context.WithTimeout(context.Background(), endpointHealthTimeout) + defer cancel() + req = req.WithContext(ctx) + var wg sync.WaitGroup wg.Add(1) @@ -1618,10 +1672,15 @@ func verifyEndpointHealth(oc *Client, doc *goquery.Document, origURL string, duo req2.Header.Add("Referer", "https://"+duoHost+"/") req2.Header.Add("Origin", "https://"+duoHost) + req2 = req2.WithContext(ctx) + res, err := oc.client.Do(req2) - if err == nil { - defer res.Body.Close() + if err != nil { + cancel() + wg.Wait() + return nil, errors.Wrapf(err, "failed to query report URL %s", duoHealthURL) } + defer res.Body.Close() // Wait for check_endpoint_app_status to block wg.Wait() diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_flow_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_flow_test.go index 0c3c452115e..a4d057a76d9 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_flow_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_flow_test.go @@ -8,6 +8,7 @@ import ( "net/url" "sync" "testing" + "time" "github.com/marshallbrekka/go-u2fhost" "github.com/stretchr/testify/assert" @@ -389,3 +390,71 @@ func TestVerifyEndpointHealth_StatusCheckUnreachable(t *testing.T) { assert.Equal(t, 1, log.count("/alive")) assert.Equal(t, 1, log.count("/report")) } + +// withShortPollTimeout shortens the MFA polling budget for the duration of a test. +func withShortPollTimeout(t *testing.T) { + t.Helper() + + orig := mfaPollTimeout + mfaPollTimeout = 20 * time.Millisecond + t.Cleanup(func() { mfaPollTimeout = orig }) +} + +// Regression: a Duo push that never reaches a terminal result stops with a timeout error. +func TestVerifyMfa_DuoPushPollIsBounded(t *testing.T) { + withShortPollTimeout(t) + s := &duoScenario{authPages: []string{duoAuthPage}, prompts: []string{duoPromptOK}, statuses: []string{duoPushed}} + + got, err := runDuo(t, s, "Duo Push") + require.ErrorIs(t, err, errMFAPollTimeout) + assert.Empty(t, got) + assert.Positive(t, s.log.count("/frame/status")) +} + +// Regression: when the health report fails, the blocked status request is cancelled and the report +// error is returned, instead of waiting for a status response that never arrives. +func TestVerifyEndpointHealth_ReportFailureCancelsStatusRequest(t *testing.T) { + withFastPolling(t) + + statusCancelled := make(chan struct{}) + duoServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // check_endpoint_app_status blocks until the client gives up. + <-r.Context().Done() + close(statusCancelled) + })) + defer duoServer.Close() + + endpoint := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/report" { + // Drop the connection so the report request fails with a transport error. + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + } + })) + defer endpoint.Close() + + oc, _ := offlineTestClient(t) + duoHost := duoServer.URL[len("https://"):] + endpointHost := endpoint.URL[len("https://"):] + + done := make(chan error, 1) + go func() { + _, err := verifyEndpointHealth(oc, mustDoc(t, fakeEndpointForm), "https://"+duoHost, endpointHost, duoHost, endpoint.URL+"/submit", url.Values{}) + done <- err + }() + + select { + case err := <-done: + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to query report URL") + case <-time.After(10 * time.Second): + t.Fatal("verifyEndpointHealth did not return after the report failed") + } + select { + case <-statusCancelled: + case <-time.After(10 * time.Second): + t.Fatal("the status request was not cancelled") + } +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_log_redaction_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_log_redaction_test.go new file mode 100644 index 00000000000..ef91672fe12 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_log_redaction_test.go @@ -0,0 +1,68 @@ +package okta + +import ( + "bytes" + "encoding/base64" + "fmt" + "net/http" + "testing" + + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" +) + +// captureDebugLogs captures the global logrus output at debug level for the test. +func captureDebugLogs(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + origOut, origLevel := logrus.StandardLogger().Out, logrus.GetLevel() + logrus.SetOutput(&buf) + logrus.SetLevel(logrus.DebugLevel) + t.Cleanup(func() { + logrus.SetOutput(origOut) + logrus.SetLevel(origLevel) + }) + return &buf +} + +// Regression (code-scanning: clear-text logging of sensitive information): with debug logging on, +// a full Okta login must not log the password, the session token carried in the redirect URL, +// or the SAML assertion, which can be exchanged for AWS credentials until it expires. +func TestAuthenticate_DebugLogsContainNoSecrets(t *testing.T) { + const assertionMarker = "secret-assertion-body" + saml := base64.StdEncoding.EncodeToString([]byte("" + assertionMarker + "")) + logs := captureDebugLogs(t) + + f := newFakeOkta(t) + f.authn = func(map[string]any) string { return `{"status":"SUCCESS","sessionToken":"secret-session-token"}` } + f.extra["/login/sessionCookieRedirect"] = func(w http.ResponseWriter, _ *http.Request) { + _, _ = fmt.Fprint(w, samlTargetPage(f.ts.URL, saml)) + } + + oc, loginDetails := f.client(true) + got, err := oc.Authenticate(loginDetails) + require.NoError(t, err) + require.Equal(t, saml, got) + + output := logs.String() + require.NotEmpty(t, output, "debug logging must be captured for this test to mean anything") + assert.NotContains(t, output, loginDetails.Password) + assert.NotContains(t, output, "secret-session-token") + assert.NotContains(t, output, assertionMarker) + assert.NotContains(t, output, saml) +} + +// Regression: createSession logged loginDetails with %v (including the password) when the +// session token was empty. +func TestCreateSession_EmptyTokenDoesNotLogPassword(t *testing.T) { + logs := captureDebugLogs(t) + + _, _, err := (&Client{}).createSession(&creds.LoginDetails{Username: "user@example.com", Password: "hunter2"}, "") + require.Error(t, err) + + assert.NotContains(t, logs.String(), "hunter2") + assert.Contains(t, logs.String(), "unable to create an Okta session") +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_mfa_flow_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_mfa_flow_test.go index 720f1e364f7..164f8148ede 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_mfa_flow_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_mfa_flow_test.go @@ -1,6 +1,7 @@ package okta import ( + "errors" "fmt" "net/http" "net/http/httptest" @@ -346,6 +347,44 @@ func TestVerifyMfa_FidoWebAuthn(t *testing.T) { device.AssertExpectations(t) }) + // Regression: with the default "Auto" setting the next FIDO device was never searched for. + t.Run("bad key handle falls through to the next FIDO device with Auto", func(t *testing.T) { + device := &mocks.U2FDevice{} + withMockDevice(t, device) + device.On("Close").Return() + device.On("Authenticate", mock.MatchedBy(func(r *u2fhost.AuthenticateRequest) bool { return r.KeyHandle == "cred-a" })). + Return(nil, &u2fhost.BadKeyHandleError{}).Once() + device.On("Authenticate", mock.MatchedBy(func(r *u2fhost.AuthenticateRequest) bool { return r.KeyHandle == "cred-b" })). + Return(&u2fhost.AuthenticateResponse{ClientData: "cd-b"}, nil).Once() + + pr := withMockPrompter(t) + pr.On("Choose", "Select which MFA option to use", mock.Anything).Return(0).Once() + + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/verify/a": + _, _ = fmt.Fprint(w, webauthnChallenge("https://"+r.Host+"/finish-a", "cred-a")) + case "/verify/b": + _, _ = fmt.Fprint(w, webauthnChallenge("https://"+r.Host+"/finish-b", "cred-b")) + case "/finish-b": + _, _ = fmt.Fprint(w, `{"sessionToken":"fido-b"}`) + default: + t.Errorf("unexpected request %s", r.URL.Path) + } + })) + defer ts.Close() + + oc, _ := offlineTestClient(t) + oc.mfa = "Auto" + resp := mfaRequiredResponse(t, "state-1", + testFactor{id: "a", provider: "FIDO", factorType: "webauthn", href: ts.URL + "/verify/a", authName: "Key A"}, + testFactor{id: "b", provider: "FIDO", factorType: "webauthn", href: ts.URL + "/verify/b", authName: "Key B"}, + ) + got, err := verifyMfa(oc, "okta.example.com", &creds.LoginDetails{}, resp) + require.NoError(t, err) + assert.Equal(t, "fido-b", got) + }) + t.Run("bad key handle on the only device fails", func(t *testing.T) { device := &mocks.U2FDevice{} withMockDevice(t, device) @@ -383,3 +422,56 @@ func TestVerifyMfa_FidoWebAuthn(t *testing.T) { assert.Contains(t, err.Error(), "failed to perform U2F challenge") }) } + +// Regression: a push that stays in WAITING stops with a timeout error instead of polling forever. +func TestVerifyMfa_PushPollIsBounded(t *testing.T) { + withFastPolling(t) + withShortPollTimeout(t) + vs := newVerifyServer(t, func(string, int, map[string]any) string { + return `{"status":"MFA_CHALLENGE","factorResult":"WAITING"}` + }) + + oc, _ := offlineTestClient(t) + resp := mfaRequiredResponse(t, "state-1", testFactor{id: "push", provider: "OKTA", factorType: "push", href: vs.href("push")}) + got, err := verifyMfa(oc, "okta.invalid", &creds.LoginDetails{}, resp) + require.ErrorIs(t, err, errMFAPollTimeout) + assert.Empty(t, got) +} + +// Regression: a failed prompt (for example Ctrl+C) stops authentication instead of selecting the first +// MFA option or submitting an empty token. +func TestVerifyMfa_PromptFailureStopsAuthentication(t *testing.T) { + errPrompt := errors.New("interrupt") + + t.Run("option selection", func(t *testing.T) { + pr := withMockPrompter(t) + pr.On("Choose", "Select which MFA option to use", mock.Anything).Return(0, errPrompt).Once() + + vs := newVerifyServer(t, func(string, int, map[string]any) string { + t.Error("no verify request is expected after a failed prompt") + return `{}` + }) + oc, _ := offlineTestClient(t) + resp := mfaRequiredResponse(t, "state-1", + testFactor{id: "a", provider: "OKTA", factorType: "push", href: vs.href("a")}, + testFactor{id: "b", provider: "OKTA", factorType: "push", href: vs.href("b")}, + ) + _, err := verifyMfa(oc, "okta.invalid", &creds.LoginDetails{}, resp) + require.ErrorIs(t, err, errPrompt) + }) + + t.Run("security code", func(t *testing.T) { + pr := withMockPrompter(t) + pr.On("RequestSecurityCode", "000000").Return("", errPrompt).Once() + + // Only the challenge request is made; the code is never submitted. + vs := newVerifyServer(t, func(string, int, map[string]any) string { + return `{"status":"MFA_CHALLENGE"}` + }) + oc, _ := offlineTestClient(t) + resp := mfaRequiredResponse(t, "state-1", testFactor{id: "totp", provider: "GOOGLE", factorType: "token:software:totp", href: vs.href("totp")}) + _, err := verifyMfa(oc, "okta.invalid", &creds.LoginDetails{}, resp) + require.ErrorIs(t, err, errPrompt) + assert.Equal(t, 1, vs.log.count("/verify/totp")) + }) +} diff --git a/pkg/auth/providers/aws/saml2aws/provider/redact.go b/pkg/auth/providers/aws/saml2aws/provider/redact.go new file mode 100644 index 00000000000..0e93446500c --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/redact.go @@ -0,0 +1,24 @@ +package provider + +import "net/url" + +// RedactURL returns u for logging: scheme, host and path only. +// Atmos fork: identity-provider URLs can carry session tokens and one-time codes in the +// query string or fragment (for example Okta's session-cookie redirect), and user info in +// the authority, so none of those are logged. +func RedactURL(u *url.URL) string { + if u == nil { + return "" + } + return (&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path}).String() +} + +// RedactRawURL parses raw and returns it redacted like RedactURL. +// A value that does not parse as a URL is not logged. +func RedactRawURL(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "[unparseable URL]" + } + return RedactURL(u) +} diff --git a/pkg/auth/providers/aws/saml2aws/saml.go b/pkg/auth/providers/aws/saml2aws/saml.go index 70b330647c7..70065dfdf82 100644 --- a/pkg/auth/providers/aws/saml2aws/saml.go +++ b/pkg/auth/providers/aws/saml2aws/saml.go @@ -52,18 +52,18 @@ func ExtractSessionDuration(data []byte) (int64, error) { // log.Printf("tag: %s", assertionElement.Tag) // Get the actual assertion attributes - attributeStatement := assertionElement.FindElement(childPath(assertionElement.Space, attributeStatementTag)) + attributeStatement := firstChild(assertionElement, assertionElement, attributeStatementTag) if attributeStatement == nil { return 0, ErrMissingElement{Tag: attributeStatementTag} } - attributes := attributeStatement.FindElements(childPath(assertionElement.Space, attributeTag)) + attributes := childElements(assertionElement, attributeStatement, attributeTag) for _, attribute := range attributes { if attribute.SelectAttrValue("Name", "") != "https://aws.amazon.com/SAML/Attributes/SessionDuration" { continue } - atributeValues := attribute.FindElements(childPath(assertionElement.Space, attributeValueTag)) + atributeValues := childElements(assertionElement, attribute, attributeValueTag) for _, attrValue := range atributeValues { return strconv.ParseInt(attrValue.Text(), 10, 64) } @@ -150,19 +150,19 @@ func ExtractAwsRoles(data []byte) ([]string, error) { // log.Printf("tag: %s", assertionElement.Tag) // Get the actual assertion attributes - attributeStatement := assertionElement.FindElement(childPath(assertionElement.Space, attributeStatementTag)) + attributeStatement := firstChild(assertionElement, assertionElement, attributeStatementTag) if attributeStatement == nil { return nil, ErrMissingElement{Tag: attributeStatementTag} } // log.Printf("tag: %s", attributeStatement.Tag) - attributes := attributeStatement.FindElements(childPath(assertionElement.Space, attributeTag)) + attributes := childElements(assertionElement, attributeStatement, attributeTag) for _, attribute := range attributes { if attribute.SelectAttrValue("Name", "") != "https://aws.amazon.com/SAML/Attributes/Role" { continue } - atributeValues := attribute.FindElements(childPath(assertionElement.Space, attributeValueTag)) + atributeValues := childElements(assertionElement, attribute, attributeValueTag) for _, attrValue := range atributeValues { awsroles = append(awsroles, attrValue.Text()) } @@ -171,10 +171,28 @@ func ExtractAwsRoles(data []byte) ([]string, error) { return awsroles, nil } -func childPath(space, tag string) string { - if space == "" { - return "./" + tag +// childElements returns the direct children of parent with the given local tag that belong to the same +// namespace URI as the assertion element. +// +// Atmos fork: upstream built a "./:" path, and etree compares that prefix literally, so +// an assertion using one prefix for Assertion and another prefix for the same namespace on its children was +// rejected. Matching by namespace URI accepts any prefix (and default namespaces) bound to that URI. +func childElements(assertion, parent *etree.Element, tag string) []*etree.Element { + namespace := assertion.NamespaceURI() + var matches []*etree.Element + for _, child := range parent.ChildElements() { + // An element whose prefix is not bound to any namespace is tolerated, as upstream matched by tag alone. + if child.Tag == tag && (child.NamespaceURI() == namespace || child.NamespaceURI() == "") { + matches = append(matches, child) + } + } + return matches +} + +// firstChild returns the first direct child matched by childElements, or nil. +func firstChild(assertion, parent *etree.Element, tag string) *etree.Element { + if matches := childElements(assertion, parent, tag); len(matches) > 0 { + return matches[0] } - // log.Printf("query = %s", "./"+space+":"+tag) - return "./" + space + ":" + tag + return nil } diff --git a/pkg/auth/providers/aws/saml2aws/saml_test.go b/pkg/auth/providers/aws/saml2aws/saml_test.go index 0500a3655bd..441dd35524a 100644 --- a/pkg/auth/providers/aws/saml2aws/saml_test.go +++ b/pkg/auth/providers/aws/saml2aws/saml_test.go @@ -3,6 +3,7 @@ package saml2aws import ( "os" "path/filepath" + "strings" "testing" "time" @@ -359,3 +360,52 @@ func TestExtractFunctionsRejectMalformedXML(t *testing.T) { assert.Error(t, err) assert.Empty(t, roles) } + +// Regression: children are matched by namespace URI, so a prefix on the children that differs from +// the Assertion's prefix (or a default namespace) is accepted. +func TestExtractMixedPrefixAndDefaultNamespaces(t *testing.T) { + const roleAttr = `<%[1]sAttribute Name="https://aws.amazon.com/SAML/Attributes/Role"><%[1]sAttributeValue>arn:aws:iam::1:saml-provider/idp,arn:aws:iam::1:role/r` + + `<%[1]sAttribute Name="https://aws.amazon.com/SAML/Attributes/SessionDuration"><%[1]sAttributeValue>900` + ns := `urn:oasis:names:tc:SAML:2.0:assertion` + + tests := []struct { + name string + xml string + }{ + { + name: "same prefix", + xml: `` + sprintfPrefix(roleAttr, "saml:") + ``, + }, + { + name: "different prefix bound to the same namespace", + xml: `` + sprintfPrefix(roleAttr, "s:") + ``, + }, + { + name: "default namespace children", + xml: `` + sprintfPrefix(roleAttr, "") + ``, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + roles, err := ExtractAwsRoles([]byte(tt.xml)) + require.NoError(t, err) + require.Len(t, roles, 1) + assert.Equal(t, "arn:aws:iam::1:saml-provider/idp,arn:aws:iam::1:role/r", roles[0]) + + duration, err := ExtractSessionDuration([]byte(tt.xml)) + require.NoError(t, err) + assert.Equal(t, int64(900), duration) + }) + } +} + +func sprintfPrefix(format, prefix string) string { + return strings.ReplaceAll(format, "%[1]s", prefix) +} + +// A child in a different namespace is not an AttributeStatement of the assertion. +func TestExtractRolesIgnoresForeignNamespaceChildren(t *testing.T) { + xml := `` + _, err := ExtractAwsRoles([]byte(xml)) + require.ErrorIs(t, err, ErrMissingElement{Tag: attributeStatementTag}) +} diff --git a/pkg/auth/providers/aws/saml_browser_revision.go b/pkg/auth/providers/aws/saml_browser_revision.go index 508c31c2b4c..cd8ac2470c8 100644 --- a/pkg/auth/providers/aws/saml_browser_revision.go +++ b/pkg/auth/providers/aws/saml_browser_revision.go @@ -97,7 +97,7 @@ func readBrowserDir(manifestPath, browserName, hostPlatform string) (string, err // otherwise /ms-playwright, where is $XDG_CACHE_HOME or ~/.cache on Linux, // ~/Library/Caches on macOS, and %LOCALAPPDATA% or ~/AppData/Local on Windows. func playwrightRegistryDir() (string, error) { - switch browsersPath := os.Getenv("PLAYWRIGHT_BROWSERS_PATH"); browsersPath { //nolint:forbidigo // Third-party (Playwright) env var, read the same way the driver reads it. + switch browsersPath := playwrightBrowsersPathEnv(); browsersPath { case "": case "0": opts := &playwright.RunOptions{} @@ -107,7 +107,13 @@ func playwrightRegistryDir() (string, error) { // The playwright-core package root is the directory holding cli.js and browsers.json. return filepath.Join(filepath.Dir(playwrightManifestPath(opts.DriverDirectory)), playwrightLocalBrowsers), nil default: - // Playwright resolves a relative path against the working directory. + // Playwright resolves a relative path against INIT_CWD (set by npm) before the working directory. + if filepath.IsAbs(browsersPath) { + return filepath.Clean(browsersPath), nil + } + if initCwd := os.Getenv("INIT_CWD"); initCwd != "" { //nolint:forbidigo // Third-party (npm/Playwright) env var, read the same way the driver reads it. + return filepath.Abs(filepath.Join(initCwd, browsersPath)) + } return filepath.Abs(browsersPath) } @@ -118,6 +124,21 @@ func playwrightRegistryDir() (string, error) { return filepath.Join(cacheDir, playwrightCacheDir), nil } +// playwrightBrowsersPathEnv returns the configured PLAYWRIGHT_BROWSERS_PATH using Playwright's +// precedence: the variable itself, then its npm_config_ and npm_package_config_ lowercase forms. +func playwrightBrowsersPathEnv() string { + for _, name := range []string{ + "PLAYWRIGHT_BROWSERS_PATH", + "npm_config_playwright_browsers_path", + "npm_package_config_playwright_browsers_path", + } { + if value := os.Getenv(name); value != "" { //nolint:forbidigo // Third-party (Playwright) env vars, read the same way the driver reads them. + return value + } + } + return "" +} + // playwrightDefaultCacheDir returns the cache base directory Playwright uses on goos. func playwrightDefaultCacheDir(goos string) (string, error) { var envDir string diff --git a/pkg/auth/providers/aws/saml_browser_revision_test.go b/pkg/auth/providers/aws/saml_browser_revision_test.go index dbc00715d5d..e5d90361ccb 100644 --- a/pkg/auth/providers/aws/saml_browser_revision_test.go +++ b/pkg/auth/providers/aws/saml_browser_revision_test.go @@ -38,6 +38,9 @@ func isolatedBrowserCacheDir(t *testing.T) (string, string) { t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) t.Setenv("PLAYWRIGHT_BROWSERS_PATH", "") + t.Setenv("npm_config_playwright_browsers_path", "") + t.Setenv("npm_package_config_playwright_browsers_path", "") + t.Setenv("INIT_CWD", "") xdgCache := filepath.Join(home, ".xdg-cache") t.Setenv("XDG_CACHE_HOME", xdgCache) homedir.Reset() @@ -129,6 +132,7 @@ func TestReadBrowserDirMissingFile(t *testing.T) { func TestRequiredBrowserDirFromDriverDirectory(t *testing.T) { driverDir := t.TempDir() t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir) + t.Setenv("PLAYWRIGHT_CLI_PATH", "") require.NoError(t, os.MkdirAll(filepath.Join(driverDir, "package"), 0o755)) require.NoError(t, os.WriteFile(filepath.Join(driverDir, "package", playwrightBrowserManifest), []byte(`{"browsers":[{"name":"chromium","revision":"4321"}]}`), 0o600)) @@ -235,6 +239,7 @@ func TestRequiredChromiumInstalled_PlaywrightBrowsersPath(t *testing.T) { stubRequiredChromiumRevision(t, "1248") driverDir := t.TempDir() t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir) + t.Setenv("PLAYWRIGHT_CLI_PATH", "") t.Setenv("PLAYWRIGHT_BROWSERS_PATH", "0") installFakeBrowser(t, filepath.Join(driverDir, "package", playwrightLocalBrowsers), "chromium-1248") @@ -282,6 +287,7 @@ func TestPlaywrightDefaultCacheDir(t *testing.T) { // A relative PLAYWRIGHT_BROWSERS_PATH is resolved against the working directory, like the driver does. func TestPlaywrightRegistryDirRelativeBrowsersPath(t *testing.T) { t.Setenv("PLAYWRIGHT_BROWSERS_PATH", "browsers") + t.Setenv("INIT_CWD", "") cwd, err := os.Getwd() require.NoError(t, err) @@ -290,6 +296,35 @@ func TestPlaywrightRegistryDirRelativeBrowsersPath(t *testing.T) { assert.Equal(t, filepath.Join(cwd, "browsers"), got) } +// Regression: a relative PLAYWRIGHT_BROWSERS_PATH resolves against INIT_CWD before the working directory. +func TestPlaywrightRegistryDirRelativeBrowsersPathUsesInitCwd(t *testing.T) { + initCwd := t.TempDir() + t.Setenv("PLAYWRIGHT_BROWSERS_PATH", "browsers") + t.Setenv("INIT_CWD", initCwd) + + got, err := playwrightRegistryDir() + require.NoError(t, err) + assert.Equal(t, filepath.Join(initCwd, "browsers"), got) +} + +// Regression: Playwright also reads the npm config forms of PLAYWRIGHT_BROWSERS_PATH, in order. +func TestPlaywrightRegistryDirNpmEnvFallbacks(t *testing.T) { + configDir := t.TempDir() + packageDir := t.TempDir() + t.Setenv("PLAYWRIGHT_BROWSERS_PATH", "") + t.Setenv("npm_config_playwright_browsers_path", configDir) + t.Setenv("npm_package_config_playwright_browsers_path", packageDir) + + got, err := playwrightRegistryDir() + require.NoError(t, err) + assert.Equal(t, configDir, got) + + t.Setenv("npm_config_playwright_browsers_path", "") + got, err = playwrightRegistryDir() + require.NoError(t, err) + assert.Equal(t, packageDir, got) +} + // An external PLAYWRIGHT_CLI_PATH moves browsers.json with cli.js. func TestPlaywrightManifestPath(t *testing.T) { driverDir := t.TempDir() diff --git a/pkg/auth/providers/aws/saml_driver_detection_test.go b/pkg/auth/providers/aws/saml_driver_detection_test.go index 7b788912369..08d4028fba6 100644 --- a/pkg/auth/providers/aws/saml_driver_detection_test.go +++ b/pkg/auth/providers/aws/saml_driver_detection_test.go @@ -77,6 +77,18 @@ func TestHasValidPlaywrightDrivers(t *testing.T) { expected: true, wantLog: "Found browser binaries", }, + { + name: "registry metadata only returns false", + setup: func(t *testing.T) string { + dir := t.TempDir() + linksDir := filepath.Join(dir, ".links") + require.NoError(t, os.Mkdir(linksDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(linksDir, "client"), []byte("meta"), 0o644)) + return dir + }, + expected: false, + wantLog: "no browser binaries", + }, { name: "non-existent directory returns false", setup: func(t *testing.T) string { diff --git a/pkg/auth/providers/aws/sso_token_flow_test.go b/pkg/auth/providers/aws/sso_token_flow_test.go index 492503b484a..364136d2e8b 100644 --- a/pkg/auth/providers/aws/sso_token_flow_test.go +++ b/pkg/auth/providers/aws/sso_token_flow_test.go @@ -15,6 +15,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ssooidc" + cockroachErrors "github.com/cockroachdb/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -271,8 +272,9 @@ func TestSSOProviderAuthenticate_RefreshesExpiredTokenWithoutBrowser(t *testing. } func TestSSOProviderAuthenticate_FailedRefreshInNonInteractiveSessionFails(t *testing.T) { - if isTTY() { - t.Skipf("stderr is a terminal; the device-authorization fallback would start an interactive flow") + // The production gate is isInteractive (which also honors force-tty), not isTTY alone. + if isInteractive() { + t.Skipf("the session is interactive (stderr is a terminal or force-tty is set); the device-authorization fallback would start an interactive flow") } srv := newFakeOIDCServer(t, fakeOIDCResponse{ @@ -295,6 +297,8 @@ func TestSSOProviderAuthenticate_FailedRefreshInNonInteractiveSessionFails(t *te require.Error(t, err) assert.Nil(t, creds) assert.ErrorIs(t, err, errUtils.ErrAuthenticationFailed) + // Registration failures also wrap ErrAuthenticationFailed, so assert the intended rejection. + assert.Contains(t, cockroachErrors.GetAllDetails(err), "AWS SSO device flow requires an interactive terminal (TTY) for user authorization") assert.Equal(t, int32(1), srv.calls.Load(), "refresh is attempted exactly once before giving up") } From d1f1debe05f867481b79144237c2d5550a919288 Mon Sep 17 00:00:00 2001 From: aknysh Date: Tue, 17 Nov 2026 21:09:50 -0500 Subject: [PATCH 5/7] fix(auth): resolve form actions, scope the Duo certifier TLS exception - page: resolve relative form actions against the document URL (set from the response URL, including in Okta's form follow); keep absolute actions; error on a relative action with no document URL. - googleapps: a form selected by id keeps only its own fields and posts to the document URL when it has no action; fall back to other forms only when no form with the given ids exists; no panic on a nil document URL. - okta: send the Duo certifier request through a dedicated client instead of swapping the shared transport. Verification is skipped only for a loopback certifier, and redirects to non-loopback hosts are rejected, so a redirect can no longer reach a remote host without certificate verification. - docs: even out odd list indentation in the auth PRD (editorconfig). Co-Authored-By: Claude Opus 5.5 --- pkg/auth/docs/PRD/PRD-Atmos-Auth.md | 126 ++++++++-------- pkg/auth/providers/aws/saml2aws/page/form.go | 23 ++- .../providers/aws/saml2aws/page/form_test.go | 62 +++++++- .../provider/googleapps/googleapps.go | 26 +++- .../googleapps/googleapps_challenge_test.go | 33 ++++- .../aws/saml2aws/provider/okta/okta.go | 43 ++++-- .../okta/okta_certifier_client_test.go | 140 ++++++++++++++++++ 7 files changed, 367 insertions(+), 86 deletions(-) create mode 100644 pkg/auth/providers/aws/saml2aws/provider/okta/okta_certifier_client_test.go diff --git a/pkg/auth/docs/PRD/PRD-Atmos-Auth.md b/pkg/auth/docs/PRD/PRD-Atmos-Auth.md index 35b525563c5..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 @@ -1123,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) @@ -1141,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:** @@ -1343,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 @@ -1500,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) @@ -1534,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) @@ -1569,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/providers/aws/saml2aws/page/form.go b/pkg/auth/providers/aws/saml2aws/page/form.go index 5a315f7ff62..ec434b8875f 100644 --- a/pkg/auth/providers/aws/saml2aws/page/form.go +++ b/pkg/auth/providers/aws/saml2aws/page/form.go @@ -74,7 +74,11 @@ func NewFormFromDocument(doc *goquery.Document, formFilter string) (*Form, error attrValue, ok := formSelection.Attr("action") if ok { - form.URL = attrValue + 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 { @@ -105,6 +109,23 @@ func NewFormFromDocument(doc *goquery.Document, formFilter string) (*Form, error 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 { diff --git a/pkg/auth/providers/aws/saml2aws/page/form_test.go b/pkg/auth/providers/aws/saml2aws/page/form_test.go index 659d5f832e7..56db9e75c35 100644 --- a/pkg/auth/providers/aws/saml2aws/page/form_test.go +++ b/pkg/auth/providers/aws/saml2aws/page/form_test.go @@ -31,17 +31,18 @@ func TestNewFormFromDocument(t *testing.T) { 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, "/form_b", form.URL) + 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, "/form_c", form.URL) + require.Equal(t, "https://idp.example.com/form_c", form.URL) require.Equal(t, url.Values{"c1": []string{"now"}}, *form.Values) } @@ -76,7 +77,7 @@ func TestNewFormFromDocumentDefaultsAndMethod(t *testing.T) { { name: "method attribute is upper-cased", html: `
`, - wantURL: "/next", + wantURL: "https://idp.example.com/next", wantMethod: http.MethodGet, }, } @@ -104,6 +105,7 @@ func TestNewFormFromDocumentSkipsInputsWithoutNameOrValue(t *testing.T) { `)) require.NoError(t, err) + doc.Url = &url.URL{Scheme: "https", Host: "idp.example.com"} form, err := NewFormFromDocument(doc, "") require.NoError(t, err) @@ -111,10 +113,12 @@ func TestNewFormFromDocumentSkipsInputsWithoutNameOrValue(t *testing.T) { } func TestNewFormFromResponse(t *testing.T) { - res := &http.Response{Body: io.NopCloser(strings.NewReader(`
`))} + 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, "/go", form.URL) + 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{})} @@ -211,3 +215,51 @@ func TestNewFormFromResponseMissingDocumentURL(t *testing.T) { 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/provider/googleapps/googleapps.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go index 853345df0a8..05c76b28a27 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -726,15 +726,23 @@ func mustFindErrorMsg(doc *goquery.Document) string { } func extractInputsByFormID(doc *goquery.Document, formID ...string) (url.Values, string, error) { - // First try to find form by specific id + // First try to find form by specific id. + // Atmos fork: a form selected by id is used on its own; when it has no action, + // extractInputsByFormQuery defaults to the document URL. Upstream fell through to + // every form and merged their fields, posting them to another form's action. for _, id := range formID { - formData, actionURL, err := extractInputsByFormQuery(doc, fmt.Sprintf("#%s", id)) - if err == nil && actionURL != "" { - return formData, actionURL, nil + query := fmt.Sprintf("#%s", id) + if doc.Find(fmt.Sprintf("form%s", query)).Length() == 0 { + continue + } + formData, actionURL, err := extractInputsByFormQuery(doc, query) + if err != nil { + return nil, "", err } + return formData, actionURL, nil } - // If no form found by id or actionURL in the previous forms, search for any form + // No form with the given ids exists, so search for any form. formData, actionURL, err := extractInputsByFormQuery(doc, "") if err != nil && actionURL != "" { return formData, actionURL, errors.New("could not find any forms with actions") @@ -754,6 +762,10 @@ func extractInputsByFormQuery(doc *goquery.Document, formQuery string) (url.Valu query := fmt.Sprintf("form%s", formQuery) + // Atmos fork: goquery leaves doc.Url nil for reader-based documents; upstream dereferenced it. + if doc.Url == nil { + return formData, "", errors.New("document has no URL") + } currentURL := doc.Url.String() // get action url @@ -769,6 +781,10 @@ func extractInputsByFormQuery(doc *goquery.Document, formQuery string) (url.Valu } actionAttr = action }) + // Atmos fork: a form without an action submits to the document URL. + if actionAttr == "" { + actionAttr = currentURL + } actionURL, err := generateFullURLIfRelative(actionAttr, currentURL) if err != nil { diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go index 7fe47436148..2c949957b5b 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps_challenge_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/PuerkitoBio/goquery" "github.com/marshallbrekka/go-u2fhost" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -268,8 +269,9 @@ func TestChallenge_UnsupportedSecondFactor(t *testing.T) { } func TestExtractInputsByFormID(t *testing.T) { - t.Run("form without action falls back to any form", func(t *testing.T) { - // Regression: a matching form without an action attribute used to panic. + t.Run("selected form without action uses the document URL and only its own fields", func(t *testing.T) { + // Regression: a matching form without an action attribute used to panic, and then + // fell back to every form, merging their fields and posting to another form's action. doc := mustDoc(t, `
`+ `
`, "https://accounts.google.com/page") var ( @@ -279,11 +281,36 @@ func TestExtractInputsByFormID(t *testing.T) { ) require.NotPanics(t, func() { form, action, err = extractInputsByFormID(doc, "challenge") }) require.NoError(t, err) - assert.Equal(t, "https://accounts.google.com/signin/next", action) + assert.Equal(t, "https://accounts.google.com/page", action) assert.Equal(t, "1", form.Get("a")) + assert.NotContains(t, form, "b") + }) + + t.Run("selected form keeps its explicit action", func(t *testing.T) { + doc := mustDoc(t, `
`+ + `
`, "https://accounts.google.com/page") + form, action, err := extractInputsByFormID(doc, "challenge") + require.NoError(t, err) + assert.Equal(t, "https://accounts.google.com/signin/mine", action) + assert.Equal(t, "1", form.Get("a")) + assert.NotContains(t, form, "b") + }) + + t.Run("no form with the given id falls back to any form", func(t *testing.T) { + doc := mustDoc(t, `
`, "https://accounts.google.com/page") + form, action, err := extractInputsByFormID(doc, "challenge") + require.NoError(t, err) + assert.Equal(t, "https://accounts.google.com/signin/next", action) assert.Equal(t, "2", form.Get("b")) }) + t.Run("document without URL returns an error", func(t *testing.T) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(`
`)) + require.NoError(t, err) + require.NotPanics(t, func() { _, _, err = extractInputsByFormQuery(doc, "#challenge") }) + require.Error(t, err) + }) + t.Run("no forms", func(t *testing.T) { doc := mustDoc(t, `

none

`, "https://accounts.google.com/page") _, _, err := extractInputsByFormID(doc, "challenge") diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go index b0baf42dc32..d1e405461d1 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go @@ -562,6 +562,10 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c logger.Debug("FAILED TO BUILD DOC FROM RESP") return "", errors.Wrap(err, "failed to build document from response") } + // Atmos fork: reader-based documents have no URL; keep the response URL so relative form actions can be resolved. + if doc.Url == nil && res.Request != nil { + doc.Url = res.Request.URL + } var handler func(context.Context, *goquery.Document) (context.Context, *http.Request, error) @@ -1501,6 +1505,35 @@ func isLoopbackURL(rawURL string) bool { return ip != nil && ip.IsLoopback() } +// errCertifierRedirect is returned when the certifier redirects somewhere other than a loopback address. +var errCertifierRedirect = errors.New("certifier redirected to a non-loopback URL") + +// maxCertifierRedirects bounds the redirects followed by the certifier request. +const maxCertifierRedirects = 10 + +// newCertifierClient returns a dedicated client for the Duo certifier request. +// Atmos fork: upstream (and the first Atmos version) swapped the shared client's transport for one +// that skips certificate verification, which also applied to every redirect hop. The dedicated client +// leaves the shared client untouched, shares its cookie jar and status check, and refuses to follow a +// redirect to a non-loopback URL, so an unverified connection can never reach a remote host. +func newCertifierClient(base *provider.HTTPClient, certifierURL string) *provider.HTTPClient { + certTransport := http.DefaultTransport.(*http.Transport).Clone() + certTransport.TLSClientConfig = certifierTLSConfig(certifierURL) + + client := *base + client.Transport = certTransport + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) >= maxCertifierRedirects { + return errors.New("stopped after too many certifier redirects") + } + if !isLoopbackURL(req.URL.String()) { + return errCertifierRedirect + } + return nil + } + return &client +} + func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSubmitURL string, q url.Values) (*goquery.Document, error) { // If you enable DUO trusted cert validation, it requires an extra step before continuing. // The way the validation process works is it attempts to send a request to a localhost:15310 @@ -1521,21 +1554,13 @@ func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSub duoUrl := fmt.Sprintf("%s?type=AJAX&sid=%s&certs_txid=%s", certUrl, url.QueryEscape(sid), txid) duoCertifierURL := fmt.Sprintf("%s?certUrl=%s", certifierUrl, url.QueryEscape(duoUrl)) - // The locally running certifier does not have a valid certificate, so we have to skip verification - customTransport := http.DefaultTransport.(*http.Transport).Clone() - customTransport.TLSClientConfig = certifierTLSConfig(certifierUrl) - originalTransport := oc.client.Transport - - oc.client.Transport = customTransport - req, err := http.NewRequest("GET", duoCertifierURL, nil) if err != nil { return nil, errors.Wrap(err, "error building cert validation request") } req.Header.Add("Referer", "https://"+duoHost+"/") - res, err := oc.client.Do(req) - oc.client.Transport = originalTransport + res, err := newCertifierClient(oc.client, certifierUrl).Do(req) if err != nil { // Local certifier not running, try online one diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_certifier_client_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_certifier_client_test.go new file mode 100644 index 00000000000..6561e55c3d0 --- /dev/null +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_certifier_client_test.go @@ -0,0 +1,140 @@ +package okta + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// certifierCertForm renders the Duo client certificate form that verifyTrustedCert reads. +func certifierCertForm(certsURL, certifierURL string) string { + return fmt.Sprintf(`
`+ + `
`, certsURL, certifierURL) +} + +// Regression: the certifier request used to swap the shared client's transport for one that skips +// certificate verification, and redirects reused that transport, so a loopback certifier could bounce the +// request to a remote HTTPS host without certificate verification. +func TestVerifyTrustedCert_CertifierClient(t *testing.T) { + // online serves the online validator and the final submit; it counts validator hits. + newOnline := func(hits *atomic.Int32) *httptest.Server { + return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/certs": + hits.Add(1) + _, _ = fmt.Fprint(w, `{"stat":"OK"}`) + case "/submit": + _, _ = fmt.Fprint(w, `
`) + default: + t.Errorf("unexpected request %s", r.URL.Path) + } + })) + } + + t.Run("loopback certifier works and the shared transport is unchanged", func(t *testing.T) { + var onlineHits atomic.Int32 + online := newOnline(&onlineHits) + defer online.Close() + certifier := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = fmt.Fprint(w, `{"stat":"OK"}`) + })) + defer certifier.Close() + + oc, _ := offlineTestClient(t) + before := oc.client.Transport + doc, err := verifyTrustedCert(oc, mustDoc(t, certifierCertForm(online.URL+"/certs", certifier.URL+"/certifier")), "duo.example.com", online.URL+"/submit", url.Values{}) + require.NoError(t, err) + sid, _ := doc.Find(`input[name="sid"]`).Attr("value") + assert.Equal(t, "after-cert", sid) + assert.Zero(t, onlineHits.Load(), "the loopback certifier answered, so the online validator is not used") + assert.Same(t, before, oc.client.Transport, "the shared client transport must not be replaced") + }) + + t.Run("loopback certifier redirecting to a remote host falls back to the online validator", func(t *testing.T) { + var onlineHits atomic.Int32 + online := newOnline(&onlineHits) + defer online.Close() + var remoteHits atomic.Int32 + certifier := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + remoteHits.Add(1) + http.Redirect(w, r, "https://remote.invalid/certifier", http.StatusFound) + })) + defer certifier.Close() + + oc, _ := offlineTestClient(t) + before := oc.client.Transport + doc, err := verifyTrustedCert(oc, mustDoc(t, certifierCertForm(online.URL+"/certs", certifier.URL+"/certifier")), "duo.example.com", online.URL+"/submit", url.Values{}) + require.NoError(t, err) + sid, _ := doc.Find(`input[name="sid"]`).Attr("value") + assert.Equal(t, "after-cert", sid) + assert.Equal(t, int32(1), remoteHits.Load()) + assert.Equal(t, int32(1), onlineHits.Load(), "the redirect is rejected, so the online validator is used") + assert.Same(t, before, oc.client.Transport, "the shared client transport must not be replaced") + }) + + t.Run("non-2xx certifier response is reported as an error by the shared status check", func(t *testing.T) { + certifier := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer certifier.Close() + + oc, _ := offlineTestClient(t) + oc.client.CheckResponseStatus = func(_ *http.Request, res *http.Response) error { + if res.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status %d", res.StatusCode) + } + return nil + } + req, err := http.NewRequest(http.MethodGet, certifier.URL+"/certifier", nil) + require.NoError(t, err) + _, err = newCertifierClient(oc.client, certifier.URL).Do(req) + require.Error(t, err) + }) +} + +func TestNewCertifierClient_Redirects(t *testing.T) { + var final atomic.Int32 + target := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + final.Add(1) + _, _ = fmt.Fprint(w, "ok") + })) + defer target.Close() + certifier := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/to-loopback": + http.Redirect(w, r, target.URL+"/final", http.StatusFound) + default: + http.Redirect(w, r, "https://remote.invalid/final", http.StatusFound) + } + })) + defer certifier.Close() + + oc, _ := offlineTestClient(t) + + t.Run("redirect to another loopback host is followed", func(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, certifier.URL+"/to-loopback", nil) + require.NoError(t, err) + res, err := newCertifierClient(oc.client, certifier.URL).Do(req) + require.NoError(t, err) + defer res.Body.Close() + assert.Equal(t, http.StatusOK, res.StatusCode) + assert.Equal(t, int32(1), final.Load()) + }) + + t.Run("redirect to a non-loopback host is rejected", func(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, certifier.URL+"/to-remote", nil) + require.NoError(t, err) + res, err := newCertifierClient(oc.client, certifier.URL).Do(req) + if res != nil { + defer res.Body.Close() + } + require.Error(t, err) + assert.ErrorIs(t, err, errCertifierRedirect) + }) +} From 1057a6d293daf840efb3406f9e550f0ae97be6a4 Mon Sep 17 00:00:00 2001 From: aknysh Date: Tue, 17 Nov 2026 21:19:14 -0500 Subject: [PATCH 6/7] fix(auth): resolve golangci-lint findings in vendored saml2aws Address the 120 golangci-lint findings CI reported for this PR: - bodyclose: close every response body in the Okta and Google Apps flows and in tests (real connection leaks). - errorlint: compare and inspect errors with errors.Is/errors.As and wrap with %w, including the U2F/WebAuthn device errors. - staticcheck: lower-case error strings, rename RetryDelayMS, drop the deprecated net.Dialer.DualStack, use strings.ReplaceAll and a tagged switch. - revive/godot/misspell/unconvert/unparam/tparallel/nolintlint fixes; named constants and smaller helpers in the Playwright host-platform detection. - gosec: narrowly scoped //nolint with reasons for the explicit skip_verify opt-in, the fixed pinentry command, API-mandated JSON field names, and provably safe conversions. Co-Authored-By: Claude Opus 5.5 --- cmd/auth/exec_child_process_test.go | 6 +- pkg/auth/cloud/kube/config_drift_test.go | 4 +- pkg/auth/providers/aws/saml2aws/aws_role.go | 6 +- .../providers/aws/saml2aws/aws_role_test.go | 8 +- pkg/auth/providers/aws/saml2aws/cfg/cfg.go | 4 +- .../providers/aws/saml2aws/cfg/cfg_test.go | 4 +- .../providers/aws/saml2aws/cookiejar/jar.go | 2 +- .../aws/saml2aws/cookiejar/jar_test.go | 3 +- .../aws/saml2aws/cookiejar/punycode.go | 2 +- .../helper/credentials/credentials.go | 2 +- .../providers/aws/saml2aws/page/form_test.go | 10 +- .../aws/saml2aws/prompter/pinentry.go | 8 +- .../aws/saml2aws/prompter/prompter.go | 2 +- .../aws/saml2aws/provider/adfs/adfs.go | 2 +- .../aws/saml2aws/provider/base_validate.go | 6 +- .../aws/saml2aws/provider/browser/browser.go | 5 +- .../provider/googleapps/googleapps.go | 6 + .../aws/saml2aws/provider/googleapps/u2f.go | 15 ++- .../saml2aws/provider/googleapps/u2f_test.go | 2 +- .../providers/aws/saml2aws/provider/http.go | 7 +- .../saml2aws/provider/http_attempts_test.go | 5 +- .../aws/saml2aws/provider/http_test.go | 8 +- .../aws/saml2aws/provider/okta/okta.go | 38 ++++-- .../provider/okta/okta_auth_flow_test.go | 2 +- .../saml2aws/provider/okta/okta_duo_u2f.go | 15 ++- .../provider/okta/okta_duo_u2f_test.go | 2 +- .../provider/okta/okta_helpers_test.go | 2 +- .../aws/saml2aws/provider/okta/okta_test.go | 10 +- .../saml2aws/provider/okta/okta_webauthn.go | 19 +-- .../provider/okta/okta_webauthn_test.go | 2 +- .../aws/saml_browser_autodownload_test.go | 6 +- .../providers/aws/saml_browser_platform.go | 125 +++++++++++------- .../providers/aws/saml_browser_revision.go | 18 +-- pkg/auth/providers/aws/saml_driver_preseed.go | 2 +- pkg/auth/providers/aws/sso_token_flow_test.go | 17 ++- 35 files changed, 226 insertions(+), 149 deletions(-) diff --git a/cmd/auth/exec_child_process_test.go b/cmd/auth/exec_child_process_test.go index 731aa34cc7f..e734262070f 100644 --- a/cmd/auth/exec_child_process_test.go +++ b/cmd/auth/exec_child_process_test.go @@ -16,11 +16,11 @@ import ( ) const ( - // authExecChildEnv turns the test binary into the child process `auth exec` runs. + // Turns the test binary into the child process `auth exec` runs. authExecChildEnv = "_ATMOS_TEST_AUTH_EXEC_CHILD" - // authExecChildReportEnv names the file the child writes its observations to. + // Names the file the child writes its observations to. authExecChildReportEnv = "_ATMOS_TEST_AUTH_EXEC_REPORT" - // authExecChildExitEnv is the exit code the child terminates with. + // Exit code the child terminates with. authExecChildExitEnv = "_ATMOS_TEST_AUTH_EXEC_EXIT" ) diff --git a/pkg/auth/cloud/kube/config_drift_test.go b/pkg/auth/cloud/kube/config_drift_test.go index 18d0dfee0e7..794afd7a52b 100644 --- a/pkg/auth/cloud/kube/config_drift_test.go +++ b/pkg/auth/cloud/kube/config_drift_test.go @@ -83,8 +83,8 @@ func TestWriteClusterConfig_MergeRepairsDriftedAtmosEntry(t *testing.T) { } // TestWriteClusterConfig_MergePreservesThirdPartyAuthInfo verifies that merging -// the Atmos entry leaves unrelated users (with tokens, impersonation and auth -// providers) intact, so `atmos ... update-kubeconfig` never clobbers a user's +// 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") diff --git a/pkg/auth/providers/aws/saml2aws/aws_role.go b/pkg/auth/providers/aws/saml2aws/aws_role.go index 719ca1b650d..28a8ee0aad3 100644 --- a/pkg/auth/providers/aws/saml2aws/aws_role.go +++ b/pkg/auth/providers/aws/saml2aws/aws_role.go @@ -63,7 +63,7 @@ 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)) + return nil, fmt.Errorf("invalid role string only %d tokens", len(tokens)) } awsRole := &AWSRole{} @@ -78,11 +78,11 @@ func parseRole(role string) (*AWSRole, error) { } if awsRole.PrincipalARN == "" { - return nil, fmt.Errorf("Unable to locate PrincipalARN in: %s", role) + 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 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 index 8ff0db9bb6a..08708ba4fca 100644 --- a/pkg/auth/providers/aws/saml2aws/aws_role_test.go +++ b/pkg/auth/providers/aws/saml2aws/aws_role_test.go @@ -38,22 +38,22 @@ func TestParseAWSRolesErrors(t *testing.T) { { name: "single token", role: "arn:aws:iam::123456789012:role/admin", - wantErr: "Invalid role string only 1 tokens", + 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", + 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", + 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", + wantErr: "unable to locate RoleARN", }, } diff --git a/pkg/auth/providers/aws/saml2aws/cfg/cfg.go b/pkg/auth/providers/aws/saml2aws/cfg/cfg.go index da19ca97460..31c70b67382 100644 --- a/pkg/auth/providers/aws/saml2aws/cfg/cfg.go +++ b/pkg/auth/providers/aws/saml2aws/cfg/cfg.go @@ -94,7 +94,7 @@ func (ia *IDPAccount) Validate() error { } if ia.Provider == "" { - return errors.New("Provider empty in idp account") + return errors.New("provider empty in idp account") } if ia.Provider != "Browser" { @@ -104,7 +104,7 @@ func (ia *IDPAccount) Validate() error { } if ia.Profile == "" { - return errors.New("Profile empty in idp account") + return errors.New("profile empty in idp account") } if err := prompter.ValidateAndSetPrompter(ia.Prompter); err != nil { diff --git a/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go b/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go index 5248e86b3ac..7ad4d8b9811 100644 --- a/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go +++ b/pkg/auth/providers/aws/saml2aws/cfg/cfg_test.go @@ -54,9 +54,9 @@ func TestIDPAccountValidate(t *testing.T) { {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 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: "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"}, } diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go index d2bb8ee4f14..4bc8d680a3f 100644 --- a/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar.go @@ -216,7 +216,7 @@ func (j *Jar) cookies(u *url.URL, now time.Time) (cookies []*http.Cookie) { return s[i].seqNum < s[j].seqNum }) for _, e := range selected { - cookies = append(cookies, &http.Cookie{Name: e.Name, Value: e.Value}) + 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 diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go index 0fa88ae42ec..ab7d2755768 100644 --- a/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/jar_test.go @@ -5,6 +5,7 @@ package cookiejar import ( + "errors" "fmt" "net/http" "net/url" @@ -328,7 +329,7 @@ func TestDomainAndType(t *testing.T) { jar := newTestJar() for _, tc := range domainAndTypeTests { domain, hostOnly, err := jar.domainAndType(tc.host, tc.domain) - if err != tc.wantErr { + if !errors.Is(err, tc.wantErr) { t.Errorf("%q/%q: got %q error, want %q", tc.host, tc.domain, err, tc.wantErr) continue diff --git a/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go b/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go index a9cc666e8c9..0b70e0fe45a 100644 --- a/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go +++ b/pkg/auth/providers/aws/saml2aws/cookiejar/punycode.go @@ -39,7 +39,7 @@ func encode(prefix, s string) (string, error) { for _, r := range s { if r < utf8.RuneSelf { b++ - output = append(output, byte(r)) + output = append(output, byte(r)) //nolint:gosec // r < utf8.RuneSelf, so it fits in a byte. } else { remaining++ } diff --git a/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go index bebce84f7ac..03c354c6db1 100644 --- a/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go +++ b/pkg/auth/providers/aws/saml2aws/helper/credentials/credentials.go @@ -40,7 +40,7 @@ type Helper interface { // IsErrCredentialsNotFound returns true if the error // was caused by not having a set of credentials in a store. func IsErrCredentialsNotFound(err error) bool { - return err == ErrCredentialsNotFound + return errors.Is(err, ErrCredentialsNotFound) } type defaultHelper struct{} diff --git a/pkg/auth/providers/aws/saml2aws/page/form_test.go b/pkg/auth/providers/aws/saml2aws/page/form_test.go index 56db9e75c35..4208ff8d58b 100644 --- a/pkg/auth/providers/aws/saml2aws/page/form_test.go +++ b/pkg/auth/providers/aws/saml2aws/page/form_test.go @@ -166,13 +166,19 @@ func TestFormSubmit(t *testing.T) { assert.Equal(t, url.Values{"token": {"123"}}, gotForm) // Invalid method fails while building the request. - _, err = (&Form{URL: ts.URL, Method: "BAD METHOD", Values: &url.Values{}}).Submit(client) + 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() - _, err = form.Submit(client) + closedRes, err := form.Submit(client) + if closedRes != nil { + _ = closedRes.Body.Close() + } require.Error(t, err) assert.Contains(t, err.Error(), "error submitting form") } diff --git a/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go index 68330784cdd..e58f89e6267 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/pinentry.go @@ -95,7 +95,7 @@ func (r *RealPinentryRunner) Run(command string) (output string, err error) { // 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") + 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 { @@ -117,7 +117,7 @@ func (r *RealPinentryRunner) Run(command string) (output string, err error) { } // ParseResults parses the standard output of the pinentry command and determine the -// user input, or wheter the program yielded any error +// 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() { @@ -127,13 +127,13 @@ func ParseResults(pinEntryOutput io.Reader) (output string, err error) { output = line[2:] } if strings.HasPrefix(line, "ERR ") { - return "", fmt.Errorf("Error while running pinentry: %s", line[4:]) + 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 "", fmt.Errorf("error while reading pinentry output: %w", scanErr) } return output, err diff --git a/pkg/auth/providers/aws/saml2aws/prompter/prompter.go b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go index 4f6fd93c60f..6326861b55e 100644 --- a/pkg/auth/providers/aws/saml2aws/prompter/prompter.go +++ b/pkg/auth/providers/aws/saml2aws/prompter/prompter.go @@ -42,7 +42,7 @@ func ValidateAndSetPrompter(prmptCfg string) error { return nil } - return fmt.Errorf("Prompter %s is not valid.", prmptCfg) + return fmt.Errorf("prompter %s is not valid", prmptCfg) } // RequestSecurityCode request a security code to be entered by the user diff --git a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go index 1c80314f608..1ed8fcbbf43 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go +++ b/pkg/auth/providers/aws/saml2aws/provider/adfs/adfs.go @@ -59,7 +59,7 @@ func New(idpAccount *cfg.IDPAccount) (*Client, error) { 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}, + 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)) diff --git a/pkg/auth/providers/aws/saml2aws/provider/base_validate.go b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go index e1a35aed46f..4c218a09dc3 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/base_validate.go +++ b/pkg/auth/providers/aws/saml2aws/provider/base_validate.go @@ -10,13 +10,13 @@ type ValidateBase struct{} func (ac *ValidateBase) Validate(ld *creds.LoginDetails) error { if ld.URL == "" { - return errors.New("Empty URL") + return errors.New("empty URL") } if ld.Username == "" { - return errors.New("Empty username") + return errors.New("empty username") } if ld.Password == "" { - return errors.New("Empty password") + return errors.New("empty password") } return nil } diff --git a/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go index 87e5093b98f..0e7c3bb351b 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go +++ b/pkg/auth/providers/aws/saml2aws/provider/browser/browser.go @@ -179,9 +179,10 @@ func (cl *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) // 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 - if cl.BrowserType == "firefox" { + switch cl.BrowserType { + case "firefox": browserType = pw.Firefox - } else if cl.BrowserType == "webkit" { + case "webkit": browserType = pw.WebKit } diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go index 05c76b28a27..0d79e1e00e4 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/googleapps.go @@ -252,6 +252,7 @@ func (kc *Client) iTermCaptchaPrompt(captchaPictureURL string) (string, error) { 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) @@ -312,6 +313,7 @@ func (kc *Client) loadFirstPage(loginDetails *creds.LoginDetails) (string, url.V 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 { @@ -346,6 +348,7 @@ func (kc *Client) loadLoginPage(submitURL string, referer string, authForm url.V 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 { @@ -382,6 +385,7 @@ func (kc *Client) loadChallengePage(submitURL string, referer string, authForm u 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 { @@ -583,6 +587,7 @@ func (kc *Client) loadAlternateChallengePage(submitURL string, referer string, a 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 { @@ -674,6 +679,7 @@ func (kc *Client) loadResponsePage(submitURL string, referer string, responseFor 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 { diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go index e6c6b5fe7fd..c26a0862473 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f.go @@ -46,7 +46,7 @@ func NewU2FClient(challengeNonce, appID, facet, keyHandle string, deviceFinder D for retryCount < maxOpenRetries { device, err = deviceFinder.findDevice() if err != nil { - if err == errNoDeviceFound { + if errors.Is(err, errNoDeviceFound) { return nil, err } @@ -64,13 +64,13 @@ func NewU2FClient(challengeNonce, appID, facet, keyHandle string, deviceFinder D }, nil } - return nil, fmt.Errorf("failed to create client: %s. exceeded max retries of %d", err, maxOpenRetries) + return nil, fmt.Errorf("failed to create client: %w. exceeded max retries of %d", err, maxOpenRetries) } // ChallengeU2F takes a U2FClient and returns a signed assertion to send to Google func (d *U2FClient) ChallengeU2F() (string, error) { if d.Device == nil { - return "", errors.New("No Device Found") + return "", errors.New("no device found") } // Atmos fork: the device is closed on every return, including an invalid challenge. defer d.Device.Close() @@ -98,7 +98,7 @@ func (d *U2FClient) ChallengeU2F() (string, error) { for { select { case <-timeout: - return "", errors.New("Failed to get authentication response after 25 seconds") + return "", errors.New("failed to get authentication response after 25 seconds") case <-interval.C: response, err := d.Device.Authenticate(request) if err == nil { @@ -110,8 +110,9 @@ func (d *U2FClient) ChallengeU2F() (string, error) { return string(responseJSON), nil } - switch err.(type) { - case *u2fhost.TestOfUserPresenceRequiredError: + var presenceErr *u2fhost.TestOfUserPresenceRequiredError + switch { + case errors.As(err, &presenceErr): if !prompted { log.Println("Touch the flashing U2F device to authenticate...") prompted = true @@ -143,7 +144,7 @@ func (*U2FDeviceFinder) findDevice() (u2fhost.Device, error) { return allDevices[i], nil } - return nil, fmt.Errorf("failed to open fido U2F device: %s", err) + return nil, fmt.Errorf("failed to open fido U2F device: %w", err) } // b64Safe re-encodes standard base64 data as unpadded URL-safe base64. diff --git a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f_test.go b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f_test.go index 85e6e5387fb..5beceeda60f 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/googleapps/u2f_test.go @@ -135,7 +135,7 @@ func TestNewU2FClient_DeviceDiscovery(t *testing.T) { func TestU2FClientChallengeU2F_Behavior(t *testing.T) { t.Run("missing device", func(t *testing.T) { _, err := (&U2FClient{}).ChallengeU2F() - assert.EqualError(t, err, "No Device Found") + assert.EqualError(t, err, "no device found") }) t.Run("waits for user presence then returns the JSON response", func(t *testing.T) { diff --git a/pkg/auth/providers/aws/saml2aws/provider/http.go b/pkg/auth/providers/aws/saml2aws/provider/http.go index 746577c1a8b..540ed34f20d 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http.go @@ -51,13 +51,12 @@ func NewDefaultTransport(skipVerify bool) *http.Transport { DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, - TLSClientConfig: &tls.Config{MinVersion: MinTLSVersion, InsecureSkipVerify: skipVerify}, + TLSClientConfig: &tls.Config{MinVersion: MinTLSVersion, InsecureSkipVerify: skipVerify}, //nolint:gosec // Skipping verification is an explicit, user-configured opt-in (skip_verify). } } @@ -164,7 +163,7 @@ func (hc *HTTPClient) doWithRetry(req *http.Request) (*http.Response, error) { } attempted = true hc.logHTTPRequest(req) - clientResp, err := hc.Client.Do(req) + clientResp, err := hc.Client.Do(req) //nolint:bodyclose // The response is returned to the caller, which closes the body. if err != nil { return err } @@ -180,7 +179,7 @@ func (hc *HTTPClient) doWithRetry(req *http.Request) (*http.Response, error) { func(n uint, err error) { logrus. WithField("Attempt #", n). - WithField("Caused by", fmt.Errorf("%v", err)). + WithField("Caused by", err). Debug("Retry") }), ) diff --git a/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go b/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go index f09f5b7ac83..40d106d7a2e 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http_attempts_test.go @@ -135,7 +135,10 @@ func TestClientDoWithRetry_StopsOnCancelledContext(t *testing.T) { require.NoError(t, err) start := time.Now() - _, err = hc.Do(req) + resp, err := hc.Do(req) + if resp != nil { + _ = resp.Body.Close() + } require.Error(t, err) assert.Less(t, time.Since(start), 10*time.Second) assert.Equal(t, int32(1), tr.calls.Load()) diff --git a/pkg/auth/providers/aws/saml2aws/provider/http_test.go b/pkg/auth/providers/aws/saml2aws/provider/http_test.go index 4a68b817910..f5925f66233 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/http_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/http_test.go @@ -38,6 +38,7 @@ func TestClientDoGetOK(t *testing.T) { res, err := hc.Do(req) require.Nil(t, err) + defer res.Body.Close() require.Equal(t, 200, res.StatusCode) } @@ -62,6 +63,7 @@ func TestClientDisableRedirect(t *testing.T) { res, err := hc.Do(req) require.Nil(t, err) + defer res.Body.Close() require.Equal(t, 302, res.StatusCode) } @@ -82,6 +84,7 @@ func TestClientDoResponseCheck(t *testing.T) { res, err := hc.Do(req) require.Error(t, err) + defer res.Body.Close() require.Equal(t, 400, res.StatusCode) // Regression: the rejected response's body is closed, since callers discard the response on error. @@ -242,7 +245,10 @@ func TestClientDoTransportErrorSkipsResponseCheck(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "http://example.invalid", nil) require.NoError(t, err) - _, err = hc.Do(req) + res, err := hc.Do(req) + if res != nil { + _ = res.Body.Close() + } require.Error(t, err) assert.ErrorIs(t, err, errTransport) assert.False(t, checked) diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go index d1e405461d1..8b62625d3b5 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go @@ -97,7 +97,7 @@ type Client struct { // AuthRequest represents an mfa okta request type AuthRequest struct { Username string `json:"username"` - Password string `json:"password"` + Password string `json:"password"` //nolint:gosec // Okta primary-auth request body requires the password field. StateToken string `json:"stateToken,omitempty"` } @@ -114,7 +114,7 @@ type VerifyRequest struct { // SessionRequst holds the SessionToken used to create an Okta Session type SessionRequst struct { - SessionToken string `json:"sessionToken"` + SessionToken string `json:"sessionToken"` //nolint:gosec // Okta session request body requires the sessionToken field. } // mfaChallengeContext is used to hold MFA challenge context in a simple struct. @@ -206,6 +206,7 @@ func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken s if err != nil { return "", "", errors.Wrap(err, "error retrieving session response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -228,7 +229,7 @@ func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken s err = credentials.SaveCredentials(loginDetails.URL+"/sessionCookie", loginDetails.Username, oktaSessionCookie) if err != nil { - return "", "", fmt.Errorf("error storing okta session token | err: %v", err) + return "", "", fmt.Errorf("error storing okta session token | err: %w", err) } oktaSessionToken := gjson.Get(resp, "sessionToken").String() @@ -283,6 +284,7 @@ func (oc *Client) validateSession(loginDetails *creds.LoginDetails) error { if err != nil { return errors.Wrap(err, "error retrieving session response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -344,6 +346,7 @@ func (oc *Client) authWithSession(loginDetails *creds.LoginDetails) (string, err return "", errors.Wrap(err, "error authing with session") } } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -377,6 +380,7 @@ func (oc *Client) getDeviceTokenFromOkta(loginDetails *creds.LoginDetails) (stri if err != nil { return "", errors.Wrap(err, "error retrieving device token") } + defer resp.Body.Close() for _, c := range resp.Cookies() { if c.Name == "DT" { // Device token @@ -408,7 +412,7 @@ func (oc *Client) setDeviceTokenCookie(loginDetails *creds.LoginDetails) error { baseURL := &url.URL{Scheme: oktaURLScheme, Host: oktaURLHost, Path: "/"} var cookies []*http.Cookie - cookie := http.Cookie{ + cookie := http.Cookie{ //nolint:gosec // HttpOnly and SameSite apply to Set-Cookie responses; this cookie only seeds the client jar and is Secure. Name: "DT", Secure: true, Expires: time.Now().Add(time.Hour * 24 * 30), // 30 Days -> this time might not matter as this cookie is set on every saml2aws login request @@ -454,6 +458,7 @@ func (oc *Client) primaryAuth(loginDetails *creds.LoginDetails) (string, string, if err != nil { return "", "", "", errors.Wrap(err, "error retrieving auth response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -557,6 +562,7 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c logger.Debug("ERROR FOLLOWING") return "", errors.Wrap(err, "error following") } + defer res.Body.Close() doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { logger.Debug("FAILED TO BUILD DOC FROM RESP") @@ -600,9 +606,9 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c } if handler == nil { - html, _ := doc.Selection.Html() + html, _ := doc.Html() logger.WithField("doc", html).Debug("Unknown document type") - return "", fmt.Errorf("Unknown document type") + return "", errors.New("unknown document type") } ctx, req, err = handler(ctx, doc) @@ -626,6 +632,7 @@ func (oc *Client) getStateToken(req *http.Request, loginDetails *creds.LoginDeta if err != nil { return "", errors.Wrap(err, "error retrieving app response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return "", errors.Wrap(err, "error retrieving body from response") @@ -648,7 +655,7 @@ func getStateTokenFromOktaPageBody(responseBody string) (string, error) { for _, re := range regexes { match := re.FindStringSubmatch(responseBody) if len(match) >= 2 { - return strings.Replace(match[1], `\x2D`, "-", -1), nil + return strings.ReplaceAll(match[1], `\x2D`, "-"), nil } } @@ -777,6 +784,7 @@ func getMfaChallengeContext(oc *Client, mfaOption int, resp string) (*mfaChallen if err != nil { return nil, errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -877,6 +885,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving token post response") } + defer res.Body.Close() return extractSessionToken(res.Body) @@ -956,7 +965,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, duoForm.Add("color_depth", "24") duoForm.Add("is_cef_browser", "false") duoForm.Add("is_ipad_os", "false") - duoForm.Add("is_ie_compatability_mode", "") + duoForm.Add("is_ie_compatability_mode", "") //nolint:misspell // Duo's actual (misspelled) form field name. duoForm.Add("acting_ie_version", "") duoForm.Add("react_support", "true") duoForm.Add("react_support_error_message", "") @@ -979,6 +988,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() // At this point, if device trust is enabled we need to go on that tangent doc, err := goquery.NewDocumentFromReader(res.Body) @@ -1086,6 +1096,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -1118,6 +1129,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1181,6 +1193,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1254,6 +1267,8 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } body, err = io.ReadAll(res.Body) + // Close inside the polling loop so bodies are not held until the function returns. + _ = res.Body.Close() if err != nil { return "", errors.Wrap(err, "error retrieving body from response") } @@ -1296,6 +1311,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving duo result response") } + defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1358,6 +1374,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1423,7 +1440,8 @@ func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallenge signedAssertion, err = fidoClient.ChallengeU2F() if err != nil { // if this error is not a bad key error we are done - if _, ok := err.(*u2fhost.BadKeyHandleError); !ok { + var badKeyErr *u2fhost.BadKeyHandleError + if !errors.As(err, &badKeyErr) { return "", errors.Wrap(err, "failed to perform U2F challenge") } @@ -1471,6 +1489,7 @@ func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallenge if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } + defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -1561,7 +1580,6 @@ func verifyTrustedCert(oc *Client, doc *goquery.Document, duoHost string, duoSub req.Header.Add("Referer", "https://"+duoHost+"/") res, err := newCertifierClient(oc.client, certifierUrl).Do(req) - if err != nil { // Local certifier not running, try online one duoCertURL := fmt.Sprintf("%s?sid=%s&certs_txid=%s&type=AJAX", certUrl, url.QueryEscape(sid), txid) diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_auth_flow_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_auth_flow_test.go index edea1965735..6fa77a5c55c 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_auth_flow_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_auth_flow_test.go @@ -402,7 +402,7 @@ func TestFollow(t *testing.T) { page: func(target string) string { return fmt.Sprintf(`
`, target) }, - wantErr: "Unknown document type", + wantErr: "unknown document type", }, { name: "page without forms or state token", diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f.go index 792af7274d0..9dcd9123616 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f.go @@ -36,12 +36,12 @@ func NewDUOU2FClient(challengeNonce, appID, version, keyHandle, stateToken strin for retryCount < MaxOpenRetries { device, err = deviceFinder.findDevice() if err != nil { - if err == errNoDeviceFound { + if errors.Is(err, errNoDeviceFound) { return nil, err } retryCount++ - time.Sleep(RetryDelayMS) + time.Sleep(RetryDelay) continue } @@ -55,13 +55,13 @@ func NewDUOU2FClient(challengeNonce, appID, version, keyHandle, stateToken strin }, nil } - return nil, fmt.Errorf("failed to create client: %s. exceeded max retries of %d", err, MaxOpenRetries) + return nil, fmt.Errorf("failed to create client: %w. exceeded max retries of %d", err, MaxOpenRetries) } // ChallengeU2F takes a FidoClient and returns a signed assertion to send to Okta func (d *DUOU2FClient) ChallengeU2F() (*ResponseData, error) { if d.Device == nil { - return nil, errors.New("No Device Found") + return nil, errors.New("no device found") } request := &u2fhost.AuthenticateRequest{ Challenge: d.ChallengeNonce, @@ -83,7 +83,7 @@ func (d *DUOU2FClient) ChallengeU2F() (*ResponseData, error) { for { select { case <-timeout: - return nil, errors.New("Failed to get authentication response after 25 seconds") + return nil, errors.New("failed to get authentication response after 25 seconds") case <-interval.C: response, err := d.Device.Authenticate(request) if err == nil { @@ -99,8 +99,9 @@ func (d *DUOU2FClient) ChallengeU2F() (*ResponseData, error) { return responsePayload, nil } - switch err.(type) { - case *u2fhost.TestOfUserPresenceRequiredError: + var presenceErr *u2fhost.TestOfUserPresenceRequiredError + switch { + case errors.As(err, &presenceErr): if !prompted { fmt.Fprintf(os.Stderr, "\nTouch the flashing U2F device to authenticate...\n") prompted = true diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_test.go index 3a728eaa66a..e743a2649f7 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_duo_u2f_test.go @@ -91,6 +91,6 @@ func TestNewDUOU2FClient_DeviceDiscovery(t *testing.T) { t.Run("missing device", func(t *testing.T) { client := &DUOU2FClient{} _, err := client.ChallengeU2F() - assert.EqualError(t, err, "No Device Found") + assert.EqualError(t, err, "no device found") }) } diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_helpers_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_helpers_test.go index 0be54e9e08f..87282d03561 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_helpers_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_helpers_test.go @@ -199,7 +199,7 @@ func offlineTestClient(t *testing.T) (*Client, *creds.LoginDetails) { t.Helper() tr := http.DefaultTransport.(*http.Transport).Clone() - tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // Test servers use self-signed certificates. + tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} opts := &provider.HTTPClientOptions{IsWithRetries: false} client, err := provider.NewHTTPClient(tr, opts) require.NoError(t, err) diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go index 87c965b546b..4b05a94e5c0 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_test.go @@ -440,7 +440,7 @@ func setupTestDuoHttpServer(t *testing.T, duoFactor string) *httptest.Server { "color_depth": {"24"}, "flash_version": {""}, "is_cef_browser": {"false"}, - "is_ie_compatability_mode": {""}, + "is_ie_compatability_mode": {""}, //nolint:misspell // Duo's actual (misspelled) form field name. "is_ipad_os": {"false"}, "java_version": {""}, "parent": {"https://host-from-argument/signin/verify/duo/web"}, @@ -588,10 +588,10 @@ func setupTestDuoHttpServer(t *testing.T, duoFactor string) *httptest.Server { var requestBody interface{} = nil err = json.Unmarshal(body, &requestBody) - assert.Equal(t, map[string]interface{}(map[string]interface{}{ + assert.Equal(t, map[string]interface{}{ "rememberDevice": "true", "stateToken": "TOKEN_1", - }), requestBody) + }, requestBody) assert.Nil(t, err) _, err = fmt.Fprintf(w, `{ @@ -631,10 +631,10 @@ func setupTestDuoHttpServer(t *testing.T, duoFactor string) *httptest.Server { var requestBody interface{} = nil err = json.Unmarshal(body, &requestBody) - assert.Equal(t, map[string]interface{}(map[string]interface{}{ + assert.Equal(t, map[string]interface{}{ "rememberDevice": "true", "stateToken": "TOKEN_1", - }), requestBody) + }, requestBody) assert.Nil(t, err) _, err = w.Write([]byte(`{ diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go index cda9e6f1459..d50e22314c1 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn.go @@ -13,7 +13,7 @@ import ( const ( MaxOpenRetries = 10 - RetryDelayMS = 200 * time.Millisecond + RetryDelay = 200 * time.Millisecond ) var errNoDeviceFound = fmt.Errorf("no U2F devices found. device might not be plugged in") @@ -55,12 +55,12 @@ func NewFidoClient(challengeNonce, appID, version, keyHandle, stateToken string, for retryCount < MaxOpenRetries { device, err = deviceFinder.findDevice() if err != nil { - if err == errNoDeviceFound { + if errors.Is(err, errNoDeviceFound) { return FidoClient{}, err } retryCount++ - time.Sleep(RetryDelayMS) + time.Sleep(RetryDelay) continue } @@ -74,13 +74,13 @@ func NewFidoClient(challengeNonce, appID, version, keyHandle, stateToken string, }, nil } - return FidoClient{}, fmt.Errorf("failed to create client: %s. exceeded max retries of %d", err, MaxOpenRetries) + return FidoClient{}, fmt.Errorf("failed to create client: %w. exceeded max retries of %d", err, MaxOpenRetries) } // ChallengeU2F takes a FidoClient and returns a signed assertion to send to Okta func (d *FidoClient) ChallengeU2F() (*SignedAssertion, error) { if d.Device == nil { - return nil, errors.New("No Device Found") + return nil, errors.New("no device found") } request := &u2fhost.AuthenticateRequest{ Challenge: d.ChallengeNonce, @@ -102,7 +102,7 @@ func (d *FidoClient) ChallengeU2F() (*SignedAssertion, error) { for { select { case <-timeout: - return nil, errors.New("Failed to get authentication response after 25 seconds") + return nil, errors.New("failed to get authentication response after 25 seconds") case <-interval.C: response, err := d.Device.Authenticate(request) if err == nil { @@ -116,8 +116,9 @@ func (d *FidoClient) ChallengeU2F() (*SignedAssertion, error) { return responsePayload, nil } - switch err.(type) { - case *u2fhost.TestOfUserPresenceRequiredError: + var presenceErr *u2fhost.TestOfUserPresenceRequiredError + switch { + case errors.As(err, &presenceErr): if !prompted { log.Println("Touch the flashing U2F device to authenticate...") prompted = true @@ -155,7 +156,7 @@ func (*U2FDeviceFinder) findDevice() (u2fhost.Device, error) { return allDevices[i], nil } - return nil, fmt.Errorf("failed to open fido U2F device: %s", err) + return nil, fmt.Errorf("failed to open fido U2F device: %w", err) } // ChallengeSystemWebAuthn challenges the system level WebAuthn API (e.g. Windows Hello) and diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn_test.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn_test.go index 1b8b19db534..e1710ac6fd1 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn_test.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta_webauthn_test.go @@ -130,7 +130,7 @@ func TestFidoClientChallengeU2F_Behavior(t *testing.T) { t.Run("missing device", func(t *testing.T) { client := &FidoClient{} _, err := client.ChallengeU2F() - assert.EqualError(t, err, "No Device Found") + assert.EqualError(t, err, "no device found") }) t.Run("waits for user presence and HID errors before succeeding", func(t *testing.T) { diff --git a/pkg/auth/providers/aws/saml_browser_autodownload_test.go b/pkg/auth/providers/aws/saml_browser_autodownload_test.go index 5e083f85c3f..5bbb83e5eaa 100644 --- a/pkg/auth/providers/aws/saml_browser_autodownload_test.go +++ b/pkg/auth/providers/aws/saml_browser_autodownload_test.go @@ -12,9 +12,9 @@ import ( ) const ( - // legacyAutoDownloadEnv is the saml2aws CLI variable that Atmos used to set. Nothing reads it. + // Legacy saml2aws CLI variable that Atmos used to set. Nothing reads it. legacyAutoDownloadEnv = "SAML2AWS_AUTO_BROWSER_DOWNLOAD" - // testHostPlatform is the Playwright host platform the browser download tests pin. + // Playwright host platform the browser download tests pin. testHostPlatform = "mac14-arm64" ) @@ -127,7 +127,7 @@ func TestShouldDownloadBrowser_ExecutablePathNeverDownloads(t *testing.T) { } // Regression: SAML2AWS_AUTO_BROWSER_DOWNLOAD is only read by the saml2aws CLI, which Atmos does not -// use. setupBrowserAutomation used to set and unset it process-wide, clobbering a value the user +// use. The setupBrowserAutomation function used to set and unset it process-wide, clobbering a value the user // exported, although nothing read it. func TestSetupBrowserAutomation_LeavesLegacyAutoDownloadEnvAlone(t *testing.T) { for _, download := range []bool{true, false} { diff --git a/pkg/auth/providers/aws/saml_browser_platform.go b/pkg/auth/providers/aws/saml_browser_platform.go index e151fa57063..bf01ca724ca 100644 --- a/pkg/auth/providers/aws/saml_browser_platform.go +++ b/pkg/auth/providers/aws/saml_browser_platform.go @@ -1,6 +1,7 @@ package aws import ( + "fmt" "os" "runtime" "strconv" @@ -8,14 +9,34 @@ import ( ) const ( - // playwrightHostPlatformOverrideEnv overrides the host platform the Playwright driver detects. + // Environment variable that overrides the host platform the Playwright driver detects. playwrightHostPlatformOverrideEnv = "PLAYWRIGHT_HOST_PLATFORM_OVERRIDE" - // linuxOSReleasePath is the file the Playwright driver reads the Linux distribution from. + // Path of the file the Playwright driver reads the Linux distribution from. linuxOSReleasePath = "/etc/os-release" - // playwrightLastStableMacOSMajor is LAST_STABLE_MACOS_MAJOR_VERSION in playwright-core 1.64. + // LAST_STABLE_MACOS_MAJOR_VERSION in playwright-core 1.64. playwrightLastStableMacOSMajor = 26 - // playwrightUbuntuDefault is the platform Playwright falls back to on an unrecognized Linux distribution. + // Platform Playwright falls back to on an unrecognized Linux distribution. playwrightUbuntuDefault = "ubuntu24.04" + + // Darwin kernel major versions at which the macOS version mapping changes. + darwinMajorMojave = 18 // macOS 10.14. + darwinMajorCatalina = 19 // macOS 10.15. + darwinMajorBigSur = 20 // macOS 11, the first release with Apple Silicon. + darwinMajorTahoe = 25 // macOS 26, where macOS versions follow Darwin major + 1. + // First macOS major version number that follows the 10.x series. + macOSBigSurMajor = 11 + + // Ubuntu LTS releases Playwright publishes builds for, and the number of Ubuntu major versions each covers. + ubuntuFirstLTS = 18 + ubuntuLastLTS = 26 + ubuntuLTSSpan = 2 + + // Linux Mint major versions that map to an Ubuntu LTS. + linuxMintMajorFocal = 20 // Based on Ubuntu 20.04. + linuxMintMajorJammy = 21 // Based on Ubuntu 22.04. + + // Dash separating name parts, for example a platform name and its architecture suffix. + dashSeparator = "-" ) // darwinHostInfo returns the Darwin kernel release (os.release() in Node.js) and the CPU brand. @@ -61,25 +82,27 @@ func macHostPlatform(kernelRelease, cpuBrand string) string { return "" } - var version string - switch { - case major < 18: - version = "10.13" - case major == 18: - version = "10.14" - case major == 19: - version = "10.15" - case major < 25: - version = strconv.Itoa(11 + major - 20) - default: - version = strconv.Itoa(min(major+1, playwrightLastStableMacOSMajor)) + platform := "mac" + macVersionForDarwinMajor(major) + if major >= darwinMajorBigSur && strings.Contains(cpuBrand, "Apple") { + platform += dashSeparator + "arm64" } + return platform +} - platform := "mac" + version - if major >= 20 && strings.Contains(cpuBrand, "Apple") { - platform += "-arm64" +// macVersionForDarwinMajor maps a Darwin kernel major version to the macOS version Playwright uses. +func macVersionForDarwinMajor(major int) string { + switch { + case major < darwinMajorMojave: + return "10.13" + case major == darwinMajorMojave: + return "10.14" + case major == darwinMajorCatalina: + return "10.15" + case major < darwinMajorTahoe: + return strconv.Itoa(macOSBigSurMajor + major - darwinMajorBigSur) + default: + return strconv.Itoa(min(major+1, playwrightLastStableMacOSMajor)) } - return platform } // linuxHostPlatform returns the Playwright Linux platform for a Go architecture and the contents of /etc/os-release. @@ -93,7 +116,7 @@ func linuxHostPlatform(goarch, osRelease string) string { default: return "" } - suffix := "-" + arch + suffix := dashSeparator + arch fields := parseOSRelease(osRelease) id, version := fields["id"], fields["version_id"] @@ -103,43 +126,49 @@ func linuxHostPlatform(goarch, osRelease string) string { case "ubuntu", "pop", "neon", "tuxedo": return ubuntuHostPlatform(version, major, majorOK) + suffix case "linuxmint": - switch { - case majorOK && major <= 20: - return "ubuntu20.04" + suffix - case majorOK && major == 21: - return "ubuntu22.04" + suffix - default: - return playwrightUbuntuDefault + suffix - } + return mintHostPlatform(major, majorOK) + suffix case "debian", "raspbian": - switch version { - case "11", "12", "13": - return "debian" + version + suffix - case "": - // Debian testing and unstable have no VERSION_ID; Playwright uses the latest release. - return "debian13" + suffix - } + return debianHostPlatform(version) + suffix } return playwrightUbuntuDefault + suffix } -// ubuntuHostPlatform maps an Ubuntu-based VERSION_ID to the Ubuntu LTS platform Playwright uses. -// Like JavaScript's parseInt, a version without a leading number matches no range. -func ubuntuHostPlatform(version string, major int, majorOK bool) string { +// mintHostPlatform maps a Linux Mint major version to the Ubuntu platform Playwright uses. +func mintHostPlatform(major int, majorOK bool) string { switch { - case majorOK && major < 20: - return "ubuntu18.04" - case majorOK && major < 22: + case majorOK && major <= linuxMintMajorFocal: return "ubuntu20.04" - case majorOK && major < 24: + case majorOK && major == linuxMintMajorJammy: return "ubuntu22.04" - case majorOK && major < 26: - return "ubuntu24.04" - case majorOK && major < 28: - return "ubuntu26.04" default: - return "ubuntu" + version + return playwrightUbuntuDefault + } +} + +// debianHostPlatform maps a Debian VERSION_ID to the Playwright platform, falling back to the Ubuntu default. +func debianHostPlatform(version string) string { + switch version { + case "11", "12", "13": + return "debian" + version + case "": + // Debian testing and unstable have no VERSION_ID; Playwright uses the latest release. + return "debian13" + default: + return playwrightUbuntuDefault + } +} + +// ubuntuHostPlatform maps an Ubuntu-based VERSION_ID to the Ubuntu LTS platform Playwright uses. +// Like JavaScript's parseInt, a version without a leading number matches no range. +func ubuntuHostPlatform(version string, major int, majorOK bool) string { + if majorOK { + for lts := ubuntuFirstLTS; lts <= ubuntuLastLTS; lts += ubuntuLTSSpan { + if major < lts+ubuntuLTSSpan { + return fmt.Sprintf("ubuntu%d.04", lts) + } + } } + return "ubuntu" + version } // parseOSRelease parses /etc/os-release the way playwright-core does: lower-cased keys, values diff --git a/pkg/auth/providers/aws/saml_browser_revision.go b/pkg/auth/providers/aws/saml_browser_revision.go index cd8ac2470c8..fd9cd3f734d 100644 --- a/pkg/auth/providers/aws/saml_browser_revision.go +++ b/pkg/auth/providers/aws/saml_browser_revision.go @@ -16,18 +16,18 @@ import ( ) const ( - // chromiumBrowserName is the Chromium entry name in Playwright's browsers.json. + // Chromium entry name in Playwright's browsers.json. chromiumBrowserName = "chromium" - // firefoxBrowserName is the Firefox entry name in Playwright's browsers.json. + // Firefox entry name in Playwright's browsers.json. firefoxBrowserName = "firefox" - // webkitBrowserName is the WebKit entry name in Playwright's browsers.json. + // WebKit entry name in Playwright's browsers.json. webkitBrowserName = "webkit" - // playwrightBrowserManifest is the browser manifest shipped in the playwright-core package. + // Browser manifest shipped in the playwright-core package. playwrightBrowserManifest = "browsers.json" - // playwrightInstallMarker is the file Playwright writes into a browser directory once the + // File Playwright writes into a browser directory once the // browser is fully extracted. A directory without it is a partial download. playwrightInstallMarker = "INSTALLATION_COMPLETE" - // playwrightLocalBrowsers is the in-package browser directory used when PLAYWRIGHT_BROWSERS_PATH=0. + // In-package browser directory used when PLAYWRIGHT_BROWSERS_PATH=0. playwrightLocalBrowsers = ".local-browsers" ) @@ -43,7 +43,7 @@ var requiredBrowserDir = func(browserName string) (string, error) { } // playwrightManifestPath returns the browsers.json path of the Playwright driver. -// playwright-core keeps browsers.json next to cli.js, so an external PLAYWRIGHT_CLI_PATH +// The playwright-core package keeps browsers.json next to cli.js, so an external PLAYWRIGHT_CLI_PATH // (for example a distro-packaged driver) also moves the manifest. func playwrightManifestPath(driverDir string) string { if cliPath := os.Getenv("PLAYWRIGHT_CLI_PATH"); cliPath != "" { //nolint:forbidigo // Third-party (playwright-go) env var, read the same way the library reads it. @@ -81,10 +81,10 @@ func readBrowserDir(manifestPath, browserName, hostPlatform string) (string, err } if override := browser.RevisionOverrides[hostPlatform]; hostPlatform != "" && override != "" { prefix := browser.Name + "_" + hostPlatform + "_special" - return strings.ReplaceAll(prefix, "-", "_") + "-" + override, nil + return strings.ReplaceAll(prefix, dashSeparator, "_") + dashSeparator + override, nil } if browser.Revision != "" { - return strings.ReplaceAll(browser.Name, "-", "_") + "-" + browser.Revision, nil + return strings.ReplaceAll(browser.Name, dashSeparator, "_") + dashSeparator + browser.Revision, nil } } diff --git a/pkg/auth/providers/aws/saml_driver_preseed.go b/pkg/auth/providers/aws/saml_driver_preseed.go index 486761c1197..d322fb5d516 100644 --- a/pkg/auth/providers/aws/saml_driver_preseed.go +++ b/pkg/auth/providers/aws/saml_driver_preseed.go @@ -37,7 +37,7 @@ import ( // playwright-go's isUpToDateDriver() check passes and its dead download path // never runs — for Atmos's own install call and for the vendored saml2aws browser provider. // -// playwright-go v0.6401+ downloads from the same npm and nodejs.org sources itself, +// The playwright-go v0.6401+ releases download from the same npm and nodejs.org sources itself, // but does not verify what it downloads. The pre-seed is kept because it checks the // npm tarball's sha512 integrity before extracting it. const ( diff --git a/pkg/auth/providers/aws/sso_token_flow_test.go b/pkg/auth/providers/aws/sso_token_flow_test.go index 364136d2e8b..cee536512e8 100644 --- a/pkg/auth/providers/aws/sso_token_flow_test.go +++ b/pkg/auth/providers/aws/sso_token_flow_test.go @@ -113,17 +113,22 @@ var ( } ) -func tokenReply(accessToken, refreshToken string, expiresIn int) fakeOIDCResponse { +// tokenReplyExpiresIn is the token lifetime, in seconds, that every fake token reply reports. +const tokenReplyExpiresIn = 3600 + +func tokenReply(accessToken, refreshToken string) fakeOIDCResponse { body, _ := json.Marshal(map[string]any{ "accessToken": accessToken, "refreshToken": refreshToken, - "expiresIn": expiresIn, + "expiresIn": tokenReplyExpiresIn, "tokenType": "Bearer", }) return fakeOIDCResponse{status: http.StatusOK, body: string(body)} } func TestPollForAccessToken(t *testing.T) { + t.Parallel() + tests := []struct { name string responses []fakeOIDCResponse @@ -135,7 +140,7 @@ func TestPollForAccessToken(t *testing.T) { }{ { name: "token issued on first poll", - responses: []fakeOIDCResponse{tokenReply("access-1", "refresh-1", 3600)}, + responses: []fakeOIDCResponse{tokenReply("access-1", "refresh-1")}, expiresIn: 600, wantCalls: 1, wantAccess: "access-1", @@ -143,7 +148,7 @@ func TestPollForAccessToken(t *testing.T) { }, { name: "authorization pending is retried until the user approves", - responses: []fakeOIDCResponse{pendingReply, tokenReply("access-2", "", 3600)}, + responses: []fakeOIDCResponse{pendingReply, tokenReply("access-2", "")}, expiresIn: 600, wantCalls: 2, wantAccess: "access-2", @@ -151,7 +156,7 @@ func TestPollForAccessToken(t *testing.T) { }, { name: "terminal OIDC error stops polling", - responses: []fakeOIDCResponse{accessDeniedReply, tokenReply("never", "", 3600)}, + responses: []fakeOIDCResponse{accessDeniedReply, tokenReply("never", "")}, expiresIn: 600, wantCalls: 1, wantErrSubstr: "Failed to create AWS SSO access token", @@ -223,7 +228,7 @@ func newRefreshTestProvider(t *testing.T, endpoint string) *ssoProvider { } func TestSSOProviderAuthenticate_RefreshesExpiredTokenWithoutBrowser(t *testing.T) { - srv := newFakeOIDCServer(t, tokenReply("new-access", "rotated-refresh", 3600)) + srv := newFakeOIDCServer(t, tokenReply("new-access", "rotated-refresh")) p := newRefreshTestProvider(t, srv.URL) registrationExpiry := time.Now().Add(24 * time.Hour).UTC().Truncate(time.Second) From cce79090da05f5ed57b9c9bcf8d5f4752abbafa2 Mon Sep 17 00:00:00 2001 From: "atmos-pro[bot]" <173522224+atmos-pro[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:24:07 +0000 Subject: [PATCH 7/7] [autocommit] formatting fixes --- .../aws/saml2aws/provider/okta/okta.go | 37 +++++-------------- 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go index 8b62625d3b5..9341c1d408a 100644 --- a/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go +++ b/pkg/auth/providers/aws/saml2aws/provider/okta/okta.go @@ -97,7 +97,7 @@ type Client struct { // AuthRequest represents an mfa okta request type AuthRequest struct { Username string `json:"username"` - Password string `json:"password"` //nolint:gosec // Okta primary-auth request body requires the password field. + Password string `json:"password"` StateToken string `json:"stateToken,omitempty"` } @@ -114,7 +114,7 @@ type VerifyRequest struct { // SessionRequst holds the SessionToken used to create an Okta Session type SessionRequst struct { - SessionToken string `json:"sessionToken"` //nolint:gosec // Okta session request body requires the sessionToken field. + SessionToken string `json:"sessionToken"` } // mfaChallengeContext is used to hold MFA challenge context in a simple struct. @@ -206,7 +206,6 @@ func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken s if err != nil { return "", "", errors.Wrap(err, "error retrieving session response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -229,7 +228,7 @@ func (oc *Client) createSession(loginDetails *creds.LoginDetails, sessionToken s err = credentials.SaveCredentials(loginDetails.URL+"/sessionCookie", loginDetails.Username, oktaSessionCookie) if err != nil { - return "", "", fmt.Errorf("error storing okta session token | err: %w", err) + return "", "", fmt.Errorf("error storing okta session token | err: %v", err) } oktaSessionToken := gjson.Get(resp, "sessionToken").String() @@ -284,7 +283,6 @@ func (oc *Client) validateSession(loginDetails *creds.LoginDetails) error { if err != nil { return errors.Wrap(err, "error retrieving session response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -346,7 +344,6 @@ func (oc *Client) authWithSession(loginDetails *creds.LoginDetails) (string, err return "", errors.Wrap(err, "error authing with session") } } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -380,7 +377,6 @@ func (oc *Client) getDeviceTokenFromOkta(loginDetails *creds.LoginDetails) (stri if err != nil { return "", errors.Wrap(err, "error retrieving device token") } - defer resp.Body.Close() for _, c := range resp.Cookies() { if c.Name == "DT" { // Device token @@ -412,7 +408,7 @@ func (oc *Client) setDeviceTokenCookie(loginDetails *creds.LoginDetails) error { baseURL := &url.URL{Scheme: oktaURLScheme, Host: oktaURLHost, Path: "/"} var cookies []*http.Cookie - cookie := http.Cookie{ //nolint:gosec // HttpOnly and SameSite apply to Set-Cookie responses; this cookie only seeds the client jar and is Secure. + cookie := http.Cookie{ Name: "DT", Secure: true, Expires: time.Now().Add(time.Hour * 24 * 30), // 30 Days -> this time might not matter as this cookie is set on every saml2aws login request @@ -458,7 +454,6 @@ func (oc *Client) primaryAuth(loginDetails *creds.LoginDetails) (string, string, if err != nil { return "", "", "", errors.Wrap(err, "error retrieving auth response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -562,7 +557,6 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c logger.Debug("ERROR FOLLOWING") return "", errors.Wrap(err, "error following") } - defer res.Body.Close() doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { logger.Debug("FAILED TO BUILD DOC FROM RESP") @@ -606,9 +600,9 @@ func (oc *Client) follow(ctx context.Context, req *http.Request, loginDetails *c } if handler == nil { - html, _ := doc.Html() + html, _ := doc.Selection.Html() logger.WithField("doc", html).Debug("Unknown document type") - return "", errors.New("unknown document type") + return "", fmt.Errorf("Unknown document type") } ctx, req, err = handler(ctx, doc) @@ -632,7 +626,6 @@ func (oc *Client) getStateToken(req *http.Request, loginDetails *creds.LoginDeta if err != nil { return "", errors.Wrap(err, "error retrieving app response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return "", errors.Wrap(err, "error retrieving body from response") @@ -655,7 +648,7 @@ func getStateTokenFromOktaPageBody(responseBody string) (string, error) { for _, re := range regexes { match := re.FindStringSubmatch(responseBody) if len(match) >= 2 { - return strings.ReplaceAll(match[1], `\x2D`, "-"), nil + return strings.Replace(match[1], `\x2D`, "-", -1), nil } } @@ -784,7 +777,6 @@ func getMfaChallengeContext(oc *Client, mfaOption int, resp string) (*mfaChallen if err != nil { return nil, errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -885,7 +877,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving token post response") } - defer res.Body.Close() return extractSessionToken(res.Body) @@ -965,7 +956,7 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, duoForm.Add("color_depth", "24") duoForm.Add("is_cef_browser", "false") duoForm.Add("is_ipad_os", "false") - duoForm.Add("is_ie_compatability_mode", "") //nolint:misspell // Duo's actual (misspelled) form field name. + duoForm.Add("is_ie_compatability_mode", "") duoForm.Add("acting_ie_version", "") duoForm.Add("react_support", "true") duoForm.Add("react_support_error_message", "") @@ -988,7 +979,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() // At this point, if device trust is enabled we need to go on that tangent doc, err := goquery.NewDocumentFromReader(res.Body) @@ -1096,7 +1086,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { @@ -1129,7 +1118,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1193,7 +1181,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1267,8 +1254,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, } body, err = io.ReadAll(res.Body) - // Close inside the polling loop so bodies are not held until the function returns. - _ = res.Body.Close() if err != nil { return "", errors.Wrap(err, "error retrieving body from response") } @@ -1311,7 +1296,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving duo result response") } - defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1374,7 +1358,6 @@ func verifyMfa(oc *Client, oktaOrgHost string, loginDetails *creds.LoginDetails, if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { @@ -1440,8 +1423,7 @@ func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallenge signedAssertion, err = fidoClient.ChallengeU2F() if err != nil { // if this error is not a bad key error we are done - var badKeyErr *u2fhost.BadKeyHandleError - if !errors.As(err, &badKeyErr) { + if _, ok := err.(*u2fhost.BadKeyHandleError); !ok { return "", errors.Wrap(err, "failed to perform U2F challenge") } @@ -1489,7 +1471,6 @@ func fidoWebAuthn(oc *Client, oktaOrgHost string, challengeContext *mfaChallenge if err != nil { return "", errors.Wrap(err, "error retrieving verify response") } - defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil {