From a73b58b9edbad572025a31d66296989a346f6341 Mon Sep 17 00:00:00 2001 From: General Kroll Date: Sat, 21 Nov 2026 11:37:48 +1100 Subject: [PATCH 1/4] fundamental-soundness Summary: - Deprecation warnings added for obsolete and undesriable inputs. - Paging, overall result set size and proxy aspects configurable in provider hierarchy as well as existing global. - Added robot test `HTTP Settings Follow Provider And Alias Precedence`. --- docs/provider_sessions.md | 19 +++++ internal/stackql/cmd/root.go | 12 ++- internal/stackql/handler/handler.go | 9 --- internal/stackql/handler/provider_session.go | 79 ++++++++++++++++++- internal/stackql/intrinsic/doc.go | 4 +- internal/stackql/runtimeconfig/runtime_ctx.go | 16 +--- internal/stackql/sessionconfig/set.go | 3 +- .../functional/ProviderSessionLibrary.py | 32 +++++++- .../stackql_provider_sessions.robot | 3 + 9 files changed, 140 insertions(+), 37 deletions(-) diff --git a/docs/provider_sessions.md b/docs/provider_sessions.md index 776ab9f0..e9db704f 100644 --- a/docs/provider_sessions.md +++ b/docs/provider_sessions.md @@ -75,6 +75,25 @@ snapshot. Updating credentials affects subsequent queries, not queries already r binding/tuning changes start a new governor generation. Aliases cover document-driven metadata, reads, mutations and legacy EXEC; they do not extend native built-in or IaC resource addresses. +Use the canonical provider name to set defaults for the current session. + +```sql +SET "$.tuning_by_provider.google" = '{"page_limit":3}'; +SET "$.params_by_provider.google" = '{"maxResults":"200"}'; +``` + +Page limits resolve from alias `tuning.page_limit`, then canonical provider tuning, then +`--http.response.pageLimit`. Zero inherits and a negative value removes the cap. +For reads that declare a `maxResults` query parameter, precedence is explicit SQL, alias +`params.maxResults`, canonical provider parameters, then `--http.response.maxResults`. +Use `UNSET` on either canonical configuration path to restore its inherited defaults. + +With an OmniSDK build that supports `proxy_port`, set it in canonical tuning or the alias's +`tuning` object. A positive value replaces the port on the proxy selected by the HTTP transport. +Zero inherits and `-1` restores the transport's original port. The transport still selects which +requests use a proxy, including any `NO_PROXY` exclusions. The root `--http.proxy.port` flag +continues to configure the registry transport. + ## Typed dereferencing and expressions Use `$name` without single quotes, including for string variables. Resolution replaces AST nodes diff --git a/internal/stackql/cmd/root.go b/internal/stackql/cmd/root.go index 10f176bf..17ff60cc 100644 --- a/internal/stackql/cmd/root.go +++ b/internal/stackql/cmd/root.go @@ -191,8 +191,6 @@ func init() { // Cobra supports persistent flags, which, if defined here, // will be global for your application. - var dummyString string - rootCmd.PersistentFlags().StringVar(&runtimeCtx.DBInternalCfgRaw, dto.DBInternalCfgRawKey, "{}", "JSON / YAML string to configure DBMS housekeeping query handling") rootCmd.PersistentFlags().StringVar(&runtimeCtx.SQLBackendCfgRaw, dto.SQLBackendCfgRawKey, "{}", "JSON / YAML string representing SQL Backend System Config") rootCmd.PersistentFlags().StringVar(&runtimeCtx.NamespaceCfgRaw, dto.NamespaceCfgRawKey, "{}", "JSON / YAML string representing namespaces for cacheing, views etc") @@ -205,7 +203,7 @@ func init() { `eg: '{ "exporter": { "endpoint": "http://localhost:4318/v1/logs", "headers": { "authorization": "" } } }'`) rootCmd.PersistentFlags().StringVar(&runtimeCtx.SessionCtxRaw, dto.SessionCtxKey, "{}", "JSON / YAML string representing session config") rootCmd.PersistentFlags().IntVar(&runtimeCtx.APIRequestTimeout, dto.APIRequestTimeoutKey, 45, "API request timeout in seconds, 0 for no timeout.") //nolint:mnd // TODO: investigate - rootCmd.PersistentFlags().StringVar(&dummyString, dto.ColorSchemeKey, "", "DEPRECATED: color schems no longer active") + _ = rootCmd.PersistentFlags().String(dto.ColorSchemeKey, "", "DEPRECATED: color schemes are no longer supported") rootCmd.PersistentFlags().StringVar(&runtimeCtx.CABundle, dto.CABundleKey, "", "Path to CA bundle, if not specified then system defaults used.") rootCmd.PersistentFlags().BoolVar(&runtimeCtx.AllowInsecure, dto.AllowInsecureKey, false, "Allow trust of insecure certificates (not recommended)") rootCmd.PersistentFlags().StringVar(&runtimeCtx.ConfigFilePath, dto.ConfigFilePathKey, config.GetDefaultConfigFilePath(), "Config file full path; defaults to current dir") @@ -224,9 +222,9 @@ func init() { rootCmd.PersistentFlags().IntVar(&runtimeCtx.HTTPPageLimit, dto.HTTPPAgeLimitKey, 20, "Max pages of results that will be returned per resource, any number <=0 results in no limitation") //nolint:mnd // TODO: investigate rootCmd.PersistentFlags().IntVar(&runtimeCtx.HTTPProxyPort, dto.HTTPProxyPortKey, -1, "http proxy port, any number <=0 will result in the default port for a given scheme (eg: http -> 80)") rootCmd.PersistentFlags().IntVar(&runtimeCtx.ExecutionConcurrencyLimit, dto.ExecutionConcurrencyLimitKey, 1, "concurrency limit for query execution") - rootCmd.PersistentFlags().IntVar(&runtimeCtx.IndirectDepthMax, dto.IndirectDepthMaxKey, 5, "max depth for indirect queries: views and subqueries") //nolint:mnd // TODO: investigate - rootCmd.PersistentFlags().IntVar(&runtimeCtx.DataflowDependencyMax, dto.DataflowDependencyMaxKey, 50, "max dataflow dependency depth for a given query") - rootCmd.PersistentFlags().IntVar(&runtimeCtx.DataflowComponentsMax, dto.DataflowComponentsMaxKey, 50, "max dataflow weakly connected components for a given query") + rootCmd.PersistentFlags().IntVar(&runtimeCtx.IndirectDepthMax, dto.IndirectDepthMaxKey, 5, "DEPRECATED: max depth for indirect queries: views and subqueries") //nolint:mnd // TODO: investigate + _ = rootCmd.PersistentFlags().Int(dto.DataflowDependencyMaxKey, 50, "DEPRECATED: max dataflow dependency depth for a given query") + _ = rootCmd.PersistentFlags().Int(dto.DataflowComponentsMaxKey, 50, "DEPRECATED: max dataflow weakly connected components for a given query") rootCmd.PersistentFlags().StringVar(&runtimeCtx.HTTPProxyHost, dto.HTTPProxyHostKey, "", "http proxy host, empty means no proxy") rootCmd.PersistentFlags().StringVar(&runtimeCtx.HTTPProxyScheme, dto.HTTPProxySchemeKey, "http", "http proxy scheme, eg 'http'") rootCmd.PersistentFlags().StringVar(&runtimeCtx.HTTPProxyPassword, dto.HTTPProxyPasswordKey, "", "http proxy password") @@ -234,7 +232,7 @@ func init() { rootCmd.PersistentFlags().StringVar(&runtimeCtx.ProviderStr, dto.ProviderStrKey, "", "stackql provider") rootCmd.PersistentFlags().StringVar(&runtimeCtx.ExportAlias, dto.ExportAliasKey, "", "export alias prefix (namespace or schema)") rootCmd.PersistentFlags().BoolVar(&runtimeCtx.PGSrvIsDebugNoticesEnabled, dto.PgSrvIsDebugNoticesEnabledKey, false, "Publish debug notices to clients, for server mode only") - rootCmd.PersistentFlags().BoolVar(&runtimeCtx.WorkOffline, dto.WorkOfflineKey, false, "Work offline, using cached data") + _ = rootCmd.PersistentFlags().Bool(dto.WorkOfflineKey, false, "DEPRECATED: work offline using cached data") rootCmd.PersistentFlags().BoolVarP(&runtimeCtx.VerboseFlag, dto.VerboseFlagKey, "v", false, "Verbose flag") rootCmd.PersistentFlags().BoolVar(&runtimeCtx.DryRunFlag, dto.DryRunFlagKey, false, "dryrun flag; preprocessor only will run and output returned") rootCmd.PersistentFlags().BoolVarP(&runtimeCtx.CSVHeadersDisable, dto.CSVHeadersDisableKey, "H", false, "Disable CSV headers flag") diff --git a/internal/stackql/handler/handler.go b/internal/stackql/handler/handler.go index 147f4009..b2742b47 100644 --- a/internal/stackql/handler/handler.go +++ b/internal/stackql/handler/handler.go @@ -112,8 +112,6 @@ type HandlerContext interface { //nolint:revive // don't mind stuttering this on SetExportNamespace(string) GetExportNamespace() string - GetDataFlowCfg() dto.DataFlowCfg - // ResolveVariables(sqlparser.Statement) error SetConfigAtPath(path string, rhs interface{}, scope string) error @@ -191,13 +189,6 @@ func (hc *standardHandlerContext) SetStrictUpstreamErrors(isStrict bool) { hc.strictUpstreamErrors = isStrict } -func (hc *standardHandlerContext) GetDataFlowCfg() dto.DataFlowCfg { - return dto.NewDataFlowCfg( - hc.runtimeContext.DataflowDependencyMax, - hc.runtimeContext.DataflowComponentsMax, - ) -} - func (hc *standardHandlerContext) GetStacqklSemver() string { return hc.stackqlSemver } diff --git a/internal/stackql/handler/provider_session.go b/internal/stackql/handler/provider_session.go index 92cddca9..7fa48acd 100644 --- a/internal/stackql/handler/provider_session.go +++ b/internal/stackql/handler/provider_session.go @@ -29,6 +29,7 @@ type providerSessionState struct { client omnisdk.ClientSession store secrets.Store bindings map[string]omnisdk.ProviderBinding + providerParams map[string]map[string]string documentView string } @@ -150,7 +151,7 @@ func (hc *standardHandlerContext) setProviderSessionConfig(path string, rhs inte switch parts[0] { case "transaction": return true, hc.configureProviderTransaction(parts, rhs, scope) - case "providers", "secret_store", "secrets": + case "providers", "tuning_by_provider", "params_by_provider", "secret_store", "secrets": default: return false, nil } @@ -161,6 +162,10 @@ func (hc *standardHandlerContext) setProviderSessionConfig(path string, rhs inte state.mu.Lock() defer state.mu.Unlock() switch parts[0] { + case "tuning_by_provider": + return true, state.setProviderTuning(parts[1:], rhs) + case "params_by_provider": + return true, state.setProviderParams(parts[1:], rhs) case "secret_store": if len(parts) == 1 && rhs == nil { state.store, state.client = newSessionSecretStore(), nil @@ -260,6 +265,67 @@ func (hc *standardHandlerContext) setProviderSessionConfig(path string, rhs inte } } +func providerConfigName(path []string) (string, error) { + if len(path) != 1 { + return "", fmt.Errorf("provider configuration requires one provider and a configuration object") + } + provider := strings.TrimPrefix(path[0], "stackql_unstable_") + if provider == "" || strings.ContainsAny(provider, "/\\.\x00") { + return "", fmt.Errorf("provider configuration requires a provider identifier") + } + return provider, nil +} + +// setProviderTuning runs with the session lock held. +func (state *providerSessionState) setProviderTuning(path []string, rhs interface{}) error { + provider, err := providerConfigName(path) + if err != nil { + return err + } + tuning := maps.Clone(state.base.TuningByProvider) + if rhs == nil { + delete(tuning, provider) + } else { + var override omnisdk.ProviderTuning + if err := decodeSessionObject(rhs, &override); err != nil { + return err + } + if tuning == nil { + tuning = make(map[string]omnisdk.ProviderTuning) + } + tuning[provider] = override + } + args := state.sessionArgs() + args.TuningByProvider = tuning + client, err := omnisdk.NewClientSession(args, state.store) + if err != nil { + return err + } + state.base.TuningByProvider, state.client = tuning, client + return nil +} + +// setProviderParams runs with the session lock held. +func (state *providerSessionState) setProviderParams(path []string, rhs interface{}) error { + provider, err := providerConfigName(path) + if err != nil { + return err + } + if rhs == nil { + delete(state.providerParams, provider) + return nil + } + var params map[string]string + if err := decodeSessionObject(rhs, ¶ms); err != nil { + return err + } + if state.providerParams == nil { + state.providerParams = make(map[string]map[string]string) + } + state.providerParams[provider] = params + return nil +} + func (hc *standardHandlerContext) ReplaceAuthContext(provider string, auth *dto.AuthCtx) { hc.authMapMutex.Lock() defer hc.authMapMutex.Unlock() @@ -279,10 +345,13 @@ func (hc *standardHandlerContext) ProviderBindingParams(address string) map[stri defer state.mu.Unlock() provider, _, _ := strings.Cut(address, ".") provider = strings.TrimPrefix(provider, "stackql_unstable_") - params := map[string]string{} - for key, value := range state.bindings[provider].Params { - params[key] = value + binding, aliased := state.bindings[provider] + if aliased { + provider = strings.TrimPrefix(binding.Provider, "stackql_unstable_") } + params := map[string]string{} + maps.Copy(params, state.providerParams[provider]) + maps.Copy(params, binding.Params) return params } @@ -311,6 +380,8 @@ func (source *standardHandlerContext) NewClientContext() HandlerContext { source.runtimeContext.APIRequestTimeout, source.runtimeContext.HTTPPageLimit, ) target.providerSession.variables = maps.Clone(state.variables) + target.providerSession.base.TuningByProvider = maps.Clone(state.base.TuningByProvider) + target.providerSession.providerParams = maps.Clone(state.providerParams) target.providerSession.documentView = state.documentView target.providerSession.bindings = make(map[string]omnisdk.ProviderBinding, len(state.bindings)) for alias, binding := range state.bindings { diff --git a/internal/stackql/intrinsic/doc.go b/internal/stackql/intrinsic/doc.go index e17a40b1..c8dd255c 100644 --- a/internal/stackql/intrinsic/doc.go +++ b/internal/stackql/intrinsic/doc.go @@ -342,11 +342,11 @@ func planDocQuery(ctx queryContext, translated docQuery) (omnisdk.Plan, string, if dialectErr != nil { return nil, "", dialectErr } - q, environmentErr := bindReadPageSize(q, tables, ctx.GetRuntimeContext().HTTPMaxResults) + q, environmentErr := bindProviderDefaults(ctx, q, tables) if environmentErr != nil { return nil, "", environmentErr } - q, environmentErr = bindProviderDefaults(ctx, q, tables) + q, environmentErr = bindReadPageSize(q, tables, ctx.GetRuntimeContext().HTTPMaxResults) if environmentErr != nil { return nil, "", environmentErr } diff --git a/internal/stackql/runtimeconfig/runtime_ctx.go b/internal/stackql/runtimeconfig/runtime_ctx.go index 275ab95f..0de23cf0 100644 --- a/internal/stackql/runtimeconfig/runtime_ctx.go +++ b/internal/stackql/runtimeconfig/runtime_ctx.go @@ -28,8 +28,6 @@ type RuntimeCtx struct { HTTPProxyScheme string HTTPProxyUser string IndirectDepthMax int - DataflowComponentsMax int - DataflowDependencyMax int InfilePath string LogLevelStr string OutfilePath string @@ -60,7 +58,6 @@ type RuntimeCtx struct { VarList []string VerboseFlag bool ViperCfgFileName string - WorkOffline bool CLIPayload string CLIPayloadType string CLIParameters string @@ -152,10 +149,8 @@ func (rc *RuntimeCtx) Set(key string, val string) error { retVal = setInt(&rc.HTTPProxyPort, val) case IndirectDepthMaxKey: retVal = setInt(&rc.IndirectDepthMax, val) - case DataflowComponentsMaxKey: - retVal = setInt(&rc.DataflowComponentsMax, val) - case DataflowDependencyMaxKey: - retVal = setInt(&rc.DataflowDependencyMax, val) + case DataflowComponentsMaxKey, DataflowDependencyMaxKey: // deprecated + _, retVal = strconv.Atoi(val) case HTTPProxySchemeKey: rc.HTTPProxyScheme = val case HTTPProxyUserKey: @@ -212,8 +207,8 @@ func (rc *RuntimeCtx) Set(key string, val string) error { retVal = setBool(&rc.VerboseFlag, val) case ViperCfgFileNameKey: rc.ViperCfgFileName = val - case WorkOfflineKey: - retVal = setBool(&rc.WorkOffline, val) + case WorkOfflineKey: // deprecated + _, retVal = strconv.ParseBool(val) } return retVal } @@ -245,8 +240,6 @@ func (rc RuntimeCtx) Copy() RuntimeCtx { HTTPProxyScheme: rc.HTTPProxyScheme, HTTPProxyUser: rc.HTTPProxyUser, IndirectDepthMax: rc.IndirectDepthMax, - DataflowComponentsMax: rc.DataflowComponentsMax, - DataflowDependencyMax: rc.DataflowDependencyMax, InfilePath: rc.InfilePath, LogLevelStr: rc.LogLevelStr, OutfilePath: rc.OutfilePath, @@ -277,7 +270,6 @@ func (rc RuntimeCtx) Copy() RuntimeCtx { VarList: rc.VarList, VerboseFlag: rc.VerboseFlag, ViperCfgFileName: rc.ViperCfgFileName, - WorkOffline: rc.WorkOffline, } } diff --git a/internal/stackql/sessionconfig/set.go b/internal/stackql/sessionconfig/set.go index da883427..b08958fb 100644 --- a/internal/stackql/sessionconfig/set.go +++ b/internal/stackql/sessionconfig/set.go @@ -21,7 +21,8 @@ func Apply(host interface { lhsTrimmed = strings.TrimPrefix(strings.TrimPrefix(lhsTrimmed, "$"), ".") root, _, _ := strings.Cut(lhsTrimmed, ".") switch root { - case "auth", "providers", "secret_store", "secrets", "document_merge", "transaction": + case "auth", "providers", "tuning_by_provider", "params_by_provider", "secret_store", "secrets", + "document_merge", "transaction": default: return fmt.Errorf("unknown intrinsic session configuration %q", lhsTrimmed) } diff --git a/test/robot/functional/ProviderSessionLibrary.py b/test/robot/functional/ProviderSessionLibrary.py index 6a8c3ff0..226cf47f 100644 --- a/test/robot/functional/ProviderSessionLibrary.py +++ b/test/robot/functional/ProviderSessionLibrary.py @@ -18,6 +18,7 @@ def prepare_session_provider(self, binary, execution_platform="native", backend= self.prefix = [shutil.which(binary) or str(Path(binary).resolve())] self.root = Path(tempfile.mkdtemp(prefix="stackql-session-")) self.calls = [] + self.page_sizes = [] self.aws_calls = [] self.view_calls = [] self.concurrent_gate = None @@ -65,14 +66,19 @@ def do_GET(self): self.end_headers() self.wfile.write(payload) return - region = parse_qs(urlparse(self.path).query).get("region", [""])[0] + query = parse_qs(urlparse(self.path).query) + region = query.get("region", [""])[0] if owner.concurrent_gate is not None: owner.concurrent_gate.wait(timeout=10) owner.calls.append((token, region)) + owner.page_sizes.append(query.get("maxResults", [""])[0]) payload = json.dumps([{"id": region or "account", "active": True, "count": 42}]).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) + if region == "paged" and "page" not in query: + next_path = urlparse(self.path)._replace(query=urlencode({**query, "page": ["2"]}, doseq=True)) + self.send_header("Link", f'<{endpoint}{next_path.geturl()}>; rel="next"') self.end_headers() self.wfile.write(payload) @@ -107,9 +113,11 @@ def do_POST(self): "config": {"auth": {"type": "bearer"}}} doc = {"openapi": "3.0.0", "info": {"title": "things", "version": "v1"}, "servers": [{"url": endpoint}], "paths": {"/widgets": {"get": {"operationId": "list_widgets", - "parameters": [{"name": "region", "in": "query", "required": True, "schema": {"type": "string"}}], + "parameters": [{"name": "region", "in": "query", "required": True, "schema": {"type": "string"}}, + {"name": "maxResults", "in": "query", "schema": {"type": "integer"}}], "responses": {"200": {"content": {"application/json": {"schema": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "active": {"type": "boolean"}, "count": {"type": "integer"}}}}}}}}}}}, "components": {"x-stackQL-resources": {"widgets": {"id": "widgets.things.widgets", "name": "widgets", + "config": {"pagination": {"responseToken": {"key": "Link", "location": "header"}}}, "methods": {"list": {"operation": {"$ref": "#/paths/~1widgets/get"}, "response": {"mediaType": "application/json", "openAPIDocKey": "200"}}}, "sqlVerbs": {"select": [{"$ref": "#/components/x-stackQL-resources/widgets/methods/list"}]}}}}} registry = self.root / "registry" @@ -171,6 +179,26 @@ def provider_aliases_survive_session_edits(self): sql += "SELECT id FROM east.things.widgets WHERE region = 'override';" self.run_sql(sql, [("Bearer east-token", "east"), ("Bearer west-token", "west"), ("Bearer changed-token", "override")]) + def http_settings_follow_provider_alias_precedence(self): + sql = self.setting("tuning_by_provider.widgets", {"page_limit": 1}) + sql += self.setting("params_by_provider.widgets", {"maxResults": "6"}) + binding = {"provider": "widgets", "tenancy": "first", "auth": {"type": "bearer", "credentials": "first"}, + "params": {"region": "paged", "maxResults": "7"}} + sql += self.setting("providers.first", binding) + sql += self.setting("providers.second", {**binding, "tenancy": "second", "tuning": {"page_limit": 2}, + "auth": {"type": "bearer", "credentials": "second"}, + "params": {"region": "paged"}}) + sql += "SELECT id FROM first.things.widgets; SELECT id FROM second.things.widgets; " + sql += "SELECT id FROM first.things.widgets WHERE maxResults = 9;" + sql += 'UNSET "$.tuning_by_provider.widgets", "$.params_by_provider.widgets";' + sql += "SELECT id FROM first.things.widgets; SELECT id FROM second.things.widgets;" + before = len(self.page_sizes) + self.run_sql(sql, [("Bearer first", "paged"), ("Bearer second", "paged"), ("Bearer second", "paged"), + ("Bearer first", "paged"), ("Bearer first", "paged"), ("Bearer first", "paged"), + ("Bearer second", "paged"), ("Bearer second", "paged")], + ["--http.response.maxResults=5", "--http.response.pageLimit=2"]) + assert self.page_sizes[before:] == ["7", "6", "6", "9", "7", "7", "5", "5"], self.page_sizes[before:] + def aws_aliases_union_buckets_with_independent_signing_credentials(self): registry = self.root / "registry/src" provider = json.loads((registry / "widgets/v00.00.00000/provider.yaml").read_text()) diff --git a/test/robot/functional/stackql_provider_sessions.robot b/test/robot/functional/stackql_provider_sessions.robot index a27e2b16..728e0455 100644 --- a/test/robot/functional/stackql_provider_sessions.robot +++ b/test/robot/functional/stackql_provider_sessions.robot @@ -9,6 +9,9 @@ Suite Teardown Stop Session Provider Provider Aliases Keep Their Credentials And Scope Across Session Edits Provider Aliases Survive Session Edits +HTTP Settings Follow Provider And Alias Precedence + HTTP Settings Follow Provider Alias Precedence + AWS Aliases Union Buckets With Independent Signing Credentials AWS Aliases Union Buckets With Independent Signing Credentials From f0b2d4b39971ccbc61792d4018a2f73887773049 Mon Sep 17 00:00:00 2001 From: General Kroll Date: Sat, 21 Nov 2026 11:45:00 +1100 Subject: [PATCH 2/4] - Consume latest omni. --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 1c6a4a90..26acf5a3 100644 --- a/go.mod +++ b/go.mod @@ -24,7 +24,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.13-alpha01 + github.com/stackql-labs/omnisdk v0.1.13-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 diff --git a/go.sum b/go.sum index c17a6145..7174ed95 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.13-alpha01 h1:iEmWSXYIRMNBhextyZdr8lCwP2X8kn2WY6c9PU1XOr4= -github.com/stackql-labs/omnisdk v0.1.13-alpha01/go.mod h1:G6qZy+6Vbuy9sSfws6erzpbbuThI+cD/uXDQPgQkRBI= +github.com/stackql-labs/omnisdk v0.1.13-beta01 h1:ck+fgCAAvlt6tXk986BHVAfHkcZBTDSJpAombF+lcLk= +github.com/stackql-labs/omnisdk v0.1.13-beta01/go.mod h1:G6qZy+6Vbuy9sSfws6erzpbbuThI+cD/uXDQPgQkRBI= 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= From 3e2a8d02356decdc1ef080b14750dee866b9e9d7 Mon Sep 17 00:00:00 2001 From: General Kroll Date: Sat, 21 Nov 2026 11:50:08 +1100 Subject: [PATCH 3/4] - Update omni landing zone. --- AGENTS.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 625961c7..b97817e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ These guidelines help contributors, human and otherwise, understand and work effectively on this repository. -We also encourage reading [`docs/developer_guide.md`](/docs/developer_guide.md) for further useful information. For deeper understanding of the "brains" of `stackql`, it is worthwhile to consult [the omnisdk developer invariants](https://github.com/stackql-labs/omnisdk/blob/main/docs/developer/invariants.md) and linked documents from there. +We also encourage reading [`docs/developer_guide.md`](/docs/developer_guide.md) for further useful information. For deeper understanding of the "brains" of `stackql`, it is worthwhile to consult [the omnisdk developer guide](https://github.com/stackql-labs/omnisdk/blob/main/docs/developer/developer_guide.md) and linked documents from there. We have upgraded to golang `>= 1.27.3` in order to take advantage of [time simulation and other capabilities in `testing/synctest`](https://go.dev/blog/testing-time). diff --git a/README.md b/README.md index 4e4a3900..c3b58f57 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ StackQL is a standalone application that can be used in client mode (via __`exec StackQL parses SQL statements and transpiles them into API requests to the (cloud) resource provider. The API calls are then executed and the results are returned to the user. -StackQL provider interfaces are canonically defined in OpenAPI extensions to the providers' specification. These definitions are then used to generate the SQL schema and the API client. The source for the provider definitions are stored in the [__StackQL Registry__][registry]. The semantics of provider interactions are defined in the [`omnisdk` library](https://github.com/stackql-labs/omnisdk). For more detail on nuts and bolts, please see [the local `AGENTS.md` file](/AGENTS.md) and [the `omnisdk` developer invariants](https://github.com/stackql-labs/omnisdk/blob/main/docs/developer/invariants.md). +StackQL provider interfaces are canonically defined in OpenAPI extensions to the providers' specification. These definitions are then used to generate the SQL schema and the API client. The source for the provider definitions are stored in the [__StackQL Registry__][registry]. The semantics of provider interactions are defined in the [`omnisdk` library](https://github.com/stackql-labs/omnisdk). For more detail on nuts and bolts, please see [the local `AGENTS.md` file](/AGENTS.md) and [the `omnisdk` developer guide](https://github.com/stackql-labs/omnisdk/blob/main/docs/developer/developer_guide.md).
StackQL Context Diagram From 9b65ca1c95590cd8f9f21de196fc058c0382efc6 Mon Sep 17 00:00:00 2001 From: General Kroll Date: Sat, 21 Nov 2026 12:24:39 +1100 Subject: [PATCH 4/4] - Added robot test `Structured Config And Env Files Accept Only Scalars`. --- docs/mcp.md | 8 +- go.mod | 2 +- internal/stackql/cmd/root.go | 38 ++++-- internal/stackql/envfile/envfile.go | 43 ++++--- internal/stackql/envfile/envfile_test.go | 31 ++++- internal/stackql/flatfile/flatfile.go | 111 ++++++++++++++++++ internal/stackql/handler/provider_session.go | 8 +- .../stackql/mcpbackend/credential_reload.go | 2 +- .../stackql/mcpbackend/mcp_service_stackql.go | 2 +- .../functional/ProviderSessionLibrary.py | 41 +++++++ .../stackql_provider_sessions.robot | 3 + 11 files changed, 251 insertions(+), 38 deletions(-) create mode 100644 internal/stackql/flatfile/flatfile.go diff --git a/docs/mcp.md b/docs/mcp.md index 0b9f95de..ab235cfb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -91,7 +91,7 @@ The HTTP listener is registered for `Stop()`. Stopping the server or cancelling ### Credential (re)sourcing (`--env.file` + `reload_credentials`) -`--env.file` is a root flag: it nominates a dotenv-style file that every stackql entrypoint (`exec`, `shell`, `srv`, `mcp`) sources into the process environment at startup. For the MCP server it additionally acts as a mutable credential store: a process env block is fixed at spawn, so a stdio server launched without credential vars (eg by Claude Desktop) can only pick them up from such a file, re-sourced on each `reload_credentials` tool call. +`--env.file` is a root flag: it nominates a credential file that every stackql entrypoint (`exec`, `shell`, `srv`, `mcp`) sources into the process environment at startup. For the MCP server it additionally acts as a mutable credential store: a process env block is fixed at spawn, so a stdio server launched without credential vars (eg by Claude Desktop) can only pick them up from such a file, re-sourced on each `reload_credentials` tool call. ```bash @@ -102,14 +102,14 @@ The HTTP listener is registered for `Stop()`. Stopping the server or cancelling Semantics: - Sourced at startup (if the file exists) and again on every `reload_credentials` call; only keys with non-empty values are set, nothing is ever unset. -- An absent file is created at startup as an empty commented dotenv file (`0600` on unix, parent directories included), so packaged installs (eg MCPB bundles in Claude Desktop) can pass the flag unconditionally; an existing file is never touched, so bundle updates cannot wipe populated credentials. +- An absent file is created at startup in the format selected by its suffix (`0600` on unix, parent directories included), so packaged installs (eg MCPB bundles in Claude Desktop) can pass the flag unconditionally; an existing file is never touched, so bundle updates cannot wipe populated credentials. - The file may be created, updated or rotated at any time while the server runs. - `reload_credentials` runs three ordered phases: re-source the file, invalidate auth contexts registered lazily from provider documents (contexts supplied via `--auth` are retained), then report every installed provider against the now-current environment. The report is identical before and after a provider's first query; the optional `provider` argument filters it, and an unknown provider name is the only scoped error. - Each report row carries variable names, per-provider status (`ok`, `unresolved`, `not_checked`) and `changed` (whether the resolved credential material differs from before the reload); secret values are never returned, logged or audited. A second reload against an unchanged file is idempotent (`changed: false` throughout). Without `--env.file` it degrades to a pure status probe; a configured file that has gone missing is an explicit error naming the path. - Credentials resolve automatically at query time, so no reload is ever required before querying. Credential resolution failures on the query tools name the provider and the recovery sequence (fix the env file, call `reload_credentials`, retry); `changed: false` after a failure means the file was not updated. - Reload semantics are per process. In a replicated stateless HTTP deployment an in-band reload mutates one replica only; rotation there belongs at the deployment layer (redeploy, shared secret store, file watcher). -File format: one `KEY=VALUE` per line; `#` comments, blank lines, `export ` prefixes, surrounding quotes and CRLF are tolerated. +Files ending in `.toml`, `.yaml`, `.yml`, `.yalm`, or `.json` must contain a flat mapping with string keys and scalar values. A structured null becomes the text `null`. Other suffixes use dotenv syntax with one `KEY=VALUE` per line. Dotenv supports `#` comments, blank lines, `export ` prefixes, surrounding quotes, and CRLF. Note for Claude Desktop on Windows: `setx` writes the registry, not running processes, and Claude Desktop passes its own (stale) environment to MCP subprocesses; `--env.file` avoids restarts entirely. @@ -190,7 +190,7 @@ Tools also carry a `title` and every MCP behavioural hint as an explicit boolean | `run_lifecycle_operation` | KV | Execute a stackql `EXEC` lifecycle operation. Returns `{messages, timestamp}`. Gated by the server [mode](#server-modes). | | `list_registry` | Table | Providers (and their versions) available in the configured registry. Optional `provider` lists versions for that provider. | | `pull_provider` | KV | Install a provider from the registry into the local approot cache. Requires `provider`; `version` optional. Local cache write only. | -| `reload_credentials` | Table | Live-reload credentials: re-source the [`--env.file`](#credential-resourcing---envfile--reload_credentials) dotenv file into the process environment, invalidate cached auth contexts and report resolution status (with a `changed` flag) for every installed provider. Never returns secret values. Optional `provider` filters the report. Recovery and rotation only, never a pre-query step. Allowed in every mode. | +| `reload_credentials` | Table | Live-reload credentials: re-source the [`--env.file`](#credential-resourcing---envfile--reload_credentials) file into the process environment, invalidate cached auth contexts and report resolution status (with a `changed` flag) for every installed provider. Never returns secret values. Optional `provider` filters the report. Recovery and rotation only, never a pre-query step. Allowed in every mode. | | `query_library_search` | Table | Search the curated query library by natural-language `intent` (optional `provider` / `service` / `tags` filters). Consult before composing SQL from scratch. Read-only, no credentials. | | `query_library_get` | KV | Retrieve one library entry by `id`; with `params` the server validates them and returns rendered SQL plus the tool to execute it with. Read-only, no credentials. | diff --git a/go.mod b/go.mod index 26acf5a3..8bf922b3 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/stackql/stackql go 1.27.3 require ( + github.com/BurntSushi/toml v1.4.0 github.com/DATA-DOG/go-sqlmock v1.5.1 github.com/Masterminds/semver v1.4.2 github.com/PaesslerAG/gval v1.0.0 @@ -49,7 +50,6 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.1 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0 // indirect - github.com/BurntSushi/toml v1.4.0 // indirect github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c // indirect github.com/apache/arrow-go/v18 v18.0.0 // indirect github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect diff --git a/internal/stackql/cmd/root.go b/internal/stackql/cmd/root.go index 17ff60cc..723bbd98 100644 --- a/internal/stackql/cmd/root.go +++ b/internal/stackql/cmd/root.go @@ -16,6 +16,7 @@ limitations under the License. package cmd import ( + "errors" "fmt" "os" "path" @@ -26,6 +27,7 @@ import ( "github.com/stackql/stackql/internal/stackql/config" "github.com/stackql/stackql/internal/stackql/constants" "github.com/stackql/stackql/internal/stackql/envfile" + "github.com/stackql/stackql/internal/stackql/flatfile" "github.com/stackql/stackql/internal/stackql/intrinsic" "github.com/stackql/stackql/internal/stackql/logging" "github.com/stackql/stackql/internal/stackql/output" @@ -206,7 +208,7 @@ func init() { _ = rootCmd.PersistentFlags().String(dto.ColorSchemeKey, "", "DEPRECATED: color schemes are no longer supported") rootCmd.PersistentFlags().StringVar(&runtimeCtx.CABundle, dto.CABundleKey, "", "Path to CA bundle, if not specified then system defaults used.") rootCmd.PersistentFlags().BoolVar(&runtimeCtx.AllowInsecure, dto.AllowInsecureKey, false, "Allow trust of insecure certificates (not recommended)") - rootCmd.PersistentFlags().StringVar(&runtimeCtx.ConfigFilePath, dto.ConfigFilePathKey, config.GetDefaultConfigFilePath(), "Config file full path; defaults to current dir") + rootCmd.PersistentFlags().StringVar(&runtimeCtx.ConfigFilePath, dto.ConfigFilePathKey, config.GetDefaultConfigFilePath(), "Config file path (properties, TOML, YAML or JSON). A configfile entry in the file is ignored.") rootCmd.PersistentFlags().StringVar(&runtimeCtx.ApplicationFilesRootPath, dto.ApplicationFilesRootPathKey, config.GetDefaultApplicationFilesRoot(), "Application config and cache root path") rootCmd.PersistentFlags().Uint32Var(&runtimeCtx.ApplicationFilesRootPathMode, dto.ApplicationFilesRootPathModeKey, config.GetDefaultProviderCacheDirFileMode(), "Application config and cache file mode") rootCmd.PersistentFlags().StringVar(&runtimeCtx.ViperCfgFileName, dto.ViperCfgFileNameKey, config.GetDefaultViperConfigFileName(), "Config filename") @@ -278,24 +280,40 @@ func init() { rootCmd.PersistentFlags().StringVar(&mcpServerType, "mcp.server.type", "", "MCP server type (http or stdio for now)") rootCmd.PersistentFlags().StringVar(&mcpLogFormat, "mcp.log.format", "", "MCP audit log format: jsonl (default) or otel (OTLP/JSON log records); overrides server.audit.format in mcp.config") rootCmd.PersistentFlags().StringVar(&mcpProtocolVersion, "mcp.protocol.version", "", "newest MCP protocol revision advertised: auto (default, every SDK revision), 2026-07-28 (sessionless only; implies stateless HTTP) or an older revision such as 2025-11-25 (that revision and earlier); overrides server.protocol_version in mcp.config") - rootCmd.PersistentFlags().StringVar(&envFilePath, "env.file", "", "optional dotenv-style file sourced into the process environment at startup, created empty if absent; the MCP reload_credentials tool re-sources it on demand") + rootCmd.PersistentFlags().StringVar(&envFilePath, "env.file", "", "Optional dotenv, TOML, YAML or JSON file sourced at startup and by MCP reload_credentials. Created empty if absent.") } -func mergeConfigFromFile(runtimeCtx *dto.RuntimeCtx, flagSet pflag.FlagSet) { - props, err := properties.LoadFile(runtimeCtx.ConfigFilePath, properties.UTF8) - if err == nil { - propertiesMap := props.Map() - for k, v := range propertiesMap { - if flagSet.Lookup(k) != nil && !flagSet.Lookup(k).Changed { - runtimeCtx.Set(k, v) //nolint:errcheck // TODO: investigate +func mergeConfigFromFile(runtimeCtx *dto.RuntimeCtx, flagSet *pflag.FlagSet) error { + values, err := flatfile.Load(runtimeCtx.ConfigFilePath, func(data []byte) (map[string]string, error) { + loader := properties.Loader{Encoding: properties.UTF8, DisableExpansion: true} + props, err := loader.LoadBytes(data) + if err != nil { + return nil, fmt.Errorf("invalid properties configuration") + } + return props.Map(), nil + }, dto.ConfigFilePathKey) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + for key, value := range values { + if flag := flagSet.Lookup(key); key != dto.ConfigFilePathKey && flag != nil && !flag.Changed { + if setErr := runtimeCtx.Set(key, value); setErr != nil { + return fmt.Errorf("invalid value for config key %q", key) } } } + return nil } // initConfig reads in config file and ENV variables if set. func initConfig() { - mergeConfigFromFile(&runtimeCtx, *rootCmd.PersistentFlags()) + if err := mergeConfigFromFile(&runtimeCtx, rootCmd.PersistentFlags()); err != nil { + fmt.Fprintf(os.Stderr, "failed to load config file '%s': %v\n", runtimeCtx.ConfigFilePath, err) + os.Exit(1) + } intrinsic.Init(previewCfgRaw) if err := output.InitOTelConfig(otelConfigRaw); err != nil { diff --git a/internal/stackql/envfile/envfile.go b/internal/stackql/envfile/envfile.go index 72da1c95..08d02c02 100644 --- a/internal/stackql/envfile/envfile.go +++ b/internal/stackql/envfile/envfile.go @@ -1,10 +1,13 @@ package envfile import ( + "fmt" "os" "path/filepath" "sort" "strings" + + "github.com/stackql/stackql/internal/stackql/flatfile" ) const defaultContent = `# StackQL credential store, sourced at startup and on each reload_credentials call @@ -19,7 +22,7 @@ const ( ) // EnsureExists creates path (parent directories included) as an empty -// commented dotenv file when absent, so packaged installs (eg MCP bundles) +// credential file when absent, so packaged installs (eg MCP bundles) // get a working credential store on first launch; an existing file is never // touched, since bundle updates must not wipe populated credentials. Returns // whether this call created the file. An empty path is a no-op. @@ -45,22 +48,27 @@ func EnsureExists(path string) (bool, error) { return false, err } defer f.Close() //nolint:errcheck // write error is surfaced below - if _, writeErr := f.WriteString(defaultContent); writeErr != nil { + content := defaultContent + switch flatfile.Format(path) { + case "json", "yaml": + content = "{}\n" + case "toml": + content = "" + } + if _, writeErr := f.WriteString(content); writeErr != nil { return false, writeErr } return true, nil } -// parse reads a dotenv-style file: KEY=VALUE lines; `#` comments, blanks, -// `export ` prefixes, surrounding quotes and CRLF tolerated. Keys with -// empty values are dropped so a reload cannot blank out a working credential. func parse(path string) (map[string]string, error) { - b, err := os.ReadFile(path) - if err != nil { - return nil, err - } + return flatfile.Load(path, parseDotenv) +} + +// parseDotenv accepts KEY=VALUE lines, comments, blanks, export prefixes and surrounding quotes. +func parseDotenv(b []byte) (map[string]string, error) { rv := map[string]string{} - for _, line := range strings.Split(string(b), "\n") { + for lineNumber, line := range strings.Split(string(b), "\n") { line = strings.TrimSpace(strings.TrimSuffix(line, "\r")) if line == "" || strings.HasPrefix(line, "#") { continue @@ -69,7 +77,7 @@ func parse(path string) (map[string]string, error) { key, val, found := strings.Cut(line, "=") key = strings.TrimSpace(key) if !found || key == "" { - continue + return nil, fmt.Errorf("expected KEY=VALUE on line %d", lineNumber+1) } val = strings.TrimSpace(val) if len(val) >= 2 { //nolint:mnd // shortest quoted form is "" @@ -78,10 +86,9 @@ func parse(path string) (map[string]string, error) { val = val[1 : len(val)-1] } } - if val == "" { - continue + if val != "" { + rv[key] = val } - rv[key] = val } return rv, nil } @@ -100,8 +107,16 @@ func Source(path string) ([]string, bool, error) { } return nil, false, err } + for k, v := range vars { + if k == "" || strings.ContainsAny(k, "=\x00") || strings.ContainsRune(v, '\x00') { + return nil, false, fmt.Errorf("invalid environment entry for key %q", k) + } + } keys := make([]string, 0, len(vars)) for k, v := range vars { + if v == "" { + continue + } if setErr := os.Setenv(k, v); setErr != nil { return nil, false, setErr } diff --git a/internal/stackql/envfile/envfile_test.go b/internal/stackql/envfile/envfile_test.go index b0e96824..bc2b2016 100644 --- a/internal/stackql/envfile/envfile_test.go +++ b/internal/stackql/envfile/envfile_test.go @@ -19,7 +19,6 @@ func TestParse(t *testing.T) { "SINGLE_QUOTED='single quoted value'", "CRLF_KEY=crlf-value\r", "EMPTY_KEY=", - "NOT_A_PAIR", "SPACED_KEY = spaced-value", }, "\n") if err := os.WriteFile(path, []byte(content), 0o600); err != nil { @@ -48,8 +47,34 @@ func TestParse(t *testing.T) { if _, present := got["EMPTY_KEY"]; present { t.Errorf("empty-valued key must be dropped, got %v", got) } - if _, present := got["NOT_A_PAIR"]; present { - t.Errorf("non-pair line must be dropped, got %v", got) +} + +func TestSourceRejectsMalformedDotenv(t *testing.T) { + path := filepath.Join(t.TempDir(), "bad.env") + const key = "STACKQL_TEST_RELOAD_VAR" + t.Setenv(key, "original") + if err := os.WriteFile(path, []byte(key+"=new\nNOT_A_PAIR\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, _, err := Source(path); err == nil { + t.Fatal("expected malformed dotenv error") + } + if got := os.Getenv(key); got != "original" { + t.Fatalf("invalid file changed environment to %q", got) + } +} + +func TestEnsureExistsCreatesParseableStructuredFiles(t *testing.T) { + for _, suffix := range []string{"json", "toml", "yaml", "yml", "yalm"} { + t.Run(suffix, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "creds."+suffix) + if created, err := EnsureExists(path); err != nil || !created { + t.Fatalf("created=%t, err=%v", created, err) + } + if keys, sourced, err := Source(path); err != nil || !sourced || len(keys) != 0 { + t.Fatalf("keys=%v, sourced=%t, err=%v", keys, sourced, err) + } + }) } } diff --git a/internal/stackql/flatfile/flatfile.go b/internal/stackql/flatfile/flatfile.go new file mode 100644 index 00000000..0c3e5f08 --- /dev/null +++ b/internal/stackql/flatfile/flatfile.go @@ -0,0 +1,111 @@ +// Package flatfile reads flat maps of scalar configuration values. +package flatfile + +import ( + "bytes" + "encoding" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/BurntSushi/toml" + "gopkg.in/yaml.v3" +) + +// Format returns the structured format inferred from path, or an empty string for legacy files. +func Format(path string) string { + switch strings.ToLower(filepath.Ext(path)) { + case ".json": + return "json" + case ".yaml", ".yml", ".yalm": + return "yaml" + case ".toml": + return "toml" + default: + return "" + } +} + +// Load uses the file suffix to select a structured parser or the supplied legacy parser. +func Load(path string, legacy func([]byte) (map[string]string, error), ignore ...string) (map[string]string, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + format := Format(path) + if format == "" { + return legacy(data) + } + var decoded any + switch format { + case "toml": + fields := map[string]any{} + _, err = toml.Decode(string(data), &fields) + decoded = fields + case "json": + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + decoded, err = decodeOne(decoder) + case "yaml": + decoder := yaml.NewDecoder(bytes.NewReader(data)) + decoded, err = decodeOne(decoder) + } + if err != nil { + if format == "yaml" && errors.Is(err, io.EOF) { + return map[string]string{}, nil + } + // Parser diagnostics can include source values, including credentials. + return nil, fmt.Errorf("invalid %s configuration", format) + } + fields, ok := decoded.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s configuration must be a mapping with string keys", format) + } + values := make(map[string]string, len(fields)) + for key, value := range fields { + if slices.Contains(ignore, key) { + continue + } + text, scalarErr := scalarText(value) + if scalarErr != nil { + return nil, fmt.Errorf("configuration key %q: %w", key, scalarErr) + } + values[key] = text + } + return values, nil +} + +func decodeOne(decoder interface{ Decode(any) error }) (any, error) { + var value any + if err := decoder.Decode(&value); err != nil { + return nil, err + } + if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) { + return nil, fmt.Errorf("expected one document") + } + return value, nil +} + +func scalarText(value any) (string, error) { + switch v := value.(type) { + case nil: + return "null", nil + case string: + return v, nil + case bool, int, int64, uint64, float64, json.Number: + return fmt.Sprint(v), nil + case encoding.TextMarshaler: + text, err := v.MarshalText() + if err != nil { + return "", fmt.Errorf("invalid scalar value") + } + return string(text), nil + default: + return "", fmt.Errorf("expected a scalar value") + } +} diff --git a/internal/stackql/handler/provider_session.go b/internal/stackql/handler/provider_session.go index 7fa48acd..85bdb906 100644 --- a/internal/stackql/handler/provider_session.go +++ b/internal/stackql/handler/provider_session.go @@ -287,8 +287,8 @@ func (state *providerSessionState) setProviderTuning(path []string, rhs interfac delete(tuning, provider) } else { var override omnisdk.ProviderTuning - if err := decodeSessionObject(rhs, &override); err != nil { - return err + if decodeErr := decodeSessionObject(rhs, &override); decodeErr != nil { + return decodeErr } if tuning == nil { tuning = make(map[string]omnisdk.ProviderTuning) @@ -316,8 +316,8 @@ func (state *providerSessionState) setProviderParams(path []string, rhs interfac return nil } var params map[string]string - if err := decodeSessionObject(rhs, ¶ms); err != nil { - return err + if decodeErr := decodeSessionObject(rhs, ¶ms); decodeErr != nil { + return decodeErr } if state.providerParams == nil { state.providerParams = make(map[string]map[string]string) diff --git a/internal/stackql/mcpbackend/credential_reload.go b/internal/stackql/mcpbackend/credential_reload.go index baea120a..9c03e4e5 100644 --- a/internal/stackql/mcpbackend/credential_reload.go +++ b/internal/stackql/mcpbackend/credential_reload.go @@ -19,7 +19,7 @@ import ( // Credential (re)sourcing for the MCP server (issue #688). A process env // block is fixed at spawn, so a stdio child launched without credential vars -// can never see them; re-sourcing the --env.file dotenv file into this +// can never see them; re-sourcing --env.file into this // process's environment bridges that gap. Values are never echoed, logged // or audited - only names and per-provider statuses. diff --git a/internal/stackql/mcpbackend/mcp_service_stackql.go b/internal/stackql/mcpbackend/mcp_service_stackql.go index 855f533e..55e2e9fb 100644 --- a/internal/stackql/mcpbackend/mcp_service_stackql.go +++ b/internal/stackql/mcpbackend/mcp_service_stackql.go @@ -284,7 +284,7 @@ type stackqlMCPService struct { handlerCtx handler.HandlerContext logger *logrus.Logger serverInfo serverBuildInfo - // envFile is the --env.file dotenv path re-sourced by reload_credentials + // envFile is the path re-sourced by reload_credentials // (issue #688); empty means none configured. envFile string } diff --git a/test/robot/functional/ProviderSessionLibrary.py b/test/robot/functional/ProviderSessionLibrary.py index 226cf47f..f1b05349 100644 --- a/test/robot/functional/ProviderSessionLibrary.py +++ b/test/robot/functional/ProviderSessionLibrary.py @@ -199,6 +199,47 @@ def http_settings_follow_provider_alias_precedence(self): ["--http.response.maxResults=5", "--http.response.pageLimit=2"]) assert self.page_sizes[before:] == ["7", "6", "6", "9", "7", "7", "5", "5"], self.page_sizes[before:] + def structured_config_and_env_files(self): + formats = { + "json": ('{"http.response.maxResults": 7, "configfile": {"ignored": true}}', + '{"STACKQL_TEST_FILE_TOKEN": 42}', '{"nested": ["secret"]}'), + "toml": ('"http.response.maxResults" = 7\n[configfile]\nignored = true', + 'STACKQL_TEST_FILE_TOKEN = 42', 'nested = ["secret"]'), + **{suffix: ('http.response.maxResults: 7\nconfigfile: {ignored: true}', + 'STACKQL_TEST_FILE_TOKEN: 42', 'nested: [secret]') + for suffix in ("yaml", "yml", "yalm")}, + } + sql = self.setting("providers.filetest", {"provider": "widgets", "tenancy": "filetest", + "auth": {"type": "bearer", "credentialsenvvar": "STACKQL_TEST_FILE_TOKEN"}, + "params": {"region": "filetest"}}) + sql += "SELECT id FROM filetest.things.widgets;" + legacy_config = self.root / "config.properties" + legacy_env = self.root / "creds.env" + legacy_config.write_text("http.response.maxResults=7\nconfigfile=${configfile}\n") + legacy_env.write_text('export STACKQL_TEST_FILE_TOKEN="legacy"\n') + self.run_sql(sql, [("Bearer legacy", "filetest")], + ["--configfile", str(legacy_config), "--env.file", str(legacy_env)]) + assert self.page_sizes[-1] == "7" + for suffix, (config, env, invalid) in formats.items(): + config_path = self.root / f"config.{suffix}" + env_path = self.root / f"env.{suffix}" + config_path.write_text(config) + env_path.write_text(env) + flags = ["--configfile", str(config_path), "--env.file", str(env_path)] + self.run_sql(sql, [("Bearer 42", "filetest")], flags) + assert self.page_sizes[-1] == "7", suffix + self.run_sql(sql, [("Bearer 42", "filetest")], flags + ["--http.response.maxResults=8"]) + assert self.page_sizes[-1] == "8", suffix + for path in (config_path, env_path): + before = len(self.calls) + original = path.read_text() + path.write_text(invalid) + result = subprocess.run(self.prefix + ["exec", sql] + self.flags + flags, + text=True, capture_output=True, timeout=30, env=self.env) + path.write_text(original) + assert result.returncode != 0 and "expected a scalar value" in result.stderr, result.stderr + assert len(self.calls) == before, suffix + def aws_aliases_union_buckets_with_independent_signing_credentials(self): registry = self.root / "registry/src" provider = json.loads((registry / "widgets/v00.00.00000/provider.yaml").read_text()) diff --git a/test/robot/functional/stackql_provider_sessions.robot b/test/robot/functional/stackql_provider_sessions.robot index 728e0455..ac7d0f27 100644 --- a/test/robot/functional/stackql_provider_sessions.robot +++ b/test/robot/functional/stackql_provider_sessions.robot @@ -12,6 +12,9 @@ Provider Aliases Keep Their Credentials And Scope Across Session Edits HTTP Settings Follow Provider And Alias Precedence HTTP Settings Follow Provider Alias Precedence +Structured Config And Env Files Accept Only Scalars + Structured Config And Env Files + AWS Aliases Union Buckets With Independent Signing Credentials AWS Aliases Union Buckets With Independent Signing Credentials