Skip to content
Closed
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
101 changes: 101 additions & 0 deletions docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,107 @@ 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
```

## Native workload federation

This configuration requires a StackQL build that includes Omni's workload federation support.
Configure the cloud to trust your issuer and restrict it to the workload's subject and audience.

For **Bitbucket Pipelines → AWS**, enable `oidc: true` on the pipeline step. Register the
workspace issuer and audience in AWS IAM and allow the step's subject to assume the role.
In that step, set `STACKQL_AWS_ROLE_ARN` to the role ARN and run:

```sh
stackql exec 'SELECT name FROM aws.s3.buckets;' --preview='{"unstable":true}' --auth='{
"aws": {
"federation": {
"source": "bitbucket",
"target": "aws",
"role_arn_env_var": "STACKQL_AWS_ROLE_ARN",
"region": "us-east-1"
}
}
}'
```

StackQL passes the provider's federation config to Omni. Omni reads
`BITBUCKET_STEP_OIDC_TOKEN`, exchanges it for temporary AWS credentials, and signs the API
request. For GitHub use `source: github` with `audience` and `id-token: write`. For GitLab
use `source: gitlab` with `token_env_var`. For Kubernetes use `source: kubernetes` with
`token_file`. An issuer such as Keycloak can also supply an assertion via `source: keycloak`
with its token URL and client credential environment selectors.

[Bitbucket Pipelines OIDC setup](https://support.atlassian.com/bitbucket-cloud/docs/integrate-pipelines-with-resource-servers-using-oidc/)

### GitHub Actions

Give the job `permissions: {id-token: write}`. Configure the cloud to trust
`https://token.actions.githubusercontent.com` and restrict the subject to your repository and
branch or deployment environment. To run the AWS example above from the job, replace its
`federation` block with this one. StackQL requests the assertion from the runner.

```json
{
"source": "github",
"audience": "sts.amazonaws.com",
"target": "aws",
"role_arn_env_var": "STACKQL_AWS_ROLE_ARN",
"region": "us-east-1"
}
```

[GitHub OIDC setup for AWS](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws)

### Kubernetes

Run StackQL in a Pod with a dedicated service account. Add a projected `serviceAccountToken`
to a volume mounted at `/var/run/federation`. This example uses an AWS trust policy that accepts
the cluster issuer, audience `sts.amazonaws.com`, and subject
`system:serviceaccount:<namespace>:<service-account>`.

```yaml
volumes:
- name: federation
projected:
sources:
- serviceAccountToken:
audience: sts.amazonaws.com
expirationSeconds: 3600
path: token
```

Mount the volume in the StackQL container. In the AWS example above, set
`"source": "kubernetes"` and add `"token_file": "/var/run/federation/token"`.
Omni reads the current file when it needs to exchange an assertion. [Kubernetes token projection](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection)

### Keycloak

In your realm, create an OpenID Connect client with **Client authentication** and
**Service accounts roles** enabled. Configure an audience mapper so the client access token
carries the audience your cloud trusts. Set `KEYCLOAK_CLIENT_ID` and `KEYCLOAK_CLIENT_SECRET`
in the StackQL process environment. For Google Cloud, create an OIDC workload identity pool
provider for the realm and bind the mapped principal to the resource it can read.

Pass this object to `--auth` and run a query such as
`SELECT name FROM google.storage.buckets WHERE project = 'my-project';`. Substitute your realm
endpoint, workload identity pool provider resource, and project.

```json
{
"google": {
"federation": {
"source": "keycloak",
"target": "gcp",
"issuer_token_url": "https://keycloak.example/realms/demo/protocol/openid-connect/token",
"issuer_client_id_env_var": "KEYCLOAK_CLIENT_ID",
"issuer_client_secret_env_var": "KEYCLOAK_CLIENT_SECRET",
"google_audience": "//iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/demo/providers/keycloak"
}
}
}
```

Set `google_service_account` if the workload should impersonate a service account. [Google Cloud federation setup](https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-other-providers)

## OIDC from github

GHA → cloud federation via each provider's official action; stackql then uses its standard auth types — **no federation-specific `--auth` string needed**.
Expand Down
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-alpha05
github.com/stackql-labs/omnisdk v0.1.15-beta01
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-alpha05 h1:Y15AoeFUBqpIFlcwbM83eR2frkCiIPy9ERKU5UINYfQ=
github.com/stackql-labs/omnisdk v0.1.15-alpha05/go.mod h1:PFwcN2mZrrtwpRTc361IVbQ0FME4OIbKK7B51Z+mDrE=
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/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/runtimeconfig/auth_ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ func (ac *AuthCtx) Clone() *AuthCtx {
return nil
}
cloned := *ac
if ac.Federation != nil {
federation := *ac.Federation
cloned.Federation = &federation
}
cloned.Scopes = append([]string(nil), ac.Scopes...)
cloned.Values = make(url.Values, len(ac.Values))
for key, values := range ac.Values {
Expand Down
1 change: 1 addition & 0 deletions internal/stackql/runtimeconfig/omnisdk_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ func OmniAuth(authCtx *AuthCtx) *omnisdk.Auth {
return nil
}
auth := &omnisdk.Auth{
Federation: authCtx.Federation,
TenancyOCID: authCtx.OciTenancyOCID,
TenancyOCIDEnvVar: authCtx.OciTenancyOCIDEnvVar,
UserOCID: authCtx.OciUserOCID,
Expand Down
6 changes: 6 additions & 0 deletions test/robot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,5 +185,11 @@ From the repository root, after building `build/stackql`, run
robot --outputdir /tmp/stackql-keycloak test/robot/keycloak/stackql_keycloak_oauth.robot
```

The same directory covers workload federation through the StackQL CLI. The mock suite tests
GitHub, GitLab, Kubernetes, and Bitbucket assertions, checks the AWS STS, Google STS, and Entra
requests, and verifies that rejected exchanges block the dependent query. The Keycloak suite
also exercises a real workload issuer against a mocked Google STS endpoint. To run both suites,
pass `test/robot/keycloak` to Robot.

See the [StackQL OAuth walkthrough](../../docs/auth.md#interactive-oauth-authorization-code)
for configuring a provider and signing in from the shell.
192 changes: 192 additions & 0 deletions test/robot/functional/FederationLibrary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""StackQL CLI federation checks with local identity and cloud endpoints."""
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import subprocess
import threading
from datetime import datetime, timedelta, timezone
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import Request, urlopen
from base64 import b64encode

from ProviderSessionLibrary import ProviderSessionLibrary


class FederationLibrary(ProviderSessionLibrary):
def prepare_session_provider(self, binary, execution_platform="native", backend="{}"):
super().prepare_session_provider(binary, execution_platform, backend)
version = self.root / "registry/src/widgets/v00.00.00000"
self.federation_provider_path = version / "provider.yaml"
self.federation_document_path = version / "services/things.yaml"
self.federation_document = self.federation_document_path.read_text()

@contextmanager
def federation_endpoint(self, target, reject, check_assertion):
calls, failures = [], []

class Cloud(BaseHTTPRequestHandler):
def log_message(self, *_):
pass

def reply(self, value, content_type="application/json", status=200):
body = (value if isinstance(value, str) else json.dumps(value)).encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def do_GET(self):
path = urlsplit(self.path)
if path.path == "/oidc":
calls.append("runner")
if (self.headers.get("Authorization") != "Bearer runner-credential"
or parse_qs(path.query).get("audience") != ["fixture-audience"]):
failures.append("incorrect GitHub runner request")
self.reply({"value": "fixture-assertion"})
return
calls.append("api")
bearer = self.headers.get("Authorization", "")
if target == "aws":
valid = ("Credential=TEMPKEY/" in bearer
and self.headers.get("X-Amz-Security-Token") == "sts-session")
else:
valid = bearer == "Bearer cloud-access-token"
if not valid:
failures.append("incorrect credentials on the dependent request")
self.reply({}, status=401)
return
self.reply([{"id": "federated-row"}])

def do_POST(self):
calls.append("exchange")
fields = parse_qs(self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode())
expected, assertion_field = {
"aws": ({"Action": "AssumeRoleWithWebIdentity",
"RoleArn": "arn:aws:iam::123456789012:role/stackql-fixture"}, "WebIdentityToken"),
"gcp": ({"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": "//iam.googleapis.com/fixture-provider"}, "subject_token"),
"entra": ({"grant_type": "client_credentials", "client_id": "entra-client",
"scope": "https://management.azure.com/.default"}, "client_assertion"),
}[target]
if any(fields.get(key) != [value] for key, value in expected.items()):
failures.append("incorrect cloud token exchange parameters")
if self.headers.get("Authorization"):
failures.append("unexpected authorization header on cloud token exchange")
assertion = fields.get(assertion_field, [""])[0]
if not check_assertion(assertion):
failures.append("incorrect assertion on cloud token exchange")
if reject or failures:
if target == "aws":
self.reply("<ErrorResponse><Error><Code>InvalidIdentityToken</Code></Error></ErrorResponse>",
"application/xml", 403)
else:
self.reply({"error": "invalid_grant"}, status=403)
return
if target == "aws":
expiry = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
self.reply(
"<AssumeRoleWithWebIdentityResponse><AssumeRoleWithWebIdentityResult><Credentials>"
"<AccessKeyId>TEMPKEY</AccessKeyId><SecretAccessKey>TEMPSECRET</SecretAccessKey>"
f"<SessionToken>sts-session</SessionToken><Expiration>{expiry}</Expiration>"
"</Credentials></AssumeRoleWithWebIdentityResult></AssumeRoleWithWebIdentityResponse>",
"application/xml",
)
else:
self.reply({"access_token": "cloud-access-token", "expires_in": 3600})

server = ThreadingHTTPServer(("127.0.0.1", 0), Cloud)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
yield f"http://127.0.0.1:{server.server_port}", calls, failures
finally:
server.shutdown()
server.server_close()
worker.join(timeout=5)

def check_mocked_federation(self, source, target, reject=False, missing=False):
self.check_federation(source, target, reject, missing=missing)

def check_federation(self, source, target, reject, token_endpoint=None, missing=False):
env = dict(self.env)
settings = {"source": source, "target": target}
check_assertion = lambda token: token == "fixture-assertion"
if source == "github":
settings["audience"] = "fixture-audience"
env.pop("ACTIONS_ID_TOKEN_REQUEST_TOKEN", None)
if not missing:
env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = "runner-credential"
elif source == "gitlab":
settings["token_env_var"] = "GITLAB_FEDERATION_TOKEN"
env["GITLAB_FEDERATION_TOKEN"] = "fixture-assertion"
elif source == "kubernetes":
path = self.root / "kubernetes.jwt"
path.unlink(missing_ok=True)
if not missing:
path.write_text("fixture-assertion\n")
settings["token_file"] = str(path)
elif source == "bitbucket":
env["BITBUCKET_STEP_OIDC_TOKEN"] = "fixture-assertion"
elif source == "keycloak":
settings.update(issuer_token_url=token_endpoint, issuer_client_id_env_var="KEYCLOAK_CLIENT_ID",
issuer_client_secret_env_var="KEYCLOAK_CLIENT_SECRET")
env.update(KEYCLOAK_CLIENT_ID="stackql-workload", KEYCLOAK_CLIENT_SECRET="fixture-secret")
check_assertion = lambda token: self.keycloak_issued_assertion(token_endpoint, token)
else:
raise ValueError(f"unexpected source {source}")
if target == "aws":
settings.update(role_arn_env_var="STACKQL_FIXTURE_ROLE", region="us-east-1")
env["STACKQL_FIXTURE_ROLE"] = "arn:aws:iam::123456789012:role/stackql-fixture"
elif target == "gcp":
settings["google_audience"] = "//iam.googleapis.com/fixture-provider"

provider_path, doc_path = self.federation_provider_path, self.federation_document_path
original_provider, original_doc = provider_path.read_text(), doc_path.read_text()
try:
with self.federation_endpoint(target, reject, check_assertion) as (endpoint, calls, failures):
provider = json.loads(original_provider)
provider["config"]["auth"] = {"type": "aws_signing_v4" if target == "aws" else "bearer"}
provider_path.write_text(json.dumps(provider))
doc = json.loads(self.federation_document)
doc["servers"] = [{"url": endpoint}]
doc_path.write_text(json.dumps(doc))
settings["exchange_url"] = endpoint + "/exchange"
env["ACTIONS_ID_TOKEN_REQUEST_URL"] = endpoint + "/oidc?runner=1"
auth = {"widgets": {"federation": settings, "client_id": "entra-client"},
"unused": {"federation": {"source": "must-not-run", "target": target}}}
flags = list(self.flags)
flags[flags.index("--preview") + 1] = json.dumps({"unstable": True})
result = subprocess.run(
self.prefix + ["exec", "SELECT id FROM widgets.things.widgets WHERE region = 'us-east-1';"]
+ flags + ["--auth", json.dumps(auth)],
text=True, capture_output=True, env=env, timeout=30,
)
assert not failures, failures
if missing:
expected_error = {"github": "OIDC request credential is missing",
"kubernetes": "cannot open workload assertion file"}[source]
assert expected_error in result.stderr and not calls, (calls, result.stderr)
assert "federated-row" not in result.stdout
return
assert "exchange" in calls, (calls, result.stderr)
assert ("runner" in calls) == (source == "github"), calls
assert "fixture-assertion" not in result.stdout + result.stderr
if reject:
assert "403" in result.stderr and "api" not in calls, (calls, result.stderr)
assert "federated-row" not in result.stdout
else:
assert result.returncode == 0 and "federated-row" in result.stdout, (result.stdout, result.stderr)
expected = ["runner", "exchange", "api"] if source == "github" else ["exchange", "api"]
assert calls == expected, calls
finally:
provider_path.write_text(original_provider)
doc_path.write_text(original_doc)

@staticmethod
def keycloak_issued_assertion(endpoint, token):
credentials = b64encode(b"stackql-workload:fixture-secret").decode()
request = Request(endpoint + "/introspect", data=urlencode({"token": token}).encode(),
headers={"Authorization": "Basic " + credentials})
with urlopen(request, timeout=5) as response:
return json.load(response).get("active") is True
Loading
Loading