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
4 changes: 3 additions & 1 deletion docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,9 @@ flow and signs requests with the temporary role credentials. The AWS CLI is opti
```

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.
the request in the browser. Add `"open_browser": true` to the AWS auth object to
launch the default browser automatically. StackQL still prints the URL and code.
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`.
Expand Down
17 changes: 17 additions & 0 deletions docs/iac_walkthrough.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,20 @@ the returned diagnostics; do not switch collection names or erase state to bypas
That failure reported both resources compensated and no outstanding resources. The local ledger
contains tombstones for both keys. Verify the old IDs are absent in AWS before starting the create
step again with the fixed binary. Do not delete the ledger or its old journals.

## Shrink a collection

Pass the complete desired state and opt into pruning. The ledger supplies the
identity of each omitted resource. StackQL converges the retained resources
first and then deletes omitted resources in dependency order.

```sql
INSERT INTO stackql_preview.iac.run (resources_file, collection, state, region, prune)
VALUES ('smaller-collection.json', 'workshop', 'workshop-state', 'ap-southeast-2', 1);
```

To review exact deletions first, query `stackql_preview.iac.plan` with
`prune = 1` and apply the returned change set through
`INSERT INTO stackql_preview.iac.plan`. Omit `prune` to keep existing resources
that are missing from the declaration. Use explicit destroy to remove an entire
collection.
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-beta03
github.com/stackql-labs/omnisdk v0.1.15-beta04
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-beta03 h1:gkbYjg2npvDSRsKHgx89OsGbUTPnSZ4QNrvfi4Nna+0=
github.com/stackql-labs/omnisdk v0.1.15-beta03/go.mod h1:76RVs6Uq5WIzFzsskvFiOToyxkELPbdNABFNgDR90d4=
github.com/stackql-labs/omnisdk v0.1.15-beta04 h1:n6ad3JjC5fZx4LMp0+ejEFtqLps+YfAmfcyd1xuqSwQ=
github.com/stackql-labs/omnisdk v0.1.15-beta04/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
11 changes: 10 additions & 1 deletion internal/stackql/intrinsic/iac.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ func convergeFunc(
handle := popPredicate(params, blueprintPredicate)
spec := popPredicate(params, resourcesPredicate)
file := popPredicate(params, resourcesFilePredicate)
prune, pruneErr := iacPruneOption(params)
if pruneErr != nil {
return nil, pruneErr
}
if prune {
if accessErr := checkHost(ctx, "host/iac/"+destroyRelation, "execute"); accessErr != nil {
return nil, accessErr
}
}
if countSupplied(handle, spec, file) != 1 {
return nil, fmt.Errorf(
"relation '%s' needs exactly one of '%s', '%s' or '%s'; "+
Expand All @@ -85,7 +94,7 @@ func convergeFunc(
if argsErr != nil {
return internaldto.NewErroneousExecutorOutput(argsErr)
}
args.Inputs, args.Environment = inputs, environment
args.Inputs, args.Environment, args.IACPrune = inputs, environment, prune
plan, planErr := omnisdk.Prepare(registryRoot(ctx), omnisdk.DesiredState(resources), ledger, args)
if planErr != nil {
return internaldto.NewErroneousExecutorOutput(planErr)
Expand Down
24 changes: 23 additions & 1 deletion internal/stackql/intrinsic/iac_plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"

"github.com/stackql-labs/omnisdk/pkg/omnisdk"
"github.com/stackql/stackql-parser/go/vt/sqlparser"
Expand All @@ -13,7 +14,7 @@ import (
func iacPlanColumns() []column {
return []column{
{name: "resource_key", dataType: "string", description: "resource key within the collection"},
{name: "action", dataType: "string", description: "create, update, replace, no-op or unknown"},
{name: "action", dataType: "string", description: "create, update, replace, delete, no-op or unknown"},
{name: "reason", dataType: "string", description: "why the action was selected"},
{name: "depends_on", dataType: "string", description: "JSON array of dependency keys"},
{name: "change_set", dataType: "string", description: "versioned JSON accepted by INSERT INTO iac.plan"},
Expand Down Expand Up @@ -60,6 +61,10 @@ func iacPlanSelect(ctx queryContext, node *sqlparser.Select) func() internaldto.
return refuse(ledgerErr)
}
spec := popPredicate(params, resourcesPredicate)
prune, pruneErr := iacPruneOption(params)
if pruneErr != nil {
return refuse(pruneErr)
}
if spec == "" {
return refuse(errors.New("iac.plan SELECT requires the resources parameter"))
}
Expand All @@ -72,6 +77,7 @@ func iacPlanSelect(ctx queryContext, node *sqlparser.Select) func() internaldto.
if err != nil {
return internaldto.NewErroneousExecutorOutput(err)
}
args.IACPrune = prune
preview := iacPreviewPlan(func(execution context.Context) (omnisdk.ChangeSet, error) {
return omnisdk.Preview(execution, registryRoot(ctx), omnisdk.DesiredState(resources), wal, args)
})
Expand All @@ -95,6 +101,11 @@ func iacPlanInsert(
if err := json.Unmarshal([]byte(raw), &set); err != nil {
return nil, err
}
if set.Prune {
if err := checkHost(ctx, "host/iac/"+destroyRelation, "execute"); err != nil {
return nil, err
}
}
return func() internaldto.ExecutorOutput {
resources, err := specResources(string(set.Desired))
if err != nil {
Expand Down Expand Up @@ -123,3 +134,14 @@ func iacPlanArgs(
args.Inputs, args.Environment = inputs, environment
return args, err
}

func iacPruneOption(params map[string]string) (bool, error) {
switch value := popPredicate(params, "prune"); value {
case "", "0":
return false, nil
case "1":
return true, nil
default:
return false, fmt.Errorf("IaC prune must be 0 or 1, got %q", value)
}
}
25 changes: 25 additions & 0 deletions internal/stackql/intrinsic/oauth_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"

Expand Down Expand Up @@ -113,6 +115,9 @@ func interactiveDeviceLogin(ctx queryContext, auth *dto.AuthCtx) error {
if err = writeDevicePrompt(ctx, prompt); err != nil {
return err
}
if auth.OpenBrowser && openDeviceLoginBrowser(prompt.VerificationURI) != nil {
_, _ = fmt.Fprintln(authPromptWriter(ctx), "Could not start the default browser. Open the URL above to continue.")
}
auth.AWSSSOSession, err = login.Complete(deadline)
return err
}
Expand Down Expand Up @@ -144,3 +149,23 @@ func sessionAuth(ctx queryContext, auth *dto.AuthCtx) *omnisdk.Auth {
}
return config
}

// openDeviceLoginBrowser starts the platform launcher without waiting for the browser to exit.
func openDeviceLoginBrowser(address string) error {
var command *exec.Cmd
switch runtime.GOOS {
case "darwin":
command = exec.Command("open", address)
case "linux", "freebsd", "netbsd", "openbsd", "dragonfly":
command = exec.Command("xdg-open", address)
case "windows":
command = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", address)
default:
return errors.New("opening the default browser is unsupported on this platform")
}
if err := command.Start(); err != nil {
return err
}
go func() { _ = command.Wait() }()
return nil
}
1 change: 1 addition & 0 deletions internal/stackql/runtimeconfig/auth_ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func (as AuthContexts) Clone() AuthContexts {
}

type AuthCtx struct {
OpenBrowser bool `json:"open_browser,omitempty" yaml:"open_browser,omitempty"`
AWSSSOSession *omnisdk.AWSSSOSession `json:"-" yaml:"-"`
OAuthSession *omnisdk.OAuthSession `json:"-" yaml:"-"`
omnisdk.AuthConfig `yaml:",inline"`
Expand Down
14 changes: 14 additions & 0 deletions test/robot/functional/IdentityCenterLibrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,20 @@ def identity_center_cache_is_private(self):
data = files[0].read_text()
assert "FIXTURE_SECRET" not in data and "FIXTURE_SESSION" not in data

def enable_mock_default_browser(self):
launcher = {"darwin": "open", "linux": "xdg-open"}.get(sys.platform)
if launcher is None:
raise SkipExecution("Mock browser launcher requires macOS or Linux")
self.browser_log = self.root / "browser-url"
command = self.root / launcher
command.write_text('#!/bin/sh\nprintf "%s\\n" "$1" > "$STACKQL_TEST_BROWSER_LOG"\n')
command.chmod(0o700)
self.env["STACKQL_TEST_BROWSER_LOG"] = str(self.browser_log)
self.auth["open_browser"] = True

def default_browser_received_verification_url(self):
assert self.browser_log.read_text().strip() == "https://example.awsapps.com/verify"

def stop_identity_center(self):
if hasattr(self, "server"):
self.server.shutdown()
Expand Down
43 changes: 37 additions & 6 deletions test/robot/functional/ProviderSessionLibrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def prepare_session_provider(self, binary, execution_platform="native", backend=
self.aws_calls = []
self.view_calls = []
self.iac_calls = []
self.iac_widget = None
self.iac_widgets = {}
self.concurrent_gate = None
self.env = os.environ.copy()
if os.name != "nt":
Expand All @@ -36,7 +36,9 @@ def log_message(self, *_):
def do_GET(self):
if urlparse(self.path).path == "/iac-widget":
owner.iac_calls.append("read")
self.iac_response([owner.iac_widget] if owner.iac_widget else [])
identity = parse_qs(urlparse(self.path).query).get("id", [""])[0]
widget = owner.iac_widgets.get(identity)
self.iac_response([widget] if widget else [])
return
token = self.headers.get("Authorization", "")
if urlparse(self.path).path == "/buckets":
Expand Down Expand Up @@ -100,8 +102,10 @@ def do_POST(self):
if urlparse(self.path).path == "/iac-widget":
owner.iac_calls.append("create")
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))))
owner.iac_widget = {**body, "id": "iac-widget-1"}
self.iac_response(owner.iac_widget)
identity = f"iac-widget-{owner.iac_calls.count('create')}"
widget = {**body, "id": identity}
owner.iac_widgets[identity] = widget
self.iac_response(widget)
return
if urlparse(self.path).path != "/resource":
self.send_error(404)
Expand All @@ -116,6 +120,18 @@ def do_POST(self):
self.end_headers()
self.wfile.write(payload)

def do_DELETE(self):
url = urlparse(self.path)
if url.path != "/iac-widget":
self.send_error(404)
return
identity = parse_qs(url.query).get("id", [""])[0]
if owner.iac_widgets.pop(identity, None) is None:
self.send_error(404)
return
owner.iac_calls.append("delete")
self.iac_response({"id": identity})

self.server = ThreadingHTTPServer(("0.0.0.0" if execution_platform == "docker" else "127.0.0.1", 0), API)
self.worker = threading.Thread(target=self.server.serve_forever, daemon=True)
self.worker.start()
Expand Down Expand Up @@ -765,23 +781,38 @@ def media(schema):
"get": {"operationId": "read_iac_widget",
"parameters": [{"name": "id", "in": "query", "required": True, "schema": {"type": "string"}}],
"responses": {"200": media({"type": "array", "items": widget})}},
"delete": {"operationId": "delete_iac_widget",
"parameters": [{"name": "id", "in": "query", "required": True, "schema": {"type": "string"}}],
"responses": {"200": media(widget)}},
"post": {"operationId": "create_iac_widget", "requestBody": media(widget),
"responses": {"200": media(widget)}},
}
resource = "iac_widget"
methods = {"find": "get", "create": "post"}
methods = {"find": "get", "create": "post", "remove": "delete"}
prefix = "#/components/x-stackQL-resources/" + resource + "/methods/"
doc["components"]["x-stackQL-resources"][resource] = {
"id": "widgets.things." + resource, "name": resource,
"methods": {name: {"operation": {"$ref": "#/paths/~1iac-widget/" + verb},
"response": {"mediaType": "application/json", "openAPIDocKey": "200"}}
for name, verb in methods.items()},
"sqlVerbs": {"select": [{"$ref": prefix + "find"}], "insert": [{"$ref": prefix + "create"}]},
"sqlVerbs": {"select": [{"$ref": prefix + "find"}], "insert": [{"$ref": prefix + "create"}],
"delete": [{"$ref": prefix + "remove"}]},
}
path.write_text(json.dumps(doc))
self.env["ROBOT_IAC_FIXTURE_TOKEN"] = "iac-fixture-token"
return ["--auth", json.dumps({"widgets": {"type": "bearer", "credentialsenvvar": "ROBOT_IAC_FIXTURE_TOKEN"}})]

def iac_insert_prunes_omitted_resources(self, expand, shrink):
auth = self.install_iac_widget_fixture()
self.iac_calls.clear()
self.iac_widgets.clear()
self.run_sql(expand, [], auth)
assert sorted(widget["color"] for widget in self.iac_widgets.values()) == ["drop", "keep"]
result = json.loads(self.run_sql(shrink, [], auth).stdout)
assert {row["status"] for row in result} == {"applied", "destroyed"}, result
assert self.iac_calls.count("delete") == 1, self.iac_calls
assert [widget["color"] for widget in self.iac_widgets.values()] == ["keep"]

def iac_plan_select_insert_round_trip(self, preview_sql, apply_sql, describe_sql, methods_sql):
auth = self.install_iac_widget_fixture()
description = json.loads(self.run_sql(describe_sql, []).stdout)
Expand Down
7 changes: 7 additions & 0 deletions test/robot/functional/stackql_identity_center.robot
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,10 @@ Fresh Processes Refresh And Reuse The Updated Login
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

Opt In Opens The Browser And Prints The Verification Prompt
Enable Mock Default Browser
${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
Default Browser Received Verification Url
5 changes: 5 additions & 0 deletions test/robot/functional/stackql_provider_sessions.robot
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,8 @@ Recover Verified Absent Create Without Provider Calls

Provider View Declared Bare Inputs Override Placeholder Defaults
Provider View Declared Inputs Override Placeholders

IaC Insert Prunes Omitted Resources
${expand} = Set Variable INSERT INTO stackql_preview.iac.run (collection, resources) VALUES ('robot-prune', '[{"key":"keep","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"keep"}},{"key":"drop","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"drop"}}]');
${shrink} = Set Variable INSERT INTO stackql_preview.iac.run (collection, resources, prune) VALUES ('robot-prune', '[{"key":"keep","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"keep"}}]', 1) RETURNING status;
IaC Insert Prunes Omitted Resources ${expand} ${shrink}
Loading