diff --git a/AGENTS.md b/AGENTS.md index b97817e5..3cea13fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ Common commands (run from repo root): - Fork-and-pull for external contributors; public contributions, issues, and comments are welcome. - PR title doubles as the squash-merge commit subject (see recent `main` history for the prevailing style: short hyphenated slug, optional `(#NNN)` appended on merge). -- Keep PRs focused; include a brief summary and a test plan (robot scenario added/modified, or a justification when not applicable). +- Keep PRs focused; please see the [informal convention document](/docs/developer/expected_commit_message.md). - All required checks (build, lint, robot) must be green before merge. ## Security & Configuration Tips diff --git a/docs/auth.md b/docs/auth.md index 28223155..5d7a5a9e 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -141,6 +141,72 @@ source cicd/vol/vendor-secrets/foreign_to_stackql_user.sh stackql --auth '{"aws":{"type":"aws_assume_role","keyIDenvvar":"AWS_ACCESS_KEY_ID","credentialsenvvar":"AWS_SECRET_ACCESS_KEY","aws_role_arn":"'"${STACKQL_AUDIT_ROLE_ARN}"'"}}' shell ``` +## AWS IAM Identity Center walkthrough + +Use a StackQL build with native Identity Center support and an AWS permission set that +allows `ec2:DescribeVpcs` in the account you want to query. StackQL handles the device +flow and signs requests with the temporary role credentials. The AWS CLI is optional. + +1. Configure a named profile in `~/.aws/config` or the file selected by + `AWS_CONFIG_FILE`. Replace the example account, permission set role, portal URL, and + Identity Center region with the values provided by your AWS administrator. + + ```ini + [profile engineering] + sso_session = company + sso_account_id = 123456789012 + sso_role_name = ReadOnlyAccess + [sso-session company] + sso_start_url = https://example.awsapps.com/start + sso_region = us-east-1 + sso_registration_scopes = sso:account:access + ``` + +2. Start StackQL with the profile selection. Clearing shell credentials for this command + lets the shared-config profile supply the credentials. Use a profile name with no static + keys in the shared credentials file and no `credential_process`. + + ```sh + env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY -u AWS_SESSION_TOKEN \ + stackql shell --preview='{"unstable":true}' \ + --auth='{"aws":{"type":"aws_identity_center","aws_profile":"engineering"}}' + ``` + +3. If the AWS provider is missing, install it from the StackQL registry. Start the login + in the same shell. + + ```sql + REGISTRY PULL aws v26.08.00444; + AUTH LOGIN aws INTERACTIVE; + ``` + + Open the verification URL printed by StackQL, enter the displayed code, and approve + the request in the browser. Return to StackQL after the browser confirms sign-in. + +4. List VPCs with a read-only query. Set the query region to the region containing + your VPCs. The query region is independent of `sso_region`. + + ```sql + SELECT VpcId + FROM stackql_unstable_aws.ec2.vpcs + WHERE region = 'ap-southeast-2'; + ``` + + StackQL saves the login in the private `aws-sso` directory under `--approot`. + With the same app root and AWS configuration, a new shell can reuse or refresh + the login automatically. Keep the app root on a private local filesystem. + If a second profile + references the same `sso_session`, select it with + `SET "$.auth.aws.aws_profile" = 'another-profile';` and rerun the query. A profile + referencing a different SSO session needs its own `AUTH LOGIN`. + +5. Run `AUTH REVOKE aws;` to delete the saved StackQL login. Trying the query again + returns a sign-in-required error. The next login may reuse your browser's AWS session. + +The [Identity Center Robot suite](../test/robot/functional/stackql_identity_center.robot) +runs without the AWS CLI and verifies the login prompts, account and role selection, +credential reuse and refresh, and SigV4 requests. + ## Native workload federation This configuration requires a StackQL build that includes Omni's workload federation support. diff --git a/docs/developer/expected_commit_message.md b/docs/developer/expected_commit_message.md new file mode 100644 index 00000000..28876215 --- /dev/null +++ b/docs/developer/expected_commit_message.md @@ -0,0 +1,17 @@ + +## Expected commmit message + + +On very top line, a short string hyphen worded. Eg `iac-and-rollback` + +Then a blank line. + +Then a line only `Summary:` + +Then a blank line. + +Then, bullet points **with no indentation, briefly describing aspects of the branch as it related to changes vs target branch. This is predicated in the assumption that all local branches have amerge target remote branch. Eg line item: `- Support for SAGA rollback based on naive assumptions, intractible actions detected ahead of time.`. + +Then, for each `robot` test added, "- Added `robot` test ``. + + diff --git a/docs/developer_guide.md b/docs/developer_guide.md index 87b316dd..d3b0b78e 100644 --- a/docs/developer_guide.md +++ b/docs/developer_guide.md @@ -19,9 +19,9 @@ The short of things is that for basic build and unit testing, these are needed: Then, each of these should be run from the repository root: - - Get required `go` libs: `go get ./...`. - - Run unit tests: `python cicd/python/build.py --test`. - - Build the application: `python cicd/python/build.py --build` (this will generate an executable at `./build/stackql`). +- Get required `go` libs: `go get ./...`. +- Run unit tests: `python cicd/python/build.py --test`. +- Build the application: `python cicd/python/build.py --build` (this will generate an executable at `./build/stackql`). If you want to include decent versioning then `patchVersion=282 && source ./cicd/version.txt && BUILDMAJORVERSION="$MajorVersion" BUILDMINORVERSION="$MinorVersion" BUILDPATCHVERSION="$patchVersion" BUILDCOMMITSHA="$(git rev-parse HEAD)" python ./cicd/python/build.py --build`. You can check with `./build/stackql --version`. For serious development, simulated integration tests are essential. So, there are more dependencies: diff --git a/docs/omni-aws-identity-center.md b/docs/omni-aws-identity-center.md new file mode 100644 index 00000000..78219c38 --- /dev/null +++ b/docs/omni-aws-identity-center.md @@ -0,0 +1,40 @@ + +# Native AWS IAM Identity Center SSO in Omni + +## Goal + +Let a StackQL user select an AWS IAM Identity Center profile, approve a browser sign-in, and query AWS with the assigned role. Implement the SSO path in Omni using Go's HTTP and JSON libraries and the existing SigV4 signer. The acceptance environment should run without an AWS CLI executable or a new AWS SDK dependency. + +## Omni implementation + +1. **Resolve the profile.** Extend the AWS shared-config loader to resolve a named profile's `sso_session`, `sso_account_id`, and `sso_role_name`, and read `sso_start_url` and `sso_region` from its referenced `[sso-session ...]` section. Respect the existing profile selection and `AWS_CONFIG_FILE` behavior. Keep current explicit key, environment credential, static profile, and `credential_process` behavior compatible. Treat legacy inline SSO profiles as out of scope for the first implementation and return an actionable error for them. +2. **Start an explicit login.** Implement the device authorization flow using `RegisterClient`, `StartDeviceAuthorization`, and `CreateToken`. Return the verification URL and user code to the caller. Poll at the server-provided interval, handle `authorization_pending` and `slow_down`, and stop on denial, expiry, or caller cancellation. Resolve the regional endpoints from the SSO region and support test endpoint injection. +3. **Resolve role credentials.** Call `GetRoleCredentials` with the access token and the configured account and role. Pass the returned access key, secret key, and session token to the existing SigV4 signer. Keep the Identity Center region independent of the AWS service region used by the query. +4. **Manage expiry.** Track the OIDC client registration, SSO tokens, and role credentials with their separate expirations. Refresh role credentials before expiry using the current SSO token, and refresh that token when needed and supported. Serialize concurrent refreshes for the same credential scope. Scope cached role credentials by login session, account, and role. Use session-scoped storage for the first implementation. Return a sign-in-required error when the session cannot be refreshed. Keep credentials and tokens out of errors and logs. + +StackQL should expose the explicit device flow through its interactive auth entry point, display the verification URL and code, and use the resulting session for later queries. A query that needs sign-in should return an actionable error without initiating a device flow. Omni owns AWS protocol behavior and StackQL owns terminal interaction. + +## Mocked StackQL Robot coverage + +Use local mock endpoints for Identity Center OIDC, the Identity Center portal, and an AWS API such as EC2. Supply a temporary AWS config, clear competing AWS credential variables, and run with the AWS CLI unavailable. Drive StackQL through its normal login and query entry points. Record calls at the mocks and verify the SigV4 signature with fixture credentials, including the expected session token. + +| Scenario | Mock setup and expected result | +| --- | --- | +| Native device login authorizes a query | Return a verification URL and code, then `authorization_pending` followed by a token. Check the login output, account and role sent to the portal, bearer token on the portal request, and signed EC2 request. Use distinct SSO and EC2 regions. | +| A query before login requires sign-in | Load a valid SSO profile with no session. Assert an actionable error and zero OIDC, portal, and EC2 calls. | +| Repeated queries reuse valid credentials | Run two statements after one login. Assert one device login and one role credential exchange. | +| Expiring role credentials are renewed | Return role credentials with a controlled expiry. Assert the next query is signed with the renewed fixture credentials and that the valid SSO token was reused. | +| An expired SSO token refreshes | Supply a refresh token, expire the access token, and require a new role credential exchange. Assert the refresh grant is used, the portal receives the new token, and no new device login occurs. | +| Rejected or expired device authorization stops login | Return a terminal device-flow error. Assert login fails and the portal and EC2 mocks receive no calls. | +| Expired session with a rejected refresh requires sign-in | Reject the refresh grant after successful login. Assert the query reports that sign-in is required and sends no EC2 request. | +| Portal denies access to the configured role | Issue an SSO token, then return a portal access error. Assert the query fails before reaching EC2. | +| Changing profiles uses the selected account and role | Configure two profiles with different account or role values. Assert each exchange uses the selected values and each query uses its own role credentials. | + +Use Omni unit tests with a controllable clock for polling intervals, `slow_down`, cancellation, expiry boundaries, and concurrent refresh. Cover malformed profiles and credential-source precedence there as well. For Robot expiry scenarios, use deterministic fixture expirations or a controllable clock. Keep SQL inline in each Robot scenario. + +## AWS references + +- [RegisterClient](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_RegisterClient.html) +- [StartDeviceAuthorization](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_StartDeviceAuthorization.html) +- [CreateToken](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) +- [GetRoleCredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) diff --git a/go.mod b/go.mod index 5b2647d9..2bf98b43 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.10.1 - github.com/stackql-labs/omnisdk v0.1.15-beta01 + github.com/stackql-labs/omnisdk v0.1.15-beta03 github.com/stackql/go-suffix-map v0.0.1-alpha02 github.com/stackql/psql-wire v0.1.2-beta02 github.com/stackql/stackql-parser v0.0.17-alpha05 diff --git a/go.sum b/go.sum index b322eb28..fded3a66 100644 --- a/go.sum +++ b/go.sum @@ -327,8 +327,8 @@ github.com/spf13/viper v1.10.1 h1:nuJZuYpG7gTj/XqiUwg8bA0cp1+M2mC3J4g5luUYBKk= github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU= github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= -github.com/stackql-labs/omnisdk v0.1.15-beta01 h1:1Jf1+KyNQhQKU7nwkCuUmTeWN5P8Gf6IsIh2uJcMDLo= -github.com/stackql-labs/omnisdk v0.1.15-beta01/go.mod h1:PFwcN2mZrrtwpRTc361IVbQ0FME4OIbKK7B51Z+mDrE= +github.com/stackql-labs/omnisdk v0.1.15-beta03 h1:gkbYjg2npvDSRsKHgx89OsGbUTPnSZ4QNrvfi4Nna+0= +github.com/stackql-labs/omnisdk v0.1.15-beta03/go.mod h1:76RVs6Uq5WIzFzsskvFiOToyxkELPbdNABFNgDR90d4= github.com/stackql/go-suffix-map v0.0.1-alpha02 h1:JI4aiq/OfHW4a/BiNqK31NbyaR94zlUOhGZof3G/OUo= github.com/stackql/go-suffix-map v0.0.1-alpha02/go.mod h1:6BSMz4K/gIYfqdVRb7V8xL165wiPYyCjD9Kx7hLMd9Y= github.com/stackql/psql-wire v0.1.2-beta02 h1:7DfliBpyyCaUHVJ1Jxk37q3zVwVLyh6+FCHeM0/gbAQ= diff --git a/internal/stackql/handler/handler.go b/internal/stackql/handler/handler.go index b2742b47..6e790f79 100644 --- a/internal/stackql/handler/handler.go +++ b/internal/stackql/handler/handler.go @@ -605,6 +605,10 @@ func (hc *standardHandlerContext) setAuthContextAtPath(path string, rhs interfac if err = decodeSessionObject(fields, &updated); err != nil { return err } + if len(parts) == 2 && parts[1] == "aws_profile" { + // Omni checks that the new profile uses the same Identity Center session. + updated.AWSSSOSession = candidate.AWSSSOSession + } if scope == "local" { hc.authContexts = hc.authContexts.Clone() } diff --git a/internal/stackql/intrinsic/auth.go b/internal/stackql/intrinsic/auth.go index 4e7bc17f..1b3ee778 100644 --- a/internal/stackql/intrinsic/auth.go +++ b/internal/stackql/intrinsic/auth.go @@ -19,7 +19,9 @@ func authFunc(ctx queryContext, node *sqlparser.Auth) func() internaldto.Executo return internaldto.NewExecutorOutput(nil, nil, nil, nil, err) } previousSession := configured.OAuthSession + previousAWS := configured.AWSSSOSession candidate := configured.Clone() + candidate.OAuthSession, candidate.AWSSSOSession = nil, nil configureAuthCandidate(candidate, node) if err = authenticateCandidate(ctx, node.Provider, candidate); err != nil { return internaldto.NewErroneousExecutorOutput(err) @@ -30,6 +32,9 @@ func authFunc(ctx queryContext, node *sqlparser.Auth) func() internaldto.Executo } else { *configured = *candidate } + if previousAWS != nil { + previousAWS.Close() + } if previousSession != nil { previousSession.Close() } @@ -44,6 +49,12 @@ func configureAuthCandidate(candidate *dto.AuthCtx, node *sqlparser.Auth) { if node.KeyEnvVar != "" { candidate.KeyEnvVar = node.KeyEnvVar } + if node.Type == "" || strings.EqualFold(node.Type, dto.AuthInteractiveStr) { + switch strings.ToLower(candidate.Type) { + case dto.AuthAWSIdentityCenter, dto.AuthAzureDeviceCode, dto.AuthGoogleSSO: + return + } + } candidate.Type = strings.ToLower(node.Type) if candidate.Type != "" { return @@ -55,6 +66,10 @@ func configureAuthCandidate(candidate *dto.AuthCtx, node *sqlparser.Auth) { } func authenticateCandidate(ctx queryContext, provider string, candidate *dto.AuthCtx) error { + switch strings.ToLower(candidate.Type) { + case dto.AuthAWSIdentityCenter, dto.AuthAzureDeviceCode: + return interactiveDeviceLogin(ctx, candidate) + } if candidate.UsesInteractiveOAuth() { return interactiveOAuthLogin(ctx, candidate) } @@ -62,7 +77,6 @@ func authenticateCandidate(ctx queryContext, provider string, candidate *dto.Aut if err := credential.Check(); err != nil { return err } - candidate.OAuthSession = nil if principal, err := credential.Principal(); err == nil { candidate.ID = principal } @@ -77,10 +91,17 @@ func authRevokeFunc(ctx queryContext, node *sqlparser.AuthRevoke) func() interna } deadline, cancel := context.WithTimeout(executionContext(ctx), time.Minute) defer cancel() - if configured.OAuthSession != nil { + switch { + case strings.EqualFold(configured.Type, dto.AuthAWSIdentityCenter): + err = sessionAuth(ctx, configured).RevokeAWSSSO(deadline) + if err == nil && configured.AWSSSOSession != nil { + configured.AWSSSOSession.Close() + configured.AWSSSOSession = nil + } + case configured.OAuthSession != nil: configured.OAuthSession.Close() configured.OAuthSession = nil - } else { + default: err = omnisdk.NewCredential(node.Provider, *dto.OmniAuth(configured)).Revoke(deadline) } if err == nil { diff --git a/internal/stackql/intrinsic/oauth_login.go b/internal/stackql/intrinsic/oauth_login.go index 6446c3ae..7b84fed1 100644 --- a/internal/stackql/intrinsic/oauth_login.go +++ b/internal/stackql/intrinsic/oauth_login.go @@ -9,6 +9,8 @@ import ( "net/http" "net/url" "os" + "path/filepath" + "strings" "time" "github.com/stackql-labs/omnisdk/pkg/omnisdk" @@ -36,7 +38,7 @@ func interactiveOAuthLogin(ctx queryContext, auth *dto.AuthCtx) error { return errors.New("OAuth redirect URI must be an HTTP loopback address with an explicit port and callback path") } login, address, err := (omnisdk.Auth{ - TokenURL: auth.GetTokenURL(), Scopes: auth.Scopes, + Type: auth.Type, TokenURL: auth.GetTokenURL(), Scopes: auth.Scopes, ClientID: auth.ClientID, ClientIDEnvVar: auth.ClientIDEnvVar, ClientSecret: auth.ClientSecret, ClientSecretEnvVar: auth.ClientSecretEnvVar, AuthorizationURL: auth.AuthorizationURL, AuthorizationURLEnvVar: auth.AuthorizationURLEnvVar, @@ -50,10 +52,7 @@ func interactiveOAuthLogin(ctx queryContext, auth *dto.AuthCtx) error { return fmt.Errorf("start OAuth callback listener: %w", err) } defer listener.Close() - writer := io.Writer(os.Stderr) - if output, ok := ctx.(interface{ GetOutErrFile() io.Writer }); ok && output.GetOutErrFile() != nil { - writer = output.GetOutErrFile() - } + writer := authPromptWriter(ctx) if _, err = fmt.Fprintf(writer, "Open this URL to sign in: %s\n", address); err != nil { return err } @@ -95,3 +94,53 @@ func interactiveOAuthLogin(ctx queryContext, auth *dto.AuthCtx) error { return deadline.Err() } } + +func authPromptWriter(ctx queryContext) io.Writer { + if output, ok := ctx.(interface{ GetOutErrFile() io.Writer }); ok && output.GetOutErrFile() != nil { + return output.GetOutErrFile() + } + return os.Stderr +} + +func interactiveDeviceLogin(ctx queryContext, auth *dto.AuthCtx) error { + deadline := executionContext(ctx) + config := sessionAuth(ctx, auth) + if strings.EqualFold(auth.Type, dto.AuthAWSIdentityCenter) { + login, prompt, err := config.BeginAWSDeviceLogin(deadline) + if err != nil { + return err + } + if err = writeDevicePrompt(ctx, prompt); err != nil { + return err + } + auth.AWSSSOSession, err = login.Complete(deadline) + return err + } + config.ClientID, config.ClientIDEnvVar = auth.ClientID, auth.ClientIDEnvVar + config.TokenURLEnvVar, config.ScopesEnvVar = auth.TokenURLEnvVar, auth.ScopesEnvVar + login, prompt, err := config.BeginAzureDeviceLogin(deadline) + if err != nil { + return err + } + if err = writeDevicePrompt(ctx, prompt); err != nil { + return err + } + auth.OAuthSession, err = login.Complete(deadline) + return err +} + +func writeDevicePrompt(ctx queryContext, prompt omnisdk.DevicePrompt) error { + _, err := fmt.Fprintf(authPromptWriter(ctx), "Open this URL to sign in: %s\nEnter code: %s\n", + prompt.VerificationURI, prompt.UserCode) + return err +} + +func sessionAuth(ctx queryContext, auth *dto.AuthCtx) *omnisdk.Auth { + config := dto.OmniAuth(auth) + if strings.EqualFold(auth.Type, dto.AuthAWSIdentityCenter) { + if root := ctx.GetRuntimeContext().ApplicationFilesRootPath; root != "" { + config.AWSSSOCacheDir = filepath.Join(root, "aws-sso") + } + } + return config +} diff --git a/internal/stackql/intrinsic/omnisdk.go b/internal/stackql/intrinsic/omnisdk.go index 10213abc..7f1ff5d5 100644 --- a/internal/stackql/intrinsic/omnisdk.go +++ b/internal/stackql/intrinsic/omnisdk.go @@ -650,15 +650,15 @@ func providerAuthByProvider(ctx queryContext, cloud string) (map[string]*omnisdk if authCtx == nil { return map[string]*omnisdk.Auth{}, nil } - credential := omnisdkAuth(authCtx) + credential := sessionAuth(ctx, authCtx) if authCtx.OAuthSession != nil { bearer, err := authCtx.OAuthSession.Auth(executionContext(ctx)) if err != nil { return nil, err } credential = &bearer - } else if authCtx.UsesInteractiveOAuth() { - return nil, fmt.Errorf("OAuth sign-in required for %s", authProviderName(cloud)) + } else if authCtx.UsesInteractiveOAuth() || strings.EqualFold(authCtx.Type, dto.AuthAzureDeviceCode) { + return nil, fmt.Errorf("OAuth sign-in required; run AUTH LOGIN %s INTERACTIVE", authProviderName(cloud)) } return map[string]*omnisdk.Auth{authProviderName(cloud): credential}, nil } diff --git a/internal/stackql/runtimeconfig/auth_ctx.go b/internal/stackql/runtimeconfig/auth_ctx.go index 02aa70b4..7bd7b13b 100644 --- a/internal/stackql/runtimeconfig/auth_ctx.go +++ b/internal/stackql/runtimeconfig/auth_ctx.go @@ -21,14 +21,22 @@ func (as AuthContexts) Clone() AuthContexts { } type AuthCtx struct { - OAuthSession *omnisdk.OAuthSession `json:"-" yaml:"-"` + AWSSSOSession *omnisdk.AWSSSOSession `json:"-" yaml:"-"` + OAuthSession *omnisdk.OAuthSession `json:"-" yaml:"-"` omnisdk.AuthConfig `yaml:",inline"` SQLCfg *SQLBackendCfg `json:"sqlDataSource" yaml:"sqlDataSource"` Successor *AuthCtx `json:"successor" yaml:"successor"` } +const ( + AuthAWSIdentityCenter = "aws_identity_center" + AuthAzureDeviceCode = "azure_device_code" + AuthGoogleSSO = "google_sso" +) + func (ac *AuthCtx) UsesInteractiveOAuth() bool { - return strings.EqualFold(ac.Type, "interactive") && (ac.AuthorizationURL != "" || ac.AuthorizationURLEnvVar != "") + return strings.EqualFold(ac.Type, AuthGoogleSSO) || + strings.EqualFold(ac.Type, "interactive") && (ac.AuthorizationURL != "" || ac.AuthorizationURLEnvVar != "") } func (ac *AuthCtx) GetSQLCfg() (SQLBackendCfg, bool) { @@ -44,6 +52,14 @@ func (ac *AuthCtx) Clone() *AuthCtx { return nil } cloned := *ac + if ac.AWSIdentityCenter != nil { + config := *ac.AWSIdentityCenter + cloned.AWSIdentityCenter = &config + } + if ac.AzureDeviceCode != nil { + config := *ac.AzureDeviceCode + cloned.AzureDeviceCode = &config + } if ac.Federation != nil { federation := *ac.Federation cloned.Federation = &federation diff --git a/internal/stackql/runtimeconfig/omnisdk_auth.go b/internal/stackql/runtimeconfig/omnisdk_auth.go index 0195d5f4..c3ead252 100644 --- a/internal/stackql/runtimeconfig/omnisdk_auth.go +++ b/internal/stackql/runtimeconfig/omnisdk_auth.go @@ -26,6 +26,11 @@ func OmniAuth(authCtx *AuthCtx) *omnisdk.Auth { PassphraseEnvVar: authCtx.OciPassphraseEnvVar, ConfigFilePath: authCtx.OciConfigFilePath, Profile: authCtx.OciProfile, + AWSIdentityCenter: authCtx.AWSIdentityCenter, + AWSSSOSession: authCtx.AWSSSOSession, + AzureDeviceCode: authCtx.AzureDeviceCode, + Tenant: authCtx.AzureTenant, + TenantEnvVar: authCtx.AzureTenantEnvVar, Type: authCtx.Type, ValuePrefix: authCtx.ValuePrefix, @@ -37,6 +42,9 @@ func OmniAuth(authCtx *AuthCtx) *omnisdk.Auth { UsernameEnvVar: authCtx.EnvVarUsername, PasswordEnvVar: authCtx.EnvVarPassword, } + if authCtx.AWSProfile != "" { + auth.Profile = authCtx.AWSProfile + } if strings.EqualFold(authCtx.Type, "basic") && auth.ValuePrefix == "" { // Preserve the CLI's established Basic scheme spelling. auth.ValuePrefix = "BASIC " diff --git a/pkg/mcp_server/policy/policy.go b/pkg/mcp_server/policy/policy.go index f4190e26..a087ae22 100644 --- a/pkg/mcp_server/policy/policy.go +++ b/pkg/mcp_server/policy/policy.go @@ -81,10 +81,19 @@ func classPrivilege(class QueryClass) int { // that StackQL's parser does not currently support. func classifyStatement(trimmed string) QueryClass { if node, err := sqlparser.Parse(trimmed); err == nil { - switch node.(type) { + switch stmt := node.(type) { case sqlparser.SelectStatement: return classifyReadAST(node, nil) - case *sqlparser.Insert, *sqlparser.Update: + case *sqlparser.Insert: + if strings.EqualFold(stmt.Table.Name.GetRawVal(), "run") { + for _, column := range stmt.Columns { + if strings.EqualFold(column.GetRawVal(), "prune") { + return QueryClassMutationDelete + } + } + } + return QueryClassMutationCreate + case *sqlparser.Update: return QueryClassMutationCreate case *sqlparser.Delete: return QueryClassMutationDelete diff --git a/pkg/mcp_server/policy/policy_test.go b/pkg/mcp_server/policy/policy_test.go index 035e5c61..f41caa84 100644 --- a/pkg/mcp_server/policy/policy_test.go +++ b/pkg/mcp_server/policy/policy_test.go @@ -277,3 +277,10 @@ func TestIsLongRunningIaC(t *testing.T) { } } } + +func TestPruningApplyRequiresDeleteApproval(t *testing.T) { + query := "INSERT INTO stackql_preview.iac.run (collection, resources, prune) VALUES ('cohort', '[]', 1)" + if got := policy.ClassifyQuery(query); got != policy.QueryClassMutationDelete { + t.Fatalf("pruning apply class = %v, want delete", got) + } +} diff --git a/test/python/stackql_test_tooling/flask/identity_center.py b/test/python/stackql_test_tooling/flask/identity_center.py new file mode 100644 index 00000000..52d73a43 --- /dev/null +++ b/test/python/stackql_test_tooling/flask/identity_center.py @@ -0,0 +1,80 @@ +"""Local IAM Identity Center and SigV4-protected EC2 fixture.""" +import time + +from flask import Flask, jsonify, request + +from sts import STSFixture + + +def create_app(state): + app = Flask(__name__) + + @app.post("/client/register") + def register(): + state.calls.append("register") + data = request.get_json() + assert data["clientType"] == "public" + assert data["scopes"] == ["sso:account:access"] + return jsonify(clientId="fixture-client", clientSecret="FIXTURE_CLIENT_SECRET", + clientSecretExpiresAt=int(time.time()) + 3600) + + @app.post("/device_authorization") + def authorize(): + state.calls.append("authorize") + data = request.get_json() + assert data["clientId"] == "fixture-client" + assert data["clientSecret"] == "FIXTURE_CLIENT_SECRET" + assert data["startUrl"] == "https://example.awsapps.com/start" + return jsonify(deviceCode="FIXTURE_DEVICE", userCode="TEST-CODE", + verificationUri="https://example.awsapps.com/verify", interval=1, expiresIn=30) + + @app.post("/token") + def token(): + data = request.get_json() + assert data["clientId"] == "fixture-client" + assert data["clientSecret"] == "FIXTURE_CLIENT_SECRET" + if data["grantType"] == "refresh_token": + state.calls.append("refresh") + assert data["refreshToken"] == "FIXTURE_REFRESH" + if state.mode == "rejected refresh": + return jsonify(error="invalid_grant", error_description="FIXTURE_REFRESH"), 400 + return jsonify(accessToken="FIXTURE_REFRESHED_ACCESS", expiresIn=3600) + assert data["grantType"] == "urn:ietf:params:oauth:grant-type:device_code" + assert data["deviceCode"] == "FIXTURE_DEVICE" + state.calls.append("poll") + if state.mode in ("access_denied", "expired_token"): + return jsonify(error=state.mode, error_description="FIXTURE_DEVICE"), 400 + if state.mode == "pending" and state.calls.count("poll") == 1: + return jsonify(error="authorization_pending"), 400 + expiry = 1 if state.mode in ("refresh", "rejected refresh") else 3600 + return jsonify(accessToken="FIXTURE_ACCESS", refreshToken="FIXTURE_REFRESH", expiresIn=expiry) + + @app.get("/federation/credentials") + def credentials(): + account, role = request.args["account_id"], request.args["role_name"] + bearer = request.environ["identity_center.bearer"] + assert (account, role) in {("123456789012", "Viewer"), ("210987654321", "Operator")} + assert bearer == ("FIXTURE_REFRESHED_ACCESS" if "refresh" in state.calls else "FIXTURE_ACCESS") + state.calls.append(("portal", account, role, bearer)) + if state.mode == "portal denial": + return jsonify(message="FIXTURE_ACCESS"), 403 + n = len(state.issued) + 1 + key, secret, token_value = f"FIXTURE_KEY{n}", f"FIXTURE_SECRET{n}", f"FIXTURE_SESSION{n}" + state.issued[key] = (key, secret, token_value) + # The first result crosses Omni's early refresh window by construction. + short = n == 1 and state.mode in ("role expiry", "refresh", "rejected refresh") + return jsonify(roleCredentials=dict(accessKeyId=key, secretAccessKey=secret, sessionToken=token_value, + expiration=int((time.time() + (40 if short else 3600)) * 1000))) + + @app.get("/instances") + def instances(): + key = request.headers.get("Authorization", "").partition("Credential=")[2].split("/")[0] + assert key in state.issued + STSFixture.verify_signature(request, state.issued[key], "ap-southeast-2", "ec2") + state.calls.append(("ec2", key)) + if key == "FIXTURE_KEY1" and state.mode in ("refresh", "rejected refresh"): + # Ensure the fixture access token has expired when the next statement runs. + time.sleep(1.1) + return jsonify([{"id": "i-fixture"}]) + + return app diff --git a/test/robot/functional/IdentityCenterLibrary.py b/test/robot/functional/IdentityCenterLibrary.py new file mode 100644 index 00000000..1036c93c --- /dev/null +++ b/test/robot/functional/IdentityCenterLibrary.py @@ -0,0 +1,139 @@ +"""Drive the StackQL AUTH LOGIN and query entry points against local AWS mocks.""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import threading +from types import SimpleNamespace + +from robot.api import SkipExecution +from werkzeug.serving import WSGIRequestHandler, make_server + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python/stackql_test_tooling/flask")) +from identity_center import create_app + + +class IdentityCenterRequestHandler(WSGIRequestHandler): + def make_environ(self): + environ = super().make_environ() + # Werkzeug drops headers with underscores. The AWS portal protocol uses one. + environ["identity_center.bearer"] = self.headers.get("x-amz-sso_bearer_token") + return environ + + +class IdentityCenterLibrary: + def prepare_identity_center(self, binary, execution_platform): + if execution_platform != "native": + raise SkipExecution("Identity Center suite uses native loopback endpoints") + self.root = Path(tempfile.mkdtemp(prefix="stackql-identity-center-")) + self.state = SimpleNamespace(calls=[], issued={}, mode="") + self.server = make_server("127.0.0.1", 0, create_app(self.state), request_handler=IdentityCenterRequestHandler) + self.worker = threading.Thread(target=self.server.serve_forever, daemon=True) + self.worker.start() + self.endpoint = f"http://127.0.0.1:{self.server.server_port}" + self.binary = str(Path(shutil.which(binary) or binary).resolve()) + registry = self.root / "registry" + version = registry / "src/awsfixture/v00.00.00000" + (version / "services").mkdir(parents=True) + provider = { + "name": "awsfixture", "id": "awsfixture", "version": "v00.00.00000", + "config": {"auth": {"type": "aws_signing_v4"}}, + "providerServices": {"ec2": { + "id": "ec2:v00.00.00000", "name": "ec2", "preferred": True, + "service": {"$ref": "awsfixture/v00.00.00000/services/ec2.yaml"}, + }}, + } + operation = {"operationId": "DescribeInstances", "responses": {"200": {"content": { + "application/json": {"schema": {"type": "array", "items": { + "type": "object", "properties": {"id": {"type": "string"}}, + }}}, + }}}} + resource = { + "id": "awsfixture.ec2.instances", "name": "instances", + "methods": {"list": {"operation": {"$ref": "#/paths/~1instances/get"}, + "response": {"mediaType": "application/json", "openAPIDocKey": "200"}}}, + "sqlVerbs": {"select": [{"$ref": "#/components/x-stackQL-resources/instances/methods/list"}]}, + } + doc = { + "openapi": "3.0.0", "info": {"title": "EC2 fixture", "version": "1", "x-serviceName": "ec2"}, + "servers": [{"url": "https://ec2.{region}.example", "variables": {"region": {"default": "us-west-2"}}}], + "paths": {"/instances": {"get": operation}}, + "components": {"x-stackQL-resources": {"instances": resource}}, + } + (version / "provider.yaml").write_text(json.dumps(provider)) + (version / "services/ec2.yaml").write_text(json.dumps(doc)) + config = self.root / "aws-config" + config.write_text("""[profile viewer] +sso_session = staff +sso_account_id = 123456789012 +sso_role_name = Viewer +[profile operator] +sso_session = staff +sso_account_id = 210987654321 +sso_role_name = Operator +[sso-session staff] +sso_region = us-east-1 +sso_start_url = https://example.awsapps.com/start +""") + self.env = {k: v for k, v in os.environ.items() if not k.startswith("AWS_")} + self.env.update(AWS_CONFIG_FILE=str(config), AWS_PROFILE="viewer", + AWS_SHARED_CREDENTIALS_FILE=str(self.root / "no-credentials"), + PATH=str(self.root)) + self.auth = {"type": "aws_identity_center", "aws_identity_center": { + "oidc_endpoint": self.endpoint, "portal_endpoint": self.endpoint, + }} + self.flags = [ + "--approot", str(self.root / "app"), + "--registry", json.dumps({"localDocRoot": str(registry), "verifyConfig": {"nopVerify": True}}), + "--preview", json.dumps({"unstable": True, "endpoint": self.endpoint}), + "--output", "json", "--sqlBackend", json.dumps({"dsn": str(self.root / "session.db")}), + ] + + def identity_center_mode(self, mode): + self.state.mode = mode + + def identity_center_sql(self, sql, error="", profile="", query=True): + auth = dict(self.auth) + if profile: + auth["aws_profile"] = profile + result = subprocess.run( + [self.binary, "exec", sql, *self.flags, "--auth", json.dumps({"awsfixture": auth})], + env=self.env, capture_output=True, text=True, timeout=30, + ) + output = result.stderr + result.stdout + for marker in ("FIXTURE_CLIENT_SECRET", "FIXTURE_DEVICE", "FIXTURE_ACCESS", "FIXTURE_REFRESH", "FIXTURE_SECRET", "FIXTURE_SESSION"): + assert marker not in output, "a credential leaked to StackQL output" + if error: + assert error in output, output + else: + assert result.returncode == 0 and (not query or "i-fixture" in result.stdout), output + assert not any("error" in line.lower() for line in result.stderr.splitlines()), output + return output + + def identity_center_calls(self, *expected): + calls = [":".join(call) if isinstance(call, tuple) else call for call in self.state.calls] + assert calls == list(expected), calls + + def identity_center_portal_denied(self): + assert self.state.calls[:3] == ["register", "authorize", "poll"], self.state.calls + portal_calls = self.state.calls[3:] + assert portal_calls, "no portal request" + assert set(portal_calls) == {("portal", "123456789012", "Viewer", "FIXTURE_ACCESS")}, portal_calls + + def identity_center_cache_is_private(self): + if os.name != "nt": + cache = self.root / "app" / "aws-sso" + assert cache.stat().st_mode & 0o777 == 0o700 + files = list(cache.glob("*.json")) + assert len(files) == 1 and files[0].stat().st_mode & 0o777 == 0o600 + data = files[0].read_text() + assert "FIXTURE_SECRET" not in data and "FIXTURE_SESSION" not in data + + def stop_identity_center(self): + if hasattr(self, "server"): + self.server.shutdown() + self.worker.join(5) + shutil.rmtree(self.root) diff --git a/test/robot/functional/stackql_identity_center.robot b/test/robot/functional/stackql_identity_center.robot new file mode 100644 index 00000000..7acf7fc2 --- /dev/null +++ b/test/robot/functional/stackql_identity_center.robot @@ -0,0 +1,74 @@ +*** Settings *** +Documentation Native AWS Identity Center login and SigV4 against local AWS mocks. +Library IdentityCenterLibrary.py +Test Setup Prepare Identity Center ${STACKQL_EXE} ${EXECUTION_PLATFORM} +Test Teardown Stop Identity Center + +*** Variables *** +${STACKQL_EXE} ${EXECDIR}/build/stackql +${EXECUTION_PLATFORM} native + +*** Test Cases *** +Native Device Login Authorizes A Query + Identity Center Mode pending + ${output}= Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Should Contain ${output} https://example.awsapps.com/verify + Should Contain ${output} TEST-CODE + Identity Center Calls register authorize poll poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 + +Query Before Login Requires Sign In + Identity Center SQL SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; error=sign-in required + Identity Center Calls + +Repeated Queries Reuse Valid Role Credentials + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 ec2:FIXTURE_KEY1 + +Expiring Role Credentials Renew With The Same Access Token + Identity Center Mode role expiry + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY2 + +Expired Access Token Refreshes Before The Next Role Exchange + Identity Center Mode refresh + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 refresh portal:123456789012:Viewer:FIXTURE_REFRESHED_ACCESS ec2:FIXTURE_KEY2 + +Rejected Device Authorization Stops Login + Identity Center Mode access_denied + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; error=access denied + Identity Center Calls register authorize poll + +Expired Device Authorization Stops Login + Identity Center Mode expired_token + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; error=device authorization expired + Identity Center Calls register authorize poll + +Rejected Refresh Requires Sign In + Identity Center Mode rejected refresh + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; error=sign-in required + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 refresh + +Portal Role Denial Prevents The EC2 Request + Identity Center Mode portal denial + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; error=credentials for the configured account and role + Identity Center Portal Denied + +Different Profiles In The Same Session Use Their Own Role Credentials + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SET "$.auth.awsfixture.aws_profile" = 'operator'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; SET "$.auth.awsfixture.aws_profile" = 'viewer'; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 portal:210987654321:Operator:FIXTURE_ACCESS ec2:FIXTURE_KEY2 ec2:FIXTURE_KEY1 + +Fresh Process Reuses And Can Revoke A Saved Login + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; query=${False} + Identity Center Cache Is Private + Identity Center SQL SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center SQL AUTH REVOKE awsfixture; query=${False} + Identity Center SQL SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; error=sign-in required + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 + +Fresh Processes Refresh And Reuse The Updated Login + Identity Center Mode refresh + Identity Center SQL AUTH LOGIN awsfixture INTERACTIVE; SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center SQL SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center SQL SELECT id FROM awsfixture.ec2.instances WHERE region = 'ap-southeast-2'; + Identity Center Calls register authorize poll portal:123456789012:Viewer:FIXTURE_ACCESS ec2:FIXTURE_KEY1 refresh portal:123456789012:Viewer:FIXTURE_REFRESHED_ACCESS ec2:FIXTURE_KEY2 portal:123456789012:Viewer:FIXTURE_REFRESHED_ACCESS ec2:FIXTURE_KEY3