Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions docs/developer/expected_commit_message.md
Original file line number Diff line number Diff line change
@@ -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 `<name of robot test>`.


6 changes: 3 additions & 3 deletions docs/developer_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
40 changes: 40 additions & 0 deletions docs/omni-aws-identity-center.md
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
4 changes: 4 additions & 0 deletions internal/stackql/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
27 changes: 24 additions & 3 deletions internal/stackql/intrinsic/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
}
Expand All @@ -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
Expand All @@ -55,14 +66,17 @@ 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)
}
credential := omnisdk.NewCredential(provider, *dto.OmniAuth(candidate))
if err := credential.Check(); err != nil {
return err
}
candidate.OAuthSession = nil
if principal, err := credential.Principal(); err == nil {
candidate.ID = principal
}
Expand All @@ -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 {
Expand Down
59 changes: 54 additions & 5 deletions internal/stackql/intrinsic/oauth_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"

"github.com/stackql-labs/omnisdk/pkg/omnisdk"
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
6 changes: 3 additions & 3 deletions internal/stackql/intrinsic/omnisdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Loading
Loading