diff --git a/README.md b/README.md index 20f80a2..64f9f9d 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ omni models list --name marketing omni models validate 550e8400-e29b-41d4-a716-446655440000 omni models topics list 550e8400-e29b-41d4-a716-446655440000 omni connections list +omni connections create omni connections create --file connection.json omni connections dbt update 550e8400-e29b-41d4-a716-446655440000 --file connection-dbt.json omni connections schedules list 550e8400-e29b-41d4-a716-446655440000 @@ -191,6 +192,7 @@ See also: - `omni documents list|get|create|delete|rename|move|draft create|draft discard|duplicate|favorite add|favorite remove|access list|permissions get|permissions add|permissions update|permissions revoke|permissions settings|label add|label remove|labels bulk-update|queries|transfer-ownership` - `omni models list|get|create|refresh|validate|branch delete|branch merge|cache-reset|topics list|get|update|delete|views list|update|delete|fields create|update|delete|git get|create|update|delete|sync|migrate|content-validator get|replace|yaml get|create|delete` - `omni connections list|create|update|dbt get|dbt update|dbt delete|schedules list|schedules create|schedules get|schedules update|schedules delete|environments list|environments create|environments update|environments delete` + `connections create` supports an interactive wizard or `--file` JSON input - `omni folders list|create|delete|permissions get|permissions add|permissions update|permissions revoke` - `omni labels list|get|create|update|delete` - `omni schedules list|create|get|update|delete|pause|resume|trigger|recipients get|recipients add|recipients remove|transfer-ownership` diff --git a/internal/cli/connections.go b/internal/cli/connections.go index 32f8465..f5aa292 100644 --- a/internal/cli/connections.go +++ b/internal/cli/connections.go @@ -1,15 +1,20 @@ package cli import ( + "bufio" "context" + "encoding/json" "errors" "flag" "fmt" "io" + "os" + "strconv" "strings" "time" "github.com/omni-co/omni-cli/internal/client" + "github.com/omni-co/omni-cli/internal/client/gen" "github.com/omni-co/omni-cli/internal/output" ) @@ -79,6 +84,10 @@ func runConnectionsList(rt *runtime, args []string) int { } func runConnectionsCreate(rt *runtime, args []string) int { + return runConnectionsCreateWithPrompts(rt, args, !rt.NoInput && stdinIsTerminal(), bufio.NewReader(os.Stdin), promptSecretInput) +} + +func runConnectionsCreateWithPrompts(rt *runtime, args []string, canPrompt bool, reader *bufio.Reader, promptSecret func(*bufio.Reader, string) (string, error)) int { fs := flag.NewFlagSet("connections create", flag.ContinueOnError) fs.SetOutput(io.Discard) @@ -91,13 +100,25 @@ func runConnectionsCreate(rt *runtime, args []string) int { } return usageFail(rt, err.Error()) } - if fs.NArg() != 0 || strings.TrimSpace(filePath) == "" { + if fs.NArg() != 0 { return usageFail(rt, "usage: omni connections create --file ") } - payload, err := readJSONFile(filePath) - if err != nil { - return fail(rt, 1, codeConfigError, "failed to read connections create body", map[string]any{"error": err.Error()}) + var payload []byte + var err error + if strings.TrimSpace(filePath) != "" { + payload, err = readJSONFile(filePath) + if err != nil { + return fail(rt, 1, codeConfigError, "failed to read connections create body", map[string]any{"error": err.Error()}) + } + } else { + if !canPrompt { + return usageFail(rt, "usage: omni connections create --file (or run from a terminal for interactive setup)") + } + payload, err = promptConnectionCreatePayload(reader, promptSecret) + if err != nil { + return fail(rt, 1, codeUsageError, "interactive connection setup failed", map[string]any{"error": err.Error()}) + } } api, err := client.New(rt.Resolved.Profile.BaseURL, rt.Resolved.Profile.Token) @@ -114,6 +135,622 @@ func runConnectionsCreate(rt *runtime, args []string) int { return succeedOrFail(rt, resp.StatusCode(), "connections create", resp.Body) } +func promptConnectionCreatePayload(reader *bufio.Reader, promptSecret func(*bufio.Reader, string) (string, error)) ([]byte, error) { + if reader == nil { + reader = bufio.NewReader(os.Stdin) + } + if promptSecret == nil { + promptSecret = promptSecretInput + } + + fmt.Fprintln(os.Stderr, "Interactive connection setup") + fmt.Fprintf(os.Stderr, "Press Enter to accept defaults. Supported interactive dialects: %s.\n", strings.Join(connectionWizardDialects(), ", ")) + + dialect, err := promptInput(reader, "Dialect", string(gen.Postgres)) + if err != nil { + return nil, err + } + normalizedDialect := normalizeConnectionDialect(dialect) + if normalizedDialect == "" { + return nil, fmt.Errorf("invalid dialect %q", strings.TrimSpace(dialect)) + } + spec, ok := connectionWizardSpecForDialect(normalizedDialect) + if !ok { + return nil, fmt.Errorf("interactive setup does not yet support %q; use --file for this dialect", normalizedDialect) + } + + name, err := promptRequiredInput(reader, "Display name", "") + if err != nil { + return nil, err + } + body := map[string]any{ + "dialect": string(normalizedDialect), + "name": name, + } + if err := populateConnectionWizardBody(reader, promptSecret, spec, body); err != nil { + return nil, err + } + + baseRoleInput, err := promptInput(reader, "Base role", string(gen.QUERIER)) + if err != nil { + return nil, err + } + baseRole, err := parseConnectionBaseRole(baseRoleInput) + if err != nil { + return nil, err + } + systemTimezone, err := promptInput(reader, "Database timezone", "UTC") + if err != nil { + return nil, err + } + queryTimezone, err := promptInput(reader, "Query timezone (blank for no conversion)", "") + if err != nil { + return nil, err + } + queryTimeout, err := promptOptionalPositiveInt(reader, "Query timeout seconds", "900") + if err != nil { + return nil, err + } + includeSchemas, err := promptInput(reader, "Include schemas (optional)", "") + if err != nil { + return nil, err + } + scratchSchema, err := promptInput(reader, "Schema for table uploads (optional)", "") + if err != nil { + return nil, err + } + allowsUserSpecificTimezones, err := promptOptionalBool(reader, "Allow user-specific timezones", false) + if err != nil { + return nil, err + } + + body["baseRole"] = string(baseRole) + if tz := strings.TrimSpace(systemTimezone); tz != "" { + body["systemTimezone"] = tz + } + if tz := strings.TrimSpace(queryTimezone); tz != "" { + body["queryTimezone"] = tz + } + if queryTimeout > 0 { + body["queryTimeoutSeconds"] = queryTimeout + } + if schemas := strings.TrimSpace(includeSchemas); schemas != "" { + body["includeSchemas"] = schemas + } + if schema := strings.TrimSpace(scratchSchema); schema != "" { + body["scratchSchema"] = schema + } + if allowsUserSpecificTimezones { + body["allowsUserSpecificTimezones"] = true + } + + payload, err := json.Marshal(body) + if err != nil { + return nil, err + } + return payload, nil +} + +type connectionWizardSpec struct { + HostLabel string + HostRequired bool + PortLabel string + PortDefault string + PortRequired bool + DatabaseLabel string + DatabaseRequired bool + DefaultSchemaLabel string + DefaultSchemaRequired bool + UsernameLabel string + UsernameRequired bool + PasswordLabel string + PasswordRequired bool + RegionLabel string + RegionRequired bool + WarehouseLabel string + WarehouseRequired bool + SupportsTrustCertificate bool + SupportsPrivateKey bool + PrivateKeyLabel string + SupportsServiceAccountKey bool + ServiceAccountKeyLabel string + SupportsMaxBillingBytes bool + SupportsOtherCatalogs bool +} + +func connectionWizardDialects() []string { + return []string{ + string(gen.Postgres), + string(gen.Redshift), + string(gen.Mysql), + string(gen.Mariadb), + string(gen.Mssql), + string(gen.Snowflake), + string(gen.Databricks), + string(gen.Bigquery), + string(gen.Athena), + string(gen.Motherduck), + string(gen.Clickhouse), + string(gen.Exasol), + string(gen.Starrocks), + string(gen.Trino), + } +} + +func connectionWizardSpecForDialect(dialect gen.ConnectionsCreateJSONBodyDialect) (connectionWizardSpec, bool) { + switch dialect { + case gen.Postgres: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + PortLabel: "Port", + PortDefault: "5432", + PortRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: true, + }, true + case gen.Redshift: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + PortLabel: "Port", + PortDefault: "5439", + PortRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: true, + }, true + case gen.Mysql, gen.Mariadb: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + PortLabel: "Port", + PortDefault: "3306", + PortRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: true, + }, true + case gen.Mssql: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + PortLabel: "Port", + PortDefault: "1433", + PortRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + DefaultSchemaLabel: "Default schema", + DefaultSchemaRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: true, + SupportsTrustCertificate: true, + }, true + case gen.Snowflake: + return connectionWizardSpec{ + HostLabel: "Account identifier", + HostRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: false, + WarehouseLabel: "Warehouse", + WarehouseRequired: true, + SupportsPrivateKey: true, + PrivateKeyLabel: "Private key file path", + SupportsOtherCatalogs: true, + }, true + case gen.Databricks: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + DatabaseLabel: "Default catalog", + DatabaseRequired: true, + UsernameLabel: "Username or client ID", + UsernameRequired: true, + PasswordLabel: "Token or client secret", + PasswordRequired: true, + WarehouseLabel: "HTTP path", + WarehouseRequired: true, + SupportsOtherCatalogs: true, + }, true + case gen.Bigquery: + return connectionWizardSpec{ + DatabaseLabel: "Project ID", + DatabaseRequired: true, + DefaultSchemaLabel: "Default dataset (optional)", + UsernameLabel: "Client email", + UsernameRequired: true, + RegionLabel: "Region", + RegionRequired: true, + SupportsServiceAccountKey: true, + ServiceAccountKeyLabel: "Service account JSON file path", + SupportsMaxBillingBytes: true, + SupportsOtherCatalogs: true, + }, true + case gen.Athena: + return connectionWizardSpec{ + DatabaseLabel: "Data catalog", + DatabaseRequired: true, + UsernameLabel: "AWS access key ID", + UsernameRequired: true, + PasswordLabel: "AWS secret access key", + PasswordRequired: true, + RegionLabel: "AWS region", + RegionRequired: true, + SupportsOtherCatalogs: true, + }, true + case gen.Motherduck: + return connectionWizardSpec{ + DatabaseLabel: "Database (optional)", + PasswordLabel: "Service token", + PasswordRequired: true, + SupportsOtherCatalogs: true, + }, true + case gen.Clickhouse, gen.Exasol, gen.Starrocks, gen.Trino: + return connectionWizardSpec{ + HostLabel: "Host", + HostRequired: true, + PortLabel: "Port", + PortRequired: true, + DatabaseLabel: "Database", + DatabaseRequired: true, + UsernameLabel: "Username", + UsernameRequired: true, + PasswordLabel: "Password", + PasswordRequired: true, + SupportsTrustCertificate: dialect == gen.Clickhouse || dialect == gen.Exasol, + SupportsOtherCatalogs: dialect == gen.Trino, + }, true + default: + return connectionWizardSpec{}, false + } +} + +func populateConnectionWizardBody(reader *bufio.Reader, promptSecret func(*bufio.Reader, string) (string, error), spec connectionWizardSpec, body map[string]any) error { + serviceAccountDefaults := map[string]string{} + if spec.SupportsServiceAccountKey { + path, err := promptRequiredInput(reader, spec.ServiceAccountKeyLabel, "") + if err != nil { + return err + } + content, defaults, err := readConnectionSecretFile(path) + if err != nil { + return err + } + body["passwordUnencrypted"] = content + serviceAccountDefaults = defaults + } + + if spec.HostRequired || spec.HostLabel != "" { + host, err := promptMaybeRequiredInput(reader, spec.HostLabel, "", spec.HostRequired) + if err != nil { + return err + } + if host != "" { + body["host"] = host + } + } + if spec.PortRequired || spec.PortLabel != "" { + port, err := promptMaybeRequiredPositiveInt(reader, spec.PortLabel, spec.PortDefault, spec.PortRequired) + if err != nil { + return err + } + if port > 0 { + body["port"] = port + } + } + if spec.DatabaseRequired || spec.DatabaseLabel != "" { + defaultValue := "" + if spec.SupportsServiceAccountKey { + defaultValue = serviceAccountDefaults["project_id"] + } + database, err := promptMaybeRequiredInput(reader, spec.DatabaseLabel, defaultValue, spec.DatabaseRequired) + if err != nil { + return err + } + if database != "" { + body["database"] = database + } + } + if spec.DefaultSchemaRequired || spec.DefaultSchemaLabel != "" { + defaultSchema, err := promptMaybeRequiredInput(reader, spec.DefaultSchemaLabel, "", spec.DefaultSchemaRequired) + if err != nil { + return err + } + if defaultSchema != "" { + body["defaultSchema"] = defaultSchema + } + } + if spec.UsernameRequired || spec.UsernameLabel != "" { + defaultValue := "" + if spec.SupportsServiceAccountKey { + defaultValue = serviceAccountDefaults["client_email"] + } + username, err := promptMaybeRequiredInput(reader, spec.UsernameLabel, defaultValue, spec.UsernameRequired) + if err != nil { + return err + } + if username != "" { + body["username"] = username + } + } + + if spec.SupportsPrivateKey { + authMethod, err := promptInput(reader, "Authentication method (password|private-key)", "password") + if err != nil { + return err + } + switch strings.ToLower(strings.TrimSpace(authMethod)) { + case "", "password": + password, err := promptConnectionSecretValue(promptSecret, reader, spec.PasswordLabel, true) + if err != nil { + return err + } + body["passwordUnencrypted"] = password + case "private-key", "private_key", "keypair", "key-pair": + privateKeyPath, err := promptRequiredInput(reader, spec.PrivateKeyLabel, "") + if err != nil { + return err + } + privateKey, err := readRequiredFile(privateKeyPath) + if err != nil { + return err + } + body["privateKey"] = privateKey + default: + return fmt.Errorf("invalid authentication method %q", strings.TrimSpace(authMethod)) + } + } else if spec.PasswordRequired || spec.PasswordLabel != "" { + password, err := promptConnectionSecretValue(promptSecret, reader, spec.PasswordLabel, spec.PasswordRequired) + if err != nil { + return err + } + if password != "" { + body["passwordUnencrypted"] = password + } + } + + if spec.WarehouseRequired || spec.WarehouseLabel != "" { + warehouse, err := promptMaybeRequiredInput(reader, spec.WarehouseLabel, "", spec.WarehouseRequired) + if err != nil { + return err + } + if warehouse != "" { + body["warehouse"] = warehouse + } + } + if spec.RegionRequired || spec.RegionLabel != "" { + region, err := promptMaybeRequiredInput(reader, spec.RegionLabel, "", spec.RegionRequired) + if err != nil { + return err + } + if region != "" { + body["region"] = region + } + } + if spec.SupportsMaxBillingBytes { + maxBillingBytes, err := promptInput(reader, "Max billing bytes (optional)", "") + if err != nil { + return err + } + if strings.TrimSpace(maxBillingBytes) != "" { + body["maxBillingBytes"] = strings.TrimSpace(maxBillingBytes) + } + } + if spec.SupportsOtherCatalogs { + includeOtherCatalogs, err := promptInput(reader, "Include other catalogs/databases (optional)", "") + if err != nil { + return err + } + if strings.TrimSpace(includeOtherCatalogs) != "" { + body["includeOtherCatalogs"] = strings.TrimSpace(includeOtherCatalogs) + } + } + if spec.SupportsTrustCertificate { + trustServerCertificate, err := promptOptionalBool(reader, "Trust server certificate", false) + if err != nil { + return err + } + if trustServerCertificate { + body["trustServerCertificate"] = true + } + } + return nil +} + +func promptRequiredInput(reader *bufio.Reader, label, defaultValue string) (string, error) { + value, err := promptInput(reader, label, defaultValue) + if err != nil { + return "", err + } + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s is required", strings.ToLower(label)) + } + return value, nil +} + +func promptMaybeRequiredInput(reader *bufio.Reader, label, defaultValue string, required bool) (string, error) { + if required { + return promptRequiredInput(reader, label, defaultValue) + } + value, err := promptInput(reader, label, defaultValue) + if err != nil { + return "", err + } + return strings.TrimSpace(value), nil +} + +func promptRequiredPositiveInt(reader *bufio.Reader, label, defaultValue string) (int, error) { + value, err := promptRequiredInput(reader, label, defaultValue) + if err != nil { + return 0, err + } + return parsePositiveInt(value, label) +} + +func promptMaybeRequiredPositiveInt(reader *bufio.Reader, label, defaultValue string, required bool) (int, error) { + if required { + return promptRequiredPositiveInt(reader, label, defaultValue) + } + return promptOptionalPositiveInt(reader, label, defaultValue) +} + +func promptOptionalPositiveInt(reader *bufio.Reader, label, defaultValue string) (int, error) { + value, err := promptInput(reader, label, defaultValue) + if err != nil { + return 0, err + } + value = strings.TrimSpace(value) + if value == "" { + return 0, nil + } + return parsePositiveInt(value, label) +} + +func promptOptionalBool(reader *bufio.Reader, label string, defaultValue bool) (bool, error) { + defaultText := "no" + if defaultValue { + defaultText = "yes" + } + value, err := promptInput(reader, label+" (yes|no)", defaultText) + if err != nil { + return false, err + } + switch strings.ToLower(strings.TrimSpace(value)) { + case "": + return defaultValue, nil + case "y", "yes", "true", "1": + return true, nil + case "n", "no", "false", "0": + return false, nil + default: + return false, fmt.Errorf("%s must be yes or no", strings.ToLower(label)) + } +} + +func promptConnectionSecretValue(promptSecret func(*bufio.Reader, string) (string, error), reader *bufio.Reader, label string, required bool) (string, error) { + value, err := promptSecret(reader, label) + if err != nil { + return "", err + } + value = strings.TrimSpace(value) + if required && value == "" { + return "", fmt.Errorf("%s is required", strings.ToLower(label)) + } + return value, nil +} + +func parsePositiveInt(value, label string) (int, error) { + n, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil || n <= 0 { + return 0, fmt.Errorf("%s must be a positive integer", strings.ToLower(label)) + } + return n, nil +} + +func normalizeConnectionDialect(value string) gen.ConnectionsCreateJSONBodyDialect { + switch strings.ToLower(strings.TrimSpace(value)) { + case string(gen.Postgres): + return gen.Postgres + case string(gen.Mysql): + return gen.Mysql + case string(gen.Mariadb): + return gen.Mariadb + case string(gen.Redshift): + return gen.Redshift + case string(gen.Snowflake): + return gen.Snowflake + case string(gen.Bigquery): + return gen.Bigquery + case string(gen.Athena): + return gen.Athena + case string(gen.Databricks): + return gen.Databricks + case string(gen.Clickhouse): + return gen.Clickhouse + case string(gen.Exasol): + return gen.Exasol + case string(gen.Motherduck): + return gen.Motherduck + case string(gen.Mssql): + return gen.Mssql + case string(gen.Starrocks): + return gen.Starrocks + case string(gen.Trino): + return gen.Trino + default: + return "" + } +} + +func parseConnectionBaseRole(value string) (gen.ConnectionsCreateJSONBodyBaseRole, error) { + normalized := strings.ToUpper(strings.TrimSpace(value)) + normalized = strings.ReplaceAll(normalized, "-", "_") + normalized = strings.ReplaceAll(normalized, " ", "_") + switch normalized { + case string(gen.CONNECTIONADMIN): + return gen.CONNECTIONADMIN, nil + case string(gen.MODELER): + return gen.MODELER, nil + case string(gen.NOACCESS): + return gen.NOACCESS, nil + case string(gen.QUERIER): + return gen.QUERIER, nil + case string(gen.RESTRICTEDQUERIER): + return gen.RESTRICTEDQUERIER, nil + case string(gen.VIEWER): + return gen.VIEWER, nil + default: + return "", fmt.Errorf("invalid base role %q", strings.TrimSpace(value)) + } +} + +func readRequiredFile(path string) (string, error) { + content, err := os.ReadFile(strings.TrimSpace(path)) + if err != nil { + return "", err + } + if strings.TrimSpace(string(content)) == "" { + return "", fmt.Errorf("file %q is empty", strings.TrimSpace(path)) + } + return string(content), nil +} + +func readConnectionSecretFile(path string) (string, map[string]string, error) { + content, err := readRequiredFile(path) + if err != nil { + return "", nil, err + } + + defaults := map[string]string{} + var parsed map[string]any + if err := json.Unmarshal([]byte(content), &parsed); err == nil { + if v, ok := parsed["project_id"].(string); ok { + defaults["project_id"] = strings.TrimSpace(v) + } + if v, ok := parsed["client_email"].(string); ok { + defaults["client_email"] = strings.TrimSpace(v) + } + } + return content, defaults, nil +} + func runConnectionsUpdate(rt *runtime, args []string) int { fs := flag.NewFlagSet("connections update", flag.ContinueOnError) fs.SetOutput(io.Discard) @@ -494,6 +1131,7 @@ func runConnectionEnvironments(rt *runtime, args []string) int { func printConnectionsUsage() { fmt.Print(`omni connections commands: omni connections list [--name ] + omni connections create omni connections create --file omni connections update --file omni connections dbt get @@ -508,5 +1146,7 @@ func printConnectionsUsage() { omni connections environments create --file omni connections environments update --file omni connections environments delete + +create without --file starts an interactive setup wizard. `) } diff --git a/internal/cli/connections_test.go b/internal/cli/connections_test.go new file mode 100644 index 0000000..05a3a29 --- /dev/null +++ b/internal/cli/connections_test.go @@ -0,0 +1,281 @@ +package cli + +import ( + "bufio" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/omni-co/omni-cli/internal/auth" + "github.com/omni-co/omni-cli/internal/client/gen" + "github.com/omni-co/omni-cli/internal/config" +) + +func TestRunConnectionsCreateWithFile(t *testing.T) { + tmp := t.TempDir() + bodyPath := filepath.Join(tmp, "connection.json") + if err := os.WriteFile(bodyPath, []byte(`{"dialect":"postgres","name":"Coverage Postgres","passwordUnencrypted":"secret"}`), 0o600); err != nil { + t.Fatalf("write connection body: %v", err) + } + + var gotAuth string + var gotBody map[string]any + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/api/v1/connections" { + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + gotAuth = r.Header.Get("Authorization") + if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil { + t.Fatalf("decode body: %v", err) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":"conn-1"}`)) + })) + defer server.Close() + + rt := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + Profile: config.Profile{ + BaseURL: server.URL, + Token: "org-token", + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runConnectionsCreateWithPrompts(rt, []string{"--file", bodyPath}, false, nil, nil) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"id": "conn-1"`) { + t.Fatalf("expected create response, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } + if gotAuth != "Bearer org-token" { + t.Fatalf("expected bearer auth header, got %q", gotAuth) + } + if gotBody["dialect"] != "postgres" || gotBody["name"] != "Coverage Postgres" { + t.Fatalf("unexpected request body: %#v", gotBody) + } +} + +func TestRunConnectionsCreateInteractivePostgresWizard(t *testing.T) { + var gotBody gen.ConnectionsCreateJSONBody + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/api/v1/connections" { + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil { + t.Fatalf("decode body: %v", err) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":"conn-wizard"}`)) + })) + defer server.Close() + + rt := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + Profile: config.Profile{ + BaseURL: server.URL, + Token: "org-token", + }, + }, + } + + reader := bufio.NewReader(strings.NewReader(strings.Join([]string{ + "", + "Coverage Postgres", + "db.example.internal", + "", + "analytics", + "omni", + "", + "", + "", + "", + "", + "", + "", + }, "\n") + "\n")) + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runConnectionsCreateWithPrompts(rt, nil, true, reader, func(_ *bufio.Reader, _ string) (string, error) { + return "top-secret", nil + }) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"id": "conn-wizard"`) { + t.Fatalf("expected create response, got %q", stdout) + } + if !strings.Contains(stderr, "Interactive connection setup") { + t.Fatalf("expected wizard prompt text, got %q", stderr) + } + if gotBody.Dialect != gen.Postgres { + t.Fatalf("expected postgres dialect, got %q", gotBody.Dialect) + } + if gotBody.Name != "Coverage Postgres" { + t.Fatalf("expected name to be preserved, got %q", gotBody.Name) + } + if gotBody.Host == nil || *gotBody.Host != "db.example.internal" { + t.Fatalf("expected host to be set, got %#v", gotBody.Host) + } + if gotBody.Port == nil || *gotBody.Port != 5432 { + t.Fatalf("expected default port 5432, got %#v", gotBody.Port) + } + if gotBody.Database == nil || *gotBody.Database != "analytics" { + t.Fatalf("expected database to be set, got %#v", gotBody.Database) + } + if gotBody.Username == nil || *gotBody.Username != "omni" { + t.Fatalf("expected username to be set, got %#v", gotBody.Username) + } + if gotBody.PasswordUnencrypted != "top-secret" { + t.Fatalf("expected password to be forwarded, got %q", gotBody.PasswordUnencrypted) + } + if gotBody.BaseRole == nil || *gotBody.BaseRole != gen.QUERIER { + t.Fatalf("expected default base role QUERIER, got %#v", gotBody.BaseRole) + } + if gotBody.SystemTimezone == nil || *gotBody.SystemTimezone != "UTC" { + t.Fatalf("expected default system timezone UTC, got %#v", gotBody.SystemTimezone) + } + if gotBody.QueryTimezone != nil { + t.Fatalf("expected blank query timezone to be omitted, got %#v", gotBody.QueryTimezone) + } + if gotBody.QueryTimeoutSeconds == nil || *gotBody.QueryTimeoutSeconds != 900 { + t.Fatalf("expected default query timeout 900, got %#v", gotBody.QueryTimeoutSeconds) + } +} + +func TestRunConnectionsCreateRequiresFileOrInteractiveTTY(t *testing.T) { + rt := &runtime{JSON: true} + + _, stderr, exit := captureRuntimeIO(t, func() int { + return runConnectionsCreateWithPrompts(rt, nil, false, nil, nil) + }) + if exit != 2 { + t.Fatalf("expected usage exit 2, got %d", exit) + } + if !strings.Contains(stderr, "run from a terminal for interactive setup") { + t.Fatalf("expected interactive guidance, got %q", stderr) + } +} + +func TestPromptConnectionCreatePayloadValidation(t *testing.T) { + tests := []struct { + name string + input string + secret string + want string + }{ + { + name: "invalid dialect", + input: "duckdb\n", + want: `invalid dialect "duckdb"`, + }, + { + name: "invalid port", + input: strings.Join([]string{ + "postgres", + "Coverage Postgres", + "db.example.internal", + "zero", + }, "\n") + "\n", + want: "port must be a positive integer", + }, + { + name: "invalid base role", + input: strings.Join([]string{ + "postgres", + "Coverage Postgres", + "db.example.internal", + "5432", + "analytics", + "omni", + "not-a-role", + }, "\n") + "\n", + secret: "top-secret", + want: `invalid base role "not-a-role"`, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + _, err := promptConnectionCreatePayload(bufio.NewReader(strings.NewReader(tc.input)), func(_ *bufio.Reader, _ string) (string, error) { + return tc.secret, nil + }) + if err == nil { + t.Fatal("expected prompt error") + } + if !strings.Contains(err.Error(), tc.want) { + t.Fatalf("expected error containing %q, got %v", tc.want, err) + } + }) + } +} + +func TestPromptConnectionCreatePayloadBigQueryUsesServiceAccountDefaults(t *testing.T) { + tmp := t.TempDir() + serviceAccountPath := filepath.Join(tmp, "service-account.json") + serviceAccount := `{"project_id":"coverage-project","client_email":"svc@coverage-project.iam.gserviceaccount.com"}` + if err := os.WriteFile(serviceAccountPath, []byte(serviceAccount), 0o600); err != nil { + t.Fatalf("write service account file: %v", err) + } + + reader := bufio.NewReader(strings.NewReader(strings.Join([]string{ + "bigquery", + "Coverage BigQuery", + serviceAccountPath, + "", + "", + "", + "us", + "", + "", + "", + "", + "", + "", + "", + "", + "", + }, "\n") + "\n")) + + payload, err := promptConnectionCreatePayload(reader, func(_ *bufio.Reader, _ string) (string, error) { + return "", nil + }) + if err != nil { + t.Fatalf("expected bigquery wizard to succeed, got %v", err) + } + + var got map[string]any + if err := json.Unmarshal(payload, &got); err != nil { + t.Fatalf("unmarshal payload: %v", err) + } + if got["dialect"] != "bigquery" { + t.Fatalf("expected bigquery dialect, got %#v", got["dialect"]) + } + if got["database"] != "coverage-project" { + t.Fatalf("expected project ID default, got %#v", got["database"]) + } + if got["username"] != "svc@coverage-project.iam.gserviceaccount.com" { + t.Fatalf("expected client email default, got %#v", got["username"]) + } + if got["region"] != "us" { + t.Fatalf("expected region to be set, got %#v", got["region"]) + } + if got["passwordUnencrypted"] != serviceAccount { + t.Fatalf("expected raw service account JSON to be stored, got %#v", got["passwordUnencrypted"]) + } +}