diff --git a/README.md b/README.md index ec29966..f2fa9be 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ After installing, you'll get tab completion when typing `conductor `. * [Task Commands](#task-commands) * [Schedule Commands](#schedule-commands) * [Secret Commands](#secret-commands) + * [Integration Commands](#integration-commands) * [Webhook Commands](#webhook-commands) * [API Gateway Commands](#api-gateway-commands) * [Service Management](#service-management) @@ -391,6 +392,34 @@ cat secret.txt | conductor secret put my_secret --- +### Integration Commands + +Discover Connected Apps and manage saved connections on an Enterprise server. Set the target profile’s server type to Enterprise or pass `--server-type Enterprise`. + +``` +conductor integration [arguments] [flags] +``` + +| Command | Description | +|---------|-------------| +| `types` | List enabled integration types (optionally filter by `--category `) | +| `type-config ` | Show the configuration fields for an integration type | +| `list` | List visible saved connections (filter with `--type `) | +| `get ` | Show connection metadata and configured field names | +| `operations --type ` | List operations offered by an integration type | +| `operations [connection]` | List operations for the named saved connection | +| `create [json_payload]` | Create a connection from JSON, a file (`--file`), or stdin | +| `update [json_payload]` | Update the description, enabled state, or individual configuration fields from JSON, a file (`--file`), or stdin | +| `delete ` | Delete a saved connection | + +Use `--name ""` with either form of `operations` to inspect the operation’s input and output schemas. + +`types` and `list` print a table by default. Pass `--json` or `--csv` for structured output. Configuration and operation schemas are JSON. + +For `create`, supply a JSON object with `name`, `type`, `enabled`, `description`, and `configuration`. If `category` is omitted or empty, the CLI uses the category registered for that provider type. Use `type-config` to discover the configuration fields. For `create` and `update`, use an environment variable as the entire value of a configuration field, for example `"api_key": "$.env.SERVICE_API_KEY"`. The CLI reads the variable from its environment and sends its value as a string. An unset or empty variable stops the command. The following names are reserved for Conductor authentication: `CONDUCTOR_KEY`, `CONDUCTOR_AUTH_KEY`, `CONDUCTOR_AUTH_SECRET`, `CONDUCTOR_AUTH_TOKEN`, `CONDUCTOR_ACCESS_KEY_ID`, and `CONDUCTOR_ACCESS_KEY_SECRET`. Other names, including `CONDUCTOR_INTEGRATED_APPS_STRIPE_KEY`, are supported. To rotate a credential, set the new value and run `update` again. + +--- + ### Webhook Commands Manage webhooks (Enterprise only). diff --git a/cmd/integration.go b/cmd/integration.go new file mode 100644 index 0000000..0421a65 --- /dev/null +++ b/cmd/integration.go @@ -0,0 +1,439 @@ +/* + * Copyright 2026 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package cmd + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + neturl "net/url" + "os" + "regexp" + "runtime" + "sort" + "strconv" + "strings" + "text/tabwriter" + + "github.com/conductor-oss/conductor-cli/internal" + "github.com/conductor-oss/conductor-cli/internal/transport" + "github.com/spf13/cobra" +) + +type connectionSummary struct { + Name string `json:"name"` + Type string `json:"type"` + Category string `json:"category"` + Enabled bool `json:"enabled"` + Description string `json:"description,omitempty"` +} +type catalogOperation struct { + API string `json:"api"` + Description string `json:"description"` + Input *struct { + Data json.RawMessage `json:"data"` + } `json:"inputSchema,omitempty"` + Output *struct { + Data json.RawMessage `json:"data"` + } `json:"outputSchema,omitempty"` +} +type providerDefinition struct { + connectionSummary + Configuration json.RawMessage `json:"configuration"` + APIs []catalogOperation `json:"apis"` +} + +func integrationPath(name string) string { return "/integrations/provider/" + neturl.PathEscape(name) } + +func init() { rootCmd.AddCommand(newIntegrationCommand()) } + +func newIntegrationCommand() *cobra.Command { + group := &cobra.Command{Use: "integration", Short: "Discover and manage Orkes Conductor integrations", GroupID: "conductor"} + add := func(use, help string, args cobra.PositionalArgs, run func(*cobra.Command, []string) (any, error)) *cobra.Command { + c := &cobra.Command{Use: use, Short: help, Args: args, SilenceUsage: true, RunE: func(c *cobra.Command, a []string) error { + if !isEnterpriseServer() { + return errors.New("Connected Apps are not supported in OSS Conductor. If this profile points to Orkes Conductor, use --server-type Enterprise or set CONDUCTOR_SERVER_TYPE=Enterprise.") + } + v, err := run(c, a) + if err != nil { + return err + } + if v == nil { + return nil + } + if rows, ok := v.([]connectionSummary); ok { + return writeConnectionSummaries(c, rows) + } + enc := json.NewEncoder(c.OutOrStdout()) + enc.SetIndent("", " ") + return enc.Encode(v) + }} + group.AddCommand(c) + return c + } + types := add("types", "List enabled integration types", cobra.NoArgs, func(c *cobra.Command, _ []string) (any, error) { + var rows []connectionSummary + err := internal.Transport().DoJSON(c.Context(), "GET", "/integrations/def", nil, &rows) + cat, _ := c.Flags().GetString("category") + out := []connectionSummary{} + for _, r := range rows { + if r.Enabled && (cat == "" || r.Category == cat) { + out = append(out, r) + } + } + return out, err + }) + AddOutputFlags(types) + types.Flags().String("category", "", "Filter by category, e.g. MCP") + list := add("list", "List visible saved connections", cobra.NoArgs, func(c *cobra.Command, _ []string) (any, error) { + var rows []connectionSummary + err := internal.Transport().DoJSON(c.Context(), "GET", "/integrations/provider?activeOnly=false", nil, &rows) + t, _ := c.Flags().GetString("type") + out := []connectionSummary{} + for _, r := range rows { + if t == "" || r.Type == t { + out = append(out, r) + } + } + return out, err + }) + AddOutputFlags(list) + list.Flags().String("type", "", "Filter by provider type") + add("type-config ", "Show the provider's configuration fields", cobra.ExactArgs(1), func(c *cobra.Command, a []string) (any, error) { + var d providerDefinition + err := internal.Transport().DoJSON(c.Context(), "GET", "/integrations/def/"+neturl.PathEscape(a[0]), nil, &d) + return d.Configuration, err + }) + add("get ", "Show saved connection metadata and configured field names", cobra.ExactArgs(1), func(c *cobra.Command, a []string) (any, error) { + var r struct { + connectionSummary + Configuration map[string]json.RawMessage + } + err := internal.Transport().DoJSON(c.Context(), "GET", integrationPath(a[0]), nil, &r) + keys := []string{} + for k, v := range r.Configuration { + if string(v) != "null" && string(v) != "\"\"" { + keys = append(keys, k) + } + } + sort.Strings(keys) + return struct { + connectionSummary + Configured []string `json:"configuredFields"` + }{r.connectionSummary, keys}, err + }) + ops := add("operations [connection]", "List operations or inspect an operation schema", cobra.MaximumNArgs(1), func(c *cobra.Command, a []string) (any, error) { + t, _ := c.Flags().GetString("type") + if (t == "") == (len(a) == 0) { + return nil, fmt.Errorf("specify one connection or --type") + } + var rows []catalogOperation + var err error + if t != "" { + var d providerDefinition + err = internal.Transport().DoJSON(c.Context(), "GET", "/integrations/def/"+neturl.PathEscape(t), nil, &d) + rows = d.APIs + } else { + err = internal.Transport().DoJSON(c.Context(), "GET", "/integrations/"+neturl.PathEscape(a[0])+"/def/apis", nil, &rows) + } + if err != nil { + return nil, err + } + name, _ := c.Flags().GetString("name") + for i, r := range rows { + if name != "" && r.API == name { + return r, nil + } + rows[i].Input = nil + rows[i].Output = nil + } + if name != "" { + return nil, fmt.Errorf("unknown operation %q", name) + } + return rows, nil + }) + ops.Long = "List operations for a provider type (--type) or for a saved connection (positional argument). Supply exactly one. Add --name with an exact operation name to show its input and output schemas." + ops.Example = ` conductor integration operations --type stripe + conductor integration operations payments-test + conductor integration operations payments-test --name "List Charges"` + ops.Flags().String("type", "", "Discover by provider type") + ops.Flags().String("name", "", "Inspect an exact operation name") + create := add("create [json_payload]", "Create a saved connection from JSON, --file or stdin", cobra.MaximumNArgs(1), createConnection) + create.Long = `Create a saved connection from a JSON argument, --file, or stdin. Supply the connection name and provider type. If category is omitted or empty, the CLI uses the registered provider category. Run conductor integration type-config for provider-specific configuration fields. + +Use $.env.VAR as the entire string value of a configuration field to read it from the CLI environment. Other fields, including description, remain literal.` + create.Example = ` conductor integration create '{"name":"payments-test","type":"stripe","category":"MCP","enabled":true,"description":"Test payments","configuration":{"api_key":"$.env.STRIPE_TEST_KEY"}}' + conductor integration create --file connection.json` + create.Flags().String("file", "", "Read a JSON object from a file") + update := add("update [json_payload]", "Update a saved connection from JSON, --file or stdin", cobra.RangeArgs(1, 2), updateConnection) + update.Long = `Update a saved connection from a JSON patch supplied as an argument, via --file, or on stdin. Only description, enabled, and configuration can be updated. Each supplied configuration field replaces its saved value. Omitted fields keep their values. + +Use $.env.VAR as the entire string value of a configuration field to read it from the CLI environment. The description remains literal.` + update.Example = ` conductor integration update payments-test '{"configuration":{"api_key":"$.env.STRIPE_TEST_KEY"}}' + conductor integration update payments-test --file patch.json` + update.Flags().String("file", "", "Read a JSON patch object from a file") + add("delete ", "Delete a saved connection", cobra.ExactArgs(1), func(c *cobra.Command, a []string) (any, error) { + if !confirmDeletion("integration", a[0]) { + _, err := fmt.Fprintln(c.OutOrStdout(), "Deletion cancelled") + return nil, err + } + if err := internal.Transport().DoJSON(c.Context(), "DELETE", integrationPath(a[0]), nil, nil); err != nil { + return nil, err + } + _, err := fmt.Fprintf(c.OutOrStdout(), "Deleted connection %s\n", a[0]) + return nil, err + }) + return group +} + +func writeConnectionSummaries(c *cobra.Command, rows []connectionSummary) error { + format, err := GetOutputFormat(c) + if err != nil { + return err + } + out := c.OutOrStdout() + if format == OutputFormatJSON { + enc := json.NewEncoder(out) + enc.SetIndent("", " ") + return enc.Encode(rows) + } + records := [][]string{{"NAME", "TYPE", "CATEGORY", "ENABLED", "DESCRIPTION"}} + for _, row := range rows { + records = append(records, []string{row.Name, row.Type, row.Category, strconv.FormatBool(row.Enabled), row.Description}) + } + if format == OutputFormatCSV { + return csv.NewWriter(out).WriteAll(records) + } + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + for _, record := range records { + if _, err := fmt.Fprintln(w, strings.Join(record, "\t")); err != nil { + return err + } + } + return w.Flush() +} + +func connectionInput(c *cobra.Command, a []string, body *map[string]json.RawMessage) error { + var input io.Reader = c.InOrStdin() + file, _ := c.Flags().GetString("file") + if len(a) > 0 && file != "" { + return fmt.Errorf("use either JSON or --file") + } + if file != "" { + f, err := os.Open(file) + if err != nil { + return err + } + defer f.Close() + input = f + } else if len(a) > 0 { + input = strings.NewReader(a[0]) + } + data, err := io.ReadAll(input) + if err != nil { + return err + } + if json.Unmarshal(data, body) != nil || *body == nil { + return fmt.Errorf("expected a JSON object") + } + raw, ok := (*body)["configuration"] + if !ok { + return nil + } + var fields map[string]any + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&fields); err != nil { + return errors.New("configuration must be an object") + } + if _, err := resolveIntegrationEnv(fields, "configuration"); err != nil { + return err + } + (*body)["configuration"], err = json.Marshal(fields) + return err +} + +var integrationEnvRef = regexp.MustCompile(`^\$\.env\.([A-Za-z_][A-Za-z0-9_]*)$`) + +// Windows environment lookups are case-insensitive. Unix names are case-sensitive. +func reservedIntegrationEnv(name string) bool { + if runtime.GOOS == "windows" { + name = strings.ToUpper(name) + } + switch name { + case "CONDUCTOR_KEY", "CONDUCTOR_AUTH_KEY", "CONDUCTOR_AUTH_SECRET", "CONDUCTOR_AUTH_TOKEN", + "CONDUCTOR_ACCESS_KEY_ID", "CONDUCTOR_ACCESS_KEY_SECRET": + return true + } + return false +} + +// Resolve whole string values in the caller's configuration only, before merging an update. +func resolveIntegrationEnv(value any, path string) (any, error) { + switch v := value.(type) { + case string: + if match := integrationEnvRef.FindStringSubmatch(v); match != nil { + name := match[1] + if reservedIntegrationEnv(name) { + return nil, fmt.Errorf("%s: %s is reserved for Conductor authentication; use a provider credential variable", path, name) + } + resolved := os.Getenv(name) + if resolved == "" { + return nil, fmt.Errorf("%s: environment variable %s is unset or empty", path, name) + } + return resolved, nil + } + case map[string]any: + for k, child := range v { + resolved, err := resolveIntegrationEnv(child, path+"."+k) + if err != nil { + return nil, err + } + v[k] = resolved + } + case []any: + for i, child := range v { + resolved, err := resolveIntegrationEnv(child, fmt.Sprintf("%s[%d]", path, i)) + if err != nil { + return nil, err + } + v[i] = resolved + } + } + return value, nil +} + +func createConnection(c *cobra.Command, a []string) (any, error) { + var body map[string]json.RawMessage + if err := connectionInput(c, a, &body); err != nil { + return nil, err + } + var name, t string + if json.Unmarshal(body["name"], &name) != nil || json.Unmarshal(body["type"], &t) != nil || + strings.TrimSpace(name) == "" || strings.TrimSpace(t) == "" { + return nil, fmt.Errorf("name and type required") + } + client := internal.Transport() + path := integrationPath(name) + err := client.DoJSON(c.Context(), "GET", path, nil, nil) + if err == nil { + return nil, fmt.Errorf("integration already exists") + } + var apiErr *transport.APIError + if !errors.As(err, &apiErr) || apiErr.Status != 404 { + return nil, integrationRequestError("creation", t, err) + } + var category string + if raw := body["category"]; raw != nil && json.Unmarshal(raw, &category) != nil { + return nil, errors.New("category must be a string") + } + if strings.TrimSpace(category) == "" { + var definition connectionSummary + if err := client.DoJSON(c.Context(), "GET", "/integrations/def/"+neturl.PathEscape(t), nil, &definition); err != nil { + return nil, integrationRequestError("definition lookup", t, err) + } + if strings.TrimSpace(definition.Category) == "" { + return nil, fmt.Errorf("registered definition for %q has no category", t) + } + body["category"], err = json.Marshal(definition.Category) + if err != nil { + return nil, err + } + } + if err := client.DoJSON(c.Context(), "POST", path, body, nil); err != nil { + return nil, integrationRequestError("creation", t, err) + } + return map[string]string{"name": name, "type": t}, nil +} + +// The provider endpoint replaces these fields on POST. Keep its GET response in +// memory: configuration values can contain resolved credentials. +type savedConnection struct { + Type string `json:"type"` + Category string `json:"category"` + Description *string `json:"description"` + Enabled bool `json:"enabled"` + Configuration map[string]json.RawMessage `json:"configuration"` +} + +func updateConnection(c *cobra.Command, args []string) (any, error) { + var patch map[string]json.RawMessage + if err := connectionInput(c, args[1:], &patch); err != nil { + return nil, err + } + name := args[0] + path := integrationPath(name) + client := internal.Transport() + var saved savedConnection + if err := client.DoJSON(c.Context(), "GET", path, nil, &saved); err != nil { + return nil, integrationRequestError("update", "", err) + } + if saved.Type == "" || saved.Category == "" { + return nil, fmt.Errorf("incomplete saved integration") + } + if err := saved.applyPatch(patch); err != nil { + return nil, err + } + if err := client.DoJSON(c.Context(), "POST", path, saved, nil); err != nil { + return nil, integrationRequestError("update", saved.Type, err) + } + return map[string]string{"name": name, "type": saved.Type}, nil +} + +// A server error may echo request or stored credentials. Only expose its status. +func integrationRequestError(action, providerType string, err error) error { + var apiErr *transport.APIError + if !errors.As(err, &apiErr) { + return fmt.Errorf("integration %s request failed", action) + } + if apiErr.Status == 400 && providerType != "" { + return fmt.Errorf("integration %s failed (HTTP 400). Check the accepted fields with conductor integration type-config %s", action, providerType) + } + return fmt.Errorf("integration %s failed (HTTP %d)", action, apiErr.Status) +} + +func (saved *savedConnection) applyPatch(patch map[string]json.RawMessage) error { + if len(patch) == 0 { + return fmt.Errorf("no integration changes supplied") + } + for field, value := range patch { + switch field { + case "description": + if string(value) == "null" || json.Unmarshal(value, &saved.Description) != nil { + return fmt.Errorf("description must be a string") + } + case "enabled": + if string(value) == "null" || json.Unmarshal(value, &saved.Enabled) != nil { + return fmt.Errorf("enabled must be a boolean") + } + case "configuration": + var fields map[string]json.RawMessage + if json.Unmarshal(value, &fields) != nil || len(fields) == 0 { + return fmt.Errorf("configuration must contain fields to update") + } + if saved.Configuration == nil { + saved.Configuration = make(map[string]json.RawMessage) + } + for key, replacement := range fields { + saved.Configuration[key] = replacement + } + default: + return fmt.Errorf("only description, enabled and configuration can be updated") + } + } + return nil +} diff --git a/cmd/integration_test.go b/cmd/integration_test.go new file mode 100644 index 0000000..527a036 --- /dev/null +++ b/cmd/integration_test.go @@ -0,0 +1,497 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/conductor-oss/conductor-cli/internal" + "github.com/conductor-oss/conductor-cli/internal/transport" +) + +func TestSavedConnectionPatchPreservesCredentials(t *testing.T) { + saved := savedConnection{Type: "aws-lambda", Category: "MCP", Enabled: true, + Configuration: map[string]json.RawMessage{ + "api_key": json.RawMessage(`"original"`), + "sessionToken": json.RawMessage(`"unrelated"`), + }, + } + var patch map[string]json.RawMessage + if err := json.Unmarshal([]byte(`{"configuration":{"api_key":"replacement"},"description":"test"}`), &patch); err != nil { + t.Fatal(err) + } + if err := saved.applyPatch(patch); err != nil { + t.Fatal(err) + } + if string(saved.Configuration["api_key"]) != `"replacement"` || + string(saved.Configuration["sessionToken"]) != `"unrelated"` || + saved.Description == nil || *saved.Description != "test" || !saved.Enabled { + t.Fatal("update did not preserve the intended fields") + } +} + +func TestSavedConnectionRejectsInvalidPatch(t *testing.T) { + for _, input := range []string{`{}`, `{"category":"CLOUD"}`, `{"name":"renamed"}`, + `{"type":"different"}`, `{"enabled":null}`, `{"configuration":[]}`, `{"description":false}`} { + var patch map[string]json.RawMessage + if err := json.Unmarshal([]byte(input), &patch); err != nil { + t.Fatal(err) + } + if err := new(savedConnection).applyPatch(patch); err == nil { + t.Errorf("accepted invalid patch %s", input) + } + } +} + +func TestIntegrationCommandsRequireEnterprise(t *testing.T) { + previous := serverType + t.Cleanup(func() { serverType = previous }) + serverType = "OSS" + group, _, err := rootCmd.Find([]string{"integration"}) + if err != nil || group.Name() != "integration" { + t.Fatal("integration command missing") + } + for _, command := range group.Commands() { + t.Run(command.Name(), func(t *testing.T) { + if err := command.RunE(command, nil); err == nil || err.Error() != "Connected Apps are not supported in OSS Conductor. If this profile points to Orkes Conductor, use --server-type Enterprise or set CONDUCTOR_SERVER_TYPE=Enterprise." { + t.Fatalf("expected Enterprise guard, got %v", err) + } + }) + } +} + +func TestIntegrationEnvReferences(t *testing.T) { + const secret = "synthetic-\"key\"\n$.env.KEEP_LITERAL" + const missing = "CONDUCTOR_CLI_TEST_UNSET_130" + t.Setenv(missing, "") + if err := os.Unsetenv(missing); err != nil { + t.Fatal(err) + } + t.Setenv("CONDUCTOR_INTEGRATED_APPS_TEST_KEY", secret) + t.Setenv("TEST_CONN_EMPTY", "") + previousType, previousTransport := serverType, internal.Transport() + serverType = "Enterprise" + t.Cleanup(func() { serverType = previousType; internal.SetTransport(previousTransport) }) + + for _, operation := range []string{"create", "update"} { + for _, scenario := range []string{"success", "missing", "empty", "server rejection"} { + t.Run(operation+"/"+scenario, func(t *testing.T) { + ref := "CONDUCTOR_INTEGRATED_APPS_TEST_KEY" + switch scenario { + case "missing": + ref = missing + case "empty": + ref = "TEST_CONN_EMPTY" + } + fields := fmt.Sprintf(`"configuration":{"key":"$.env.CONDUCTOR_INTEGRATED_APPS_TEST_KEY","nested":["$.env.%s",{"literal":"prefix $.env.CONDUCTOR_INTEGRATED_APPS_TEST_KEY","number":9007199254740993}]}`, ref) + body := `{"description":"$.env.CONDUCTOR_INTEGRATED_APPS_TEST_KEY",` + fields + `}` + if operation == "create" { + body = `{"name":"example","type":"test","category":"MCP",` + body[1:] + } + + var calls []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls = append(calls, r.Method) + if r.URL.Path != "/integrations/provider/example" { + t.Error("unexpected integration path") + } + if r.Method == http.MethodGet { + if operation == "create" { + w.WriteHeader(http.StatusNotFound) + } else { + fmt.Fprint(w, `{"type":"test","category":"MCP","configuration":{"existing":"$.env.TEST_CONN_EMPTY"}}`) + } + return + } + var sent struct { + Description string + Configuration struct { + Key, Existing string + Nested []json.RawMessage + } + } + if err := json.NewDecoder(r.Body).Decode(&sent); err != nil { + t.Error("invalid JSON sent") + return + } + cfg := sent.Configuration + if sent.Description != "$.env.CONDUCTOR_INTEGRATED_APPS_TEST_KEY" || cfg.Key != secret || len(cfg.Nested) != 2 { + t.Error("unexpected resolved configuration") + return + } + var first string + var second struct { + Literal string + Number int64 + } + if json.Unmarshal(cfg.Nested[0], &first) != nil || first != secret || + json.Unmarshal(cfg.Nested[1], &second) != nil || second.Literal != "prefix $.env.CONDUCTOR_INTEGRATED_APPS_TEST_KEY" || second.Number != 9007199254740993 { + t.Error("nested reference, embedded literal or numeric precision changed") + } + if operation == "update" && cfg.Existing != "$.env.TEST_CONN_EMPTY" { + t.Error("stored configuration was reinterpreted") + } + if scenario == "server rejection" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]string{"message": secret}) + } + })) + defer server.Close() + internal.SetTransport(transport.Config{BaseURL: server.URL}) + cmd, _, err := rootCmd.Find([]string{"integration", operation}) + if err != nil { + t.Fatal(err) + } + cmd.SetContext(context.Background()) + var output bytes.Buffer + cmd.SetOut(&output) + cmd.SetErr(&output) + t.Cleanup(func() { cmd.SetOut(nil); cmd.SetErr(nil); cmd.SetIn(nil); _ = cmd.Flags().Set("file", "") }) + var args []string + if operation == "update" { + args = []string{"example"} + cmd.SetIn(strings.NewReader(body)) + } else if scenario == "success" { + file := filepath.Join(t.TempDir(), "create.json") + if err := os.WriteFile(file, []byte(body), 0600); err != nil { + t.Fatal(err) + } + if err := cmd.Flags().Set("file", file); err != nil { + t.Fatal(err) + } + } else { + args = []string{body} + } + err = cmd.RunE(cmd, args) + if strings.Contains(output.String()+fmt.Sprint(err), "synthetic-") { + t.Fatal("credential exposed in output or error") + } + if scenario == "server rejection" && (err == nil || !strings.Contains(err.Error(), "HTTP 400") || !strings.Contains(err.Error(), "conductor integration type-config test")) { + t.Fatal("expected safe type-config hint") + } + switch scenario { + case "missing", "empty": + if err == nil || !strings.Contains(err.Error(), ref) || !strings.Contains(err.Error(), "configuration.nested[0]") || len(calls) != 0 { + t.Fatal("expected field and variable error before any integration request") + } + default: + if strings.Join(calls, ",") != "GET,POST" || (err == nil) != (scenario == "success") { + t.Fatal("unexpected requests or command outcome") + } + } + }) + } + } +} + +func integrationTestServer(t *testing.T, handler http.HandlerFunc) { + t.Helper() + previousType, previousTransport := serverType, internal.Transport() + server := httptest.NewServer(handler) + serverType = "Enterprise" + internal.SetTransport(transport.Config{BaseURL: server.URL}) + t.Cleanup(func() { server.Close(); serverType = previousType; internal.SetTransport(previousTransport) }) +} + +func runIntegration(input string, args ...string) (string, error) { + c := newIntegrationCommand() + var out bytes.Buffer + c.SetOut(&out) + c.SetErr(&out) + c.SetIn(strings.NewReader(input)) + c.SetArgs(args) + err := c.Execute() + return out.String(), err +} + +func TestIntegrationDiscoveryFormats(t *testing.T) { + const rows = `[{"name":"Alpha","type":"app","category":"MCP","enabled":true,"description":"comma, here"},{"name":"Beta","type":"other","category":"EMAIL","enabled":true},{"name":"Disabled","type":"app","category":"MCP","enabled":false}]` + for _, command := range []string{"types", "list"} { + t.Run(command, func(t *testing.T) { + wantURL := "/integrations/def" + filter := []string{"--category", "MCP"} + wantNames := []string{"Alpha"} + if command == "list" { + wantURL = "/integrations/provider?activeOnly=false" + filter = []string{"--type", "app"} + wantNames = append(wantNames, "Disabled") + } + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" || r.URL.RequestURI() != wantURL { + t.Errorf("unexpected %s %s", r.Method, r.URL) + } + fmt.Fprint(w, rows) + }) + for _, format := range []string{"table", "json", "csv"} { + args := append([]string{command}, filter...) + if format != "table" { + args = append(args, "--"+format) + } + out, err := runIntegration("", args...) + if err != nil { + t.Fatal(err) + } + var names []string + switch format { + case "json": + var got []connectionSummary + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatal(err) + } + for _, v := range got { + names = append(names, v.Name) + } + case "csv": + records, err := csv.NewReader(strings.NewReader(out)).ReadAll() + if err != nil || len(records) < 2 || records[0][0] != "NAME" || records[1][4] != "comma, here" { + t.Fatalf("invalid CSV: %q", out) + } + for _, record := range records[1:] { + names = append(names, record[0]) + } + case "table": + lines := strings.Split(strings.TrimSpace(out), "\n") + if strings.Fields(lines[0])[0] != "NAME" { + t.Fatalf("invalid table: %q", out) + } + for _, line := range lines[1:] { + names = append(names, strings.Fields(line)[0]) + } + } + if !reflect.DeepEqual(names, wantNames) { + t.Fatalf("%s got %v want %v", format, names, wantNames) + } + } + if _, err := runIntegration("", command, "--json", "--csv"); err == nil { + t.Fatal("accepted conflicting formats") + } + }) + } +} + +func TestIntegrationOutputFlagScope(t *testing.T) { + group := newIntegrationCommand() + for _, cmd := range group.Commands() { + want := cmd.Name() == "list" || cmd.Name() == "types" + for _, flag := range []string{"json", "csv"} { + if got := cmd.Flag(flag) != nil; got != want { + t.Errorf("%s --%s available = %v, want %v", cmd.Name(), flag, got, want) + } + } + } +} + +func TestIntegrationGetAndOperationSchemas(t *testing.T) { + const ops = `[{"api":"Invoke","inputSchema":{"data":{"type":"object"}},"outputSchema":{"data":{"type":"string"}}}]` + calls := 0 + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != "GET" { + t.Error(r.Method) + } + switch r.URL.Path { + case "/integrations/provider/sample": + fmt.Fprint(w, `{"configuration":{"api_key":"private-marker","z":"present","empty":"","unset":null}}`) + case "/integrations/def/test": + fmt.Fprintf(w, `{"configuration":[{"fieldName":"key","dependsOn":[{"fieldName":"mode"}]}],"apis":%s}`, ops) + case "/integrations/sample/def/apis": + fmt.Fprint(w, `[{"api":"Saved-only"}]`) + default: + t.Error(r.URL.Path) + http.NotFound(w, r) + } + }) + out, err := runIntegration("", "get", "sample") + var metadata struct{ ConfiguredFields []string } + if err != nil || json.Unmarshal([]byte(out), &metadata) != nil || !reflect.DeepEqual(metadata.ConfiguredFields, []string{"api_key", "z"}) || strings.Contains(out, "private-marker") { + t.Fatal("unexpected saved connection output") + } + out, err = runIntegration("", "type-config", "test") + var schema []struct{ DependsOn []struct{ FieldName string } } + if err != nil || json.Unmarshal([]byte(out), &schema) != nil || len(schema) != 1 || len(schema[0].DependsOn) != 1 || schema[0].DependsOn[0].FieldName != "mode" { + t.Fatal("lost nested schema") + } + for _, test := range []struct { + args []string + want string + }{ + {[]string{"--type", "test"}, "Invoke"}, {[]string{"sample"}, "Saved-only"}, + } { + out, err = runIntegration("", append([]string{"operations"}, test.args...)...) + var summary []catalogOperation + if err != nil || json.Unmarshal([]byte(out), &summary) != nil || len(summary) != 1 || summary[0].API != test.want || summary[0].Input != nil || summary[0].Output != nil { + t.Fatal("incorrect operation list", out, err) + } + } + out, err = runIntegration("", "operations", "--type", "test", "--name", "Invoke") + var op struct { + Input struct{ Data struct{ Type string } } `json:"inputSchema"` + Output struct{ Data struct{ Type string } } `json:"outputSchema"` + } + if err != nil || json.Unmarshal([]byte(out), &op) != nil || op.Input.Data.Type != "object" || op.Output.Data.Type != "string" || !strings.Contains(out, "\n \"inputSchema\":") { + t.Fatal("lost operation schema") + } + if _, err = runIntegration("", "operations", "sample", "--name", "Missing"); err == nil || !strings.Contains(err.Error(), "unknown operation") { + t.Fatal("missing operation accepted") + } + before := calls + for _, args := range [][]string{{"operations"}, {"operations", "sample", "--type", "test"}} { + if _, err := runIntegration("", args...); err == nil || calls != before { + t.Fatal("expected local argument rejection") + } + } +} + +func TestIntegrationDelete(t *testing.T) { + deleted := 0 + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method == "DELETE" && r.URL.Path == "/integrations/provider/missing" { + http.NotFound(w, r) + return + } + if r.Method != "DELETE" || r.URL.Path != "/integrations/provider/sample" { + t.Error("unexpected delete target") + } + deleted++ + }) + oldYes := yes + t.Cleanup(func() { yes = oldYes }) + for _, reply := range []string{"n\n", "\n"} { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + fmt.Fprint(w, reply) + w.Close() + stdin := os.Stdin + os.Stdin = r + yes = false + out, err := runIntegration("", "delete", "sample") + os.Stdin = stdin + r.Close() + if err != nil || !strings.Contains(out, "Deletion cancelled") || deleted != 0 { + t.Fatal("decline did not cancel") + } + } + yes = true + if out, err := runIntegration("", "delete", "missing"); err == nil || strings.Contains(out, "Deleted connection") { + t.Fatal("failed delete must not print a success message") + } + if out, err := runIntegration("", "delete", "sample"); err != nil || out != "Deleted connection sample\n" || deleted != 1 { + t.Fatal("expected one confirmed delete") + } +} + +func TestIntegrationCreateCategoryAndRotation(t *testing.T) { + for _, tc := range []struct { + label, category, definition, want string + status int + }{ + {"omitted", "", "EMAIL", "EMAIL", 200}, {"empty", `"category":"",`, "CLOUD", "CLOUD", 200}, {"explicit", `"category":"MCP",`, "", "MCP", 200}, + {"unknown", "", "", "", 404}, {"no category", "", "", "", 200}, + } { + t.Run(tc.label, func(t *testing.T) { + var saved json.RawMessage + lookups := 0 + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/integrations/def/test" && r.Method == "GET": + lookups++ + w.WriteHeader(tc.status) + fmt.Fprintf(w, `{"category":%q,"message":"private-marker"}`, tc.definition) + case r.URL.Path != "/integrations/provider/sample": + t.Error(r.URL.Path) + case r.Method == "POST": + var err error + saved, err = io.ReadAll(r.Body) + if err != nil { + t.Error(err) + } + case r.Method == "GET": + if saved == nil { + w.WriteHeader(404) + } else { + w.Write(saved) + } + default: + t.Error(r.Method) + } + }) + _, err := runIntegration("", "create", `{"name":"sample","type":"test",`+tc.category+`"configuration":{"key":"first"}}`) + if (tc.label == "explicit" && lookups != 0) || (tc.label != "explicit" && lookups != 1) { + t.Fatal("incorrect catalog lookup count", lookups) + } + if tc.want == "" { + if err == nil || saved != nil || strings.Contains(err.Error(), "private-marker") { + t.Fatal("failed lookup must prevent write") + } + return + } + if err != nil { + t.Fatal(err) + } + if _, err := runIntegration("", "update", "sample", `{"configuration":{"key":"second"}}`); err != nil { + t.Fatal(err) + } + var got savedConnection + if json.Unmarshal(saved, &got) != nil || got.Category != tc.want || string(got.Configuration["key"]) != `"second"` { + t.Fatal("wrong category or credential after rotation") + } + }) + } +} + +func TestIntegrationUpdateRejectsConflictingInput(t *testing.T) { + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + t.Error("invalid input should be rejected before any request") + }) + _, err := runIntegration("", "update", "sample", `{"enabled":true}`, "--file", "patch.json") + if err == nil || !strings.Contains(err.Error(), "use either JSON or --file") { + t.Fatalf("expected conflicting input error, got %v", err) + } +} + +func TestIntegrationLookupErrorHidesServerBody(t *testing.T) { + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Error("failed lookup must prevent a write") + } + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"message":"private-marker"}`) + }) + for _, args := range [][]string{{"create", `{"type":"test","name":"sample"}`}, {"update", "sample"}} { + out, err := runIntegration(`{"enabled":true}`, args...) + if err == nil || !strings.Contains(err.Error(), "HTTP 403") || strings.Contains(out+err.Error(), "private-marker") { + t.Fatal("expected safe lookup error") + } + } +} + +func TestIntegrationRejectsReservedEnvReferences(t *testing.T) { + integrationTestServer(t, func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected integration request: %s", r.Method) + }) + for _, name := range []string{"CONDUCTOR_KEY", "CONDUCTOR_AUTH_KEY", "CONDUCTOR_AUTH_SECRET", "CONDUCTOR_AUTH_TOKEN", "CONDUCTOR_ACCESS_KEY_ID", "CONDUCTOR_ACCESS_KEY_SECRET"} { + t.Run(name, func(t *testing.T) { + const value = "synthetic-reserved-marker" + t.Setenv(name, value) + config := fmt.Sprintf(`"configuration":{"nested":[{"key":"$.env.%s"}]}`, name) + for _, args := range [][]string{{"create", `{"name":"sample","type":"test",` + config + `}`}, {"update", "sample"}} { + out, err := runIntegration("{"+config+"}", args...) + if err == nil || !strings.Contains(err.Error(), name+" is reserved") || strings.Contains(out+err.Error(), value) { + t.Fatal("expected safe rejection for", args[0]) + } + } + }) + } +}