diff --git a/AGENTS.md b/AGENTS.md index ead45614..24f411e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -185,7 +185,8 @@ func validateTypeA(flags map[string]interface{}) error { ### Using the cached OpenAPI spec - Source type enum and auth rules are available via **`pkg/cmd/sources.FetchSourceTypes()`** (fetches from the API OpenAPI URL, caches under temp with TTL). Use it for **source management** (e.g. `source create`, `source upsert`) and **connection management** (e.g. `connection create` inline source) to validate `--type` and type-specific required auth flags. -- If `FetchSourceTypes()` fails (network, parse), **warn and continue**—do not block the command; let the API validate. If the given type is not in the cached enum, let the API validate. +- It parses the `SourceTypeConfig` schemas: which types require `config.auth` (from `x-required` on the `SourceTypeConfig` oneOf entry) and which fields each type's `config.auth` requires. `validateSourceAuthFromSpec` (`pkg/cmd/source_common.go`) checks the auth flags against those fields. `x-required` also marks types whose *handshake* is required; `optionalAuthSourceTypes` lists the one that still reads as auth-required (ONFLEET). +- If `FetchSourceTypes()` fails (network, parse, or a spec with no source types), **warn and continue**—do not block the command; let the API validate. A failed or empty parse is never cached. If the given type is not in the cached enum, let the API validate. - Prefer this over hardcoding type lists or required-auth rules so the CLI stays aligned with the API. ### Validation Layers (in order) diff --git a/REFERENCE.md b/REFERENCE.md index 8e1ac6c4..91c77ccd 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -342,6 +342,8 @@ Create a connection between a source and destination. You can either reference existing resources by ID or create them inline. + The auth flags build config.auth from the source type's own verification methods in the API spec. `--webhook-secret` sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need (sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the provider's own header and algorithm apply. `--hmac-secret` sends that HMAC shape (with `--hmac-algo`) wherever the type's method takes an algorithm, and otherwise behaves like `--webhook-secret`. `--api-key` sends api_key; WEBHOOK and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag sets it: pass config.auth with header_key through `--source-config`. Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags set it to the method they used. A flag no method of the type can express is refused, with the methods the type accepts. When auth comes from `--source-config` without auth_type, it is set only if the auth fields fit exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). Set auth_type in `--source-config` to choose the method yourself. + **Usage:** ```bash @@ -400,7 +402,7 @@ hookdeck gateway connection create [flags] | `--rule-filter-query` | `string` | Filter on request query parameters using Hookdeck filter syntax (JSON) | | `--rule-retry-count` | `int` | Number of retry attempts (default "0") | | `--rule-retry-interval` | `int` | Interval between retries in milliseconds (default "0") | -| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes to retry on | +| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes or expressions to retry on: codes (404), ranges (500-599), comparisons (>400, <=499) and exclusions (!401), e.g. "429,500-599" | | `--rule-retry-strategy` | `string` | Retry strategy (linear, exponential) | | `--rule-transform-code` | `string` | Transformation code. Creates the transformation named by `--rule-transform-name`, or replaces its code if it exists | | `--rule-transform-env` | `string` | JSON string representing environment variables for transformation. Replaces the env of an existing transformation | @@ -421,7 +423,7 @@ hookdeck gateway connection create [flags] | `--source-id` | `string` | Use existing source by ID | | `--source-name` | `string` | Source name for inline creation | | `--source-type` | `string` | Source type (WEBHOOK, STRIPE, etc.) | -| `--source-webhook-secret` | `string` | Webhook secret for source verification (e.g., Stripe) | +| `--source-webhook-secret` | `string` | Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only | **Examples:** @@ -506,7 +508,7 @@ hookdeck gateway connection update [flags] | Flag | Type | Description | |------|------|-------------| | `--description` | `string` | Connection description | -| `--destination-id` | `string` | Update destination by ID | +| `--destination-id` | `string` | Destination ID the connection already uses (a different value is rejected: a connection's destination cannot be changed) | | `--name` | `string` | New connection name | | `--output` | `string` | Output format (json) | | `--rule-deduplicate-exclude-fields` | `string` | Comma-separated list of fields to exclude for deduplication | @@ -519,14 +521,14 @@ hookdeck gateway connection update [flags] | `--rule-filter-query` | `string` | Filter on request query parameters using Hookdeck filter syntax (JSON) | | `--rule-retry-count` | `int` | Number of retry attempts (default "0") | | `--rule-retry-interval` | `int` | Interval between retries in milliseconds (default "0") | -| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes to retry on | +| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes or expressions to retry on: codes (404), ranges (500-599), comparisons (>400, <=499) and exclusions (!401), e.g. "429,500-599" | | `--rule-retry-strategy` | `string` | Retry strategy (linear, exponential) | | `--rule-transform-code` | `string` | Transformation code. Creates the transformation named by `--rule-transform-name`, or replaces its code if it exists | | `--rule-transform-env` | `string` | JSON string representing environment variables for transformation. Replaces the env of an existing transformation | | `--rule-transform-name` | `string` | Name or ID of an existing transformation to apply. With `--rule-transform-code`, an existing transformation's code is replaced, or a new transformation is created with this name | | `--rules` | `string` | JSON string representing the entire rules array | | `--rules-file` | `string` | Path to a JSON file containing the rules array | -| `--source-id` | `string` | Update source by ID | +| `--source-id` | `string` | Source ID the connection already uses (a different value is rejected: a connection's source cannot be changed) | **Examples:** @@ -537,8 +539,9 @@ hookdeck gateway connection update web_abc123 --name "new-name" # Update description hookdeck gateway connection update web_abc123 --description "Updated description" -# Change the source on a connection -hookdeck gateway connection update web_abc123 --source-id src_def456 +# A connection's source and destination cannot be changed. --source-id and +# --destination-id are accepted only when they match the stored values; +# to use a different one, create a new connection. # Update rules hookdeck gateway connection update web_abc123 \ @@ -593,8 +596,18 @@ Create a new connection or update an existing one by name (idempotent). - Only updates properties that are explicitly provided - Preserves existing properties that aren't specified + An existing connection's destination cannot be changed. If the destination + you name (by ID or by name) differs from the one the connection already uses, + the command fails before changing anything. Settings of the current + destination can still be updated. The source can be changed. + + Rules are replaced as a whole when `--rules` or `--rules-file` is given, and + left alone otherwise. Pass `--rules` '[]' to remove all rules. + Use `--dry-run` to preview changes without applying them. + The auth flags build config.auth from the source type's own verification methods in the API spec. `--webhook-secret` sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need (sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the provider's own header and algorithm apply. `--hmac-secret` sends that HMAC shape (with `--hmac-algo`) wherever the type's method takes an algorithm, and otherwise behaves like `--webhook-secret`. `--api-key` sends api_key; WEBHOOK and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag sets it: pass config.auth with header_key through `--source-config`. Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags set it to the method they used. A flag no method of the type can express is refused, with the methods the type accepts. When auth comes from `--source-config` without auth_type, it is set only if the auth fields fit exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). Set auth_type in `--source-config` to choose the method yourself. + **Usage:** ```bash @@ -659,7 +672,7 @@ hookdeck gateway connection upsert [flags] | `--rule-filter-query` | `string` | Filter on request query parameters using Hookdeck filter syntax (JSON) | | `--rule-retry-count` | `int` | Number of retry attempts (default "0") | | `--rule-retry-interval` | `int` | Interval between retries in milliseconds (default "0") | -| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes to retry on | +| `--rule-retry-response-status-codes` | `string` | Comma-separated HTTP status codes or expressions to retry on: codes (404), ranges (500-599), comparisons (>400, <=499) and exclusions (!401), e.g. "429,500-599" | | `--rule-retry-strategy` | `string` | Retry strategy (linear, exponential) | | `--rule-transform-code` | `string` | Transformation code. Creates the transformation named by `--rule-transform-name`, or replaces its code if it exists | | `--rule-transform-env` | `string` | JSON string representing environment variables for transformation. Replaces the env of an existing transformation | @@ -680,7 +693,7 @@ hookdeck gateway connection upsert [flags] | `--source-id` | `string` | Use existing source by ID | | `--source-name` | `string` | Source name for inline creation | | `--source-type` | `string` | Source type (WEBHOOK, STRIPE, etc.) | -| `--source-webhook-secret` | `string` | Webhook secret for source verification (e.g., Stripe) | +| `--source-webhook-secret` | `string` | Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only | **Examples:** @@ -838,6 +851,8 @@ Create a new source. Requires `--name` and `--type`. Use `--config` or `--config-file` for authentication (e.g. webhook_secret, api_key). +The auth flags build config.auth from the source type's own verification methods in the API spec. `--webhook-secret` sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need (sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the provider's own header and algorithm apply. `--hmac-secret` sends that HMAC shape (with `--hmac-algo`) wherever the type's method takes an algorithm, and otherwise behaves like `--webhook-secret`. `--api-key` sends api_key; WEBHOOK and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag sets it: pass config.auth with header_key through `--config`. Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags set it to the method they used. A flag no method of the type can express is refused, with the methods the type accepts. When auth comes from `--config` without auth_type, it is set only if the auth fields fit exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). Set auth_type in `--config` to choose the method yourself. + **Usage:** ```bash @@ -862,7 +877,7 @@ hookdeck gateway source create [flags] | `--name` | `string` | Source name (required) | | `--output` | `string` | Output format (json) | | `--type` | `string` | Source type (e.g. WEBHOOK, STRIPE) (required) | -| `--webhook-secret` | `string` | Webhook secret for source verification (e.g., Stripe) | +| `--webhook-secret` | `string` | Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only | **Examples:** @@ -899,6 +914,10 @@ hookdeck gateway source get my-source --include-auth Update an existing source by its ID. +Config flags without `--type` are applied to the source's current type, which is looked up first. + +The auth flags build config.auth from the source type's own verification methods in the API spec. `--webhook-secret` sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need (sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the provider's own header and algorithm apply. `--hmac-secret` sends that HMAC shape (with `--hmac-algo`) wherever the type's method takes an algorithm, and otherwise behaves like `--webhook-secret`. `--api-key` sends api_key; WEBHOOK and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag sets it: pass config.auth with header_key through `--config`. Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags set it to the method they used. A flag no method of the type can express is refused, with the methods the type accepts. When auth comes from `--config` without auth_type, it is set only if the auth fields fit exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). Set auth_type in `--config` to choose the method yourself. + **Usage:** ```bash @@ -923,7 +942,7 @@ hookdeck gateway source update [flags] | `--name` | `string` | New source name | | `--output` | `string` | Output format (json) | | `--type` | `string` | Source type (e.g. WEBHOOK, STRIPE) | -| `--webhook-secret` | `string` | Webhook secret for source verification (e.g., Stripe) | +| `--webhook-secret` | `string` | Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only | **Examples:** @@ -958,6 +977,13 @@ hookdeck gateway source delete src_abc123 --force Create a new source or update an existing one by name (idempotent). +When `--type` is omitted and the source already exists, its current type is kept, +along with its verification unless you pass new auth flags or config. When the +source does not exist, it is created as a WEBHOOK source. Pass `--type` to change +an existing source's type. + +The auth flags build config.auth from the source type's own verification methods in the API spec. `--webhook-secret` sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need (sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the provider's own header and algorithm apply. `--hmac-secret` sends that HMAC shape (with `--hmac-algo`) wherever the type's method takes an algorithm, and otherwise behaves like `--webhook-secret`. `--api-key` sends api_key; WEBHOOK and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag sets it: pass config.auth with header_key through `--config`. Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags set it to the method they used. A flag no method of the type can express is refused, with the methods the type accepts. When auth comes from `--config` without auth_type, it is set only if the auth fields fit exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). Set auth_type in `--config` to choose the method yourself. + **Usage:** ```bash @@ -982,7 +1008,7 @@ hookdeck gateway source upsert [flags] | `--hmac-secret` | `string` | HMAC secret for signature verification | | `--output` | `string` | Output format (json) | | `--type` | `string` | Source type (e.g. WEBHOOK, STRIPE) | -| `--webhook-secret` | `string` | Webhook secret for source verification (e.g., Stripe) | +| `--webhook-secret` | `string` | Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only | **Examples:** diff --git a/pkg/cmd/connection_common.go b/pkg/cmd/connection_common.go index 94411147..8a595f99 100644 --- a/pkg/cmd/connection_common.go +++ b/pkg/cmd/connection_common.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "os" + "regexp" "strconv" "strings" @@ -13,6 +14,14 @@ import ( "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" ) +// retryStatusCodeExpr matches one entry of a retry rule's response_status_codes, mirroring the +// API's RetryRule pattern: a range ("500-599"), a comparison (">400", ">=500", "<=499", "=404"), +// or a code with optional exclusion ("404", "!401"). Codes are 200-599. +var retryStatusCodeExpr = regexp.MustCompile(`^(?:([2-5]\d{2})-([2-5]\d{2})|([><=]{1,2})([2-5]\d{2})|!?([2-5]\d{2}))$`) + +// maxRetryStatusCodes is the API's limit on entries in a retry rule's response_status_codes. +const maxRetryStatusCodes = 10 + // shouldShowConnectionDeprecation returns true when the user invoked the // root-level alias (hookdeck connection / hookdeck connections) and we // should print a deprecation notice. Returns false when: @@ -128,7 +137,7 @@ func addConnectionRuleFlags(cmd *cobra.Command, f *connectionRuleFlags) { cmd.Flags().StringVar(&f.RuleRetryStrategy, "rule-retry-strategy", "", "Retry strategy (linear, exponential)") cmd.Flags().IntVar(&f.RuleRetryCount, "rule-retry-count", 0, "Number of retry attempts") cmd.Flags().IntVar(&f.RuleRetryInterval, "rule-retry-interval", 0, "Interval between retries in milliseconds") - cmd.Flags().StringVar(&f.RuleRetryResponseStatusCode, "rule-retry-response-status-codes", "", "Comma-separated HTTP status codes to retry on") + cmd.Flags().StringVar(&f.RuleRetryResponseStatusCode, "rule-retry-response-status-codes", "", "Comma-separated HTTP status codes or expressions to retry on: codes (404), ranges (500-599), comparisons (>400, <=499) and exclusions (!401), e.g. \"429,500-599\"") cmd.Flags().StringVar(&f.RuleFilterBody, "rule-filter-body", "", "Filter on request body using Hookdeck filter syntax (JSON)") cmd.Flags().StringVar(&f.RuleFilterHeaders, "rule-filter-headers", "", "Filter on request headers using Hookdeck filter syntax (JSON)") @@ -251,7 +260,8 @@ func buildConnectionRules(f *connectionRuleFlags) ([]hookdeck.Rule, error) { if f.RuleRetryInterval > 0 { rule["interval"] = f.RuleRetryInterval } - // API expects response_status_codes as []string (RetryRule schema) + // API expects response_status_codes as []string (RetryRule schema). Each entry may be a + // code ("404"), a range ("500-599"), a comparison (">400", "<=499") or an exclusion ("!401"). if f.RuleRetryResponseStatusCode != "" { parts := strings.Split(f.RuleRetryResponseStatusCode, ",") strCodes := make([]string, 0, len(parts)) @@ -260,15 +270,14 @@ func buildConnectionRules(f *connectionRuleFlags) ([]hookdeck.Rule, error) { if part == "" { continue } - n, err := strconv.Atoi(part) - if err != nil { - return nil, fmt.Errorf("invalid HTTP status code %q in --rule-retry-response-status-codes: must be an integer", part) - } - if n < 100 || n > 599 { - return nil, fmt.Errorf("invalid HTTP status code %d in --rule-retry-response-status-codes: must be between 100 and 599", n) + if !retryStatusCodeExpr.MatchString(part) { + return nil, fmt.Errorf("invalid HTTP status code expression %q in --rule-retry-response-status-codes: use a code (404), range (500-599), comparison (>400, <=499) or exclusion (!401), with codes 200-599", part) } strCodes = append(strCodes, part) } + if len(strCodes) > maxRetryStatusCodes { + return nil, fmt.Errorf("--rule-retry-response-status-codes accepts at most %d entries (got %d); use ranges such as 500-599 to cover more codes", maxRetryStatusCodes, len(strCodes)) + } rule["response_status_codes"] = strCodes } built["retry"] = rule diff --git a/pkg/cmd/connection_create.go b/pkg/cmd/connection_create.go index 3f731560..a76ebe9d 100644 --- a/pkg/cmd/connection_create.go +++ b/pkg/cmd/connection_create.go @@ -114,6 +114,8 @@ func newConnectionCreateCmd() *connectionCreateCmd { Long: `Create a connection between a source and destination. You can either reference existing resources by ID or create them inline. + + ` + LongSourceAuthType("--source-config") + ` Examples: # Create with inline source and destination @@ -150,7 +152,7 @@ func newConnectionCreateCmd() *connectionCreateCmd { cc.cmd.Flags().StringVar(&cc.sourceDescription, "source-description", "", "Source description") // Universal source authentication flags - cc.cmd.Flags().StringVar(&cc.SourceWebhookSecret, "source-webhook-secret", "", "Webhook secret for source verification (e.g., Stripe)") + cc.cmd.Flags().StringVar(&cc.SourceWebhookSecret, "source-webhook-secret", "", "Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only") cc.cmd.Flags().StringVar(&cc.SourceAPIKey, "source-api-key", "", "API key for source authentication") cc.cmd.Flags().StringVar(&cc.SourceBasicAuthUser, "source-basic-auth-user", "", "Username for Basic authentication") cc.cmd.Flags().StringVar(&cc.SourceBasicAuthPass, "source-basic-auth-pass", "", "Password for Basic authentication") @@ -530,10 +532,12 @@ func (cc *connectionCreateCmd) buildSourceInput() (*hookdeck.SourceCreateInput, return nil, fmt.Errorf("error building source config: %w", err) } + // The API rejects an empty source.type, so a source given only --source-name (possible with + // upsert of a new connection) is sent as WEBHOOK, the type its config was built for. return &hookdeck.SourceCreateInput{ Name: cc.sourceName, Description: description, - Type: strings.ToUpper(cc.sourceType), + Type: strings.ToUpper(sourceTypeOrAPIDefault(cc.sourceType)), Config: sourceConfig, }, nil } @@ -788,15 +792,25 @@ func (cc *connectionCreateCmd) buildAuthConfig() (map[string]interface{}, error) return authConfig, nil } +// buildSourceConfig builds config for the inline source. An omitted --source-type is built as +// the type the API applies to a new source (WEBHOOK). func (cc *connectionCreateCmd) buildSourceConfig() (map[string]interface{}, error) { + return cc.buildSourceConfigForType(sourceTypeOrAPIDefault(cc.sourceType)) +} + +// buildSourceConfigForType builds source config from --source-config, --source-config-file or +// the individual --source-* flags, shaped for sourceType. +func (cc *connectionCreateCmd) buildSourceConfigForType(sourceType string) (map[string]interface{}, error) { // Handle JSON config first (same precedence as source commands) if cc.SourceConfig != "" { var config map[string]interface{} if err := json.Unmarshal([]byte(cc.SourceConfig), &config); err != nil { return nil, fmt.Errorf("invalid JSON in --source-config: %w", err) } - normalizeSourceConfigAuth(config, cc.sourceType) - ensureSourceConfigAuthTypeForHTTP(config, cc.sourceType) + if err := normalizeSourceConfigAuth(config, sourceType); err != nil { + return nil, err + } + ensureSourceConfigAuthType(config, sourceType) return config, nil } if cc.SourceConfigFile != "" { @@ -808,8 +822,10 @@ func (cc *connectionCreateCmd) buildSourceConfig() (map[string]interface{}, erro if err := json.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("invalid JSON in --source-config-file: %w", err) } - normalizeSourceConfigAuth(config, cc.sourceType) - ensureSourceConfigAuthTypeForHTTP(config, cc.sourceType) + if err := normalizeSourceConfigAuth(config, sourceType); err != nil { + return nil, err + } + ensureSourceConfigAuthType(config, sourceType) return config, nil } // Build from individual --source-* flags using shared logic @@ -824,13 +840,10 @@ func (cc *connectionCreateCmd) buildSourceConfig() (map[string]interface{}, erro CustomResponseBody: cc.SourceCustomResponseBody, CustomResponseType: cc.SourceCustomResponseType, } - config, err := buildSourceConfigFromIndividualFlags(f, "source-", cc.sourceType) + config, err := buildSourceConfigFromIndividualFlags(f, "source-", sourceType) if err != nil { return nil, err } - if config != nil { - ensureSourceConfigAuthTypeForHTTP(config, cc.sourceType) - } if len(config) == 0 { return make(map[string]interface{}), nil } diff --git a/pkg/cmd/connection_retry_status_codes_test.go b/pkg/cmd/connection_retry_status_codes_test.go new file mode 100644 index 00000000..a19132aa --- /dev/null +++ b/pkg/cmd/connection_retry_status_codes_test.go @@ -0,0 +1,73 @@ +package cmd + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// --rule-retry-response-status-codes accepts the same expressions as the API's RetryRule +// response_status_codes pattern (and --rules JSON): codes, ranges, comparisons, exclusions. +func TestRetryResponseStatusCodesAcceptsAPIExpressions(t *testing.T) { + tests := []struct { + name string + value string + want []string + }{ + {name: "single code", value: "429", want: []string{"429"}}, + {name: "code and range", value: "429,500-599", want: []string{"429", "500-599"}}, + {name: "comparisons", value: ">400,>=500,<=499,<300,=404", want: []string{">400", ">=500", "<=499", "<300", "=404"}}, + {name: "exclusion", value: "500-599,!501", want: []string{"500-599", "!501"}}, + {name: "whitespace and empty entries trimmed", value: " 429 , 500-599 ,, ", want: []string{"429", "500-599"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := parseRuleFlags(t, []string{ + "--rule-retry-strategy", "linear", + "--rule-retry-response-status-codes", tt.value, + }) + rules, err := buildConnectionRules(f) + require.NoError(t, err) + require.Len(t, rules, 1) + assert.Equal(t, "retry", rules[0]["type"]) + assert.Equal(t, tt.want, rules[0]["response_status_codes"]) + }) + } +} + +func TestRetryResponseStatusCodesRejectsInvalidExpressions(t *testing.T) { + for _, value := range []string{ + "abc", // not a code + "100", // API only accepts 200-599 + "600", // out of range + "500-", // incomplete range + "500-6xx", // malformed range end + ">>>400", // too many comparison characters + "!>400", // exclusion only applies to a single code + "4xx", // wildcard is not an API expression + } { + t.Run(value, func(t *testing.T) { + f := parseRuleFlags(t, []string{ + "--rule-retry-strategy", "linear", + "--rule-retry-response-status-codes", value, + }) + _, err := buildConnectionRules(f) + require.Error(t, err) + assert.Contains(t, err.Error(), "--rule-retry-response-status-codes") + assert.Contains(t, err.Error(), value) + }) + } +} + +func TestRetryResponseStatusCodesLimit(t *testing.T) { + build := func(value string) error { + f := parseRuleFlags(t, []string{"--rule-retry-strategy", "linear", "--rule-retry-response-status-codes", value}) + _, err := buildConnectionRules(f) + return err + } + assert.NoError(t, build("500,501,502,503,504,505,506,507,508,509"), "10 entries is the API maximum") + err := build("500,501,502,503,504,505,506,507,508,509,510") + require.Error(t, err) + assert.Contains(t, err.Error(), "at most 10") +} diff --git a/pkg/cmd/connection_side_guard_test.go b/pkg/cmd/connection_side_guard_test.go new file mode 100644 index 00000000..b323a4b3 --- /dev/null +++ b/pkg/cmd/connection_side_guard_test.go @@ -0,0 +1,202 @@ +package cmd + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// storedWithSides is the connection every guard test holds as the stored one. +func storedWithSides() []hookdeck.Connection { + return []hookdeck.Connection{*storedUpsertConnection()} +} + +// TestConnectionUpsertRejectsChangedSide covers each way of naming a different +// source or destination. Every case has to fail before any write: a PUT of the +// connection, or of an inline destination, is what made the change look +// applied while the API ignored it (#466). +func TestConnectionUpsertRejectsChangedSide(t *testing.T) { + cases := []struct { + name string + args []string + message string + }{ + { + name: "inline destination with a different name", + args: []string{"--source-name", "my-src", "--source-type", "WEBHOOK", "--destination-name", "other-api", "--destination-type", "HTTP", "--destination-url", "https://other.example.com"}, + message: "destination", + }, + { + name: "different destination ID with the stored source ID", + args: []string{"--source-id", "src_1", "--destination-id", "des_other"}, + message: "destination", + }, + { + name: "different destination ID alone", + args: []string{"--destination-id", "des_other"}, + message: "destination", + }, + } + + for _, tc := range cases { + for _, dryRun := range []bool{false, true} { + tc, dryRun := tc, dryRun + name := tc.name + args := append([]string{"gateway", "connection", "upsert", "my-conn"}, tc.args...) + if dryRun { + name += " (dry-run)" + args = append(args, "--dry-run") + } + t.Run(name, func(t *testing.T) { + stub, err := runConnectionCommand(t, storedWithSides(), args...) + + require.Error(t, err) + require.Contains(t, err.Error(), "cannot be changed") + require.Contains(t, err.Error(), tc.message) + require.Empty(t, stub.writes(), "no write may be made once the change is rejected") + }) + } + } +} + +// TestConnectionUpsertWithADifferentSourceIsADifferentConnection pins what the +// live API does: a connection name is only unique per source, so naming another +// source creates a second connection with the same name instead of re-pointing +// the stored one. That connection may have any destination, so the destination +// guard must not apply to it - the live API accepts this, and refusing it would +// block a working feature. +func TestConnectionUpsertWithADifferentSourceIsADifferentConnection(t *testing.T) { + t.Run("by ID, with a different destination", func(t *testing.T) { + stub, err := runConnectionCommand(t, storedWithSides(), + "gateway", "connection", "upsert", "my-conn", "--source-id", "src_other", "--destination-id", "des_other") + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + require.Equal(t, "src_other", stub.writes()[0].Body["source_id"]) + require.Equal(t, "des_other", stub.writes()[0].Body["destination_id"]) + }) + + t.Run("by inline name", func(t *testing.T) { + stub, err := runConnectionCommand(t, storedWithSides(), + "gateway", "connection", "upsert", "my-conn", "--source-name", "other-src") + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + source, ok := stub.writes()[0].Body["source"].(map[string]interface{}) + require.True(t, ok, "the new source must be sent inline") + require.Equal(t, "other-src", source["name"]) + }) +} + +// twoConnectionsNamedMyConn returns my-conn on two sources, each with its own +// destination. +func twoConnectionsNamedMyConn() []hookdeck.Connection { + first := *storedUpsertConnection() + second := *storedUpsertConnection() + second.ID = "web_2" + second.Source = &hookdeck.Source{ID: "src_2", Name: "second-src", Type: "WEBHOOK"} + second.Destination = &hookdeck.Destination{ID: "des_2", Name: "second-api", Type: "HTTP"} + return []hookdeck.Connection{first, second} +} + +// TestConnectionUpsertAmbiguousName: the same name on two sources is two +// connections, and picking the first would update the wrong one. +func TestConnectionUpsertAmbiguousName(t *testing.T) { + t.Run("no source named is refused before any write", func(t *testing.T) { + stub, err := runConnectionCommand(t, twoConnectionsNamedMyConn(), + "gateway", "connection", "upsert", "my-conn", "--description", "d") + + require.Error(t, err) + require.Contains(t, err.Error(), "--source-id") + require.Empty(t, stub.writes()) + }) + + t.Run("the source picks the connection and its destination is guarded", func(t *testing.T) { + stub, err := runConnectionCommand(t, twoConnectionsNamedMyConn(), + "gateway", "connection", "upsert", "my-conn", "--source-id", "src_2", "--destination-id", "des_1") + + require.Error(t, err) + require.Contains(t, err.Error(), "second-api", "the second connection's destination is the one being compared") + require.Empty(t, stub.writes()) + }) + + t.Run("negative control: the second connection's own destination is accepted", func(t *testing.T) { + stub, err := runConnectionCommand(t, twoConnectionsNamedMyConn(), + "gateway", "connection", "upsert", "my-conn", "--source-id", "src_2", "--destination-id", "des_2") + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + }) +} + +// TestConnectionUpsertAllowsUnchangedSides is the negative control: the same +// flags with the stored names and IDs must still reach the API, so the guard is +// rejecting the difference and not every upsert that names a destination. +func TestConnectionUpsertAllowsUnchangedSides(t *testing.T) { + cases := map[string][]string{ + "inline sides with the stored names": {"--source-name", "my-src", "--source-type", "WEBHOOK", "--destination-name", "my-api", "--destination-type", "HTTP", "--destination-url", "https://api.example.com/v2"}, + "the stored IDs": {"--source-id", "src_1", "--destination-id", "des_1"}, + } + for name, flags := range cases { + flags := flags + t.Run(name, func(t *testing.T) { + args := append([]string{"gateway", "connection", "upsert", "my-conn"}, flags...) + stub, err := runConnectionCommand(t, storedWithSides(), args...) + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + require.Equal(t, http.MethodPut, stub.writes()[0].Method) + }) + } +} + +// TestConnectionUpsertChangedSideOnNewConnectionIsACreate: when no connection +// has the name there is nothing to compare with, and the flags create one. +func TestConnectionUpsertChangedSideOnNewConnectionIsACreate(t *testing.T) { + stub, err := runConnectionCommand(t, nil, + "gateway", "connection", "upsert", "brand-new", + "--source-id", "src_x", "--destination-id", "des_x") + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + require.Equal(t, "des_x", stub.writes()[0].Body["destination_id"]) +} + +// TestConnectionUpdateRejectsChangedSide covers connection update, which sent +// the new ID to an endpoint that discards it. Unlike upsert, update ignores a +// new source as well as a new destination (verified against the live API). +func TestConnectionUpdateRejectsChangedSide(t *testing.T) { + for flag, message := range map[string]string{ + "--destination-id": "destination", + "--source-id": "source", + } { + flag, message := flag, message + t.Run(flag, func(t *testing.T) { + stub, err := runConnectionCommand(t, storedWithSides(), + "gateway", "connection", "update", "web_1", flag, "other_id") + + require.Error(t, err) + require.Contains(t, err.Error(), "cannot be changed") + require.Contains(t, err.Error(), message) + require.Empty(t, stub.writes()) + }) + } +} + +// TestConnectionUpdateAcceptsStoredSideIDs is the negative control for update: +// the stored IDs are accepted, are not sent, and other changes still go out. +func TestConnectionUpdateAcceptsStoredSideIDs(t *testing.T) { + stub, err := runConnectionCommand(t, storedWithSides(), + "gateway", "connection", "update", "web_1", + "--destination-id", "des_1", "--source-id", "src_1", "--description", "new") + + require.NoError(t, err) + require.Len(t, stub.writes(), 1) + body := stub.writes()[0].Body + require.Equal(t, "new", body["description"]) + require.NotContains(t, body, "destination_id") + require.NotContains(t, body, "source_id") +} diff --git a/pkg/cmd/connection_update.go b/pkg/cmd/connection_update.go index 5c1534c7..708a11ef 100644 --- a/pkg/cmd/connection_update.go +++ b/pkg/cmd/connection_update.go @@ -46,8 +46,9 @@ Examples: # Update description hookdeck gateway connection update web_abc123 --description "Updated description" - # Change the source on a connection - hookdeck gateway connection update web_abc123 --source-id src_def456 + # A connection's source and destination cannot be changed. --source-id and + # --destination-id are accepted only when they match the stored values; + # to use a different one, create a new connection. # Update rules hookdeck gateway connection update web_abc123 \ @@ -67,8 +68,8 @@ Examples: cu.cmd.Flags().StringVar(&cu.description, "description", "", "Connection description") // Resource references - cu.cmd.Flags().StringVar(&cu.sourceID, "source-id", "", "Update source by ID") - cu.cmd.Flags().StringVar(&cu.destinationID, "destination-id", "", "Update destination by ID") + cu.cmd.Flags().StringVar(&cu.sourceID, "source-id", "", "Source ID the connection already uses (a different value is rejected: a connection's source cannot be changed)") + cu.cmd.Flags().StringVar(&cu.destinationID, "destination-id", "", "Destination ID the connection already uses (a different value is rejected: a connection's destination cannot be changed)") addConnectionRuleFlags(cu.cmd, &cu.connectionRuleFlags) @@ -103,14 +104,18 @@ func (cu *connectionUpdateCmd) runConnectionUpdateCmd(cmd *cobra.Command, args [ hasChanges = true } - if cu.sourceID != "" { - req.SourceID = &cu.sourceID - hasChanges = true - } - - if cu.destinationID != "" { - req.DestinationID = &cu.destinationID - hasChanges = true + // The API never changes an existing connection's source or destination + // (PUT /connections/{id} drops source_id and destination_id), so a value + // that differs from the stored one is an error rather than a silent no-op + // reported as success (#466). A value equal to the stored one is not sent. + if cu.sourceID != "" || cu.destinationID != "" { + current, err := client.GetConnection(ctx, connectionID) + if err != nil { + return fmt.Errorf("failed to get connection: %w", err) + } + if err := hookdeck.CheckConnectionSidesUnchanged(current, cu.sourceID, "", cu.destinationID, ""); err != nil { + return err + } } // Build rules if any rule flags are set diff --git a/pkg/cmd/connection_upsert.go b/pkg/cmd/connection_upsert.go index 32893245..574f117e 100644 --- a/pkg/cmd/connection_upsert.go +++ b/pkg/cmd/connection_upsert.go @@ -38,7 +38,17 @@ func newConnectionUpsertCmd() *connectionUpsertCmd { - Only updates properties that are explicitly provided - Preserves existing properties that aren't specified + An existing connection's destination cannot be changed. If the destination + you name (by ID or by name) differs from the one the connection already uses, + the command fails before changing anything. Settings of the current + destination can still be updated. The source can be changed. + + Rules are replaced as a whole when --rules or --rules-file is given, and + left alone otherwise. Pass --rules '[]' to remove all rules. + Use --dry-run to preview changes without applying them. + + ` + LongSourceAuthType("--source-config") + ` Examples: # Create or update a connection with inline source and destination @@ -76,7 +86,7 @@ func newConnectionUpsertCmd() *connectionUpsertCmd { cu.cmd.Flags().StringVar(&cu.sourceDescription, "source-description", "", "Source description") // Universal source authentication flags - cu.cmd.Flags().StringVar(&cu.SourceWebhookSecret, "source-webhook-secret", "", "Webhook secret for source verification (e.g., Stripe)") + cu.cmd.Flags().StringVar(&cu.SourceWebhookSecret, "source-webhook-secret", "", "Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only") cu.cmd.Flags().StringVar(&cu.SourceAPIKey, "source-api-key", "", "API key for source authentication") cu.cmd.Flags().StringVar(&cu.SourceBasicAuthUser, "source-basic-auth-user", "", "Username for Basic authentication") cu.cmd.Flags().StringVar(&cu.SourceBasicAuthPass, "source-basic-auth-pass", "", "Password for Basic authentication") @@ -298,23 +308,23 @@ func (cu *connectionUpsertCmd) validateDestinationFlags() error { // // It is needed when: // 1. Dry-run mode (to show the preview) -// 2. Partial update (source/destination config fields without name/type) +// 2. Either side - source or destination - is not named by the flags, so it +// has to come from the stored connection // 3. A name is given without a type, which is filled in from the stored record // 4. A create-time default would otherwise be applied to a stored destination +// 5. A destination is named by ID or name, so it can be checked against the +// stored one (upsert cannot change an existing connection's destination) func (cu *connectionUpsertCmd) needsExistingConnection() bool { - hasSourceConfigOnly := (cu.SourceWebhookSecret != "" || cu.SourceAPIKey != "" || - cu.SourceBasicAuthUser != "" || cu.SourceBasicAuthPass != "" || - cu.SourceHMACSecret != "" || cu.SourceHMACAlgo != "" || - cu.SourceAllowedHTTPMethods != "" || cu.SourceCustomResponseType != "" || - cu.SourceCustomResponseBody != "" || cu.SourceConfig != "" || cu.SourceConfigFile != "") && - cu.sourceName == "" && cu.sourceType == "" && cu.sourceID == "" - - hasDestinationConfigOnly := (cu.destinationURL != "" || cu.destinationCliPath != "" || - cu.destinationPathForwardingDisabled != nil || cu.destinationHTTPMethod != "" || - cu.DestinationRateLimit != 0 || cu.DestinationRateLimitPeriod != "" || cu.DestinationDeliveryGroupKey != "" || - cu.DestinationDeliveryGroupRate != 0 || cu.DestinationDeliveryGroupRatePeriod != "" || - cu.DestinationDeliveryGroupOverrides != "" || cu.DestinationAuthMethod != "") && - cu.destinationName == "" && cu.destinationType == "" && cu.destinationID == "" + // PUT /connections must carry a source and a destination, each either by ID + // or inline. A side the flags do not name (no --*-id, --*-name or --*-type) + // can only be supplied from the stored connection: carried over by ID when + // it has no flags at all, or rebuilt with config flags merged in otherwise. + // Without the lookup it is left out of the request, and the API rejects the + // update with "must contain at least one of [destination_id, destination]". + // This covers the no-flags and config-only cases, and the one that was + // missed: an inline source with no destination flags, or the reverse. + sourceUnnamed := cu.sourceID == "" && cu.sourceName == "" && cu.sourceType == "" + destinationUnnamed := cu.destinationID == "" && cu.destinationName == "" && cu.destinationType == "" // Also need to fetch existing when name is provided without type (to fill in the type) hasPartialSourceInline := (cu.sourceName != "" && cu.sourceType == "" && cu.sourceID == "") @@ -337,9 +347,17 @@ func (cu *connectionUpsertCmd) needsExistingConnection() bool { (cu.DestinationDeliveryGroupKey != "" || cu.DestinationDeliveryGroupRate != 0 || cu.DestinationDeliveryGroupRatePeriod != "") - return cu.dryRun || - (!cu.hasAnySourceFlag() && !cu.hasAnyDestinationFlag()) || - hasSourceConfigOnly || hasDestinationConfigOnly || + // A destination named by ID or by name has to be compared with the stored + // one: upsert never re-points an existing connection's destination (#466), + // and without the comparison the change is dropped while the command reports + // success. The lookup also has to happen before an inline destination is + // upserted, or a rejected change leaves that destination behind unattached. + // The source is not compared: upsert does change it, by ID or by inline name + // (verified against the live API). + sideNamed := cu.destinationID != "" || cu.destinationName != "" + + return cu.dryRun || sideNamed || + sourceUnnamed || destinationUnnamed || hasPartialSourceInline || hasPartialDestinationInline || cliPathDefaultWouldApply || groupsWouldDropOverrides } @@ -355,16 +373,28 @@ func (cu *connectionUpsertCmd) runConnectionUpsertCmd(cmd *cobra.Command, args [ var isUpdate bool if cu.needsExistingConnection() { - connections, err := client.ListConnections(context.Background(), map[string]string{ - "name": name, - }) + candidates, err := client.FindConnectionsByName(context.Background(), name) if err != nil { return fmt.Errorf("failed to check if connection exists: %w", err) } + found, sameConnection, err := hookdeck.SelectConnectionForUpsert(candidates, name, cu.sourceID, cu.sourceName) + if err != nil { + return err + } - if connections != nil && len(connections.Models) > 0 { - existing = &connections.Models[0] + if found != nil { + existing = found isUpdate = true + + // Checked before anything is written, so a rejected change creates no + // inline source or destination that nothing then points at. Skipped when + // a different source is named: the API treats that as a different + // connection with the same name, which may have any destination. + if sameConnection { + if err := hookdeck.CheckConnectionSidesUnchanged(existing, "", "", cu.destinationID, cu.destinationName); err != nil { + return err + } + } } } @@ -557,7 +587,15 @@ func (cu *connectionUpsertCmd) buildUpsertRequest(existing *hookdeck.Connection, if err != nil { return nil, err } - if len(rules) > 0 { + // Keyed off whether --rules or --rules-file was given rather than whether it + // produced any rules, so an explicit empty array reaches the API and clears + // the ruleset, as it does for `connection update` (#472). + if cu.Rules != "" || cu.RulesFile != "" { + if rules == nil { + rules = []hookdeck.Rule{} + } + req.Rules = &rules + } else if len(rules) > 0 { req.Rules = &rules } @@ -583,12 +621,25 @@ func (cu *connectionUpsertCmd) buildSourceInputForUpdate(existingSource *hookdec } } - // Build new config from flags (this will override existing values) - newConfig, err := cu.buildSourceConfig() + // Build new config from flags (this will override existing values). Shape it for the + // stored type: no --source-type was given, and both the auth fields and the auth_type to + // infer depend on the type. + newConfig, err := cu.buildSourceConfigForType(existingSource.Type) if err != nil { return nil, err } + // The stored config carries auth_type (the method the source verifies with) but not the + // auth credentials. Sending that auth_type back without auth fails validation, and keeping + // it beside new auth names the old method for the new credentials. So it goes unless the + // stored auth is going back with it; new auth brings its own (inferred) auth_type. + if _, newAuth := newConfig["auth"]; newAuth { + delete(sourceConfig, "auth") + delete(sourceConfig, "auth_type") + } else if _, storedAuth := sourceConfig["auth"]; !storedAuth { + delete(sourceConfig, "auth_type") + } + // Merge new config into existing config for k, v := range newConfig { sourceConfig[k] = v @@ -730,7 +781,10 @@ func (cu *connectionUpsertCmd) previewUpsertChanges(existing *hookdeck.Connectio } // Check rules changes - if req.Rules != nil && len(*req.Rules) > 0 { + if req.Rules != nil && len(*req.Rules) == 0 { + changes++ + fmt.Printf(" • Rules: will be cleared (%d rules → none)\n", len(existing.Rules)) + } else if req.Rules != nil { changes++ rulesJSON, _ := json.MarshalIndent(req.Rules, " ", " ") fmt.Printf(" • Rules:\n") @@ -749,7 +803,7 @@ func (cu *connectionUpsertCmd) previewUpsertChanges(existing *hookdeck.Connectio if req.DestinationID == nil && req.Destination == nil && existing.Destination != nil { fmt.Printf(" • Destination: %s (unchanged)\n", existing.Destination.Name) } - if (req.Rules == nil || len(*req.Rules) == 0) && len(existing.Rules) > 0 { + if req.Rules == nil && len(existing.Rules) > 0 { fmt.Printf(" • Rules: %d rules (unchanged)\n", len(existing.Rules)) } } else { diff --git a/pkg/cmd/connection_upsert_command_test.go b/pkg/cmd/connection_upsert_command_test.go new file mode 100644 index 00000000..73545171 --- /dev/null +++ b/pkg/cmd/connection_upsert_command_test.go @@ -0,0 +1,128 @@ +package cmd + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/config" + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// captureConnectionUpsertBody runs `gateway connection upsert` against a stub +// API that holds stored as the existing connection, and returns the decoded +// PUT /connections body. +// +// The stub answers the PUT whatever it carries, so a passing run says nothing on +// its own: the real API rejects a body with no source or no destination, and +// that is what these tests assert against. +func captureConnectionUpsertBody(t *testing.T, stored *hookdeck.Connection, args ...string) map[string]interface{} { + t.Helper() + + var body map[string]interface{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + switch { + case r.URL.Path == hookdeck.APIPathPrefix+"/cli-auth/validate": + _ = json.NewEncoder(w).Encode(hookdeck.ValidateAPIKeyResponse{ + ProjectID: "proj_1", + ProjectMode: "inbound", + }) + case r.URL.Path == hookdeck.APIPathPrefix+"/connections" && r.Method == http.MethodGet: + models := []hookdeck.Connection{} + if stored != nil && r.URL.Query().Get("name") == *stored.Name { + models = append(models, *stored) + } + _ = json.NewEncoder(w).Encode(hookdeck.ConnectionListResponse{Models: models}) + case r.URL.Path == hookdeck.APIPathPrefix+"/connections" && r.Method == http.MethodPut: + raw, err := io.ReadAll(r.Body) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(raw, &body)) + _ = json.NewEncoder(w).Encode(stored) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(server.Close) + + config.ResetAPIClientForTesting() + t.Cleanup(config.ResetAPIClientForTesting) + + old := Config + t.Cleanup(func() { Config = old }) + Config = config.Config{APIBaseURL: server.URL, LogLevel: "info"} + Config.Profile.APIKey = "sk_test_123456789012" + Config.Profile.ProjectId = "proj_1" + Config.Profile.ProjectType = config.ProjectTypeEventGateway + + root := &cobra.Command{Use: "hookdeck", SilenceUsage: true, SilenceErrors: true} + root.AddCommand(newGatewayCmd().cmd) + root.SetArgs(args) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + + require.NoError(t, root.Execute()) + require.NotNil(t, body, "the command made no PUT /connections request") + return body +} + +func storedUpsertConnection() *hookdeck.Connection { + return &hookdeck.Connection{ + ID: "web_1", + Name: strPtr("my-conn"), + Source: &hookdeck.Source{ + ID: "src_1", Name: "my-src", Type: "WEBHOOK", + }, + Destination: &hookdeck.Destination{ + ID: "des_1", Name: "my-api", Type: "HTTP", + Config: map[string]interface{}{"url": "https://api.example.com"}, + }, + } +} + +// TestConnectionUpsertInlineSourceKeepsStoredDestination is the reported case: +// an inline source (name + type + auth) with no destination flags on an existing +// connection sent no destination at all, and the API answered 422 "value must +// contain at least one of [destination_id, destination]". +func TestConnectionUpsertInlineSourceKeepsStoredDestination(t *testing.T) { + body := captureConnectionUpsertBody(t, storedUpsertConnection(), + "gateway", "connection", "upsert", "my-conn", + "--source-name", "my-src", + "--source-type", "WEBHOOK", + "--source-hmac-secret", "s3cret", + ) + + assert.Equal(t, "des_1", body["destination_id"], "the stored destination must be carried over by ID") + assert.NotContains(t, body, "destination", "an untouched destination is referenced, not rebuilt") + + source, ok := body["source"].(map[string]interface{}) + require.True(t, ok, "the source flags must still be sent inline") + assert.Equal(t, "my-src", source["name"]) + assert.Equal(t, "WEBHOOK", source["type"]) +} + +// TestConnectionUpsertInlineDestinationKeepsStoredSource is the same defect from +// the other side: an inline destination with no source flags. +func TestConnectionUpsertInlineDestinationKeepsStoredSource(t *testing.T) { + body := captureConnectionUpsertBody(t, storedUpsertConnection(), + "gateway", "connection", "upsert", "my-conn", + "--destination-name", "my-api", + "--destination-type", "HTTP", + "--destination-url", "https://api.example.com/v2", + ) + + assert.Equal(t, "src_1", body["source_id"], "the stored source must be carried over by ID") + assert.NotContains(t, body, "source", "an untouched source is referenced, not rebuilt") + + destination, ok := body["destination"].(map[string]interface{}) + require.True(t, ok, "the destination flags must still be sent inline") + assert.Equal(t, "my-api", destination["name"]) +} diff --git a/pkg/cmd/connection_upsert_guard_test.go b/pkg/cmd/connection_upsert_guard_test.go new file mode 100644 index 00000000..f051838b --- /dev/null +++ b/pkg/cmd/connection_upsert_guard_test.go @@ -0,0 +1,123 @@ +package cmd + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/config" + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// stubCall is one call the stub API received. +type stubCall struct { + Method string + Path string + Body map[string]interface{} +} + +// stubConnectionAPI records every request, so a test can assert which writes +// did or did not happen. +type stubConnectionAPI struct { + mu sync.Mutex + requests []stubCall +} + +// writes returns the recorded requests that are not GETs. +func (s *stubConnectionAPI) writes() []stubCall { + s.mu.Lock() + defer s.mu.Unlock() + var out []stubCall + for _, r := range s.requests { + if r.Method != http.MethodGet { + out = append(out, r) + } + } + return out +} + +// runConnectionCommand runs a gateway command against a stub whose +// GET /connections returns listed whatever the name filter says (standing in +// for a loose filter) and whose GET /connections/{id} returns each listed +// connection by ID. Writes are answered with the first listed connection. It +// returns the stub and the command's error. +func runConnectionCommand(t *testing.T, listed []hookdeck.Connection, args ...string) (*stubConnectionAPI, error) { + t.Helper() + + stub := &stubConnectionAPI{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + rec := stubCall{Method: r.Method, Path: r.URL.Path} + if r.Body != nil && r.Method != http.MethodGet { + raw, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(raw, &rec.Body) + } + stub.mu.Lock() + stub.requests = append(stub.requests, rec) + stub.mu.Unlock() + + switch { + case r.URL.Path == hookdeck.APIPathPrefix+"/cli-auth/validate": + _ = json.NewEncoder(w).Encode(hookdeck.ValidateAPIKeyResponse{ProjectID: "proj_1", ProjectMode: "inbound"}) + case r.URL.Path == hookdeck.APIPathPrefix+"/connections" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(hookdeck.ConnectionListResponse{Models: listed}) + case r.Method == http.MethodGet: + for _, c := range listed { + if r.URL.Path == hookdeck.APIPathPrefix+"/connections/"+c.ID { + _ = json.NewEncoder(w).Encode(c) + return + } + } + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"not found"}`)) + default: + if len(listed) > 0 { + _ = json.NewEncoder(w).Encode(listed[0]) + } else { + _, _ = w.Write([]byte(`{"id":"web_new"}`)) + } + } + })) + t.Cleanup(server.Close) + + config.ResetAPIClientForTesting() + t.Cleanup(config.ResetAPIClientForTesting) + + old := Config + t.Cleanup(func() { Config = old }) + Config = config.Config{APIBaseURL: server.URL, LogLevel: "info"} + Config.Profile.APIKey = "sk_test_123456789012" + Config.Profile.ProjectId = "proj_1" + Config.Profile.ProjectType = config.ProjectTypeEventGateway + + root := &cobra.Command{Use: "hookdeck", SilenceUsage: true, SilenceErrors: true} + root.AddCommand(newGatewayCmd().cmd) + root.SetArgs(args) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + + return stub, root.Execute() +} + +// TestConnectionUpsertIgnoresLooseNameMatch: the stub answers the name filter +// with a different connection. Taking it unchecked made upsert carry that +// connection's source and destination over to the one being upserted. +func TestConnectionUpsertIgnoresLooseNameMatch(t *testing.T) { + loose := storedUpsertConnection() + loose.Name = strPtr("my-conn-extra") + + stub, err := runConnectionCommand(t, []hookdeck.Connection{*loose}, + "gateway", "connection", "upsert", "my-conn", "--description", "d") + require.NoError(t, err) + + puts := stub.writes() + require.Len(t, puts, 1) + require.NotContains(t, puts[0].Body, "source_id", "the loose match's source must not be carried over") + require.NotContains(t, puts[0].Body, "destination_id", "the loose match's destination must not be carried over") +} diff --git a/pkg/cmd/connection_upsert_rules_test.go b/pkg/cmd/connection_upsert_rules_test.go new file mode 100644 index 00000000..db132a25 --- /dev/null +++ b/pkg/cmd/connection_upsert_rules_test.go @@ -0,0 +1,89 @@ +package cmd + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +func storedConnectionWithRule() *hookdeck.Connection { + stored := storedUpsertConnection() + stored.Rules = []hookdeck.Rule{{"type": "retry", "strategy": "linear", "count": 2}} + return stored +} + +// TestConnectionUpsertSendsAnEmptyRulesArray covers #472: an explicit empty +// array was dropped by a len(rules) > 0 check, so the stored rules stayed. +// Each form of the flag is its own call site. +func TestConnectionUpsertSendsAnEmptyRulesArray(t *testing.T) { + emptyFile := filepath.Join(t.TempDir(), "rules.json") + require.NoError(t, os.WriteFile(emptyFile, []byte("[]"), 0o644)) + + for name, flags := range map[string][]string{ + "--rules": {"--rules", "[]"}, + "--rules-file": {"--rules-file", emptyFile}, + } { + flags := flags + t.Run(name, func(t *testing.T) { + body := captureConnectionUpsertBody(t, storedConnectionWithRule(), + append([]string{"gateway", "connection", "upsert", "my-conn"}, flags...)...) + + rules, present := body["rules"] + require.True(t, present, "an empty array must be sent, not left out") + assert.Equal(t, []interface{}{}, rules) + }) + } +} + +// TestConnectionUpsertWithoutRulesFlagOmitsRules is the negative control: only +// an explicit rules flag may touch the stored ruleset. +func TestConnectionUpsertWithoutRulesFlagOmitsRules(t *testing.T) { + body := captureConnectionUpsertBody(t, storedConnectionWithRule(), + "gateway", "connection", "upsert", "my-conn", "--description", "d") + + assert.NotContains(t, body, "rules") +} + +// TestConnectionUpsertDryRunReportsClearedRules runs the preview directly, +// because it prints to stdout. +func TestConnectionUpsertDryRunReportsClearedRules(t *testing.T) { + empty := []hookdeck.Rule{} + + preview := func(t *testing.T, req *hookdeck.ConnectionCreateRequest) string { + t.Helper() + cu := newUpsertCmdForFlags() + cu.name = "my-conn" + + r, w, err := os.Pipe() + require.NoError(t, err) + old := os.Stdout + os.Stdout = w + previewErr := cu.previewUpsertChanges(storedConnectionWithRule(), req, true) + os.Stdout = old + require.NoError(t, w.Close()) + out, err := io.ReadAll(r) + require.NoError(t, err) + require.NoError(t, previewErr) + return string(out) + } + + t.Run("an empty array says the rules will be cleared", func(t *testing.T) { + out := preview(t, &hookdeck.ConnectionCreateRequest{Rules: &empty}) + + assert.Contains(t, out, "will be cleared") + assert.NotContains(t, out, "rules (unchanged)") + }) + + t.Run("no rules flag says the rules are unchanged", func(t *testing.T) { + out := preview(t, &hookdeck.ConnectionCreateRequest{}) + + assert.Contains(t, out, "Rules: 1 rules (unchanged)") + assert.NotContains(t, out, "will be cleared") + }) +} diff --git a/pkg/cmd/connection_upsert_test.go b/pkg/cmd/connection_upsert_test.go index 8719558c..61cb6fd5 100644 --- a/pkg/cmd/connection_upsert_test.go +++ b/pkg/cmd/connection_upsert_test.go @@ -527,6 +527,14 @@ func newUpsertCmdForFlags() *connectionUpsertCmd { return &connectionUpsertCmd{connectionCreateCmd: &connectionCreateCmd{}} } +// withNamedSource names the source inline, so a case that is about the +// destination-side decision is not also triggering the lookup for an unnamed +// source. +func withNamedSource(cu *connectionUpsertCmd) { + cu.sourceName = "my-src" + cu.sourceType = "WEBHOOK" +} + // TestNeedsExistingConnection pins the lookup decision. The create-time // behaviours below are wrong against a connection that already exists, and the // ordinary idempotent invocation - --destination-name plus --destination-type @@ -550,14 +558,15 @@ func TestNeedsExistingConnection(t *testing.T) { assert.True(t, cu.needsExistingConnection()) }) - t.Run("an explicit --destination-cli-path needs no lookup", func(t *testing.T) { + t.Run("an explicit --destination-cli-path still looks up a named destination", func(t *testing.T) { cu := newUpsertCmdForFlags() + withNamedSource(cu) cu.destinationName = "local" cu.destinationType = "CLI" cu.destinationCliPath = "/webhooks" - assert.False(t, cu.needsExistingConnection(), - "the caller said what the path should be, so nothing is being defaulted") + assert.True(t, cu.needsExistingConnection(), + "nothing is defaulted, but a named destination has to be compared with the stored one (#466)") }) t.Run("delivery group flags without overrides must look the connection up", func(t *testing.T) { @@ -573,8 +582,9 @@ func TestNeedsExistingConnection(t *testing.T) { "without the lookup the bare groups object replaces the stored overrides (#393)") }) - t.Run("delivery group flags with overrides need no lookup", func(t *testing.T) { + t.Run("delivery group flags with overrides still look up a named destination", func(t *testing.T) { cu := newUpsertCmdForFlags() + withNamedSource(cu) cu.destinationName = "web" cu.destinationType = "HTTP" cu.destinationURL = "https://api.example.com" @@ -583,25 +593,63 @@ func TestNeedsExistingConnection(t *testing.T) { cu.DestinationDeliveryGroupRatePeriod = "second" cu.DestinationDeliveryGroupOverrides = `{"cust_1":{"rate":5,"rate_period":"minute"}}` - assert.False(t, cu.needsExistingConnection(), - "the caller supplied the overrides, so there is nothing to carry forward") + assert.True(t, cu.needsExistingConnection(), + "nothing is carried forward, but a named destination has to be compared with the stored one (#466)") }) - t.Run("an HTTP destination by name and type still needs no lookup", func(t *testing.T) { + t.Run("an HTTP destination by name and type looks the connection up", func(t *testing.T) { cu := newUpsertCmdForFlags() + withNamedSource(cu) cu.destinationName = "web" cu.destinationType = "HTTP" cu.destinationURL = "https://api.example.com" - assert.False(t, cu.needsExistingConnection(), - "upsert is meant to be one API call where the lookup cannot change the outcome") + assert.True(t, cu.needsExistingConnection(), + "a different destination name is ignored by the API for an existing connection, so it has to be compared before anything is written (#466)") }) - t.Run("--destination-id is the caller pointing at a destination, not creating one", func(t *testing.T) { + t.Run("--destination-id must be compared with the stored destination", func(t *testing.T) { cu := newUpsertCmdForFlags() + withNamedSource(cu) cu.destinationID = "des_1" - assert.False(t, cu.needsExistingConnection()) + assert.True(t, cu.needsExistingConnection(), + "the API ignores a different destination ID on an existing connection (#466)") + }) + + t.Run("--destination-name alone must be compared with the stored destination", func(t *testing.T) { + cu := newUpsertCmdForFlags() + withNamedSource(cu) + cu.destinationName = "web" + + assert.True(t, cu.needsExistingConnection()) + }) + + t.Run("an inline source with no destination flags must look the connection up", func(t *testing.T) { + cu := newUpsertCmdForFlags() + cu.sourceName = "my-src" + cu.sourceType = "WEBHOOK" + cu.SourceHMACSecret = "s3cret" + + assert.True(t, cu.needsExistingConnection(), + "the stored destination is only sent if the connection was looked up") + }) + + t.Run("an inline destination with no source flags must look the connection up", func(t *testing.T) { + cu := newUpsertCmdForFlags() + cu.destinationName = "web" + cu.destinationType = "HTTP" + cu.destinationURL = "https://api.example.com" + + assert.True(t, cu.needsExistingConnection(), + "the stored source is only sent if the connection was looked up") + }) + + t.Run("--source-id with no destination flags must look the connection up", func(t *testing.T) { + cu := newUpsertCmdForFlags() + cu.sourceID = "src_1" + + assert.True(t, cu.needsExistingConnection()) }) t.Run("the pre-existing conditions still hold", func(t *testing.T) { diff --git a/pkg/cmd/helptext.go b/pkg/cmd/helptext.go index de7a4b6e..556ffec9 100644 --- a/pkg/cmd/helptext.go +++ b/pkg/cmd/helptext.go @@ -62,3 +62,20 @@ func LongEnableIntro(resource string) string { func LongUpsertIntro(resource string) string { return "Create a new " + resource + " or update an existing one by name (idempotent)." } + +// LongSourceAuthType explains what the source auth flags send and when config.auth_type is set. +// configFlag is the flag that takes source config JSON ("--config" or "--source-config"). +func LongSourceAuthType(configFlag string) string { + return "The auth flags build config.auth from the source type's own verification methods in the API spec. " + + "--webhook-secret sends webhook_secret_key; on WEBHOOK and HTTP it adds the HMAC settings those types need " + + "(sha256, hex, header x-webhook-signature), and on every other type it sends the secret alone so the " + + "provider's own header and algorithm apply. --hmac-secret sends that HMAC shape (with --hmac-algo) wherever the " + + "type's method takes an algorithm, and otherwise behaves like --webhook-secret. --api-key sends api_key; WEBHOOK " + + "and HTTP also get header x-api-key, while a type that needs its own header name is refused, because no flag " + + "sets it: pass config.auth with header_key through " + configFlag + ". " + + "Types that offer a choice of method (WEBHOOK, HTTP, GITLAB, GRAFANA and others) also need auth_type; the flags " + + "set it to the method they used. A flag no method of the type can express is refused, with the methods the type " + + "accepts. When auth comes from " + configFlag + " without auth_type, it is set only if the auth fields fit " + + "exactly one method (for example, webhook_secret_key alone is STANDARD_WEBHOOKS on WEBHOOK). " + + "Set auth_type in " + configFlag + " to choose the method yourself." +} diff --git a/pkg/cmd/main_test.go b/pkg/cmd/main_test.go new file mode 100644 index 00000000..6a600c4a --- /dev/null +++ b/pkg/cmd/main_test.go @@ -0,0 +1,38 @@ +package cmd + +import ( + "os" + "path/filepath" + "testing" + + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" +) + +// TestMain keeps unit tests off the network: source auth_type inference and source auth +// validation read the OpenAPI spec, so serve the fixture cut from the real spec instead of +// downloading it. +func TestMain(m *testing.M) { + loadSourceAuthMethods = fixtureSourceAuthMethods + loadSourceTypes = fixtureSourceTypes + os.Exit(m.Run()) +} + +func readSourceSpecFixture() ([]byte, error) { + return os.ReadFile(filepath.Join("sources", "testdata", "openapi_source_auth.json")) +} + +func fixtureSourceAuthMethods() (map[string][]sources.AuthMethod, error) { + data, err := readSourceSpecFixture() + if err != nil { + return nil, err + } + return sources.ParseSourceAuthMethods(data) +} + +func fixtureSourceTypes() (map[string]sources.SourceType, error) { + data, err := readSourceSpecFixture() + if err != nil { + return nil, err + } + return sources.ParseSourceTypes(data) +} diff --git a/pkg/cmd/source_auth_build.go b/pkg/cmd/source_auth_build.go new file mode 100644 index 00000000..b9ff0c4f --- /dev/null +++ b/pkg/cmd/source_auth_build.go @@ -0,0 +1,241 @@ +package cmd + +import ( + "fmt" + "os" + "strings" + + log "github.com/sirupsen/logrus" + + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" +) + +// sourceAuthMethodSet is what the API accepts in config.auth for one source type. +type sourceAuthMethodSet struct { + // methods are the verification methods the type accepts. A type with one fixed method has + // one entry with no name. + methods []sources.AuthMethod + // choice is true when the type offers a choice of method, so config.auth_type must name one. + choice bool + // known is false when the spec could not be read or does not list the type. + known bool +} + +// isGenericSourceType reports whether sourceType is WEBHOOK or HTTP, the two types that take any +// signing scheme. Their methods are fixed by the API, so the CLI does not need the spec for them. +func isGenericSourceType(sourceType string) bool { + switch strings.ToUpper(strings.TrimSpace(sourceType)) { + case "WEBHOOK", "HTTP": + return true + } + return false +} + +// resolveSourceAuthMethods reads the type's auth methods from the cached OpenAPI spec. +func resolveSourceAuthMethods(sourceType string) sourceAuthMethodSet { + if isGenericSourceType(sourceType) { + return sourceAuthMethodSet{methods: builtinGenericAuthMethods, choice: true, known: true} + } + if strings.TrimSpace(sourceType) == "" { + return sourceAuthMethodSet{} + } + if all, err := loadSourceAuthMethods(); err != nil { + log.WithError(err).Debug("could not load source auth methods from the OpenAPI spec") + } else if m := sources.AuthMethodsFor(all, sourceType); m != nil { + return sourceAuthMethodSet{methods: m, choice: true, known: true} + } + types, err := loadSourceTypes() + if err != nil { + log.WithError(err).Debug("could not load source types from the OpenAPI spec") + return sourceAuthMethodSet{} + } + st, ok := sources.SourceTypeFor(types, sourceType) + if !ok || len(st.AuthFields) == 0 { + return sourceAuthMethodSet{} + } + return sourceAuthMethodSet{ + methods: []sources.AuthMethod{{Properties: st.AuthFields, Required: st.RequiredAuthFields}}, + known: true, + } +} + +func (m sourceAuthMethodSet) accepting(fields ...string) []sources.AuthMethod { + var out []sources.AuthMethod + for _, method := range m.methods { + ok := true + for _, f := range fields { + if !hasField(method.Properties, f) { + ok = false + break + } + } + if ok { + out = append(out, method) + } + } + return out +} + +func hasField(list []string, v string) bool { + for _, x := range list { + if x == v { + return true + } + } + return false +} + +func (m sourceAuthMethodSet) names() string { + names := make([]string, 0, len(m.methods)) + for _, method := range m.methods { + names = append(names, method.Name) + } + return strings.Join(names, ", ") +} + +// sourceAuthFromFlags builds config.auth, and config.auth_type for a type offering a choice of +// method, from the auth flags. It returns a nil auth when no auth flag is set. Only the first +// set flag counts, in this order: webhook secret, HMAC secret, API key, basic auth. +// +// The fields sent come from the source type's own auth methods in the OpenAPI spec, not from one +// shape for every type. That matters because the API merges a source's config.auth over the +// provider's own defaults when it verifies a request (a user-supplied header_key replaces +// VAPI's x-signature, for example), and strips only the keys a method does not list. So: +// +// - --webhook-secret sends webhook_secret_key, plus algorithm, encoding and header_key only +// where the method requires them (WEBHOOK and HTTP HMAC: sha256, hex, x-webhook-signature). +// Everywhere else the provider's defaults apply. +// - --hmac-secret sends that generic HMAC shape wherever a method takes algorithm, filtered +// to the keys the method lists; otherwise it behaves as --webhook-secret. +// - --api-key sends api_key. A header_key the type requires has no flag: WEBHOOK and HTTP get +// x-api-key, and every other type is refused with the --config form to use. +// +// When the spec cannot be read, WEBHOOK and HTTP still work; other types get only the secret (or +// key), which is safe because the provider's defaults then apply. +func sourceAuthFromFlags(f *sourceConfigFlags, flagPrefix, sourceType string) (map[string]interface{}, string, error) { + pre := "--" + flagPrefix + set := resolveSourceAuthMethods(sourceType) + + switch { + case f.WebhookSecret != "": + return secretAuth(set, f.WebhookSecret, false, f, pre, sourceType) + case f.HMACSecret != "": + return secretAuth(set, f.HMACSecret, true, f, pre, sourceType) + case f.APIKey != "": + return apiKeyAuth(set, f.APIKey, pre, sourceType) + case f.BasicAuthUser != "" || f.BasicAuthPass != "": + auth := map[string]interface{}{"username": f.BasicAuthUser, "password": f.BasicAuthPass} + if !set.choice { + return auth, "", nil + } + ms := set.accepting("username", "password") + if len(ms) == 0 { + return nil, "", unsupportedAuthFlag(set, pre+"basic-auth-user and "+pre+"basic-auth-pass", pre, sourceType) + } + return auth, ms[0].Name, nil + } + return nil, "", nil +} + +func secretAuth(set sourceAuthMethodSet, secret string, explicitHMAC bool, f *sourceConfigFlags, pre, sourceType string) (map[string]interface{}, string, error) { + flagName := pre + "webhook-secret" + if explicitHMAC { + flagName = pre + "hmac-secret" + } + auth := map[string]interface{}{"webhook_secret_key": secret} + if !set.known { + return auth, "", nil + } + + algo := "sha256" + if explicitHMAC && f.HMACAlgo != "" { + algo = strings.ToLower(f.HMACAlgo) + } + generic := map[string]interface{}{"algorithm": algo, "encoding": "hex", "header_key": "x-webhook-signature"} + + var method *sources.AuthMethod + if explicitHMAC { + if ms := set.accepting("webhook_secret_key", "algorithm"); len(ms) > 0 { + method = &ms[0] + for k, v := range generic { + if hasField(method.Properties, k) { + auth[k] = v + } + } + } + } + if method == nil { + ms := set.accepting("webhook_secret_key") + if len(ms) == 0 { + if !set.choice { + // One fixed method with no secret field: the required-field check names the flag to use. + return auth, "", nil + } + return nil, "", unsupportedAuthFlag(set, flagName, pre, sourceType) + } + method = &ms[0] + if explicitHMAC && f.HMACAlgo != "" { + // Ignored rather than refused: the provider fixes its own algorithm, and before + // this builder the API dropped the key, so scripts passing it (e.g. TWILIO with + // sha1) created working sources. Refusing would break them. + fmt.Fprintf(os.Stderr, "Warning: --%s is ignored for source type %s: its %s method sets its own algorithm\n", + pre+"hmac-algo", sourceType, methodLabel(*method)) + } + } + // Whatever the method requires beyond the secret and a flag can supply gets the generic value. + for _, r := range method.Required { + if _, done := auth[r]; done { + continue + } + v, ok := generic[r] + if !ok { + return nil, "", fmt.Errorf("%s does not set config.auth %s, which source type %s requires: %s", + flagName, r, sourceType, configHint([]string{r, "webhook_secret_key"}, pre)) + } + auth[r] = v + } + return auth, authTypeFor(set, *method), nil +} + +func apiKeyAuth(set sourceAuthMethodSet, key, pre, sourceType string) (map[string]interface{}, string, error) { + auth := map[string]interface{}{"api_key": key} + if !set.known { + return auth, "", nil + } + ms := set.accepting("api_key") + if len(ms) == 0 { + if !set.choice { + return auth, "", nil + } + return nil, "", unsupportedAuthFlag(set, pre+"api-key", pre, sourceType) + } + method := ms[0] + if hasField(method.Properties, "header_key") && (len(method.Required) == 0 || hasField(method.Required, "header_key")) { + if !isGenericSourceType(sourceType) { + // The header name is part of the provider's contract, and no flag sets it. + return nil, "", fmt.Errorf("%sapi-key does not set config.auth header_key, which source type %s requires: %s", + pre, sourceType, configHint([]string{"header_key", "api_key"}, pre)) + } + auth["header_key"] = "x-api-key" + } + return auth, authTypeFor(set, method), nil +} + +func authTypeFor(set sourceAuthMethodSet, method sources.AuthMethod) string { + if set.choice { + return method.Name + } + return "" +} + +func methodLabel(m sources.AuthMethod) string { + if m.Name == "" { + return "auth" + } + return m.Name +} + +func unsupportedAuthFlag(set sourceAuthMethodSet, flags, pre, sourceType string) error { + return fmt.Errorf("%s does not apply to source type %s, whose auth methods are %s; set config.auth and auth_type with %sconfig instead", + flags, sourceType, set.names(), pre) +} diff --git a/pkg/cmd/source_auth_build_test.go b/pkg/cmd/source_auth_build_test.go new file mode 100644 index 00000000..4a8fd83f --- /dev/null +++ b/pkg/cmd/source_auth_build_test.go @@ -0,0 +1,280 @@ +package cmd + +import ( + "errors" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// The API stores the config.auth keys a type's auth schema lists, and verifies a request with +// them laid over the provider's own defaults. A key the CLI adds that the provider did not ask +// for therefore changes how real requests are verified: VAPI's header_key replaces x-signature, +// for example. These tests pin the exact config.auth and auth_type each flag sends per type, +// built from the spec fixture (a cut of the 2026-09-01 spec). + +type authWant struct { + auth map[string]interface{} + authType string + err string // substring of the error, when the flag must be refused +} + +func genericHMAC(algo string) map[string]interface{} { + return map[string]interface{}{ + "algorithm": algo, "encoding": "hex", + "header_key": "x-webhook-signature", "webhook_secret_key": "S", + } +} + +var secretOnly = map[string]interface{}{"webhook_secret_key": "S"} + +func TestSourceAuthFromFlagsPerType(t *testing.T) { + tests := []struct { + flag string + sourceType string + flags sourceConfigFlags + want authWant + }{ + // --webhook-secret + {"webhook-secret", "WEBHOOK", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: genericHMAC("sha256"), authType: "HMAC"}}, + {"webhook-secret", "HTTP", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: genericHMAC("sha256"), authType: "HMAC"}}, + {"webhook-secret", "STRIPE", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly}}, + {"webhook-secret", "GITHUB", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly}}, + // VAPI and FORMSTACK take header_key, so sending the generic one would replace the header + // the provider signs with (x-signature, x-fs-signature). + {"webhook-secret", "VAPI", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly}}, + {"webhook-secret", "FORMSTACK", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly}}, + {"webhook-secret", "GITLAB", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly, authType: "STANDARD_WEBHOOKS"}}, + {"webhook-secret", "GRAFANA", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly, authType: "GRAFANA"}}, + {"webhook-secret", "PROMETHEUS_ALERTMANAGER", sourceConfigFlags{WebhookSecret: "S"}, authWant{err: "--webhook-secret does not apply to source type PROMETHEUS_ALERTMANAGER"}}, + {"webhook-secret", "BETTER_STACK", sourceConfigFlags{WebhookSecret: "S"}, authWant{err: "--webhook-secret does not apply to source type BETTER_STACK"}}, + {"webhook-secret", "ORDINAL", sourceConfigFlags{WebhookSecret: "S"}, authWant{err: "--webhook-secret does not apply to source type ORDINAL"}}, + // A single-method type with no secret field: the required-field check names the right flag. + {"webhook-secret", "ACUMATICA", sourceConfigFlags{WebhookSecret: "S"}, authWant{auth: secretOnly}}, + + // --hmac-secret keeps the generic shape where the type's method takes algorithm. + {"hmac-secret", "WEBHOOK", sourceConfigFlags{HMACSecret: "S", HMACAlgo: "SHA512"}, authWant{auth: genericHMAC("sha512"), authType: "HMAC"}}, + {"hmac-secret", "HTTP", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: genericHMAC("sha256"), authType: "HMAC"}}, + {"hmac-secret", "VAPI", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: genericHMAC("sha256")}}, + {"hmac-secret", "STRIPE", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: secretOnly}}, + {"hmac-secret", "FORMSTACK", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: secretOnly}}, + {"hmac-secret", "GITLAB", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: secretOnly, authType: "STANDARD_WEBHOOKS"}}, + {"hmac-secret", "GRAFANA", sourceConfigFlags{HMACSecret: "S"}, authWant{auth: secretOnly, authType: "GRAFANA"}}, + // --hmac-algo on a method with no algorithm is ignored with a warning, not refused: + // the provider fixes its own algorithm, and refusing broke TWILIO with sha1. + {"hmac-secret", "GITLAB", sourceConfigFlags{HMACSecret: "S", HMACAlgo: "sha512"}, authWant{auth: secretOnly, authType: "STANDARD_WEBHOOKS"}}, + {"hmac-secret", "PROMETHEUS_ALERTMANAGER", sourceConfigFlags{HMACSecret: "S"}, authWant{err: "--hmac-secret does not apply to source type PROMETHEUS_ALERTMANAGER"}}, + {"hmac-secret", "BETTER_STACK", sourceConfigFlags{HMACSecret: "S"}, authWant{err: "--hmac-secret does not apply to source type BETTER_STACK"}}, + {"hmac-secret", "ORDINAL", sourceConfigFlags{HMACSecret: "S"}, authWant{err: "--hmac-secret does not apply to source type ORDINAL"}}, + + // --api-key + {"api-key", "WEBHOOK", sourceConfigFlags{APIKey: "K"}, authWant{auth: map[string]interface{}{"header_key": "x-api-key", "api_key": "K"}, authType: "API_KEY"}}, + {"api-key", "HTTP", sourceConfigFlags{APIKey: "K"}, authWant{auth: map[string]interface{}{"header_key": "x-api-key", "api_key": "K"}, authType: "API_KEY"}}, + {"api-key", "GITLAB", sourceConfigFlags{APIKey: "K"}, authWant{auth: map[string]interface{}{"api_key": "K"}, authType: "GITLAB"}}, + {"api-key", "PROMETHEUS_ALERTMANAGER", sourceConfigFlags{APIKey: "K"}, authWant{auth: map[string]interface{}{"api_key": "K"}, authType: "PROMETHEUS_ALERTMANAGER"}}, + // The header name is the provider's contract and no flag sets it: refuse rather than guess x-api-key. + {"api-key", "GRAFANA", sourceConfigFlags{APIKey: "K"}, authWant{err: "--api-key does not set config.auth header_key"}}, + {"api-key", "BETTER_STACK", sourceConfigFlags{APIKey: "K"}, authWant{err: "--api-key does not set config.auth header_key"}}, + {"api-key", "ORDINAL", sourceConfigFlags{APIKey: "K"}, authWant{err: "--api-key does not set config.auth header_key"}}, + {"api-key", "ACUMATICA", sourceConfigFlags{APIKey: "K"}, authWant{err: "--api-key does not set config.auth header_key"}}, + {"api-key", "STRIPE", sourceConfigFlags{APIKey: "K"}, authWant{auth: map[string]interface{}{"api_key": "K"}}}, + + // --basic-auth-* + {"basic-auth", "WEBHOOK", sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, authWant{auth: map[string]interface{}{"username": "u", "password": "p"}, authType: "BASIC_AUTH"}}, + {"basic-auth", "GRAFANA", sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, authWant{auth: map[string]interface{}{"username": "u", "password": "p"}, authType: "BASIC_AUTH"}}, + {"basic-auth", "GITLAB", sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, authWant{err: "--basic-auth-user and --basic-auth-pass does not apply to source type GITLAB"}}, + } + for _, tt := range tests { + t.Run(tt.flag+"/"+tt.sourceType, func(t *testing.T) { + flags := tt.flags + auth, authType, err := sourceAuthFromFlags(&flags, "", tt.sourceType) + if tt.want.err != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want.err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want.auth, auth) + assert.Equal(t, tt.want.authType, authType) + }) + } +} + +// The legacy top-level keys in --config go through the same per-type builder as the flags, so +// webhook_secret on VAPI does not store a header_key that replaces VAPI's x-signature. +func TestLegacyConfigKeysUsePerTypeAuth(t *testing.T) { + tests := []struct { + name string + sourceType string + input string + wantConfig map[string]interface{} + wantErr string + }{ + {"WEBHOOK webhook_secret", "WEBHOOK", `{"webhook_secret":"S"}`, + map[string]interface{}{"auth": genericHMAC("sha256"), "auth_type": "HMAC"}, ""}, + {"VAPI webhook_secret", "VAPI", `{"webhook_secret":"S"}`, + map[string]interface{}{"auth": secretOnly}, ""}, + {"GITLAB webhook_secret", "GITLAB", `{"webhook_secret":"S"}`, + map[string]interface{}{"auth": secretOnly, "auth_type": "STANDARD_WEBHOOKS"}, ""}, + {"WEBHOOK api_key", "WEBHOOK", `{"api_key":"K"}`, + map[string]interface{}{"auth": map[string]interface{}{"header_key": "x-api-key", "api_key": "K"}, "auth_type": "API_KEY"}, ""}, + {"GITLAB api_key", "GITLAB", `{"api_key":"K"}`, + map[string]interface{}{"auth": map[string]interface{}{"api_key": "K"}, "auth_type": "GITLAB"}, ""}, + {"WEBHOOK hmac", "WEBHOOK", `{"hmac":{"secret":"S","algorithm":"SHA512"}}`, + map[string]interface{}{"auth": genericHMAC("sha512"), "auth_type": "HMAC"}, ""}, + {"VAPI hmac", "VAPI", `{"hmac":{"secret":"S"}}`, + map[string]interface{}{"auth": genericHMAC("sha256")}, ""}, + {"GRAFANA basic_auth", "GRAFANA", `{"basic_auth":{"username":"u","password":"p"}}`, + map[string]interface{}{"auth": map[string]interface{}{"username": "u", "password": "p"}, "auth_type": "BASIC_AUTH"}, ""}, + {"explicit auth_type is kept", "WEBHOOK", `{"auth_type":"STANDARD_WEBHOOKS","webhook_secret":"S"}`, + map[string]interface{}{"auth": genericHMAC("sha256"), "auth_type": "STANDARD_WEBHOOKS"}, ""}, + {"refused type", "BETTER_STACK", `{"webhook_secret":"S"}`, nil, `config key "webhook_secret"`}, + {"refused header", "ORDINAL", `{"api_key":"K"}`, nil, "header_key"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + config, err := buildSourceConfigFromFlags(tt.input, "", nil, tt.sourceType) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantConfig, config) + }) + } +} + +// Offline, the legacy keys still work for WEBHOOK and HTTP and give provider types the bare secret. +func TestLegacyConfigKeysWithoutSpec(t *testing.T) { + origMethods, origTypes := loadSourceAuthMethods, loadSourceTypes + t.Cleanup(func() { loadSourceAuthMethods, loadSourceTypes = origMethods, origTypes }) + loadSourceAuthMethods = func() (map[string][]sources.AuthMethod, error) { return nil, errors.New("offline") } + loadSourceTypes = func() (map[string]sources.SourceType, error) { return nil, errors.New("offline") } + + config, err := buildSourceConfigFromFlags(`{"webhook_secret":"S"}`, "", nil, "WEBHOOK") + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"auth": genericHMAC("sha256"), "auth_type": "HMAC"}, config) + + config, err = buildSourceConfigFromFlags(`{"webhook_secret":"S"}`, "", nil, "VAPI") + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"auth": secretOnly}, config) +} + +func TestSourceAuthFromFlagsNoFlag(t *testing.T) { + auth, authType, err := sourceAuthFromFlags(&sourceConfigFlags{AllowedHTTPMethods: "POST"}, "", "VAPI") + require.NoError(t, err) + assert.Nil(t, auth) + assert.Empty(t, authType) +} + +// Connection flags carry the source- prefix; the messages must name the flag the user typed. +func TestSourceAuthFromFlagsErrorsUseFlagPrefix(t *testing.T) { + _, _, err := sourceAuthFromFlags(&sourceConfigFlags{APIKey: "K"}, "source-", "ORDINAL") + require.Error(t, err) + assert.Contains(t, err.Error(), "--source-api-key") + assert.Contains(t, err.Error(), "--source-config") + + _, _, err = sourceAuthFromFlags(&sourceConfigFlags{WebhookSecret: "S"}, "source-", "BETTER_STACK") + require.Error(t, err) + assert.Contains(t, err.Error(), "--source-webhook-secret") +} + +// The same flags through the config builder: the auth_type travels with the auth. +func TestBuildSourceConfigFromIndividualFlagsPerType(t *testing.T) { + config, err := buildSourceConfigFromIndividualFlags(&sourceConfigFlags{WebhookSecret: "S"}, "", "VAPI") + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"auth": secretOnly}, config) + + config, err = buildSourceConfigFromIndividualFlags(&sourceConfigFlags{WebhookSecret: "S"}, "", "GITLAB") + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"auth": secretOnly, "auth_type": "STANDARD_WEBHOOKS"}, config) + + _, err = buildSourceConfigFromIndividualFlags(&sourceConfigFlags{WebhookSecret: "S"}, "", "BETTER_STACK") + require.Error(t, err) +} + +// Without the spec, WEBHOOK and HTTP keep working, and a provider type gets only the secret: the +// provider's own defaults then apply, which is right for every type and never overrides a header. +func TestSourceAuthFromFlagsWithoutSpec(t *testing.T) { + origMethods, origTypes := loadSourceAuthMethods, loadSourceTypes + t.Cleanup(func() { loadSourceAuthMethods, loadSourceTypes = origMethods, origTypes }) + loadSourceAuthMethods = func() (map[string][]sources.AuthMethod, error) { return nil, errors.New("offline") } + loadSourceTypes = func() (map[string]sources.SourceType, error) { return nil, errors.New("offline") } + + auth, authType, err := sourceAuthFromFlags(&sourceConfigFlags{WebhookSecret: "S"}, "", "WEBHOOK") + require.NoError(t, err) + assert.Equal(t, genericHMAC("sha256"), auth) + assert.Equal(t, "HMAC", authType) + + auth, authType, err = sourceAuthFromFlags(&sourceConfigFlags{APIKey: "K"}, "", "http") + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"header_key": "x-api-key", "api_key": "K"}, auth) + assert.Equal(t, "API_KEY", authType) + + for _, sourceType := range []string{"VAPI", "GITLAB", "STRIPE"} { + auth, authType, err = sourceAuthFromFlags(&sourceConfigFlags{WebhookSecret: "S"}, "", sourceType) + require.NoError(t, err, sourceType) + assert.Equal(t, secretOnly, auth, sourceType) + assert.Empty(t, authType, sourceType) + } +} + +// Command level: `source create --type VAPI --webhook-secret` must send the bare secret, since the +// API would store a generic header_key and verify VAPI's requests against it. +func TestSourceCreateSendsProviderShapedAuth(t *testing.T) { + tests := []struct { + name string + args []string + wantConfig map[string]interface{} + }{ + {"VAPI webhook secret", []string{"--type", "VAPI", "--webhook-secret", "S"}, + map[string]interface{}{"auth": secretOnly}}, + {"FORMSTACK webhook secret", []string{"--type", "FORMSTACK", "--webhook-secret", "S"}, + map[string]interface{}{"auth": secretOnly}}, + {"GITLAB webhook secret", []string{"--type", "GITLAB", "--webhook-secret", "S"}, + map[string]interface{}{"auth": secretOnly, "auth_type": "STANDARD_WEBHOOKS"}}, + {"GRAFANA webhook secret", []string{"--type", "GRAFANA", "--webhook-secret", "S"}, + map[string]interface{}{"auth": secretOnly, "auth_type": "GRAFANA"}}, + {"GITLAB api key", []string{"--type", "GITLAB", "--api-key", "K"}, + map[string]interface{}{"auth": map[string]interface{}{"api_key": "K"}, "auth_type": "GITLAB"}}, + {"WEBHOOK webhook secret is unchanged", []string{"--type", "WEBHOOK", "--webhook-secret", "S"}, + map[string]interface{}{"auth": map[string]interface{}{ + "algorithm": "sha256", "encoding": "hex", "header_key": "x-webhook-signature", "webhook_secret_key": "S", + }, "auth_type": "HMAC"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + return map[string]interface{}{"id": "src_1", "name": "s", "type": "VAPI"} + }, + append([]string{"source", "create", "--name", "s"}, tt.args...)..., + ) + require.NoError(t, err) + post := findRequest(t, requests, http.MethodPost, hookdeck.APIPathPrefix+"/sources") + assert.Equal(t, tt.wantConfig, post.Body["config"]) + }) + } +} + +// A flag the CLI cannot build for the type is refused before any request is sent. +func TestSourceCreateRefusesUnbuildableAuth(t *testing.T) { + for _, args := range [][]string{ + {"--type", "ORDINAL", "--api-key", "K"}, + {"--type", "BETTER_STACK", "--webhook-secret", "S"}, + {"--type", "ACUMATICA", "--api-key", "K"}, + } { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { return map[string]interface{}{} }, + append([]string{"source", "create", "--name", "s"}, args...)..., + ) + require.Error(t, err, args) + assert.Empty(t, requests, "nothing is sent for %v", args) + } +} diff --git a/pkg/cmd/source_auth_type_command_test.go b/pkg/cmd/source_auth_type_command_test.go new file mode 100644 index 00000000..1d54afeb --- /dev/null +++ b/pkg/cmd/source_auth_type_command_test.go @@ -0,0 +1,279 @@ +package cmd + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/config" + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// These run the real commands against a stub API and assert on the request body sent, so they +// pin each command's wiring - which type the config is built for, what is merged from the +// stored resource - not just the shared builders. + +type recordedRequest struct { + Method string + Path string + Body map[string]interface{} +} + +// stubStatus makes runGatewayAgainstStub answer with a non-200 status. +type stubStatus struct { + Code int + Body interface{} +} + +// runGatewayAgainstStub runs `hookdeck gateway ` against a stub API. respond returns the +// JSON body for a request (nil means `{}`, a stubStatus sets the status code). Every request +// except the credential check is recorded and returned. +func runGatewayAgainstStub(t *testing.T, respond func(r *http.Request) interface{}, args ...string) ([]recordedRequest, error) { + t.Helper() + + var requests []recordedRequest + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == hookdeck.APIPathPrefix+"/cli-auth/validate" { + _ = json.NewEncoder(w).Encode(hookdeck.ValidateAPIKeyResponse{ProjectID: "proj_1", ProjectMode: "inbound"}) + return + } + rec := recordedRequest{Method: r.Method, Path: r.URL.Path} + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + require.NoError(t, json.Unmarshal(data, &rec.Body)) + } + requests = append(requests, rec) + + body := respond(r) + if st, ok := body.(stubStatus); ok { + w.WriteHeader(st.Code) + body = st.Body + } + if body == nil { + body = map[string]interface{}{} + } + _ = json.NewEncoder(w).Encode(body) + })) + t.Cleanup(server.Close) + + config.ResetAPIClientForTesting() + t.Cleanup(config.ResetAPIClientForTesting) + + old := Config + t.Cleanup(func() { Config = old }) + Config = config.Config{APIBaseURL: server.URL, LogLevel: "info"} + Config.Profile.APIKey = "sk_test_123456789012" + Config.Profile.ProjectId = "proj_1" + Config.Profile.ProjectType = config.ProjectTypeEventGateway + + root := &cobra.Command{Use: "hookdeck", SilenceUsage: true, SilenceErrors: true} + root.AddCommand(newGatewayCmd().cmd) + root.SetArgs(append([]string{"gateway"}, args...)) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + err := root.Execute() + return requests, err +} + +func findRequest(t *testing.T, requests []recordedRequest, method, path string) recordedRequest { + t.Helper() + for _, r := range requests { + if r.Method == method && r.Path == path { + return r + } + } + require.Failf(t, "request not sent", "%s %s; sent: %v", method, path, requests) + return recordedRequest{} +} + +func bodyMap(t *testing.T, v interface{}, key string) map[string]interface{} { + t.Helper() + m, ok := v.(map[string]interface{}) + require.True(t, ok, "expected an object, got %T", v) + inner, ok := m[key].(map[string]interface{}) + require.True(t, ok, "expected %q to be an object in %v", key, m) + return inner +} + +// `source upsert` without --type: the API upserts as WEBHOOK, so auth must carry auth_type. +func TestSourceUpsertWithoutTypeSendsAuthType(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + if r.Method == http.MethodGet { // lookup by name + return map[string]interface{}{"models": []interface{}{}} + } + return map[string]interface{}{"id": "src_1", "name": "s", "type": "WEBHOOK"} + }, + "source", "upsert", "s", "--api-key", "KEY", + ) + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + cfg := bodyMap(t, put.Body, "config") + assert.Equal(t, "API_KEY", cfg["auth_type"]) + assert.Equal(t, map[string]interface{}{"header_key": "x-api-key", "api_key": "KEY"}, cfg["auth"]) +} + +// `source update ` without --type: config needs a type beside it, and the auth is shaped and +// typed for the stored type. +func TestSourceUpdateWithoutTypeUsesStoredType(t *testing.T) { + tests := []struct { + name string + storedType string + args []string + wantConfig map[string]interface{} + }{ + { + name: "WEBHOOK api key", + storedType: "WEBHOOK", + args: []string{"--api-key", "KEY"}, + wantConfig: map[string]interface{}{ + "auth_type": "API_KEY", + "auth": map[string]interface{}{"header_key": "x-api-key", "api_key": "KEY"}, + }, + }, + { + name: "STRIPE webhook secret is Stripe-shaped, no auth_type", + storedType: "STRIPE", + args: []string{"--webhook-secret", "whsec_1"}, + wantConfig: map[string]interface{}{ + "auth": map[string]interface{}{"webhook_secret_key": "whsec_1"}, + }, + }, + { + name: "non-auth config still sends the stored type", + storedType: "WEBHOOK", + args: []string{"--allowed-http-methods", "POST"}, + wantConfig: map[string]interface{}{"allowed_http_methods": []interface{}{"POST"}}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + stored := map[string]interface{}{"id": "src_1", "name": "s", "type": tt.storedType} + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { return stored }, + append([]string{"source", "update", "src_1"}, tt.args...)..., + ) + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources/src_1") + assert.Equal(t, tt.storedType, put.Body["type"]) + assert.Equal(t, tt.wantConfig, put.Body["config"]) + }) + } +} + +func TestSourceUpdateNameOnlyMakesNoLookup(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + return map[string]interface{}{"id": "src_1", "name": "n", "type": "WEBHOOK"} + }, + "source", "update", "src_1", "--name", "n", + ) + require.NoError(t, err) + require.Len(t, requests, 1, "a name-only update needs no type and no GET") + assert.NotContains(t, requests[0].Body, "type") +} + +// existingConnection is a connection whose WEBHOOK source verifies with HMAC. The API returns +// the method as config.auth_type but not the credentials. +func existingConnection(sourceConfig map[string]interface{}) map[string]interface{} { + return map[string]interface{}{ + "models": []interface{}{map[string]interface{}{ + "id": "web_1", + "name": "conn", + "source": map[string]interface{}{ + "id": "src_1", "name": "src", "type": "WEBHOOK", "config": sourceConfig, + }, + "destination": map[string]interface{}{ + "id": "des_1", "name": "dst", "type": "MOCK_API", "config": map[string]interface{}{}, + }, + }}, + } +} + +// `connection upsert conn --source-*` on an existing connection merges the flags into the stored +// source. The stored auth_type must not survive beside new auth, nor be sent without auth. +func TestConnectionUpsertPartialSourceUpdate(t *testing.T) { + stored := map[string]interface{}{"auth_type": "HMAC", "allowed_http_methods": []interface{}{"POST"}} + + tests := []struct { + name string + args []string + wantConfig map[string]interface{} + }{ + { + name: "new api key replaces the stored method", + args: []string{"--source-api-key", "NEWKEY"}, + wantConfig: map[string]interface{}{ + "auth_type": "API_KEY", + "auth": map[string]interface{}{"header_key": "x-api-key", "api_key": "NEWKEY"}, + "allowed_http_methods": []interface{}{"POST"}, + }, + }, + { + // No method fits {api_key} alone, so nothing is inferred; the stored HMAC must not + // be sent as the method for these credentials either. + name: "auth that fits no method does not inherit the stored method", + args: []string{"--source-config", `{"auth":{"api_key":"NEWKEY"}}`}, + wantConfig: map[string]interface{}{ + "auth": map[string]interface{}{"api_key": "NEWKEY"}, + "allowed_http_methods": []interface{}{"POST"}, + }, + }, + { + name: "non-auth change drops the credential-less auth_type", + args: []string{"--source-allowed-http-methods", "POST,PUT"}, + wantConfig: map[string]interface{}{ + "allowed_http_methods": []interface{}{"POST", "PUT"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + if r.Method == http.MethodGet { + return existingConnection(stored) + } + return existingConnection(stored)["models"].([]interface{})[0] + }, + append([]string{"connection", "upsert", "conn"}, tt.args...)..., + ) + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/connections") + source := bodyMap(t, put.Body, "source") + assert.Equal(t, "WEBHOOK", source["type"]) + assert.Equal(t, tt.wantConfig, source["config"]) + }) + } + assert.Equal(t, "HMAC", stored["auth_type"], "the stored config is not mutated") +} + +// A new connection with an inline source and no --source-type is sent as a WEBHOOK source. +func TestConnectionUpsertNewInlineSourceWithoutType(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + if r.Method == http.MethodGet { + return map[string]interface{}{"models": []interface{}{}} + } + return existingConnection(nil)["models"].([]interface{})[0] + }, + "connection", "upsert", "conn", + "--source-name", "src", "--source-api-key", "KEY", + "--destination-name", "dst", "--destination-type", "MOCK_API", + ) + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/connections") + source := bodyMap(t, put.Body, "source") + assert.Equal(t, "WEBHOOK", source["type"], "the API rejects an empty source.type") + assert.Equal(t, "API_KEY", bodyMap(t, source, "config")["auth_type"]) +} diff --git a/pkg/cmd/source_auth_type_test.go b/pkg/cmd/source_auth_type_test.go new file mode 100644 index 00000000..be7ca4ee --- /dev/null +++ b/pkg/cmd/source_auth_type_test.go @@ -0,0 +1,182 @@ +package cmd + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" +) + +// The API validates config.auth on WEBHOOK and HTTP sources against the method named in +// config.auth_type, and rejects auth without it ("config.auth is not allowed"). These tests +// pin that every way of building source auth adds the matching auth_type for those types, +// and leaves provider types (which take no auth_type) alone. + +func TestBuildSourceConfigFromIndividualFlagsSetsAuthType(t *testing.T) { + tests := []struct { + name string + sourceType string + flags sourceConfigFlags + wantAuthType string // "" means auth_type must be absent + }{ + {name: "WEBHOOK api key", sourceType: "WEBHOOK", flags: sourceConfigFlags{APIKey: "k"}, wantAuthType: "API_KEY"}, + {name: "webhook lowercase api key", sourceType: "webhook", flags: sourceConfigFlags{APIKey: "k"}, wantAuthType: "API_KEY"}, + {name: "WEBHOOK basic auth", sourceType: "WEBHOOK", flags: sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, wantAuthType: "BASIC_AUTH"}, + {name: "WEBHOOK hmac", sourceType: "WEBHOOK", flags: sourceConfigFlags{HMACSecret: "s", HMACAlgo: "sha512"}, wantAuthType: "HMAC"}, + {name: "WEBHOOK webhook secret", sourceType: "WEBHOOK", flags: sourceConfigFlags{WebhookSecret: "s"}, wantAuthType: "HMAC"}, + {name: "HTTP api key", sourceType: "HTTP", flags: sourceConfigFlags{APIKey: "k"}, wantAuthType: "API_KEY"}, + {name: "HTTP basic auth", sourceType: "HTTP", flags: sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, wantAuthType: "BASIC_AUTH"}, + {name: "AZURE_EVENT_GRID basic auth", sourceType: "AZURE_EVENT_GRID", flags: sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, wantAuthType: "BASIC_AUTH"}, + {name: "PROMETHEUS_ALERTMANAGER basic auth", sourceType: "PROMETHEUS_ALERTMANAGER", flags: sourceConfigFlags{BasicAuthUser: "u", BasicAuthPass: "p"}, wantAuthType: "BASIC_AUTH"}, + // --api-key sends api_key only to Prometheus, whose bearer method takes no header_key. + {name: "PROMETHEUS_ALERTMANAGER api key", sourceType: "PROMETHEUS_ALERTMANAGER", flags: sourceConfigFlags{APIKey: "k"}, wantAuthType: "PROMETHEUS_ALERTMANAGER"}, + {name: "STRIPE webhook secret takes no auth_type", sourceType: "STRIPE", flags: sourceConfigFlags{WebhookSecret: "whsec"}}, + {name: "empty type infers nothing", sourceType: "", flags: sourceConfigFlags{APIKey: "k"}}, + {name: "WEBHOOK without auth flags", sourceType: "WEBHOOK", flags: sourceConfigFlags{AllowedHTTPMethods: "POST"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + config, err := buildSourceConfigFromIndividualFlags(&tt.flags, "", tt.sourceType) + require.NoError(t, err) + require.NotNil(t, config) + if tt.wantAuthType == "" { + assert.NotContains(t, config, "auth_type") + return + } + assert.Equal(t, tt.wantAuthType, config["auth_type"]) + assert.NotNil(t, config["auth"]) + }) + } +} + +// The runbook case: connection upsert/create with an inline WEBHOOK source and --source-api-key. +func TestConnectionBuildSourceConfigWebhookAPIKey(t *testing.T) { + cc := &connectionCreateCmd{sourceType: "WEBHOOK"} + cc.SourceAPIKey = "KEY" + + config, err := cc.buildSourceConfig() + require.NoError(t, err) + + assert.Equal(t, map[string]interface{}{ + "auth_type": "API_KEY", + "auth": map[string]interface{}{ + "header_key": "x-api-key", + "api_key": "KEY", + }, + }, config) +} + +func TestConnectionBuildSourceConfigJSONWebhookAddsAuthType(t *testing.T) { + cc := &connectionCreateCmd{sourceType: "WEBHOOK"} + cc.SourceConfig = `{"auth":{"header_key":"x-api-key","api_key":"KEY"}}` + + config, err := cc.buildSourceConfig() + require.NoError(t, err) + assert.Equal(t, "API_KEY", config["auth_type"]) +} + +func TestBuildSourceConfigFromFlagsJSONAuthType(t *testing.T) { + tests := []struct { + name string + sourceType string + input string + wantAuthType interface{} // nil means auth_type must be absent + }{ + { + name: "explicit auth_type is kept", + sourceType: "WEBHOOK", + input: `{"auth_type":"API_KEY","auth":{"header_key":"x-api-key","api_key":"KEY"}}`, + wantAuthType: "API_KEY", + }, + { + name: "auth without auth_type gets one", + sourceType: "WEBHOOK", + input: `{"auth":{"username":"u","password":"p"}}`, + wantAuthType: "BASIC_AUTH", + }, + { + name: "legacy flat api_key is normalized and typed", + sourceType: "WEBHOOK", + input: `{"api_key":"KEY"}`, + wantAuthType: "API_KEY", + }, + { + name: "hmac-shaped secret is HMAC", + sourceType: "HTTP", + input: `{"auth":{"algorithm":"sha256","encoding":"hex","header_key":"x-sig","webhook_secret_key":"s"}}`, + wantAuthType: "HMAC", + }, + { + // HMAC requires algorithm/encoding/header_key, so a bare secret can only be the + // Standard Webhooks method on the API. + name: "bare secret is STANDARD_WEBHOOKS", + sourceType: "WEBHOOK", + input: `{"auth":{"webhook_secret_key":"whsec_abc"}}`, + wantAuthType: "STANDARD_WEBHOOKS", + }, + { + name: "PROMETHEUS_ALERTMANAGER bearer credentials", + sourceType: "PROMETHEUS_ALERTMANAGER", + input: `{"auth":{"api_key":"token"}}`, + wantAuthType: "PROMETHEUS_ALERTMANAGER", + }, + { + name: "provider type is left alone", + sourceType: "GITHUB", + input: `{"auth":{"webhook_secret_key":"s"}}`, + }, + { + name: "no auth means no auth_type", + sourceType: "WEBHOOK", + input: `{"allowed_http_methods":["POST"]}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + config, err := buildSourceConfigFromFlags(tt.input, "", nil, tt.sourceType) + require.NoError(t, err) + if tt.wantAuthType == nil { + assert.NotContains(t, config, "auth_type") + return + } + assert.Equal(t, tt.wantAuthType, config["auth_type"]) + }) + } +} + +// The connection's inline source defaults to WEBHOOK, the type the API applies to a new source +// created without one, so --source-api-key works without --source-type. +func TestConnectionBuildSourceConfigOmittedTypeIsWebhook(t *testing.T) { + cc := &connectionCreateCmd{} + cc.SourceAPIKey = "KEY" + + config, err := cc.buildSourceConfig() + require.NoError(t, err) + assert.Equal(t, "API_KEY", config["auth_type"]) +} + +// Without the spec (offline, or a spec-shape change), WEBHOOK and HTTP still get auth_type from +// the built-in methods; other types are left for the API to validate. +func TestEnsureSourceConfigAuthTypeWithoutSpec(t *testing.T) { + original := loadSourceAuthMethods + t.Cleanup(func() { loadSourceAuthMethods = original }) + loadSourceAuthMethods = func() (map[string][]sources.AuthMethod, error) { + return nil, errors.New("offline") + } + + for sourceType, want := range map[string]interface{}{"WEBHOOK": "API_KEY", "http": "API_KEY", "ORDINAL": nil} { + config, err := buildSourceConfigFromIndividualFlags(&sourceConfigFlags{APIKey: "k"}, "", sourceType) + require.NoError(t, err) + if want == nil { + assert.NotContains(t, config, "auth_type", sourceType) + } else { + assert.Equal(t, want, config["auth_type"], sourceType) + } + } + config, err := buildSourceConfigFromFlags(`{"auth":{"webhook_secret_key":"whsec_x"}}`, "", nil, "WEBHOOK") + require.NoError(t, err) + assert.Equal(t, "STANDARD_WEBHOOKS", config["auth_type"]) +} diff --git a/pkg/cmd/source_auth_validation_test.go b/pkg/cmd/source_auth_validation_test.go new file mode 100644 index 00000000..1cc12ac6 --- /dev/null +++ b/pkg/cmd/source_auth_validation_test.go @@ -0,0 +1,142 @@ +package cmd + +import ( + "errors" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// validateSourceAuthFromSpec reads the fixture cut from the real spec (see TestMain); the +// sources package tests pin what the parse makes of each type used here. + +func TestValidateSourceAuthFromSpec(t *testing.T) { + tests := []struct { + name string + sourceType string + configSet bool + auth sourceAuthFlags + prefix string + wantErr string + }{ + // Verification required, no auth flag. + {name: "required secret missing", sourceType: "AIRCALL", + wantErr: "--webhook-secret is required for source type AIRCALL"}, + {name: "connection flags are prefixed", sourceType: "AIRCALL", prefix: "source-", + wantErr: "--source-webhook-secret is required for source type AIRCALL"}, + {name: "type in any case", sourceType: "aircall", + wantErr: "--webhook-secret is required for source type aircall"}, + {name: "required api key missing", sourceType: "CLOUDSIGNAL", + wantErr: "--api-key is required for source type CLOUDSIGNAL"}, + {name: "required auth with only optional fields", sourceType: "VERCEL_LOG_DRAINS", + wantErr: "--webhook-secret is required for source type VERCEL_LOG_DRAINS"}, + {name: "required field no flag sets", sourceType: "ALIPAY", + wantErr: `source type ALIPAY requires config.auth public_key, which no flag sets: pass them with --config '{"auth":{"public_key":"..."}}' or --config-file`}, + {name: "required fields no flag sets, connection", sourceType: "TIKTOK_SHOP", prefix: "source-", + wantErr: `source type TIKTOK_SHOP requires config.auth app_key, webhook_secret_key, which no flag sets: pass them with --source-config '{"auth":{"app_key":"...","webhook_secret_key":"..."}}' or --source-config-file`}, + + // Verification required, satisfied. + {name: "webhook secret", sourceType: "AIRCALL", auth: sourceAuthFlags{WebhookSecret: "s"}}, + {name: "hmac secret sets the same field", sourceType: "AIRCALL", auth: sourceAuthFlags{HMACSecret: "s"}}, + {name: "api key", sourceType: "CLOUDSIGNAL", auth: sourceAuthFlags{APIKey: "k"}}, + {name: "config set by hand", sourceType: "ALIPAY", configSet: true}, + + // An auth flag that does not set a required field. + {name: "wrong flag for optional auth", sourceType: "STRIPE", auth: sourceAuthFlags{APIKey: "k"}, + wantErr: "--api-key does not set config.auth webhook_secret_key, which source type STRIPE requires: use --webhook-secret"}, + {name: "wrong flag points to basic auth", sourceType: "POSTMARK", auth: sourceAuthFlags{WebhookSecret: "s"}, + wantErr: "--webhook-secret does not set config.auth password, username, which source type POSTMARK requires: use --basic-auth-user and --basic-auth-pass"}, + {name: "flag sets only some required fields", sourceType: "TIKTOK_SHOP", auth: sourceAuthFlags{WebhookSecret: "s"}, + wantErr: `--webhook-secret does not set config.auth app_key, which source type TIKTOK_SHOP requires: pass them with --config '{"auth":{"app_key":"...","webhook_secret_key":"..."}}' or --config-file`}, + {name: "wrong flag on a handshake type", sourceType: "ONFLEET", auth: sourceAuthFlags{APIKey: "k"}, prefix: "source-", + wantErr: "--source-api-key does not set config.auth webhook_secret_key, which source type ONFLEET requires: use --source-webhook-secret"}, + + // The header name is the provider's contract and no flag sets it. + {name: "api key for a type with a user-defined header", sourceType: "ACUMATICA", auth: sourceAuthFlags{APIKey: "k"}, + wantErr: `--api-key does not set config.auth header_key, which source type ACUMATICA requires: pass them with --config '{"auth":{"header_key":"...","api_key":"..."}}' or --config-file`}, + + // Not rejected. + {name: "optional auth omitted", sourceType: "STRIPE"}, + {name: "optional auth given", sourceType: "STRIPE", auth: sourceAuthFlags{WebhookSecret: "whsec"}}, + {name: "optional basic auth given", sourceType: "POSTMARK", auth: sourceAuthFlags{BasicAuthUser: "u", BasicAuthPass: "p"}}, + {name: "handshake type, auth with fields", sourceType: "ONFLEET"}, + {name: "handshake type, auth without fields", sourceType: "STRAVA"}, + {name: "handshake type with a choice of method", sourceType: "AZURE_EVENT_GRID"}, + {name: "choice of method", sourceType: "WEBHOOK", auth: sourceAuthFlags{APIKey: "k"}}, + {name: "type not in spec", sourceType: "NOT_A_TYPE"}, + {name: "no type", sourceType: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateSourceAuthFromSpec(tt.sourceType, tt.configSet, tt.auth, tt.prefix) + if tt.wantErr == "" { + assert.NoError(t, err) + return + } + require.Error(t, err) + assert.Equal(t, tt.wantErr, err.Error()) + }) + } +} + +func TestValidateSourceAuthFromSpecSkipsWhenSpecUnavailable(t *testing.T) { + old := loadSourceTypes + t.Cleanup(func() { loadSourceTypes = old }) + loadSourceTypes = func() (map[string]sources.SourceType, error) { + return nil, errors.New("offline") + } + assert.NoError(t, validateSourceAuthFromSpec("AIRCALL", false, sourceAuthFlags{}, ""), + "the API validates when the spec cannot be fetched") +} + +// The commands run the check before any request: the stub sees nothing. +func TestSourceAuthValidationBlocksCommandsBeforeTheAPI(t *testing.T) { + respond := func(r *http.Request) interface{} { + if r.Method == http.MethodGet { + return map[string]interface{}{"models": []interface{}{}} + } + return nil + } + tests := map[string]struct { + args []string + wantErr string + }{ + "source create": { + args: []string{"source", "create", "--name", "s", "--type", "AIRCALL"}, + wantErr: "--webhook-secret is required for source type AIRCALL", + }, + "source upsert": { + args: []string{"source", "upsert", "s", "--type", "STRIPE", "--api-key", "k"}, + wantErr: "--api-key does not set config.auth webhook_secret_key, which source type STRIPE requires: use --webhook-secret", + }, + "connection create": { + args: []string{"connection", "create", "--name", "c", + "--source-name", "s", "--source-type", "CLOUDSIGNAL", + "--destination-name", "d", "--destination-type", "CLI", "--destination-cli-path", "/"}, + wantErr: "--source-api-key is required for source type CLOUDSIGNAL", + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + requests, err := runGatewayAgainstStub(t, respond, tt.args...) + require.Error(t, err) + assert.Equal(t, tt.wantErr, err.Error()) + assert.Empty(t, requests) + }) + } +} + +func TestSourceCreateWithRequiredSecretReachesTheAPI(t *testing.T) { + requests, err := runGatewayAgainstStub(t, func(r *http.Request) interface{} { + return map[string]interface{}{"id": "src_1", "name": "s", "type": "AIRCALL"} + }, "source", "create", "--name", "s", "--type", "AIRCALL", "--webhook-secret", "whsec") + require.NoError(t, err) + req := findRequest(t, requests, http.MethodPost, hookdeck.APIPathPrefix+"/sources") + auth := bodyMap(t, bodyMap(t, req.Body, "config"), "auth") + assert.Equal(t, "whsec", auth["webhook_secret_key"]) +} diff --git a/pkg/cmd/source_common.go b/pkg/cmd/source_common.go index 443c7d03..2ffdd888 100644 --- a/pkg/cmd/source_common.go +++ b/pkg/cmd/source_common.go @@ -6,6 +6,8 @@ import ( "os" "strings" + log "github.com/sirupsen/logrus" + "github.com/hookdeck/hookdeck-cli/pkg/cmd/sources" ) @@ -43,7 +45,8 @@ func flagRef(prefix, name string) string { // buildSourceConfigFromIndividualFlags builds source config from individual flags. // Source-level type (WEBHOOK, STRIPE, etc.) determines which config schema applies; config.auth -// contents depend on that type (per OpenAPI SourceTypeConfig oneOf). No auth_type field—only auth. +// contents depend on that type (per OpenAPI SourceTypeConfig oneOf). Types offering a choice of +// method (WEBHOOK, HTTP, ...) also need config.auth_type; ensureSourceConfigAuthType adds it. // Shared by source create/upsert/update (prefix "") and connection create/upsert (prefix "source-"). // flagPrefix is used only in error messages so connection errors mention --source-*. func buildSourceConfigFromIndividualFlags(f *sourceConfigFlags, flagPrefix, sourceType string) (map[string]interface{}, error) { @@ -51,40 +54,17 @@ func buildSourceConfigFromIndividualFlags(f *sourceConfigFlags, flagPrefix, sour return nil, nil } config := make(map[string]interface{}) - sourceTypeUpper := strings.ToUpper(strings.TrimSpace(sourceType)) - // Auth: only config.auth; shape depends on source type (API infers from type + auth keys). - if f.WebhookSecret != "" { - if sourceTypeUpper == "STRIPE" { - config["auth"] = map[string]interface{}{"webhook_secret_key": f.WebhookSecret} - } else { - config["auth"] = map[string]interface{}{ - "algorithm": "sha256", - "encoding": "hex", - "header_key": "x-webhook-signature", - "webhook_secret_key": f.WebhookSecret, - } - } - } else if f.HMACSecret != "" { - algo := "sha256" - if f.HMACAlgo != "" { - algo = strings.ToLower(f.HMACAlgo) - } - config["auth"] = map[string]interface{}{ - "algorithm": algo, - "encoding": "hex", - "header_key": "x-webhook-signature", - "webhook_secret_key": f.HMACSecret, - } - } else if f.APIKey != "" { - config["auth"] = map[string]interface{}{ - "header_key": "x-api-key", - "api_key": f.APIKey, - } - } else if f.BasicAuthUser != "" || f.BasicAuthPass != "" { - config["auth"] = map[string]interface{}{ - "username": f.BasicAuthUser, - "password": f.BasicAuthPass, + // Auth: config.auth shape depends on source type. auth_type is added at the end for the + // types that require it (see ensureSourceConfigAuthType). + auth, authType, err := sourceAuthFromFlags(f, flagPrefix, sourceType) + if err != nil { + return nil, err + } + if auth != nil { + config["auth"] = auth + if authType != "" { + config["auth_type"] = authType } } @@ -121,101 +101,143 @@ func buildSourceConfigFromIndividualFlags(f *sourceConfigFlags, flagPrefix, sour "body": f.CustomResponseBody, } } + ensureSourceConfigAuthType(config, sourceType) return config, nil } -// ensureSourceConfigAuthTypeForHTTP sets config.auth_type when source type is HTTP and config -// has auth. The connection API requires auth_type in config for HTTP sources. Values: API_KEY, -// BASIC_AUTH, HMAC. No-op if auth_type already set or source type is not HTTP. -func ensureSourceConfigAuthTypeForHTTP(config map[string]interface{}, sourceType string) { - if config == nil || strings.ToUpper(strings.TrimSpace(sourceType)) != "HTTP" { - return +// apiDefaultSourceType is the type the API applies when a source create or upsert omits it +// (the create schema defaults type to WEBHOOK), so that is the type its config is validated +// against. Building config for an omitted type must use the same one. +const apiDefaultSourceType = "WEBHOOK" + +// sourceTypeOrAPIDefault returns sourceType, or apiDefaultSourceType when it is empty. +// Only for create/upsert paths: an update of an existing source keeps the stored type. +func sourceTypeOrAPIDefault(sourceType string) string { + if strings.TrimSpace(sourceType) == "" { + return apiDefaultSourceType } - if _, hasAuth := config["auth"]; !hasAuth { + return sourceType +} + +// loadSourceAuthMethods returns each source type's auth methods from the cached OpenAPI spec. +// A variable so tests serve a fixture instead of downloading the spec. +var loadSourceAuthMethods = sources.FetchSourceAuthMethods + +// builtinGenericAuthMethods are the WEBHOOK and HTTP auth methods as the API defines them, +// used when the spec cannot be fetched so the auth flags keep working offline for the two +// generic types. Other types need the spec. +var builtinGenericAuthMethods = []sources.AuthMethod{ + {Name: "HMAC", Properties: []string{"algorithm", "encoding", "header_key", "webhook_secret_key"}, Required: []string{"algorithm", "encoding", "header_key", "webhook_secret_key"}}, + {Name: "BASIC_AUTH", Properties: []string{"password", "username"}, Required: []string{"username", "password"}}, + {Name: "API_KEY", Properties: []string{"api_key", "header_key"}, Required: []string{"header_key", "api_key"}}, + {Name: "STANDARD_WEBHOOKS", Properties: []string{"webhook_secret_key"}, Required: []string{"webhook_secret_key"}}, +} + +// ensureSourceConfigAuthType sets config.auth_type when config has auth but no auth_type and +// the source type offers a choice of verification method. +// +// For those types (WEBHOOK, HTTP, ORDINAL, PROMETHEUS_ALERTMANAGER and others, as listed in the +// OpenAPI spec) the API validates config.auth against the method named in config.auth_type, +// and rejects config.auth without it ("config.auth is not allowed"). Types with one fixed +// method (STRIPE, GITHUB, ...) take no auth_type, so nothing is added for them. +// +// The method is the one whose fields fit the auth keys (sources.InferAuthType). For example, +// on WEBHOOK: api_key + header_key -> API_KEY, username + password -> BASIC_AUTH, a secret with +// algorithm/encoding/header_key -> HMAC, and a bare webhook_secret_key -> STANDARD_WEBHOOKS +// (HMAC requires the other fields, so Standard Webhooks is the only method that accepts it). +// When no single method fits, auth_type is left unset and the API reports the problem. +func ensureSourceConfigAuthType(config map[string]interface{}, sourceType string) { + if config == nil || strings.TrimSpace(sourceType) == "" { return } if _, hasType := config["auth_type"]; hasType { return } auth, _ := config["auth"].(map[string]interface{}) - if auth == nil { + if len(auth) == 0 { return } - if _, ok := auth["api_key"]; ok { - config["auth_type"] = "API_KEY" - return + + var methods []sources.AuthMethod + if all, err := loadSourceAuthMethods(); err == nil { + methods = sources.AuthMethodsFor(all, sourceType) + } else { + upper := strings.ToUpper(strings.TrimSpace(sourceType)) + if upper == "WEBHOOK" || upper == "HTTP" { + methods = builtinGenericAuthMethods + } + log.WithError(err).Debug("could not load source auth methods from the OpenAPI spec; config.auth_type inferred only for WEBHOOK and HTTP") } - if _, ok := auth["username"]; ok { - config["auth_type"] = "BASIC_AUTH" - return + + keys := make([]string, 0, len(auth)) + for k := range auth { + keys = append(keys, k) } - if _, ok := auth["webhook_secret_key"]; ok { - config["auth_type"] = "HMAC" + if authType := sources.InferAuthType(methods, keys); authType != "" { + config["auth_type"] = authType } } -// normalizeSourceConfigAuth converts legacy flat auth keys (webhook_secret, api_key, etc.) -// into the API shape: config.auth only (no auth_type; type is source-level, auth shape depends on it). -// Idempotent if auth already set. -func normalizeSourceConfigAuth(config map[string]interface{}, sourceType string) { +// normalizeSourceConfigAuth converts the legacy top-level auth keys in a source config +// (webhook_secret, api_key, basic_auth, hmac) into config.auth, and config.auth_type where the +// type offers a choice of method. It builds them exactly as the matching flags do +// (webhook_secret as --webhook-secret, api_key as --api-key, hmac as --hmac-secret, basic_auth as +// the basic auth flags), so the same per-type shapes and refusals apply. Does nothing when +// config.auth is already set. An explicit config.auth_type is kept. +func normalizeSourceConfigAuth(config map[string]interface{}, sourceType string) error { if config == nil || config["auth"] != nil { - return + return nil } - sourceTypeUpper := strings.ToUpper(strings.TrimSpace(sourceType)) + var flags *sourceConfigFlags + var legacyKey string if v, ok := config["webhook_secret"].(string); ok && v != "" { - if sourceTypeUpper == "STRIPE" { - config["auth"] = map[string]interface{}{"webhook_secret_key": v} - } else { - config["auth"] = map[string]interface{}{ - "algorithm": "sha256", "encoding": "hex", - "header_key": "x-webhook-signature", "webhook_secret_key": v, - } - } - delete(config, "webhook_secret") - return - } - if v, ok := config["api_key"].(string); ok && v != "" { - config["auth"] = map[string]interface{}{"header_key": "x-api-key", "api_key": v} - delete(config, "api_key") - return - } - if m, ok := config["basic_auth"].(map[string]interface{}); ok { + flags, legacyKey = &sourceConfigFlags{WebhookSecret: v}, "webhook_secret" + } else if v, ok := config["api_key"].(string); ok && v != "" { + flags, legacyKey = &sourceConfigFlags{APIKey: v}, "api_key" + } else if m, ok := config["basic_auth"].(map[string]interface{}); ok { u, _ := m["username"].(string) p, _ := m["password"].(string) if u != "" || p != "" { - config["auth"] = map[string]interface{}{"username": u, "password": p} - delete(config, "basic_auth") + flags, legacyKey = &sourceConfigFlags{BasicAuthUser: u, BasicAuthPass: p}, "basic_auth" } - return - } - if m, ok := config["hmac"].(map[string]interface{}); ok { + } else if m, ok := config["hmac"].(map[string]interface{}); ok { secret, _ := m["secret"].(string) if secret != "" { - algo := "sha256" - if a, _ := m["algorithm"].(string); a != "" { - algo = strings.ToLower(a) - } - config["auth"] = map[string]interface{}{ - "algorithm": algo, "encoding": "hex", - "header_key": "x-webhook-signature", "webhook_secret_key": secret, - } - delete(config, "hmac") + algo, _ := m["algorithm"].(string) + flags, legacyKey = &sourceConfigFlags{HMACSecret: secret, HMACAlgo: algo}, "hmac" } } + if flags == nil { + return nil + } + auth, authType, err := sourceAuthFromFlags(flags, "", sourceType) + if err != nil { + return fmt.Errorf("config key %q: %w", legacyKey, err) + } + config["auth"] = auth + if _, has := config["auth_type"]; !has && authType != "" { + config["auth_type"] = authType + } + delete(config, legacyKey) + return nil } // buildSourceConfigFromFlags parses source config from --config/--config-file (JSON) // or from individual flags. sourceType (e.g. WEBHOOK, STRIPE) is used for correct auth shape. // When configStr or configFile is set, that takes precedence. // Used by source create, upsert, and update. Returns (nil, nil) when nothing is set. -// Normalizes legacy flat auth keys to auth_type + auth so the API accepts the payload. +// Normalizes legacy flat auth keys to config.auth and, for types offering a choice of auth +// method, sets config.auth_type so the API accepts the payload. func buildSourceConfigFromFlags(configStr, configFile string, individual *sourceConfigFlags, sourceType string) (map[string]interface{}, error) { if configStr != "" { var out map[string]interface{} if err := json.Unmarshal([]byte(configStr), &out); err != nil { return nil, fmt.Errorf("invalid JSON in --config: %w", err) } - normalizeSourceConfigAuth(out, sourceType) + if err := normalizeSourceConfigAuth(out, sourceType); err != nil { + return nil, err + } + ensureSourceConfigAuthType(out, sourceType) return out, nil } if configFile != "" { @@ -227,7 +249,10 @@ func buildSourceConfigFromFlags(configStr, configFile string, individual *source if err := json.Unmarshal(data, &out); err != nil { return nil, fmt.Errorf("invalid JSON in config file: %w", err) } - normalizeSourceConfigAuth(out, sourceType) + if err := normalizeSourceConfigAuth(out, sourceType); err != nil { + return nil, err + } + ensureSourceConfigAuthType(out, sourceType) return out, nil } return buildSourceConfigFromIndividualFlags(individual, "", sourceType) @@ -243,23 +268,45 @@ type sourceAuthFlags struct { HMACSecret string } -// optionalAuthSourceTypes are source types where authentication can be turned on or off -// but is not required. We do not reject these when auth flags are missing. -var optionalAuthSourceTypes = map[string]bool{"STRIPE": true} +// optionalAuthSourceTypes are source types the spec reads as auth-required although +// verification is optional. The spec marks a type's config required when any feature is +// required (see sources.ParseSourceTypes), and ONFLEET's required feature is its handshake. +var optionalAuthSourceTypes = map[string]bool{"ONFLEET": true} -// validateSourceAuthFromSpec uses the cached OpenAPI spec (FetchSourceTypes) to validate -// that the given source type has the required auth flags set. Used by source create/upsert -// (flagPrefix "") and connection create (flagPrefix "source-"). If configSet, skip validation. -// Types in optionalAuthSourceTypes are not required to have auth set. If FetchSourceTypes -// fails or the type is unknown, returns nil so the API can validate. +// loadSourceTypes returns each source type's auth rules from the cached OpenAPI spec. +// A variable so tests serve a fixture instead of downloading the spec. +var loadSourceTypes = sources.FetchSourceTypes + +// authFlagOptions are the auth flags a validation error can point to, each with sample values +// so sourceAuthFromFlags reports the config.auth keys it sets. --hmac-secret is not listed: it +// sets a secret like --webhook-secret does, and the message points at the plainer flag. +var authFlagOptions = []struct { + names []string + flags sourceConfigFlags +}{ + {[]string{"webhook-secret"}, sourceConfigFlags{WebhookSecret: "-"}}, + {[]string{"api-key"}, sourceConfigFlags{APIKey: "-"}}, + {[]string{"basic-auth-user", "basic-auth-pass"}, sourceConfigFlags{BasicAuthUser: "-", BasicAuthPass: "-"}}, +} + +// validateSourceAuthFromSpec checks the auth flags against the source type's config.auth +// fields in the cached OpenAPI spec (FetchSourceTypes). Used by source create/upsert +// (flagPrefix "") and connection create (flagPrefix "source-"). +// +// It rejects two cases, both of which the API would reject: +// - no auth flag, for a type that requires auth (AIRCALL, ZOOM, ...), and +// - an auth flag that does not set a field the type's auth requires (--api-key for STRIPE), +// since the API strips the keys it does not take and then finds the required one missing. +// +// The error names the flag that sets the fields, or --config when no flag does (ALIPAY's +// public_key, for example). Types offering a choice of method (WEBHOOK, HTTP, ...) are left to +// the API. If configSet, the user wrote config.auth themselves and nothing is checked. If the +// spec cannot be fetched or the type is not in it, returns nil so the API can validate. func validateSourceAuthFromSpec(sourceType string, configSet bool, auth sourceAuthFlags, flagPrefix string) error { if sourceType == "" || configSet { return nil } - if optionalAuthSourceTypes[strings.ToUpper(sourceType)] { - return nil - } - sourceTypes, err := sources.FetchSourceTypes() + sourceTypes, err := loadSourceTypes() if err != nil { // stderr, not stdout. This is advisory — validation is skipped and the // API still checks — but on stdout it lands ahead of the command's own @@ -273,28 +320,109 @@ func validateSourceAuthFromSpec(sourceType string, configSet bool, auth sourceAu fmt.Fprintf(os.Stderr, "Warning: could not fetch source types for validation: %v\n", err) return nil } - st, ok := sourceTypes[strings.ToUpper(sourceType)] + st, ok := sources.SourceTypeFor(sourceTypes, sourceType) if !ok { return nil } pre := "--" + flagPrefix - switch st.AuthScheme { - case "webhook_secret": - if auth.WebhookSecret == "" { - return fmt.Errorf("%swebhook-secret is required for source type %s", pre, sourceType) + + given, _, err := sourceAuthFromFlags(&sourceConfigFlags{ + WebhookSecret: auth.WebhookSecret, + APIKey: auth.APIKey, + BasicAuthUser: auth.BasicAuthUser, + BasicAuthPass: auth.BasicAuthPass, + HMACSecret: auth.HMACSecret, + }, flagPrefix, sourceType) + if err != nil { + return err + } + + if given == nil { + if !st.AuthRequired || optionalAuthSourceTypes[st.Name] { + return nil } - case "api_key": - if auth.APIKey == "" { - return fmt.Errorf("%sapi-key is required for source type %s", pre, sourceType) + // A required auth whose fields are all optional still needs one of them to say anything. + need := st.RequiredAuthFields + if len(need) == 0 { + need = st.AuthFields } - case "basic_auth": - if auth.BasicAuthUser == "" || auth.BasicAuthPass == "" { - return fmt.Errorf("%sbasic-auth-user and %sbasic-auth-pass are required for source type %s", pre, pre, sourceType) + if flags := authFlagsSetting(need, sourceType, pre); flags != nil { + verb := "is" + if len(flags) > 1 { + verb = "are" + } + return fmt.Errorf("%s %s required for source type %s", strings.Join(flags, " and "), verb, sourceType) } - case "hmac": - if auth.HMACSecret == "" { - return fmt.Errorf("%shmac-secret is required for source type %s", pre, sourceType) + return fmt.Errorf("source type %s requires config.auth %s, which no flag sets: %s", + sourceType, strings.Join(need, ", "), configHint(need, pre)) + } + + var missing []string + for _, field := range st.RequiredAuthFields { + if _, ok := given[field]; !ok { + missing = append(missing, field) + } + } + if len(missing) == 0 { + return nil + } + used := pre + givenAuthFlag(auth) + if flags := authFlagsSetting(st.RequiredAuthFields, sourceType, pre); flags != nil { + return fmt.Errorf("%s does not set config.auth %s, which source type %s requires: use %s", + used, strings.Join(missing, ", "), sourceType, strings.Join(flags, " and ")) + } + return fmt.Errorf("%s does not set config.auth %s, which source type %s requires: %s", + used, strings.Join(missing, ", "), sourceType, configHint(st.RequiredAuthFields, pre)) +} + +// authFlagsSetting returns the flags (with "--" and prefix) whose config.auth carries every one +// of fields, or nil when no flag does. +func authFlagsSetting(fields []string, sourceType, pre string) []string { + for _, opt := range authFlagOptions { + keys, _, err := sourceAuthFromFlags(&opt.flags, "", sourceType) + if err != nil { + continue + } + covers := true + for _, field := range fields { + if _, ok := keys[field]; !ok { + covers = false + break + } + } + if covers { + out := make([]string, len(opt.names)) + for i, name := range opt.names { + out[i] = pre + name + } + return out } } return nil } + +// givenAuthFlag names the auth flag sourceAuthFromFlags used, in its precedence order. +func givenAuthFlag(auth sourceAuthFlags) string { + switch { + case auth.WebhookSecret != "": + return "webhook-secret" + case auth.HMACSecret != "": + return "hmac-secret" + case auth.APIKey != "": + return "api-key" + case auth.BasicAuthUser != "": + return "basic-auth-user" + default: + return "basic-auth-pass" + } +} + +// configHint shows how to pass config.auth fields no flag sets. +func configHint(fields []string, pre string) string { + parts := make([]string, len(fields)) + for i, field := range fields { + parts[i] = fmt.Sprintf("%q:\"...\"", field) + } + return fmt.Sprintf("pass them with %sconfig '{\"auth\":{%s}}' or %sconfig-file", + pre, strings.Join(parts, ","), pre) +} diff --git a/pkg/cmd/source_create.go b/pkg/cmd/source_create.go index edb86dbd..f65a19f6 100644 --- a/pkg/cmd/source_create.go +++ b/pkg/cmd/source_create.go @@ -36,6 +36,8 @@ func newSourceCreateCmd() *sourceCreateCmd { Requires --name and --type. Use --config or --config-file for authentication (e.g. webhook_secret, api_key). +` + LongSourceAuthType("--config") + ` + Examples: hookdeck gateway source create --name my-webhook --type WEBHOOK hookdeck gateway source create --name stripe-prod --type STRIPE --config '{"webhook_secret":"whsec_xxx"}'`, @@ -48,7 +50,7 @@ Examples: sc.cmd.Flags().StringVar(&sc.sourceType, "type", "", "Source type (e.g. WEBHOOK, STRIPE) (required)") sc.cmd.Flags().StringVar(&sc.config, "config", "", "JSON object for source config (overrides individual flags if set)") sc.cmd.Flags().StringVar(&sc.configFile, "config-file", "", "Path to JSON file for source config (overrides individual flags if set)") - sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret for source verification (e.g., Stripe)") + sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only") sc.cmd.Flags().StringVar(&sc.APIKey, "api-key", "", "API key for source authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthUser, "basic-auth-user", "", "Username for Basic authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthPass, "basic-auth-pass", "", "Password for Basic authentication") @@ -96,9 +98,6 @@ func (sc *sourceCreateCmd) runSourceCreateCmd(cmd *cobra.Command, args []string) if err != nil { return err } - if config != nil { - ensureSourceConfigAuthTypeForHTTP(config, sc.sourceType) - } req := &hookdeck.SourceCreateRequest{ Name: sc.name, diff --git a/pkg/cmd/source_update.go b/pkg/cmd/source_update.go index 9c8d19ed..7ababb96 100644 --- a/pkg/cmd/source_update.go +++ b/pkg/cmd/source_update.go @@ -34,6 +34,10 @@ func newSourceUpdateCmd() *sourceUpdateCmd { Short: ShortUpdate(ResourceSource), Long: LongUpdateIntro(ResourceSource) + ` +Config flags without --type are applied to the source's current type, which is looked up first. + +` + LongSourceAuthType("--config") + ` + Examples: hookdeck gateway source update src_abc123 --name new-name hookdeck gateway source update src_abc123 --description "Updated" @@ -47,7 +51,7 @@ Examples: sc.cmd.Flags().StringVar(&sc.sourceType, "type", "", "Source type (e.g. WEBHOOK, STRIPE)") sc.cmd.Flags().StringVar(&sc.config, "config", "", "JSON object for source config (overrides individual flags if set)") sc.cmd.Flags().StringVar(&sc.configFile, "config-file", "", "Path to JSON file for source config (overrides individual flags if set)") - sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret for source verification (e.g., Stripe)") + sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only") sc.cmd.Flags().StringVar(&sc.APIKey, "api-key", "", "API key for source authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthUser, "basic-auth-user", "", "Username for Basic authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthPass, "basic-auth-pass", "", "Password for Basic authentication") @@ -102,8 +106,20 @@ func (sc *sourceUpdateCmd) runSourceUpdateCmd(cmd *cobra.Command, args []string) if err != nil { return err } - if config != nil { - ensureSourceConfigAuthTypeForHTTP(config, sc.sourceType) + if len(config) > 0 && sc.sourceType == "" { + // The API validates config against the source type and rejects config sent without + // type ("config is not allowed"). Without --type, use the stored source's type: send it, + // and rebuild config for it, since the auth shape and the auth_type to infer both + // depend on it. + existing, err := client.GetSource(ctx, sourceID, nil) + if err != nil { + return fmt.Errorf("failed to get source: %w", err) + } + req.Type = existing.Type + config, err = buildSourceConfigFromFlags(sc.config, sc.configFile, &sc.sourceConfigFlags, existing.Type) + if err != nil { + return err + } } if len(config) > 0 { req.Config = config diff --git a/pkg/cmd/source_upsert.go b/pkg/cmd/source_upsert.go index 22faeaba..b4b205ca 100644 --- a/pkg/cmd/source_upsert.go +++ b/pkg/cmd/source_upsert.go @@ -35,6 +35,13 @@ func newSourceUpsertCmd() *sourceUpsertCmd { Short: ShortUpsert(ResourceSource), Long: LongUpsertIntro(ResourceSource) + ` +When --type is omitted and the source already exists, its current type is kept, +along with its verification unless you pass new auth flags or config. When the +source does not exist, it is created as a WEBHOOK source. Pass --type to change +an existing source's type. + +` + LongSourceAuthType("--config") + ` + Examples: hookdeck gateway source upsert my-webhook --type WEBHOOK hookdeck gateway source upsert stripe-prod --type STRIPE --config '{"webhook_secret":"whsec_xxx"}' @@ -47,7 +54,7 @@ Examples: sc.cmd.Flags().StringVar(&sc.sourceType, "type", "", "Source type (e.g. WEBHOOK, STRIPE)") sc.cmd.Flags().StringVar(&sc.config, "config", "", "JSON object for source config (overrides individual flags if set)") sc.cmd.Flags().StringVar(&sc.configFile, "config-file", "", "Path to JSON file for source config (overrides individual flags if set)") - sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret for source verification (e.g., Stripe)") + sc.cmd.Flags().StringVar(&sc.WebhookSecret, "webhook-secret", "", "Webhook secret the source verifies signatures with; sent as webhook_secret_key, plus HMAC settings on WEBHOOK and HTTP only") sc.cmd.Flags().StringVar(&sc.APIKey, "api-key", "", "API key for source authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthUser, "basic-auth-user", "", "Username for Basic authentication") sc.cmd.Flags().StringVar(&sc.BasicAuthPass, "basic-auth-pass", "", "Password for Basic authentication") @@ -90,35 +97,51 @@ func (sc *sourceUpsertCmd) runSourceUpsertCmd(cmd *cobra.Command, args []string) client := Config.GetAPIClient() ctx := context.Background() - config, err := buildSourceConfigFromFlags(sc.config, sc.configFile, &sc.sourceConfigFlags, sc.sourceType) + // Look the source up when --dry-run needs to preview it, or when --type is + // omitted. PUT /sources validates against the create schema, where type + // defaults to WEBHOOK, so an upsert body without a type converts an + // existing source of any other type into a WEBHOOK source and drops its + // verification. Sending the stored type keeps it. + var existing *hookdeck.Source + if sc.dryRun || sc.sourceType == "" { + var err error + existing, err = findSourceByName(ctx, client, sc.name) + if err != nil { + if sc.dryRun { + return fmt.Errorf("dry-run: failed to check existing source: %w", err) + } + return fmt.Errorf("failed to look up existing source %q to keep its type (pass --type to skip the lookup): %w", sc.name, err) + } + } + + sourceType := strings.ToUpper(sc.sourceType) + if sourceType == "" && existing != nil { + sourceType = existing.Type + } + + // Build config for the type the API will apply: the stored or given type, + // or WEBHOOK when a new source is created without --type. + config, err := buildSourceConfigFromFlags(sc.config, sc.configFile, &sc.sourceConfigFlags, sourceTypeOrAPIDefault(sourceType)) if err != nil { return err } - if config != nil { - ensureSourceConfigAuthTypeForHTTP(config, sc.sourceType) - } req := &hookdeck.SourceCreateRequest{ Name: sc.name, + // Empty only when --type is omitted and no source has this name; the + // API then creates a WEBHOOK source. + Type: sourceType, } if sc.description != "" { req.Description = &sc.description } - if sc.sourceType != "" { - req.Type = strings.ToUpper(sc.sourceType) - } if len(config) > 0 { req.Config = config } if sc.dryRun { - params := map[string]string{"name": sc.name} - existing, err := client.ListSources(ctx, params) - if err != nil { - return fmt.Errorf("dry-run: failed to check existing source: %w", err) - } - if existing.Models != nil && len(existing.Models) > 0 { - fmt.Printf("-- Dry Run: UPDATE --\nSource '%s' (%s) would be updated.\n", sc.name, existing.Models[0].ID) + if existing != nil { + fmt.Printf("-- Dry Run: UPDATE --\nSource '%s' (%s) would be updated.\n", sc.name, existing.ID) } else { fmt.Printf("-- Dry Run: CREATE --\nSource '%s' would be created.\n", sc.name) } @@ -145,3 +168,19 @@ func (sc *sourceUpsertCmd) runSourceUpsertCmd(cmd *cobra.Command, args []string) fmt.Printf("URL: %s\n", src.URL) return nil } + +// findSourceByName returns the source with exactly this name, or nil when there +// is none. disabled=true includes disabled sources: the API upserts a disabled +// source by name too, so missing one here would convert it to WEBHOOK. +func findSourceByName(ctx context.Context, client *hookdeck.Client, name string) (*hookdeck.Source, error) { + resp, err := client.ListSources(ctx, map[string]string{"name": name, "disabled": "true"}) + if err != nil { + return nil, err + } + for i := range resp.Models { + if resp.Models[i].Name == name { + return &resp.Models[i], nil + } + } + return nil, nil +} diff --git a/pkg/cmd/source_upsert_test.go b/pkg/cmd/source_upsert_test.go new file mode 100644 index 00000000..99a60ab2 --- /dev/null +++ b/pkg/cmd/source_upsert_test.go @@ -0,0 +1,122 @@ +package cmd + +import ( + "net/http" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// PUT /sources validates with the API's source create schema, where a missing type defaults to +// WEBHOOK (hookdeck/core server/api/schemas/request/source.ts). So `source upsert` without +// --type must send an existing source's stored type, or the upsert converts it to WEBHOOK and +// drops its verification. + +// upsertStub answers the name lookup with existing (nil: no source has the name) and the PUT +// with the type the request carried, defaulting to WEBHOOK as the API does. It records the +// lookup's query string. +func upsertStub(existing map[string]interface{}, lookups *[]url.Values) func(r *http.Request) interface{} { + return func(r *http.Request) interface{} { + if r.Method == http.MethodGet { + *lookups = append(*lookups, r.URL.Query()) + models := []interface{}{} + if existing != nil { + models = append(models, existing) + } + return map[string]interface{}{"models": models, "pagination": map[string]interface{}{"limit": 100}} + } + return map[string]interface{}{"id": "src_1", "name": "my-stripe", "type": "WEBHOOK"} + } +} + +func existingStripeSource() map[string]interface{} { + return map[string]interface{}{"id": "src_1", "name": "my-stripe", "type": "STRIPE"} +} + +func TestSourceUpsertWithoutTypeKeepsExistingType(t *testing.T) { + var lookups []url.Values + requests, err := runGatewayAgainstStub(t, upsertStub(existingStripeSource(), &lookups), + "source", "upsert", "my-stripe", "--description", "x") + require.NoError(t, err) + + require.Len(t, lookups, 1, "the existing source must be looked up when --type is omitted") + assert.Equal(t, "my-stripe", lookups[0].Get("name")) + // A disabled source is still upserted by name, so the lookup must see it. + assert.Equal(t, "true", lookups[0].Get("disabled")) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + assert.Equal(t, "STRIPE", put.Body["type"]) + assert.Equal(t, "x", put.Body["description"]) + // No config.auth: the API keeps the stored verification only when the type is unchanged + // and the request carries no auth. + assert.NotContains(t, put.Body, "config") +} + +// Auth flags without --type are shaped for the stored type: a STRIPE secret is a bare +// webhook_secret_key, not the WEBHOOK HMAC shape built for a new source. +func TestSourceUpsertWithoutTypeShapesAuthForExistingType(t *testing.T) { + var lookups []url.Values + requests, err := runGatewayAgainstStub(t, upsertStub(existingStripeSource(), &lookups), + "source", "upsert", "my-stripe", "--webhook-secret", "whsec_new") + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + assert.Equal(t, "STRIPE", put.Body["type"]) + cfg := bodyMap(t, put.Body, "config") + assert.Equal(t, map[string]interface{}{"webhook_secret_key": "whsec_new"}, cfg["auth"]) +} + +// No source has the name: send no type, so the API creates a WEBHOOK source as before. +func TestSourceUpsertWithoutTypeCreatesWithoutType(t *testing.T) { + var lookups []url.Values + requests, err := runGatewayAgainstStub(t, upsertStub(nil, &lookups), "source", "upsert", "new-source") + require.NoError(t, err) + + require.Len(t, lookups, 1) + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + assert.NotContains(t, put.Body, "type") +} + +// The name is matched exactly on the client too: a source listed under another name is not +// the one being upserted. +func TestSourceUpsertWithoutTypeIgnoresOtherNames(t *testing.T) { + var lookups []url.Values + other := map[string]interface{}{"id": "src_2", "name": "my-stripe-2", "type": "STRIPE"} + requests, err := runGatewayAgainstStub(t, upsertStub(other, &lookups), "source", "upsert", "my-stripe") + require.NoError(t, err) + + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + assert.NotContains(t, put.Body, "type") +} + +// An explicit --type is sent as given (upper-cased), with no lookup. +func TestSourceUpsertWithTypeSkipsLookup(t *testing.T) { + var lookups []url.Values + requests, err := runGatewayAgainstStub(t, upsertStub(existingStripeSource(), &lookups), + "source", "upsert", "my-stripe", "--type", "stripe") + require.NoError(t, err) + + assert.Empty(t, lookups) + put := findRequest(t, requests, http.MethodPut, hookdeck.APIPathPrefix+"/sources") + assert.Equal(t, "STRIPE", put.Body["type"]) +} + +// If the lookup fails, do not fall back to a typeless upsert: that is the request that +// converts the source. +func TestSourceUpsertWithoutTypeFailsWhenLookupFails(t *testing.T) { + requests, err := runGatewayAgainstStub(t, + func(r *http.Request) interface{} { + return stubStatus{Code: http.StatusInternalServerError, Body: map[string]interface{}{"message": "stub failure"}} + }, + "source", "upsert", "my-stripe", "--description", "x", + ) + require.Error(t, err) + assert.Contains(t, err.Error(), "--type") + for _, r := range requests { + assert.NotEqual(t, http.MethodPut, r.Method, "no upsert may be sent after a failed lookup") + } +} diff --git a/pkg/cmd/sources/auth_methods.go b/pkg/cmd/sources/auth_methods.go new file mode 100644 index 00000000..76385f47 --- /dev/null +++ b/pkg/cmd/sources/auth_methods.go @@ -0,0 +1,247 @@ +package sources + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" +) + +// authMethodsCacheFileName caches the parsed auth methods, keyed to the API version like +// cacheFileName so an upgrade never reads methods parsed from an older spec. +var authMethodsCacheFileName = "hookdeck_source_auth_methods" + strings.ReplaceAll(hookdeck.APIPathPrefix, "/", "_") + ".json" + +// AuthMethod is one verification method a source type's config accepts: the value to send +// as config.auth_type, and the fields config.auth may carry for it. +type AuthMethod struct { + Name string `json:"name"` + Properties []string `json:"properties"` + Required []string `json:"required"` +} + +// FetchSourceAuthMethods returns, for each source type whose config takes config.auth_type +// (a type offering a choice of verification method), the methods it accepts in spec order. +// Types with a single fixed method take no auth_type and are absent from the map. +// +// It downloads the OpenAPI spec and caches the parsed result for cacheTTL. +func FetchSourceAuthMethods() (map[string][]AuthMethod, error) { + cachePath := filepath.Join(os.TempDir(), authMethodsCacheFileName) + + if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < cacheTTL { + if data, err := os.ReadFile(cachePath); err == nil { + var cached map[string][]AuthMethod + if json.Unmarshal(data, &cached) == nil && len(cached) > 0 { + return cached, nil + } + } + } + + body, err := downloadOpenAPISpec() + if err != nil { + return nil, err + } + + methods, err := ParseSourceAuthMethods(body) + if err != nil { + return nil, fmt.Errorf("failed to parse OpenAPI spec: %w", err) + } + if len(methods) == 0 { + // Do not cache an empty result: it would hide a spec-shape change for a day. + return nil, fmt.Errorf("failed to parse OpenAPI spec: no source auth methods found") + } + + writeAuthMethodsCache(methods) + // The same download feeds the source types cache. + cacheSourceTypes(body) + return methods, nil +} + +func writeAuthMethodsCache(methods map[string][]AuthMethod) { + if data, err := json.Marshal(methods); err == nil { + _ = os.WriteFile(filepath.Join(os.TempDir(), authMethodsCacheFileName), data, 0o600) + } +} + +// cacheAuthMethods parses specData and caches the auth methods, best effort. +func cacheAuthMethods(specData []byte) { + if methods, err := ParseSourceAuthMethods(specData); err == nil && len(methods) > 0 { + writeAuthMethodsCache(methods) + } +} + +// cacheSourceTypes parses specData and caches the source types, best effort. +func cacheSourceTypes(specData []byte) { + if types, err := ParseSourceTypes(specData); err == nil && len(types) > 0 { + if data, err := json.Marshal(types); err == nil { + _ = os.WriteFile(filepath.Join(os.TempDir(), cacheFileName), data, 0o600) + } + } +} + +// specSchema is the subset of an OpenAPI schema object this parser reads. +type specSchema struct { + Ref string `json:"$ref"` + Properties map[string]specSchema `json:"properties"` + Required []string `json:"required"` + Enum []string `json:"enum"` + OneOf []specSchema `json:"oneOf"` + DocsType string `json:"x-docs-type"` + // XRequired marks a oneOf entry whose schema the API requires (joi-to-swagger's x-required). + XRequired bool `json:"x-required"` +} + +const sourceTypeConfigPrefix = "SourceTypeConfig" + +// ParseSourceAuthMethods extracts each source type's auth methods from the OpenAPI spec. +// +// The spec has one SourceTypeConfig schema per source type. A type offering a choice of +// method has an auth_type enum, and its auth property refers to a oneOf with one branch per +// method; each branch names its method in x-docs-type and lists its fields. +// +// WEBHOOK's enum also lists every provider type as a legacy method (for configs created by +// old API versions). Those are left out: a method named after another source type is never +// what a WEBHOOK auth flag means, and keeping them would make every shape ambiguous. +func ParseSourceAuthMethods(specData []byte) (map[string][]AuthMethod, error) { + var spec struct { + Components struct { + Schemas map[string]specSchema `json:"schemas"` + } `json:"components"` + } + if err := json.Unmarshal(specData, &spec); err != nil { + return nil, err + } + schemas := spec.Components.Schemas + resolve := func(s specSchema) specSchema { + if s.Ref == "" { + return s + } + return schemas[refName(s.Ref)] + } + + sourceTypes := map[string]bool{} + for name := range schemas { + if strings.HasPrefix(name, sourceTypeConfigPrefix) { + sourceTypes[normalizeTypeName(strings.TrimPrefix(name, sourceTypeConfigPrefix))] = true + } + } + + out := map[string][]AuthMethod{} + for name, schema := range schemas { + if !strings.HasPrefix(name, sourceTypeConfigPrefix) { + continue + } + sourceType := strings.TrimPrefix(name, sourceTypeConfigPrefix) + authType, ok := schema.Properties["auth_type"] + if !ok || len(authType.Enum) == 0 { + continue + } + allowed := map[string]bool{} + for _, v := range authType.Enum { + allowed[v] = true + } + + var methods []AuthMethod + for _, branch := range resolve(schema.Properties["auth"]).OneOf { + branch = resolve(branch) + method := branch.DocsType + if method == "" || !allowed[method] { + continue // the hidden "Empty" branch, or a method not in the enum + } + if normalizeTypeName(method) != normalizeTypeName(sourceType) && sourceTypes[normalizeTypeName(method)] { + continue // legacy provider method on WEBHOOK + } + props := make([]string, 0, len(branch.Properties)) + for p := range branch.Properties { + props = append(props, p) + } + sort.Strings(props) + methods = append(methods, AuthMethod{Name: method, Properties: props, Required: branch.Required}) + } + if len(methods) > 0 { + out[sourceType] = methods + } + } + return out, nil +} + +// normalizeTypeName maps a source type name to the form used in spec schema names, which drop +// characters such as "-" (type PROPERTY-FINDER has schema SourceTypeConfigPROPERTYFINDER). +func normalizeTypeName(name string) string { + var b strings.Builder + for _, r := range strings.ToUpper(strings.TrimSpace(name)) { + if (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' { + b.WriteRune(r) + } + } + return b.String() +} + +// AuthMethodsFor returns the auth methods for sourceType (any case or spelling the API +// accepts), or nil when the type takes no auth_type. +func AuthMethodsFor(methods map[string][]AuthMethod, sourceType string) []AuthMethod { + want := normalizeTypeName(sourceType) + for name, m := range methods { + if normalizeTypeName(name) == want { + return m + } + } + return nil +} + +// InferAuthType picks the auth method whose fields fit the given config.auth keys, or "" +// when none or more than one fits equally well. +// +// A method fits when every key is one of its fields and every field it marks required is +// present. The spec lists required fields for some types only (WEBHOOK's HMAC lists them, +// HTTP's does not), so among fitting methods the one with the fewest unused fields wins: a +// bare webhook_secret_key fits HMAC and STANDARD_WEBHOOKS on HTTP, and only +// STANDARD_WEBHOOKS uses nothing else - which is also the only one the API accepts for it. +// A tie is left unresolved rather than guessed. +func InferAuthType(methods []AuthMethod, authKeys []string) string { + if len(authKeys) == 0 { + return "" + } + keys := map[string]bool{} + for _, k := range authKeys { + keys[k] = true + } + best, bestExtra, tied := "", -1, false + for _, m := range methods { + props := map[string]bool{} + for _, p := range m.Properties { + props[p] = true + } + fits := true + for k := range keys { + if !props[k] { + fits = false + break + } + } + for _, r := range m.Required { + if !keys[r] { + fits = false + break + } + } + if !fits { + continue + } + extra := len(props) - len(keys) + switch { + case bestExtra == -1 || extra < bestExtra: + best, bestExtra, tied = m.Name, extra, false + case extra == bestExtra: + tied = true + } + } + if tied { + return "" + } + return best +} diff --git a/pkg/cmd/sources/auth_methods_test.go b/pkg/cmd/sources/auth_methods_test.go new file mode 100644 index 00000000..e47ee6c5 --- /dev/null +++ b/pkg/cmd/sources/auth_methods_test.go @@ -0,0 +1,154 @@ +package sources + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// testdata/openapi_source_auth.json is cut from the 2026-09-01 OpenAPI spec: the source types +// that offer a choice of auth method, STRIPE, VAPI and FORMSTACK (one fixed method), and two of WEBHOOK's legacy +// provider methods (AIRCALL, and PROPERTY-FINDER whose schema name drops the hyphen). +func loadFixture(t *testing.T) map[string][]AuthMethod { + t.Helper() + data, err := os.ReadFile(filepath.Join("testdata", "openapi_source_auth.json")) + require.NoError(t, err) + methods, err := ParseSourceAuthMethods(data) + require.NoError(t, err) + return methods +} + +func methodNames(ms []AuthMethod) []string { + names := make([]string, 0, len(ms)) + for _, m := range ms { + names = append(names, m.Name) + } + return names +} + +func TestParseSourceAuthMethods(t *testing.T) { + methods := loadFixture(t) + + assert.Equal(t, []string{"HMAC", "BASIC_AUTH", "API_KEY", "STANDARD_WEBHOOKS"}, methodNames(methods["WEBHOOK"]), + "WEBHOOK keeps its own methods and drops legacy provider methods, PROPERTY-FINDER included") + assert.Equal(t, []string{"HMAC", "BASIC_AUTH", "API_KEY", "STANDARD_WEBHOOKS"}, methodNames(methods["HTTP"])) + assert.Equal(t, []string{"BASIC_AUTH", "API_KEY"}, methodNames(methods["ORDINAL"])) + assert.Equal(t, []string{"BASIC_AUTH", "PROMETHEUS_ALERTMANAGER"}, methodNames(methods["PROMETHEUS_ALERTMANAGER"]), + "a method named after its own type is kept") + assert.Equal(t, []string{"STANDARD_WEBHOOKS", "GITLAB"}, methodNames(methods["GITLAB"])) + for _, tp := range []string{"AZURE_EVENT_GRID", "SENDGRID_INBOUND", "BETTER_STACK", "GRAFANA"} { + assert.NotEmpty(t, methods[tp], tp) + } + + for _, tp := range []string{"STRIPE", "AIRCALL", "PROPERTYFINDER"} { + assert.NotContains(t, methods, tp, "%s has one fixed method and takes no auth_type", tp) + } +} + +func TestAuthMethodsForNormalizesTypeName(t *testing.T) { + methods := loadFixture(t) + assert.NotNil(t, AuthMethodsFor(methods, "webhook")) + assert.NotNil(t, AuthMethodsFor(methods, " Prometheus_Alertmanager ")) + assert.Nil(t, AuthMethodsFor(methods, "STRIPE")) + assert.Nil(t, AuthMethodsFor(methods, "")) +} + +func TestInferAuthType(t *testing.T) { + methods := loadFixture(t) + hmac := []string{"algorithm", "encoding", "header_key", "webhook_secret_key"} + + tests := []struct { + sourceType string + keys []string + want string + }{ + {"WEBHOOK", []string{"header_key", "api_key"}, "API_KEY"}, + {"WEBHOOK", []string{"username", "password"}, "BASIC_AUTH"}, + {"WEBHOOK", hmac, "HMAC"}, + {"WEBHOOK", []string{"webhook_secret_key"}, "STANDARD_WEBHOOKS"}, + // HTTP's spec lists no required fields, so a bare secret fits HMAC too; best fit wins. + {"HTTP", []string{"webhook_secret_key"}, "STANDARD_WEBHOOKS"}, + {"HTTP", hmac, "HMAC"}, + {"HTTP", []string{"header_key", "api_key"}, "API_KEY"}, + {"ORDINAL", []string{"header_key", "api_key"}, "API_KEY"}, + {"ORDINAL", []string{"username", "password"}, "BASIC_AUTH"}, + {"AZURE_EVENT_GRID", []string{"header_key", "api_key"}, "API_KEY"}, + {"SENDGRID_INBOUND", hmac, "HMAC"}, + {"BETTER_STACK", []string{"header_key", "api_key"}, "API_KEY"}, + {"GRAFANA", []string{"header_key", "api_key"}, "API_KEY"}, + {"GRAFANA", []string{"webhook_secret_key", "header_key"}, "GRAFANA"}, + {"PROMETHEUS_ALERTMANAGER", []string{"api_key"}, "PROMETHEUS_ALERTMANAGER"}, + {"GITLAB", []string{"api_key"}, "GITLAB"}, + {"GITLAB", []string{"webhook_secret_key"}, "STANDARD_WEBHOOKS"}, + // No method takes these keys: leave auth_type unset and let the API report it. + {"PROMETHEUS_ALERTMANAGER", []string{"header_key", "api_key"}, ""}, + {"WEBHOOK", []string{"api_key"}, ""}, + {"WEBHOOK", []string{"bogus"}, ""}, + {"WEBHOOK", nil, ""}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("%s %v", tt.sourceType, tt.keys), func(t *testing.T) { + assert.Equal(t, tt.want, InferAuthType(AuthMethodsFor(methods, tt.sourceType), tt.keys)) + }) + } +} + +func TestInferAuthTypeTieIsNotGuessed(t *testing.T) { + methods := []AuthMethod{ + {Name: "A", Properties: []string{"api_key", "header_key"}}, + {Name: "B", Properties: []string{"api_key", "header_key"}}, + } + assert.Equal(t, "", InferAuthType(methods, []string{"api_key"})) +} + +func TestFetchSourceAuthMethodsCaches(t *testing.T) { + data, err := os.ReadFile(filepath.Join("testdata", "openapi_source_auth.json")) + require.NoError(t, err) + requests := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + _, _ = w.Write(data) + })) + defer server.Close() + + originalURL, originalCache := openapiURL, authMethodsCacheFileName + defer func() { openapiURL, authMethodsCacheFileName = originalURL, originalCache }() + openapiURL = server.URL + authMethodsCacheFileName = "hookdeck_source_auth_methods_test_" + t.Name() + ".json" + cachePath := filepath.Join(os.TempDir(), authMethodsCacheFileName) + os.Remove(cachePath) + defer os.Remove(cachePath) + + first, err := FetchSourceAuthMethods() + require.NoError(t, err) + second, err := FetchSourceAuthMethods() + require.NoError(t, err) + assert.Equal(t, 1, requests, "second call is served from the cache") + assert.Equal(t, first, second) +} + +func TestFetchSourceAuthMethodsRejectsSpecWithoutMethods(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"components":{"schemas":{}}}`)) + })) + defer server.Close() + + originalURL, originalCache := openapiURL, authMethodsCacheFileName + defer func() { openapiURL, authMethodsCacheFileName = originalURL, originalCache }() + openapiURL = server.URL + authMethodsCacheFileName = "hookdeck_source_auth_methods_test_" + t.Name() + ".json" + cachePath := filepath.Join(os.TempDir(), authMethodsCacheFileName) + os.Remove(cachePath) + defer os.Remove(cachePath) + + _, err := FetchSourceAuthMethods() + require.Error(t, err) + _, statErr := os.Stat(cachePath) + assert.True(t, os.IsNotExist(statErr), "an empty result must not be cached") +} diff --git a/pkg/cmd/sources/testdata/openapi_source_auth.json b/pkg/cmd/sources/testdata/openapi_source_auth.json new file mode 100644 index 00000000..e79165e4 --- /dev/null +++ b/pkg/cmd/sources/testdata/openapi_source_auth.json @@ -0,0 +1,3880 @@ +{ + "components": { + "schemas": { + "SourceAllowedHTTPMethod": { + "description": "List of allowed HTTP methods. Defaults to PUT, POST, PATCH, DELETE. GET and HEAD are opt-in.", + "items": { + "enum": [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + "QUERY" + ], + "type": "string" + }, + "type": "array" + }, + "SourceConfigAcumaticaAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "required": [ + "header_key", + "api_key" + ], + "type": "object", + "x-docs-type": "Acumatica" + }, + "SourceConfigAircallAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "Aircall" + }, + "SourceConfigAlipayAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "public_key": { + "type": "string" + } + }, + "required": [ + "public_key" + ], + "type": "object", + "x-docs-type": "Alipay" + }, + "SourceConfigAzureEventGridAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigAzureEventGridAuthHMAC" + }, + { + "$ref": "#/components/schemas/SourceConfigAzureEventGridAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigAzureEventGridAuthAPIKey" + }, + { + "$ref": "#/components/schemas/SourceConfigAzureEventGridAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigAzureEventGridAuthAPIKey": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigAzureEventGridAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigAzureEventGridAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigAzureEventGridAuthHMAC": { + "additionalProperties": false, + "properties": { + "algorithm": { + "enum": [ + "sha1", + "sha256", + "sha512", + "md5" + ], + "type": "string" + }, + "encoding": { + "enum": [ + "base64", + "base64url", + "hex" + ], + "type": "string" + }, + "header_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "HMAC" + }, + "SourceConfigBetterStackAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigBetterStackAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigBetterStackAuthCustomheader" + }, + { + "$ref": "#/components/schemas/SourceConfigBetterStackAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigBetterStackAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigBetterStackAuthCustomheader": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigBetterStackAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigCloudSignalAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "api_key": { + "type": "string" + } + }, + "required": [ + "api_key" + ], + "type": "object", + "x-docs-type": "Cloud Signal" + }, + "SourceConfigGitHubAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "GitHub" + }, + "SourceConfigGitLabAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigGitLabAuthSigningtokenStandardWebhooks" + }, + { + "$ref": "#/components/schemas/SourceConfigGitLabAuthSecrettokenXGitlabToken" + }, + { + "$ref": "#/components/schemas/SourceConfigGitLabAuthEmpty" + }, + { + "additionalProperties": false, + "nullable": true, + "properties": { + "api_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigGitLabAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigGitLabAuthSecrettokenXGitlabToken": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "GITLAB" + }, + "SourceConfigGitLabAuthSigningtokenStandardWebhooks": { + "additionalProperties": false, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "STANDARD_WEBHOOKS" + }, + "SourceConfigGrafanaAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigGrafanaAuthHMACsignature" + }, + { + "$ref": "#/components/schemas/SourceConfigGrafanaAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigGrafanaAuthAuthorizationheader" + }, + { + "$ref": "#/components/schemas/SourceConfigGrafanaAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigGrafanaAuthAuthorizationheader": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigGrafanaAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigGrafanaAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigGrafanaAuthHMACsignature": { + "additionalProperties": false, + "properties": { + "header_key": { + "type": "string" + }, + "timestamp_header": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "GRAFANA" + }, + "SourceConfigHTTPAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigHTTPAuthHMAC" + }, + { + "$ref": "#/components/schemas/SourceConfigHTTPAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigHTTPAuthAPIKey" + }, + { + "$ref": "#/components/schemas/SourceConfigHTTPAuthStandardWebhooks" + }, + { + "$ref": "#/components/schemas/SourceConfigHTTPAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigHTTPAuthAPIKey": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigHTTPAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigHTTPAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigHTTPAuthHMAC": { + "additionalProperties": false, + "properties": { + "algorithm": { + "enum": [ + "sha1", + "sha256", + "sha512", + "md5" + ], + "type": "string" + }, + "encoding": { + "enum": [ + "base64", + "base64url", + "hex" + ], + "type": "string" + }, + "header_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "HMAC" + }, + "SourceConfigHTTPAuthStandardWebhooks": { + "additionalProperties": false, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "STANDARD_WEBHOOKS" + }, + "SourceConfigOnfleetAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "pattern": "^(?:[a-f0-9]{2})+$/", + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "Onfleet" + }, + "SourceConfigOrdinalAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigOrdinalAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigOrdinalAuthAPIKey" + }, + { + "$ref": "#/components/schemas/SourceConfigOrdinalAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigOrdinalAuthAPIKey": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigOrdinalAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigOrdinalAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigPostmarkAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "required": [ + "username", + "password" + ], + "type": "object", + "x-docs-type": "Postmark" + }, + "SourceConfigPrometheusAlertmanagerAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigPrometheusAlertmanagerAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigPrometheusAlertmanagerAuthBearertoken" + }, + { + "$ref": "#/components/schemas/SourceConfigPrometheusAlertmanagerAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigPrometheusAlertmanagerAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigPrometheusAlertmanagerAuthBearertoken": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "PROMETHEUS_ALERTMANAGER" + }, + "SourceConfigPrometheusAlertmanagerAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigPropertyFinderAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "Property Finder" + }, + "SourceConfigSendGridInboundParseAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigSendGridInboundParseAuthHMAC" + }, + { + "$ref": "#/components/schemas/SourceConfigSendGridInboundParseAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigSendGridInboundParseAuthAPIKey" + }, + { + "$ref": "#/components/schemas/SourceConfigSendGridInboundParseAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigSendGridInboundParseAuthAPIKey": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigSendGridInboundParseAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigSendGridInboundParseAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigSendGridInboundParseAuthHMAC": { + "additionalProperties": false, + "properties": { + "algorithm": { + "enum": [ + "sha1", + "sha256", + "sha512", + "md5" + ], + "type": "string" + }, + "encoding": { + "enum": [ + "base64", + "base64url", + "hex" + ], + "type": "string" + }, + "header_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "HMAC" + }, + "SourceConfigStravaAuth": { + "additionalProperties": false, + "nullable": true, + "properties": {}, + "type": "object", + "x-docs-type": "Strava" + }, + "SourceConfigStripeAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "Stripe" + }, + "SourceConfigTikTokShopAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "app_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key", + "app_key" + ], + "type": "object", + "x-docs-type": "TikTok Shop" + }, + "SourceConfigVercelDrainsAuth": { + "additionalProperties": false, + "nullable": true, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "type": "object", + "x-docs-type": "Vercel Drains" + }, + "SourceConfigWebhookAuth": { + "additionalProperties": false, + "oneOf": [ + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHMAC" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBasicAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAPIKey" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStandardWebhooks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAiprise" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAircall" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAlchemy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAttentive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDocuSign" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthIntercom" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMCPEvents" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSanity" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBigCommerce" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClaude" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpenAI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDelivereasy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLoyaltyLion" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayt" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSemaphoreCI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUploadcare" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOhDear" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLettermint" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthButtondown" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpnForm" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQlikCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthReditus" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTutorCruncher" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHintHealth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHighMobility" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDeliverect" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMemberful" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayTabs" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTreet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFelloh" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPlanetScale" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPlane" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgentset" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthXtremepush" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBump.sh" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAyrshare" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMorta" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSendX" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDojah" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTeachfloor" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpikeAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTop.gg" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFreemius" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMewsPOS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthViolet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLogto" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHackerOne" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudsmith" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuth1PasswordDeviceTrustKolide" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZITADEL" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTokity" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBigMailer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFormspree" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLearnHouse" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSahha" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHIFI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPreczn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRyft" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAuthgear" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFingerprint" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGitBook" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUpPromote" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthThoughtIndustries" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSurvicate" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMedplum" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthvivenu" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRoot" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGOV.UKPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPolar" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBridgeStablecoins" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBridgeAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChargebeeBilling" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChaindots" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudSignal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCoinbase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCourier" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCursor" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMeraki" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFireblocks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFrontApp" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZoom" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthX" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRecharge" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCronofy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRecurly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRetell" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRevolut" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRingCentral" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStripe" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudinary" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPropertyFinder" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQuo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQuoter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShopify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTwilio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGitHub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPostmark" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTally" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTypeform" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPicqer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthXero" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSvix" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthResend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGoogleGemini" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDeck" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthincident.io" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQuickBooks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAttio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLINE" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClickUp" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCal.com" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSumsub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMux" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShippo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEtsy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthReducto" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAdyen" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAkeneo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWooCommerce" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOkta" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOura" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCommerceLayer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCommunity.com" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHubspot" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHasura" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPrefect" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKoBoToolbox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFireberry" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHightouch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOneLogin" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthParagon" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRev.ai" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStuart" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSigfox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNium" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuth360dialog" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBitrise" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDatoCMS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthIterable" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOneSpan" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthparcelLab" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZuora" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAmazonEventBridge" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthProxyclickEpturaVisitor" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBraze" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJumpCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpsgenie" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaxos" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRudderStack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTray.io" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCopper" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBelvo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPubNub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAmplitude" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBringg" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDoorDashDrive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMake" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOry" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSocure" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVTEX" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCurrents" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthApify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBuilder.io" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFourKites" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNewRelic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOyster" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthproject44" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpeechmatics" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWorkato" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthInvoiceNinja" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthForm.io" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWorkspaceONEOmnissa" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAzureDevOps" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFreshsales" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOmnisend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaperform" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRailway" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStrapi" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthYouCanBookMe" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailerSend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailgun" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPersona" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPipedrive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSendgrid" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWorkOS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSynctera" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAWSSNS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuth3dEye" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTwitch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthElevenLabs" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEnode" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFanvue" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFaundit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFavro" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuth8x8" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAxiom" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudentitySecureAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGrist" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMetabase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthProcore" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthROLLER" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTorii" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAcumatica" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBaserow" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDynatrace" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHaloPSA" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLessonly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPax8" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBitdefender" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCyberimpact" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFactorial" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNextcloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQuickbase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAimfox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCin7Core" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDattoRMM" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFirstbase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJamfPro" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNexthink" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPeopleDataLabs" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRapidAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTripletex" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDemodesk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJamie" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMaximizer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPingOne" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRedo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStreak" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVideoAsk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAuvik" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClickHouse" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDocument360" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJobAdder" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMeilisearch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPostscript" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRocketlane" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSwoogo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWiza" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLinear" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShipBob" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShipHero" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShopline" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWhatnot" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWix" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNMIPaymentGateway" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNeon" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOrb" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPylon" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNomod" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpenlayer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSoharHealth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCerebrum" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAirweave" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRelay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNitrosend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJunction" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgntix" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMemos" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCuuro" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNovu" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBayouEnergy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCelitech" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRequesty" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpeed" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCrossmint" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTensorlake" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNotifuse" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFormbricks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMeetingBaaS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVersive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWebiny" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVern" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthepilot" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVoiceflow" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSurge" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNextPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLinq" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPineLabs" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLiveblocks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPrivy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClemta" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFlexprice" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthiSnap" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGlobalStack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGeneralTranslation" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTrunk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDoubleword" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOuthire" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBasiq" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBindbee" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRazorpay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRepay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSquare" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSolidgate" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTrello" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEbay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStorekit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSkovik" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPrividium" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDodoPayments" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRecurrente" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMonerium" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSaladCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTrackstar" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRuna" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAxilio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSupertab" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHelcim" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTolt" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSuperwall" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHireHive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJustt" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthScalekit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPinata" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLasoFinance" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChargeblast" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPipecatCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthpganalyze" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDots" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthcamelAI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSalsa" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBlindPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGoody" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpacebring" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHexclave" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthsajn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOrigami" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSwipelux" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTravtus" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOmnara" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLayerswap" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVelt" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthArgil" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTerminal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTelnyx" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClickPost" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRebilly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHoneycomb" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSoniox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDigitalSamba" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthArgoCD" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthConnecteam" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthArcadia" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGOV.UKNotify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMeasureOne" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMono" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSwan" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayrixPro" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHarbor" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVellum" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEstuary" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuth100ms" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNavattic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGumlet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGCNotify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPAY.JP" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTabby" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayroc" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTrendyol" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPlunk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSMTP2GO" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClickatell" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKibana" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRebrandly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthParticle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAuroraSolar" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPalmettoFinance" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShip24" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZoop" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCelcoin" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLeonardo.Ai" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSevalla" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSublimeSecurity" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFirstPromoter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMightyNetworks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHostaway" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthIncode" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDatacake" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVentrata" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDiscord" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTokenIO" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFiserv" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEmporix" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCoverGenius" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHoneybadger" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMiddesk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOnceHub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSalesloft" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTrigger.dev" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAssemblyAI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFoursquare" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCartesia" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthIncrease" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMistral" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOutreach" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSavvyCal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStigg" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUnit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWorkable" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLokalise" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthConfluenceDataCenter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaysafe" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSendbird" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStoryblok" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWave" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTruework" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDocumenso" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMoonPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPostHog" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShopware" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStreamgetstream.io" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthXendit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMedusa" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNorthflank" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPrintify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShortcut" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthtawk.to" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthYousign" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCoterie" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFootprint" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMercury" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRecruitee" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSignNow" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTodoist" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZohoSign" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFusionAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBondsmith" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVercelDrains" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVercelWebhooks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTebex" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSlack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSmartcar" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBelco" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHyperswitch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOnramper" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQonto" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZiina" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpacelift" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLangfuse" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOptimizely" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthConvox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRewardful" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthReferralHero" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFountain" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStorylane" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTerraAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKatanaMRP" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOxaPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthReturnless" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBVNK" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPulumiCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgora" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailcoach" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChameleon" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTaskade" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthComplyCube" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthapi.video" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCheckoutPage" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKhipu" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRootFiCommenda" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthColumn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSonarQube" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBaseten" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFluxCD" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthArgyle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMeetGeek" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthiDenfy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthThinkific" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSocotra" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthProof" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCreem" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKOMOJU" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaypercut" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTerminal49" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCryptoProcessing" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthForgejo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWistia" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthConvex" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLearnUpon" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSurveyMethods" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPartnero" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNorthpass" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTexture" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailchimp" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNuvemshop" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaddle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaypal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaymob" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPaystack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthModemPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBitculator" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthScrapfly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPortal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTreezor" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPraxis" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCustomer.IO" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthExactOnline" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFacebook" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWhatsApp" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthReplicate" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTikTok" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTikTokShop" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAirwallex" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAscend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAlipay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBird" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPropelAuth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailerLite" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGo1" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHCPTerraform" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBlandAI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDoppler" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGitea" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLoopReturns" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCodat" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSendcloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthToggl" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBoldSign" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthExpo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHeyGen" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLuma" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStedi" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAcuityScheduling" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSmartsheet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVGSVeryGoodSecurity" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBreezyHR" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFirecrawl" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJFrog" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudTalk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthExa" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWAHA" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMautic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthYapily" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCensusFivetranActivations" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFireHydrant" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKombo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGranola" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHelpScout" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCheck" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSeaTable" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAbly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCheckly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFlagsmith" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKustomer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDuffel" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTaiga" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDescope" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFourthwall" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLago" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZendesk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUpollo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSmile" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNylas" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGoCardless" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGooglePubSub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLinkedIn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLithic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOnfleet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUtila" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAffonso" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthArdoq" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBambooHR" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBreakcold" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBugSmash" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCampfire" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCashfree" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCharityStack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChatim" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthChiliPiper" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCoassemble" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthConfigCat" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCyera" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFeaturebase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGreenshades" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHume" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthInfiniteGiving" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLob" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLodgix" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMagicHour" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMetronome" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMICEtribe" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOnshape" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpenRouter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayNow" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPodium" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPurchasely" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthQuicknode" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRemote" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSchematic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSent" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSinch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpherePay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSpreeCommerce" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTidio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTiltify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTwenty" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTypefully" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUltravox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUploadPost" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthuseSend" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVitableHealth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWHOOP" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGreenDot" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZeroHash" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAirtable" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAsana" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAshby" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFastSpring" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPayProGlobal" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUSPS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWalmart" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFireflies.ai" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFlexport" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUber" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWeChatPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBunnyStream" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthShipStation" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCircle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStatsig" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVapi" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVolume" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFormstack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAfterShip" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAuth0" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBitbucket" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCalendly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAbsorbLMS" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAppstleSubscriptions" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthfolk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHolded" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNooks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPlanningCenter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSemble" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZigpoll" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthathenahealth" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBasin" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDentally" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLiveTennisAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPennylane" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPriveRecurlyCommerce" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTremendous" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgentcard" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCanny" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFullEnrich" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHumaans" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailtrap" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTeamwork.com" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgentLine" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAutosana" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCertn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEnvoy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGlean" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHuntress" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTextUs" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVimeo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAnarlog" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAutotask" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCircleback" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHail" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJazzHR" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMissive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPipelineCRM" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRoam" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTheirStack" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAutumn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCompanyCam" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFiberAI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHitPay" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJobber" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMoneybird" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPlain" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRocketReach" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthThreads" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTriNetZenefits" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCheckout.com" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCircleCI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthClerk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDeepgram" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNeedle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthActOn" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUKGReady" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAmpersand" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEgnyte" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthbeehiiv" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthYouMail" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthINGENIOUS.BUILD" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSimpro" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSafeBase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKnowBe4" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTanium" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSAPSuccessFactors" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTIMIFY" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWebinarJam" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSAPEmarsys" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLumos" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHuggingFace" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthJira" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKlaviyo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthKnock" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMollie" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNotion" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPolytomic" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPagerDuty" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOnfido" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDwolla" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDidit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPusher" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLaunchDarkly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVeriff" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZernio" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMongoDBAtlas" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTailscale" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHeroku" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMaxioChargify" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRutter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBolt" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSignalSciencesFastlyNextGenWAF" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMaintainX" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCallRail" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLemonSqueezy" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthModernTreasury" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCastle" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHiBob" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMotive" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthdbtCloud" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFivetran" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWebex" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRamp" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBuildkite" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDropbox" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStytch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDaytona" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGopuff" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWhop" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCloudflare" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMarketo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNinjaOne" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailjet" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGravityForms" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZoomInfo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUnipile" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMailparser" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthHelius" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDatabricks" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAppsFlyer" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAsaas" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpenClaw" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthMicrosoftDynamics365" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDrata" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSnipcart" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSparkPost" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSupabase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRevenueCat" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPipedream" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTelegram" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRecall.ai" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFathom" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPleo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBrowserbase" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthYoco" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNash" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthVanta" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGuesty" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAda" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAgentMail" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthCrusoe" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthLoop" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthOpenMeter" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSendoso" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSovos" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthStitch" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthTaskRabbit" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthUphold" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWeTravel" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthNango" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthSegment" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthn8n" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthZapier" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthAzureLogicApps" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthBrevo" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGorgias" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGreenAPI" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFreshdesk" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthFillout" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthInstantly" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthDealHub" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthRubrik" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthGoogleWorkspace" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthWebflow" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthPapergames" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthbundle.social" + }, + { + "$ref": "#/components/schemas/SourceConfigWebhookAuthEmpty" + } + ], + "properties": {}, + "type": "object" + }, + "SourceConfigWebhookAuthAPIKey": { + "additionalProperties": false, + "properties": { + "api_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "required": [ + "header_key", + "api_key" + ], + "type": "object", + "x-docs-type": "API_KEY" + }, + "SourceConfigWebhookAuthAircall": { + "additionalProperties": false, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "AIRCALL" + }, + "SourceConfigWebhookAuthBasicAuth": { + "additionalProperties": false, + "properties": { + "password": { + "type": "string" + }, + "username": { + "type": "string" + } + }, + "required": [ + "username", + "password" + ], + "type": "object", + "x-docs-type": "BASIC_AUTH" + }, + "SourceConfigWebhookAuthEmpty": { + "nullable": true, + "x-docs-hide": true, + "x-docs-nullable": true + }, + "SourceConfigWebhookAuthHMAC": { + "additionalProperties": false, + "properties": { + "algorithm": { + "enum": [ + "sha1", + "sha256", + "sha512", + "md5" + ], + "type": "string" + }, + "encoding": { + "enum": [ + "base64", + "base64url", + "hex" + ], + "type": "string" + }, + "header_key": { + "type": "string" + }, + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "algorithm", + "encoding", + "header_key", + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "HMAC" + }, + "SourceConfigWebhookAuthPropertyFinder": { + "additionalProperties": false, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "PROPERTY-FINDER" + }, + "SourceConfigWebhookAuthStandardWebhooks": { + "additionalProperties": false, + "properties": { + "webhook_secret_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "type": "object", + "x-docs-type": "STANDARD_WEBHOOKS" + }, + "SourceCustomResponse": { + "additionalProperties": false, + "description": "Custom response object", + "nullable": true, + "properties": { + "body": { + "description": "Body of the custom response", + "maxLength": 1000, + "type": "string" + }, + "content_type": { + "$ref": "#/components/schemas/SourceCustomResponseContentType" + } + }, + "required": [ + "content_type", + "body" + ], + "type": "object" + }, + "SourceCustomResponseContentType": { + "description": "Content type of the custom response", + "enum": [ + "json", + "text", + "xml" + ], + "type": "string" + }, + "SourceTypeConfig": { + "additionalProperties": false, + "default": {}, + "description": "The type configs for the specified type", + "oneOf": [ + { + "$ref": "#/components/schemas/SourceTypeConfigAIRCALL", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigWEBHOOK" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigHTTP" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigCLOUDSIGNAL", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigAZURE_EVENT_GRID", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigSTRIPE" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigPROPERTYFINDER" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigGITHUB" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigPOSTMARK" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigGITLAB" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigSENDGRID_INBOUND" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigACUMATICA" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigPROMETHEUS_ALERTMANAGER" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigVERCEL_LOG_DRAINS", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigTIKTOK_SHOP", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigALIPAY", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigSTRAVA", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigONFLEET", + "x-required": true + }, + { + "$ref": "#/components/schemas/SourceTypeConfigBETTER_STACK" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigGRAFANA" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigORDINAL" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigVAPI" + }, + { + "$ref": "#/components/schemas/SourceTypeConfigFORMSTACK" + } + ], + "properties": {}, + "type": "object" + }, + "SourceTypeConfigACUMATICA": { + "additionalProperties": false, + "description": "The type config for ACUMATICA. Requires type to be `ACUMATICA`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigAcumaticaAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://help.myob.com.au/advanced/Docs/Published/IntegrationDevelopmentGuide/IntegrationDev_PushNotifications_Destinations.html", + "x-docs-type": "ACUMATICA" + }, + "SourceTypeConfigAIRCALL": { + "additionalProperties": false, + "description": "The type config for AIRCALL. Requires type to be `AIRCALL`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigAircallAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://developer.aircall.io/docs/setup-webhooks", + "x-docs-type": "AIRCALL" + }, + "SourceTypeConfigALIPAY": { + "additionalProperties": false, + "description": "The type config for ALIPAY. Requires type to be `ALIPAY`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigAlipayAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.alipayplus.com/alipayplus/alipayplus/api_acq_tile/signature", + "x-docs-type": "ALIPAY" + }, + "SourceTypeConfigAZURE_EVENT_GRID": { + "additionalProperties": false, + "description": "The type config for AZURE_EVENT_GRID. Requires type to be `AZURE_EVENT_GRID`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigAzureEventGridAuth" + }, + "auth_type": { + "enum": [ + "HMAC", + "BASIC_AUTH", + "API_KEY" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://learn.microsoft.com/en-us/azure/event-grid/end-point-validation-cloud-events-schema", + "x-docs-type": "AZURE_EVENT_GRID" + }, + "SourceTypeConfigBETTER_STACK": { + "additionalProperties": false, + "description": "The type config for BETTER_STACK. Requires type to be `BETTER_STACK`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigBetterStackAuth" + }, + "auth_type": { + "enum": [ + "BASIC_AUTH", + "API_KEY" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://betterstack.com/docs/uptime/webhooks/", + "x-docs-type": "BETTER_STACK" + }, + "SourceTypeConfigCLOUDSIGNAL": { + "additionalProperties": false, + "description": "The type config for CLOUDSIGNAL. Requires type to be `CLOUDSIGNAL`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigCloudSignalAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "CLOUDSIGNAL" + }, + "SourceTypeConfigGITHUB": { + "additionalProperties": false, + "description": "The type config for GITHUB. Requires type to be `GITHUB`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigGitHubAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries", + "x-docs-type": "GITHUB" + }, + "SourceTypeConfigGITLAB": { + "additionalProperties": false, + "description": "The type config for GITLAB. Requires type to be `GITLAB`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigGitLabAuth" + }, + "auth_type": { + "enum": [ + "STANDARD_WEBHOOKS", + "GITLAB" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.gitlab.com/user/project/integrations/webhooks/#signing-tokens", + "x-docs-type": "GITLAB" + }, + "SourceTypeConfigGRAFANA": { + "additionalProperties": false, + "description": "The type config for GRAFANA. Requires type to be `GRAFANA`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigGrafanaAuth" + }, + "auth_type": { + "enum": [ + "GRAFANA", + "BASIC_AUTH", + "API_KEY" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://grafana.com/docs/grafana/latest/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier/#hmac-signature", + "x-docs-type": "GRAFANA" + }, + "SourceTypeConfigHTTP": { + "additionalProperties": false, + "description": "The type config for HTTP. Requires type to be `HTTP`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigHTTPAuth" + }, + "auth_type": { + "enum": [ + "HMAC", + "BASIC_AUTH", + "API_KEY", + "STANDARD_WEBHOOKS" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "HTTP" + }, + "SourceTypeConfigONFLEET": { + "additionalProperties": false, + "description": "The type config for ONFLEET. Requires type to be `ONFLEET`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigOnfleetAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.onfleet.com/reference/secrets", + "x-docs-type": "ONFLEET" + }, + "SourceTypeConfigORDINAL": { + "additionalProperties": false, + "description": "The type config for ORDINAL. Requires type to be `ORDINAL`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigOrdinalAuth" + }, + "auth_type": { + "enum": [ + "BASIC_AUTH", + "API_KEY" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.tryordinal.com/integrations/webhooks/introduction", + "x-docs-type": "ORDINAL" + }, + "SourceTypeConfigPOSTMARK": { + "additionalProperties": false, + "description": "The type config for POSTMARK. Requires type to be `POSTMARK`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigPostmarkAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "POSTMARK" + }, + "SourceTypeConfigPROMETHEUS_ALERTMANAGER": { + "additionalProperties": false, + "description": "The type config for PROMETHEUS_ALERTMANAGER. Requires type to be `PROMETHEUS_ALERTMANAGER`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigPrometheusAlertmanagerAuth" + }, + "auth_type": { + "enum": [ + "BASIC_AUTH", + "PROMETHEUS_ALERTMANAGER" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://prometheus.io/docs/alerting/latest/configuration/", + "x-docs-type": "PROMETHEUS_ALERTMANAGER" + }, + "SourceTypeConfigPROPERTYFINDER": { + "additionalProperties": false, + "description": "The type config for PROPERTY-FINDER. Requires type to be `PROPERTY-FINDER`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigPropertyFinderAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "PROPERTY-FINDER" + }, + "SourceTypeConfigSENDGRID_INBOUND": { + "additionalProperties": false, + "description": "The type config for SENDGRID_INBOUND. Requires type to be `SENDGRID_INBOUND`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigSendGridInboundParseAuth" + }, + "auth_type": { + "enum": [ + "HMAC", + "BASIC_AUTH", + "API_KEY" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "SENDGRID_INBOUND" + }, + "SourceTypeConfigSTRAVA": { + "additionalProperties": false, + "description": "The type config for STRAVA. Requires type to be `STRAVA`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigStravaAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "STRAVA" + }, + "SourceTypeConfigSTRIPE": { + "additionalProperties": false, + "description": "The type config for STRIPE. Requires type to be `STRIPE`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigStripeAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://docs.stripe.com/webhooks?verify=verify-manually", + "x-docs-type": "STRIPE" + }, + "SourceTypeConfigTIKTOK_SHOP": { + "additionalProperties": false, + "description": "The type config for TIKTOK_SHOP. Requires type to be `TIKTOK_SHOP`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigTikTokShopAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "TIKTOK_SHOP" + }, + "SourceTypeConfigVERCEL_LOG_DRAINS": { + "additionalProperties": false, + "description": "The type config for VERCEL_LOG_DRAINS. Requires type to be `VERCEL_LOG_DRAINS`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigVercelDrainsAuth" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-external-url": "https://vercel.com/docs/rest-api#securing-your-log-drains", + "x-docs-type": "VERCEL_LOG_DRAINS" + }, + "SourceTypeConfigWEBHOOK": { + "additionalProperties": false, + "description": "The type config for WEBHOOK. Requires type to be `WEBHOOK`.", + "properties": { + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigWebhookAuth" + }, + "auth_type": { + "enum": [ + "HMAC", + "BASIC_AUTH", + "API_KEY", + "STANDARD_WEBHOOKS", + "AIRCALL", + "PROPERTY-FINDER" + ], + "nullable": true, + "type": "string" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "type": "object", + "x-docs-type": "WEBHOOK" + }, + "SourceTypeConfigVAPI": { + "type": "object", + "properties": { + "trim_payload": { + "type": "boolean" + }, + "auth": { + "$ref": "#/components/schemas/SourceConfigVapiAuth" + }, + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "additionalProperties": false, + "description": "The type config for VAPI. Requires type to be `VAPI`.", + "x-docs-type": "VAPI", + "x-docs-external-url": "https://docs.vapi.ai/server-url/server-authentication" + }, + "SourceConfigVapiAuth": { + "type": "object", + "properties": { + "webhook_secret_key": { + "type": "string" + }, + "algorithm": { + "type": "string", + "enum": [ + "sha256", + "sha1", + "sha512" + ] + }, + "encoding": { + "type": "string", + "enum": [ + "hex", + "base64", + "base64url" + ] + }, + "header_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "additionalProperties": false, + "nullable": true, + "x-docs-type": "Vapi" + }, + "SourceTypeConfigFORMSTACK": { + "type": "object", + "properties": { + "auth": { + "$ref": "#/components/schemas/SourceConfigFormstackAuth" + }, + "allowed_http_methods": { + "$ref": "#/components/schemas/SourceAllowedHTTPMethod" + }, + "custom_response": { + "$ref": "#/components/schemas/SourceCustomResponse" + } + }, + "additionalProperties": false, + "description": "The type config for FORMSTACK. Requires type to be `FORMSTACK`.", + "x-docs-type": "FORMSTACK", + "x-docs-external-url": "https://help.formstack.com/hc/en-us/articles/44592535914387-WebHook-Submit-Actions" + }, + "SourceConfigFormstackAuth": { + "type": "object", + "properties": { + "webhook_secret_key": { + "type": "string" + }, + "header_key": { + "type": "string" + } + }, + "required": [ + "webhook_secret_key" + ], + "additionalProperties": false, + "nullable": true, + "x-docs-type": "Formstack" + } + } + } +} \ No newline at end of file diff --git a/pkg/cmd/sources/types.go b/pkg/cmd/sources/types.go index a399fec0..87b73ada 100644 --- a/pkg/cmd/sources/types.go +++ b/pkg/cmd/sources/types.go @@ -3,13 +3,15 @@ package sources import ( "encoding/json" "fmt" - "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" "io" "net/http" "os" "path/filepath" + "sort" "strings" "time" + + "github.com/hookdeck/hookdeck-cli/pkg/hookdeck" ) var ( @@ -18,142 +20,188 @@ var ( // upgrading within the 24 hour TTL served source types parsed from the // previous spec - stale auth schemes and required fields, used to validate // `source create`. + // + // The "_v2" marks the cached shape. Versions that read SourceCreateRequest wrote an empty + // map under the unversioned name, and a different struct; a new name means neither is read. openapiURL = "https://api.hookdeck.com" + hookdeck.APIPathPrefix + "/openapi" - cacheFileName = "hookdeck_source_types" + strings.ReplaceAll(hookdeck.APIPathPrefix, "/", "_") + ".json" + cacheFileName = "hookdeck_source_types_v2" + strings.ReplaceAll(hookdeck.APIPathPrefix, "/", "_") + ".json" cacheTTL = 24 * time.Hour ) -// SourceType holds the validation rules for a single source type. +// SourceType holds what the OpenAPI spec says about one source type's config.auth. type SourceType struct { - Name string `json:"name"` - AuthScheme string `json:"auth_scheme"` - RequiredFields []string `json:"required_fields"` + // Name is the type as the API spells it (PROPERTY-FINDER, not the schema's PROPERTYFINDER). + Name string `json:"name"` + // AuthRequired is true when a source of this type cannot be created without config.auth. + AuthRequired bool `json:"auth_required"` + // AuthFields are the fields config.auth takes, and RequiredAuthFields those of them it must + // carry when sent. Both are empty for types offering a choice of method (WEBHOOK, HTTP, ...): + // their fields depend on config.auth_type, see FetchSourceAuthMethods. + AuthFields []string `json:"auth_fields"` + RequiredAuthFields []string `json:"required_auth_fields"` } -// FetchSourceTypes downloads the OpenAPI spec, parses it to extract source type information, -// and caches the result. It returns a map of source types. +// FetchSourceTypes downloads the OpenAPI spec, parses each source type's auth rules, and caches +// the result for cacheTTL. The map is keyed by normalized type name: look types up with +// SourceTypeFor. +// +// An empty parse is an error and is not cached: it means the spec no longer has the shape this +// parser reads, and caching it would switch validation off for a day without a word. func FetchSourceTypes() (map[string]SourceType, error) { cachePath := filepath.Join(os.TempDir(), cacheFileName) - // Check for a valid cache file first - if info, err := os.Stat(cachePath); err == nil { - if time.Since(info.ModTime()) < cacheTTL { - file, err := os.Open(cachePath) - if err == nil { - defer file.Close() - var sourceTypes map[string]SourceType - if json.NewDecoder(file).Decode(&sourceTypes) == nil { - return sourceTypes, nil - } + if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < cacheTTL { + if data, err := os.ReadFile(cachePath); err == nil { + var cached map[string]SourceType + if json.Unmarshal(data, &cached) == nil && len(cached) > 0 { + return cached, nil } } } - // If cache is invalid or doesn't exist, fetch from URL - resp, err := http.Get(openapiURL) + body, err := downloadOpenAPISpec() + if err != nil { + return nil, err + } + sourceTypes, err := ParseSourceTypes(body) + if err != nil { + return nil, fmt.Errorf("failed to parse OpenAPI spec: %w", err) + } + if len(sourceTypes) == 0 { + return nil, fmt.Errorf("failed to parse OpenAPI spec: no source types found") + } + + if data, err := json.Marshal(sourceTypes); err == nil { + _ = os.WriteFile(cachePath, data, 0o600) + } + // The same download feeds the auth methods cache, so the next FetchSourceAuthMethods + // does not download the 1.3 MB spec a second time. + cacheAuthMethods(body) + return sourceTypes, nil +} + +// specDownloadTimeout bounds one spec download. Source create and upsert read the spec on the +// way to the API call, so a stalled connection must not hang the command. +const specDownloadTimeout = 10 * time.Second + +var specClient = &http.Client{Timeout: specDownloadTimeout} + +// downloadOpenAPISpec fetches the API's OpenAPI spec. +func downloadOpenAPISpec() ([]byte, error) { + resp, err := specClient.Get(openapiURL) if err != nil { return nil, fmt.Errorf("failed to download OpenAPI spec: %w", err) } defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("failed to download OpenAPI spec: received status code %d", resp.StatusCode) } - body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read OpenAPI spec body: %w", err) } - - sourceTypes, err := parseOpenAPISpec(body) - if err != nil { - return nil, fmt.Errorf("failed to parse OpenAPI spec: %w", err) - } - - // Cache the result - file, err := os.Create(cachePath) - if err == nil { - defer file.Close() - json.NewEncoder(file).Encode(sourceTypes) - } - - return sourceTypes, nil + return body, nil } -// parseOpenAPISpec extracts source type information from the OpenAPI JSON spec. -func parseOpenAPISpec(specData []byte) (map[string]SourceType, error) { +// ParseSourceTypes extracts each source type's auth rules from the OpenAPI spec. +// +// Every SourceTypeConfig schema is a source type. Its auth property is either a single +// object (a type with one fixed verification method, e.g. STRIPE) or, alongside an auth_type +// enum, a oneOf of methods (WEBHOOK, HTTP, ...). +// +// Whether auth is required is not on SourceTypeConfig: that schema is shared by request +// and response, so its auth is always nullable. The request-side rule shows up as +// "x-required": true on the type's entry in SourceTypeConfig.oneOf. That flag means the type's +// config is required, which the API sets when any feature is required - verification, or a +// handshake (STRAVA, MONDAY, ONFLEET, ...). So auth counts as required only when, as well: +// +// - the type has one fixed method: for a choice of method the API always accepts +// auth_type null with no auth, and +// - that method has fields: a handshake-only type's auth is an empty object, nothing to send. +// +// A "required" list naming auth on SourceTypeConfig also counts, should the spec start +// stating it there. One handshake type still reads as auth-required (ONFLEET: handshake +// required, verification optional, an auth with a secret field); callers correct for it. +func ParseSourceTypes(specData []byte) (map[string]SourceType, error) { var spec struct { Components struct { - Schemas struct { - SourceCreateRequest struct { - Properties struct { - Type struct { - Enum []string `json:"enum"` - } `json:"type"` - VerificationConfigs struct { - OneOf []struct { - Properties map[string]struct { - Required []string `json:"required"` - } `json:"properties"` - Required []string `json:"required"` - } `json:"oneOf"` - } `json:"verification_configs"` - } `json:"properties"` - } `json:"SourceCreateRequest"` - } `json:"schemas"` + Schemas map[string]specSchema `json:"schemas"` } `json:"components"` } - if err := json.Unmarshal(specData, &spec); err != nil { return nil, err } + schemas := spec.Components.Schemas + resolve := func(s specSchema) specSchema { + if s.Ref == "" { + return s + } + return schemas[refName(s.Ref)] + } - sourceTypes := make(map[string]SourceType) - sourceTypeNames := spec.Components.Schemas.SourceCreateRequest.Properties.Type.Enum - - for _, name := range sourceTypeNames { - sourceTypes[name] = SourceType{Name: name} + configRequired := map[string]bool{} + for _, entry := range schemas[sourceTypeConfigPrefix].OneOf { + if entry.XRequired && entry.Ref != "" { + configRequired[refName(entry.Ref)] = true + } } - verificationConfigs := spec.Components.Schemas.SourceCreateRequest.Properties.VerificationConfigs.OneOf - for _, config := range verificationConfigs { - if len(config.Required) != 1 { + out := map[string]SourceType{} + for schemaName, schema := range schemas { + if !strings.HasPrefix(schemaName, sourceTypeConfigPrefix) || schemaName == sourceTypeConfigPrefix { continue } - authScheme := config.Required[0] - - var requiredFields []string - if props, ok := config.Properties[authScheme]; ok { - requiredFields = props.Required + name := schema.DocsType + if name == "" { + name = strings.TrimPrefix(schemaName, sourceTypeConfigPrefix) } - - // This part is tricky as the OpenAPI spec doesn't directly link the verification config to the type enum. - // We make an assumption based on common patterns. For now, we will have to manually map them or improve this logic later. - // A simple heuristic: if a config is for a specific provider, its name might be part of the authScheme. - // This is a placeholder for a more robust mapping logic. - // For now, let's apply a generic scheme and required fields. - // A better approach would be to have this mapping defined explicitly in the spec. - - // Let's assume a simple mapping for now for demonstration. - // In a real scenario, this would need a more sophisticated parsing logic. - for _, name := range sourceTypeNames { - st := sourceTypes[name] - // This is a simplified logic. A real implementation would need to inspect the discriminator or other properties. - // For now, we'll just assign the first found scheme to all for demonstration. - if st.AuthScheme == "" { // Assign only if not already set - st.AuthScheme = authScheme - st.RequiredFields = requiredFields - sourceTypes[name] = st - } + st := SourceType{Name: name} + + _, hasAuthType := schema.Properties["auth_type"] + authProp, hasAuth := schema.Properties["auth"] + if hasAuth && !hasAuthType { + auth := resolve(authProp) + st.AuthFields = sortedKeys(auth.Properties) + st.RequiredAuthFields = sortedCopy(auth.Required) + required := configRequired[schemaName] || contains(schema.Required, "auth") + st.AuthRequired = required && len(st.AuthFields) > 0 } + out[normalizeTypeName(name)] = st } + return out, nil +} + +// SourceTypeFor returns the rules for sourceType, in any case or spelling the API accepts. +func SourceTypeFor(sourceTypes map[string]SourceType, sourceType string) (SourceType, bool) { + st, ok := sourceTypes[normalizeTypeName(sourceType)] + return st, ok +} - // Manually correcting Stripe for the sake of the test - if st, ok := sourceTypes["STRIPE"]; ok { - st.AuthScheme = "webhook_secret" - st.RequiredFields = []string{"secret"} - sourceTypes["STRIPE"] = st +// refName returns the schema name a "#/components/schemas/" reference points to. +func refName(ref string) string { + return ref[strings.LastIndex(ref, "/")+1:] +} + +func sortedKeys(m map[string]specSchema) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) } + sort.Strings(keys) + return keys +} - return sourceTypes, nil +func sortedCopy(s []string) []string { + out := append([]string{}, s...) + sort.Strings(out) + return out +} + +func contains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false } diff --git a/pkg/cmd/sources/types_test.go b/pkg/cmd/sources/types_test.go index b7c54527..82912bc0 100644 --- a/pkg/cmd/sources/types_test.go +++ b/pkg/cmd/sources/types_test.go @@ -1,7 +1,6 @@ package sources import ( - "fmt" "net/http" "net/http/httptest" "os" @@ -10,127 +9,239 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -const mockOpenAPISpec = ` -{ - "components": { - "schemas": { - "SourceCreateRequest": { - "properties": { - "type": { - "enum": [ - "STRIPE", - "GITHUB", - "TWILIO" - ] - }, - "verification_configs": { - "oneOf": [ - { - "properties": { - "webhook_secret": { - "required": ["secret"] - } - }, - "required": ["webhook_secret"] - }, - { - "properties": { - "api_key": { - "required": ["key"] - } - }, - "required": ["api_key"] - } - ] - } - } - } - } - } +// The fixture (testdata/openapi_source_auth.json, cut from the 2026-09-01 spec) holds, for +// FetchSourceTypes: the SourceTypeConfig umbrella with its x-required markers, and types that +// require verification (AIRCALL, CLOUDSIGNAL, ALIPAY, TIKTOK_SHOP, VERCEL_LOG_DRAINS), types +// where it is optional (STRIPE, GITHUB, POSTMARK, ACUMATICA), types whose config is required +// for a handshake rather than verification (STRAVA, ONFLEET, AZURE_EVENT_GRID), and types +// offering a choice of method (WEBHOOK, HTTP, ...). + +func loadSpecFixture(t *testing.T) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join("testdata", "openapi_source_auth.json")) + require.NoError(t, err) + return data } -` -func TestFetchSourceTypes_Parsing(t *testing.T) { +func parseFixtureSourceTypes(t *testing.T) map[string]SourceType { + t.Helper() + types, err := ParseSourceTypes(loadSpecFixture(t)) + require.NoError(t, err) + return types +} + +func lookup(t *testing.T, types map[string]SourceType, name string) SourceType { + t.Helper() + st, ok := SourceTypeFor(types, name) + require.True(t, ok, "%s is a source type", name) + return st +} + +func TestParseSourceTypesListsEveryTypeConfigSchema(t *testing.T) { + types := parseFixtureSourceTypes(t) + + assert.Len(t, types, 23, "one per SourceTypeConfig schema, not the umbrella") + assert.Equal(t, "PROPERTY-FINDER", lookup(t, types, "PROPERTY-FINDER").Name, + "named as the API spells it, although its schema name drops the hyphen") + assert.Equal(t, "STRIPE", lookup(t, types, " stripe ").Name, "lookup ignores case and spaces") + _, ok := SourceTypeFor(types, "NOT_A_TYPE") + assert.False(t, ok) +} + +func TestParseSourceTypesAuthRules(t *testing.T) { + types := parseFixtureSourceTypes(t) + + tests := []struct { + name string + required bool + fields []string + requiredKeys []string + }{ + // Verification required: x-required, one fixed method with fields. + {"AIRCALL", true, []string{"webhook_secret_key"}, []string{"webhook_secret_key"}}, + {"CLOUDSIGNAL", true, []string{"api_key"}, []string{"api_key"}}, + {"ALIPAY", true, []string{"public_key"}, []string{"public_key"}}, + {"TIKTOK_SHOP", true, []string{"app_key", "webhook_secret_key"}, []string{"app_key", "webhook_secret_key"}}, + {"VERCEL_LOG_DRAINS", true, []string{"webhook_secret_key"}, []string{}}, + + // Verification optional: the fields are still required whenever auth is sent. + {"STRIPE", false, []string{"webhook_secret_key"}, []string{"webhook_secret_key"}}, + {"GITHUB", false, []string{"webhook_secret_key"}, []string{"webhook_secret_key"}}, + {"POSTMARK", false, []string{"password", "username"}, []string{"password", "username"}}, + {"ACUMATICA", false, []string{"api_key", "header_key"}, []string{"api_key", "header_key"}}, + + // x-required for a handshake: STRAVA's auth has no fields, AZURE_EVENT_GRID offers a + // choice of method (the API accepts auth_type null with no auth). + {"STRAVA", false, []string{}, []string{}}, + {"AZURE_EVENT_GRID", false, nil, nil}, + + // A choice of method: fields depend on auth_type, which FetchSourceAuthMethods covers. + {"WEBHOOK", false, nil, nil}, + {"HTTP", false, nil, nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + st := lookup(t, types, tt.name) + assert.Equal(t, tt.required, st.AuthRequired, "AuthRequired") + assert.Equal(t, tt.fields, st.AuthFields, "AuthFields") + assert.Equal(t, tt.requiredKeys, st.RequiredAuthFields, "RequiredAuthFields") + }) + } +} + +// ONFLEET's config is required for its handshake, not verification, but the spec cannot tell +// the two apart for a type whose auth has fields. The cmd package corrects for it; this pins +// the limitation so a spec that starts telling them apart shows up here. +func TestParseSourceTypesReadsOnfleetAsAuthRequired(t *testing.T) { + st := lookup(t, parseFixtureSourceTypes(t), "ONFLEET") + assert.True(t, st.AuthRequired) +} + +func TestParseSourceTypesHonoursRequiredOnTypeSchema(t *testing.T) { + spec := `{"components":{"schemas":{ + "SourceTypeConfigACME":{"x-docs-type":"ACME","required":["auth"],"properties":{"auth":{"$ref":"#/components/schemas/AcmeAuth"}}}, + "AcmeAuth":{"properties":{"token":{"type":"string"}},"required":["token"]} + }}}` + types, err := ParseSourceTypes([]byte(spec)) + require.NoError(t, err) + st := lookup(t, types, "ACME") + assert.True(t, st.AuthRequired, "a required list naming auth counts without x-required") + assert.Equal(t, []string{"token"}, st.RequiredAuthFields) +} + +// The spec shape the previous parser read. It is gone from the API, which is how +// FetchSourceTypes came to return an empty map that the old tests, built on this shape, +// never noticed. +const legacySourceCreateRequestSpec = `{"components":{"schemas":{"SourceCreateRequest":{"properties":{ + "type":{"enum":["STRIPE","GITHUB"]}, + "verification_configs":{"oneOf":[{"properties":{"webhook_secret":{"required":["secret"]}},"required":["webhook_secret"]}]} +}}}}}` + +func TestParseSourceTypesFindsNothingInLegacyShape(t *testing.T) { + types, err := ParseSourceTypes([]byte(legacySourceCreateRequestSpec)) + require.NoError(t, err) + assert.Empty(t, types) +} + +// serveSpec points FetchSourceTypes at a test server returning body (per request, so a test +// can change it) and at a fresh cache directory. It returns the request count and cache path. +func serveSpec(t *testing.T, body *string) (*int, string) { + t.Helper() + requests := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, mockOpenAPISpec) + requests++ + _, _ = w.Write([]byte(*body)) })) - defer server.Close() + t.Cleanup(server.Close) - // Temporarily override the openapiURL to point to the mock server originalURL := openapiURL - defer func() { openapiURL = originalURL }() + t.Cleanup(func() { openapiURL = originalURL }) openapiURL = server.URL - // Clear any existing cache to ensure we hit the mock server - cachePath := filepath.Join(os.TempDir(), cacheFileName) - os.Remove(cachePath) + t.Setenv("TMPDIR", t.TempDir()) // os.TempDir, where the cache lives + return &requests, filepath.Join(os.TempDir(), cacheFileName) +} + +func TestFetchSourceTypesParsesAndCaches(t *testing.T) { + body := string(loadSpecFixture(t)) + requests, cachePath := serveSpec(t, &body) + + first, err := FetchSourceTypes() + require.NoError(t, err) + assert.True(t, lookup(t, first, "AIRCALL").AuthRequired) + assert.Equal(t, 1, *requests) + _, err = os.Stat(cachePath) + require.NoError(t, err, "a good parse is cached") + + second, err := FetchSourceTypes() + require.NoError(t, err) + assert.Equal(t, 1, *requests, "second call is served from the cache") + assert.Equal(t, first, second) + + expired := time.Now().Add(-(cacheTTL + time.Hour)) + require.NoError(t, os.Chtimes(cachePath, expired, expired)) + _, err = FetchSourceTypes() + require.NoError(t, err) + assert.Equal(t, 2, *requests, "an expired cache is refetched") +} - sourceTypes, err := FetchSourceTypes() +func TestFetchSourceTypesDoesNotCacheEmptyOrFailedParse(t *testing.T) { + for name, spec := range map[string]string{ + "no source type schemas": legacySourceCreateRequestSpec, + "invalid JSON": `{"components":`, + } { + t.Run(name, func(t *testing.T) { + body := spec + requests, cachePath := serveSpec(t, &body) + + _, err := FetchSourceTypes() + require.Error(t, err) + _, statErr := os.Stat(cachePath) + assert.True(t, os.IsNotExist(statErr), "nothing is cached") + + body = string(loadSpecFixture(t)) + types, err := FetchSourceTypes() + require.NoError(t, err, "the next call fetches again") + assert.NotEmpty(t, types) + assert.Equal(t, 2, *requests) + }) + } +} - assert.NoError(t, err) - assert.NotNil(t, sourceTypes) - assert.Len(t, sourceTypes, 3) +func TestFetchSourceTypesIgnoresEmptyCacheFile(t *testing.T) { + body := string(loadSpecFixture(t)) + requests, cachePath := serveSpec(t, &body) + // What the SourceCreateRequest parser left behind against the current spec. + require.NoError(t, os.WriteFile(cachePath, []byte("{}"), 0o600)) - // The parsing logic is simplified and has a manual correction for STRIPE, let's test that - stripeType, ok := sourceTypes["STRIPE"] - assert.True(t, ok) - assert.Equal(t, "STRIPE", stripeType.Name) - assert.Equal(t, "webhook_secret", stripeType.AuthScheme) - assert.Equal(t, []string{"secret"}, stripeType.RequiredFields) + types, err := FetchSourceTypes() + require.NoError(t, err) + assert.NotEmpty(t, types) + assert.Equal(t, 1, *requests, "an empty cache file is not served") +} - githubType, ok := sourceTypes["GITHUB"] - assert.True(t, ok) - assert.Equal(t, "GITHUB", githubType.Name) - // This assertion depends on the simplified parsing logic which assigns the first scheme found - assert.Equal(t, "webhook_secret", githubType.AuthScheme) +// Source types and auth methods are two views of one spec, so a cold start downloads it once, +// whichever is read first. +func TestSourceTypesAndAuthMethodsShareOneDownload(t *testing.T) { + for name, first := range map[string]func() error{ + "types first": func() error { _, err := FetchSourceTypes(); return err }, + "methods first": func() error { _, err := FetchSourceAuthMethods(); return err }, + } { + t.Run(name, func(t *testing.T) { + body := string(loadSpecFixture(t)) + requests, _ := serveSpec(t, &body) + + require.NoError(t, first()) + types, err := FetchSourceTypes() + require.NoError(t, err) + methods, err := FetchSourceAuthMethods() + require.NoError(t, err) + assert.NotEmpty(t, types) + assert.NotEmpty(t, methods) + assert.Equal(t, 1, *requests) + }) + } } -func TestFetchSourceTypes_Caching(t *testing.T) { - requestCount := 0 +// A spec server that never answers must not hang a command: the download gives up. +func TestDownloadOpenAPISpecTimesOut(t *testing.T) { + release := make(chan struct{}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount++ - fmt.Fprint(w, mockOpenAPISpec) + <-release })) - defer server.Close() + t.Cleanup(func() { close(release); server.Close() }) - // Temporarily override the openapiURL - originalURL := openapiURL - defer func() { openapiURL = originalURL }() + originalURL, originalClient := openapiURL, specClient + t.Cleanup(func() { openapiURL, specClient = originalURL, originalClient }) openapiURL = server.URL + specClient = &http.Client{Timeout: 100 * time.Millisecond} - cachePath := filepath.Join(os.TempDir(), cacheFileName) - os.Remove(cachePath) // Ensure no cache from previous runs - - // 1. First call: should fetch from the server and create a cache file - sourceTypes1, err1 := FetchSourceTypes() - assert.NoError(t, err1) - assert.NotNil(t, sourceTypes1) - assert.Equal(t, 1, requestCount, "Server should be hit on the first call") - - // Verify cache file was created - _, err := os.Stat(cachePath) - assert.NoError(t, err, "Cache file should exist after the first call") - - // 2. Second call: should load from cache, not hit the server - sourceTypes2, err2 := FetchSourceTypes() - assert.NoError(t, err2) - assert.NotNil(t, sourceTypes2) - assert.Equal(t, 1, requestCount, "Server should not be hit on the second call") - assert.Equal(t, sourceTypes1, sourceTypes2, "Data from cache should match original data") - - // 3. Third call: after cache expires, should hit the server again - // Manually set the modification time of the cache file to be older than the TTL - oldTime := time.Now().Add(-(cacheTTL + time.Hour)) - err = os.Chtimes(cachePath, oldTime, oldTime) - assert.NoError(t, err) - - sourceTypes3, err3 := FetchSourceTypes() - assert.NoError(t, err3) - assert.NotNil(t, sourceTypes3) - assert.Equal(t, 2, requestCount, "Server should be hit again after cache expires") - - // Cleanup - os.Remove(cachePath) + start := time.Now() + _, err := downloadOpenAPISpec() + require.Error(t, err) + assert.Less(t, time.Since(start), 5*time.Second) + assert.Equal(t, 10*time.Second, originalClient.Timeout, "the shipped client carries the timeout") } diff --git a/pkg/gateway/mcp/tool_connections.go b/pkg/gateway/mcp/tool_connections.go index c72966d0..16684e04 100644 --- a/pkg/gateway/mcp/tool_connections.go +++ b/pkg/gateway/mcp/tool_connections.go @@ -65,11 +65,14 @@ var connectionsSpec = mcpcore.ToolSpec{ "description": {Type: "string", Desc: "Connection description (create/upsert/update)", Write: true, Actions: []string{"create", "upsert", "update"}}, "source_id": {Type: "string", Desc: "Source ID.", Actions: []string{"list", "create", "upsert", "update"}, ActionNotes: []mcpcore.ActionNote{ {On: []string{"list"}, Text: "Filters on %s."}, - {On: []string{"create", "upsert", "update"}, Text: "Links the source on %s."}, + {On: []string{"create"}, Text: "Links the source on %s."}, + {On: []string{"upsert"}, Text: "Links the source on %s. Upsert keys on source and name, so a different source_id addresses a different connection with the same name rather than re-pointing the existing one."}, + {On: []string{"update"}, Text: "On %s it must match the source the connection already has: update cannot change it, and a different value is rejected."}, }}, "destination_id": {Type: "string", Desc: "Destination ID.", Actions: []string{"list", "create", "upsert", "update"}, ActionNotes: []mcpcore.ActionNote{ {On: []string{"list"}, Text: "Filters on %s."}, - {On: []string{"create", "upsert", "update"}, Text: "Links the destination on %s."}, + {On: []string{"create"}, Text: "Links the destination on %s."}, + {On: []string{"upsert", "update"}, Text: "On %s it must match the destination the connection already has: an existing connection's destination cannot be changed, and a different value is rejected."}, }}, "rules": {Type: "array", Desc: "Ruleset applied to the connection (create/upsert/update). Array of rule objects; replaces the stored ruleset. Order matters: filter, transform and deduplicate rules run in array order, so send the full array in the intended order.", Items: &mcpcore.Prop{Type: "object"}, Write: true, Actions: []string{"create", "upsert", "update"}}, "disabled": {Type: "boolean", Desc: "Filter disabled connections (list)", Only: []string{mcpcore.GroupRead}, Actions: []string{"list"}}, @@ -196,6 +199,27 @@ func connectionsUpsert(ctx context.Context, client *hookdeck.Client, in mcpcore. if err != nil { return mcpcore.ErrorResult(err.Error()), nil } + // Upsert never re-points an existing connection's destination, so a + // different destination_id would be dropped and the call reported as a + // success (#466). Compare against the stored connection before writing. + if req.DestinationID != nil { + candidates, err := client.FindConnectionsByName(ctx, *req.Name) + if err != nil { + return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil + } + // A different source_id addresses a different connection with the same + // name (the endpoint keys on source and name), which may have any + // destination. + existing, sameConnection, err := hookdeck.SelectConnectionForUpsert(candidates, *req.Name, derefString(req.SourceID), "") + if err != nil { + return mcpcore.ErrorResult(err.Error()), nil + } + if sameConnection { + if err := hookdeck.CheckConnectionSidesUnchanged(existing, "", "", derefString(req.DestinationID), ""); err != nil { + return mcpcore.ErrorResult(err.Error()), nil + } + } + } conn, err := client.UpsertConnection(ctx, req) if err != nil { return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil @@ -203,6 +227,13 @@ func connectionsUpsert(ctx context.Context, client *hookdeck.Client, in mcpcore. return mcpcore.JSONResultEnvelopeForClient(conn, client) } +func derefString(p *string) string { + if p == nil { + return "" + } + return *p +} + func connectionsUpdate(ctx context.Context, client *hookdeck.Client, in mcpcore.Input) (*mcpsdk.CallToolResult, error) { id, err := connectionIDFromInput(ctx, client, in, "update") if err != nil { @@ -212,6 +243,19 @@ func connectionsUpdate(ctx context.Context, client *hookdeck.Client, in mcpcore. if err != nil { return mcpcore.ErrorResult(err.Error()), nil } + // PUT /connections/{id} drops source_id and destination_id, so a different + // value would be reported as applied when it was not (#466). + if req.SourceID != nil || req.DestinationID != nil { + current, err := client.GetConnection(ctx, id) + if err != nil { + return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil + } + if err := hookdeck.CheckConnectionSidesUnchanged(current, derefString(req.SourceID), "", derefString(req.DestinationID), ""); err != nil { + return mcpcore.ErrorResult(err.Error()), nil + } + // Equal to the stored value: nothing to send. + req.SourceID, req.DestinationID = nil, nil + } conn, err := client.UpdateConnection(ctx, id, req) if err != nil { return mcpcore.ErrorResult(mcpcore.TranslateAPIError(err)), nil diff --git a/pkg/gateway/mcp/write_actions_test.go b/pkg/gateway/mcp/write_actions_test.go index c5bab79d..8225bcf9 100644 --- a/pkg/gateway/mcp/write_actions_test.go +++ b/pkg/gateway/mcp/write_actions_test.go @@ -214,8 +214,9 @@ func TestConnectionsUpdateSendsAnExplicitlyEmptyRuleset(t *testing.T) { // Upsert keys on the name, so it goes to the collection rather than to an id, // and a POST here would create a duplicate on every call. func TestConnectionsUpsertIsAPutToTheCollection(t *testing.T) { - var got wireRequest + var got, lookup wireRequest session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections": ok(&lookup, listResponse()), "PUT /2026-09-01/connections": ok(&got, connectionBody()), }) @@ -1668,3 +1669,118 @@ func contains(haystack []string, needle string) bool { } return false } + +// storedConnection is a connection with the sides the guard tests compare +// against. +func storedConnection() map[string]any { + return map[string]any{ + "id": "web_1", "name": "stripe-to-backend", + "source": map[string]any{"id": "src_1", "name": "stripe"}, + "destination": map[string]any{"id": "des_1", "name": "backend"}, + } +} + +// The API never re-points an existing connection, so a different source_id or +// destination_id has to be refused before the write rather than dropped and +// reported as applied (#466). The write handler fails the test if it is hit. +func TestConnectionsUpsertRejectsAChangedSide(t *testing.T) { + for _, tc := range []struct { + name string + args map[string]any + want string + }{ + {"destination", map[string]any{"source_id": "src_1", "destination_id": "des_other"}, "destination"}, + } { + tc := tc + t.Run(tc.name, func(t *testing.T) { + var lookup wireRequest + session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections": ok(&lookup, listResponse(storedConnection())), + "PUT /2026-09-01/connections": func(w http.ResponseWriter, r *http.Request) { + t.Errorf("a rejected change must not reach the API: %s %s", r.Method, r.URL.Path) + }, + }) + args := map[string]any{"action": "upsert", "name": "stripe-to-backend"} + for k, v := range tc.args { + args[k] = v + } + + result := callTool(t, session, "gateway_connections_write", args) + + require.True(t, result.IsError) + assert.Contains(t, textContent(t, result), "cannot be changed") + assert.Contains(t, textContent(t, result), tc.want) + assert.Contains(t, lookup.query, "name=stripe-to-backend") + }) + } +} + +// Unlike the destination, the API does re-point an existing connection's source +// on upsert (checked against the live API), so that must not be refused. +func TestConnectionsUpsertCanChangeTheSource(t *testing.T) { + var got, lookup wireRequest + session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections": ok(&lookup, listResponse(storedConnection())), + "PUT /2026-09-01/connections": ok(&got, connectionBody()), + }) + + succeeds(t, session, "gateway_connections_write", map[string]any{ + "action": "upsert", "name": "stripe-to-backend", "source_id": "src_other", "destination_id": "des_1", + }) + + assert.Equal(t, "src_other", got.decodeBody(t)["source_id"]) +} + +// Negative control: the stored IDs go through. +func TestConnectionsUpsertAcceptsTheStoredSides(t *testing.T) { + var got, lookup wireRequest + session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections": ok(&lookup, listResponse(storedConnection())), + "PUT /2026-09-01/connections": ok(&got, connectionBody()), + }) + + succeeds(t, session, "gateway_connections_write", map[string]any{ + "action": "upsert", "name": "stripe-to-backend", "source_id": "src_1", "destination_id": "des_1", + }) + + assert.Equal(t, http.MethodPut, got.method) +} + +func TestConnectionsUpdateRejectsAChangedSide(t *testing.T) { + for _, key := range []string{"source_id", "destination_id"} { + key := key + t.Run(key, func(t *testing.T) { + session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections/web_1": ok(&wireRequest{}, storedConnection()), + "PUT /2026-09-01/connections/web_1": func(w http.ResponseWriter, r *http.Request) { + t.Errorf("a rejected change must not reach the API: %s %s", r.Method, r.URL.Path) + }, + }) + + result := callTool(t, session, "gateway_connections_write", map[string]any{ + "action": "update", "id": "web_1", key: "other_id", + }) + + require.True(t, result.IsError) + assert.Contains(t, textContent(t, result), "cannot be changed") + }) + } +} + +// Negative control: stored IDs are accepted and are not sent. +func TestConnectionsUpdateAcceptsTheStoredSides(t *testing.T) { + var got wireRequest + session := writeSession(t, map[string]http.HandlerFunc{ + "GET /2026-09-01/connections/web_1": ok(&wireRequest{}, storedConnection()), + "PUT /2026-09-01/connections/web_1": ok(&got, connectionBody()), + }) + + succeeds(t, session, "gateway_connections_write", map[string]any{ + "action": "update", "id": "web_1", "source_id": "src_1", "destination_id": "des_1", "description": "d", + }) + + body := got.decodeBody(t) + assert.Equal(t, "d", body["description"]) + assert.NotContains(t, body, "source_id") + assert.NotContains(t, body, "destination_id") +} diff --git a/pkg/hookdeck/connection_select_test.go b/pkg/hookdeck/connection_select_test.go new file mode 100644 index 00000000..435517a0 --- /dev/null +++ b/pkg/hookdeck/connection_select_test.go @@ -0,0 +1,57 @@ +package hookdeck + +import "testing" + +func connectionOn(id, name, sourceID, sourceName, destinationID string) Connection { + return Connection{ + ID: id, + Name: stringPtr(name), + Source: &Source{ID: sourceID, Name: sourceName}, + Destination: &Destination{ID: destinationID, Name: destinationID}, + } +} + +func TestSelectConnectionForUpsert(t *testing.T) { + t.Parallel() + + a := connectionOn("web_a", "orders", "src_a", "src-a", "des_a") + b := connectionOn("web_b", "orders", "src_b", "src-b", "des_b") + + tests := []struct { + name string + candidates []Connection + sourceID string + sourceName string + wantID string + wantSame bool + wantErr bool + }{ + {name: "no candidates", candidates: nil}, + {name: "one candidate and no source named", candidates: []Connection{a}, wantID: "web_a", wantSame: true}, + {name: "several candidates and no source named is ambiguous", candidates: []Connection{a, b}, wantErr: true}, + {name: "source named by ID picks the connection on it", candidates: []Connection{a, b}, sourceID: "src_b", wantID: "web_b", wantSame: true}, + {name: "source named by name picks the connection on it", candidates: []Connection{a, b}, sourceName: "src-a", wantID: "web_a", wantSame: true}, + {name: "a source no candidate uses is a different connection", candidates: []Connection{a}, sourceID: "src_other", wantID: "web_a", wantSame: false}, + {name: "a source name no candidate uses is a different connection", candidates: []Connection{a}, sourceName: "src-other", wantID: "web_a", wantSame: false}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, same, err := SelectConnectionForUpsert(tt.candidates, "orders", tt.sourceID, tt.sourceName) + if (err != nil) != tt.wantErr { + t.Fatalf("err = %v, wantErr %v", err, tt.wantErr) + } + if tt.wantID == "" { + if got != nil { + t.Fatalf("got %s, want none", got.ID) + } + return + } + if got == nil || got.ID != tt.wantID || same != tt.wantSame { + t.Fatalf("got %+v same=%v, want %s same=%v", got, same, tt.wantID, tt.wantSame) + } + }) + } +} diff --git a/pkg/hookdeck/connection_sides.go b/pkg/hookdeck/connection_sides.go new file mode 100644 index 00000000..e59734ca --- /dev/null +++ b/pkg/hookdeck/connection_sides.go @@ -0,0 +1,85 @@ +package hookdeck + +import "fmt" + +// CheckConnectionSidesUnchanged returns an error when a requested source or +// destination differs from the one the connection already has. +// +// The API never re-points an existing connection: a PUT with a different +// source_id or destination_id, or an inline destination with a different name, +// is accepted and the stored side is left as it was. The caller would then see +// success for a change that did not happen, and an inline destination would be +// upserted and left attached to nothing. Run this before any write. +// +// Each side is identified by ID or by name; an empty value means that side was +// not mentioned and is not checked. Names are compared exactly, as they are +// when the API resolves them. +func CheckConnectionSidesUnchanged(existing *Connection, sourceID, sourceName, destinationID, destinationName string) error { + if existing == nil { + return nil + } + label := existing.ID + if existing.Name != nil { + label = fmt.Sprintf("%s (%s)", *existing.Name, existing.ID) + } + + if existing.Source != nil { + if sourceID != "" && sourceID != existing.Source.ID { + return sideChangeError("source", label, existing.Source.Name, existing.Source.ID, sourceID) + } + if sourceName != "" && sourceName != existing.Source.Name { + return sideChangeError("source", label, existing.Source.Name, existing.Source.ID, sourceName) + } + } + if existing.Destination != nil { + if destinationID != "" && destinationID != existing.Destination.ID { + return sideChangeError("destination", label, existing.Destination.Name, existing.Destination.ID, destinationID) + } + if destinationName != "" && destinationName != existing.Destination.Name { + return sideChangeError("destination", label, existing.Destination.Name, existing.Destination.ID, destinationName) + } + } + return nil +} + +func sideChangeError(side, connection, currentName, currentID, requested string) error { + return fmt.Errorf( + "connection %s already uses %s %s (%s), and a connection's %s cannot be changed; %q was not applied and nothing was created or modified. "+ + "To use a different %s, create a new connection, or delete this one and recreate it", + connection, side, currentName, currentID, side, requested, side) +} + +// SelectConnectionForUpsert picks the stored connection an upsert refers to from +// the connections that share its name. +// +// The upsert endpoint identifies a connection by source and name together, so +// naming a different source is a request for a different connection - the +// endpoint creates one beside the existing one rather than re-pointing it. In +// that case the stored connection is returned with sameConnection false, and +// the caller must not hold the request to the stored connection's destination. +// +// With no source named, one match is the connection; several are ambiguous, and +// guessing between them would update the wrong one. +func SelectConnectionForUpsert(candidates []Connection, name, sourceID, sourceName string) (existing *Connection, sameConnection bool, err error) { + if len(candidates) == 0 { + return nil, false, nil + } + if sourceID == "" && sourceName == "" { + if len(candidates) > 1 { + return nil, false, fmt.Errorf( + "%d connections are named %q, on different sources; name the one to upsert with --source-id or --source-name", + len(candidates), name) + } + return &candidates[0], true, nil + } + for i := range candidates { + src := candidates[i].Source + if src == nil { + continue + } + if (sourceID != "" && src.ID == sourceID) || (sourceName != "" && src.Name == sourceName) { + return &candidates[i], true, nil + } + } + return &candidates[0], false, nil +} diff --git a/pkg/hookdeck/connections.go b/pkg/hookdeck/connections.go index a61373e6..a2530f5e 100644 --- a/pkg/hookdeck/connections.go +++ b/pkg/hookdeck/connections.go @@ -86,6 +86,44 @@ func (c *Client) ListConnections(ctx context.Context, params map[string]string) return &result, nil } +// FindConnectionByName returns the connection whose name is exactly name, or nil +// when there is none. +// +// The list endpoint's name filter is an exact, case-sensitive match today, but +// its documentation only says "Filter by connection name". Taking the first +// result unchecked would let a partial or differently-cased match stand in for +// the connection the caller named, and an upsert would then update the wrong +// one, so the name is compared again here. +func (c *Client) FindConnectionByName(ctx context.Context, name string) (*Connection, error) { + matches, err := c.FindConnectionsByName(ctx, name) + if err != nil || len(matches) == 0 { + return nil, err + } + return &matches[0], nil +} + +// FindConnectionsByName returns every connection whose name is exactly name. +// +// More than one can match: a connection name is only unique per source, so the +// same name under two sources is two connections. Use SelectConnectionForUpsert +// to pick the one an upsert refers to. +func (c *Client) FindConnectionsByName(ctx context.Context, name string) ([]Connection, error) { + result, err := c.ListConnections(ctx, map[string]string{"name": name}) + if err != nil { + return nil, err + } + if result == nil { + return nil, nil + } + var matches []Connection + for _, m := range result.Models { + if m.Name != nil && *m.Name == name { + matches = append(matches, m) + } + } + return matches, nil +} + // GetConnection retrieves a single connection by ID func (c *Client) GetConnection(ctx context.Context, id string) (*Connection, error) { path, err := apiPath("connections", id) diff --git a/pkg/hookdeck/connections_find_test.go b/pkg/hookdeck/connections_find_test.go new file mode 100644 index 00000000..325cd865 --- /dev/null +++ b/pkg/hookdeck/connections_find_test.go @@ -0,0 +1,62 @@ +package hookdeck + +import ( + "context" + "encoding/json" + "net/http" + "testing" +) + +// TestFindConnectionByNameRequiresExactMatch pins that the name comparison is +// made here as well as by the API. The stub answers every query with the same +// list, standing in for an API whose name filter matched loosely. +func TestFindConnectionByNameRequiresExactMatch(t *testing.T) { + t.Parallel() + + returned := []Connection{ + {ID: "web_partial", Name: stringPtr("orders-extra")}, + {ID: "web_case", Name: stringPtr("Orders")}, + {ID: "web_unnamed"}, + {ID: "web_exact", Name: stringPtr("orders")}, + } + + tests := []struct { + name string + models []Connection + wantID string + wantNil bool + }{ + {name: "exact match among loose ones is chosen", models: returned, wantID: "web_exact"}, + {name: "partial and case-different matches alone are not a match", models: returned[:3], wantNil: true}, + {name: "empty result", models: nil, wantNil: true}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + client, server := newTestClient(func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("name"); got != "orders" { + t.Errorf("name filter = %q, want %q", got, "orders") + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(ConnectionListResponse{Models: tt.models}) + }) + defer server.Close() + + got, err := client.FindConnectionByName(context.Background(), "orders") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if tt.wantNil { + if got != nil { + t.Fatalf("got %s, want no connection", got.ID) + } + return + } + if got == nil || got.ID != tt.wantID { + t.Fatalf("got %+v, want %s", got, tt.wantID) + } + }) + } +} diff --git a/test/acceptance/connection_test.go b/test/acceptance/connection_test.go index e1561680..df4d8559 100644 --- a/test/acceptance/connection_test.go +++ b/test/acceptance/connection_test.go @@ -3036,3 +3036,90 @@ func TestConnectionDeleteWithoutForceFailsNonInteractively(t *testing.T) { require.NoError(t, cli.RunJSON(&check, "gateway", "connection", "get", connID)) assert.Equal(t, connID, check.ID, "connection must not have been deleted") } + +// connectionSourceAuthType returns the source's config.auth_type for a connection. +func connectionSourceAuthType(t *testing.T, cli *CLIRunner, connID string) string { + t.Helper() + var resp map[string]interface{} + require.NoError(t, cli.RunJSON(&resp, "gateway", "connection", "get", connID, "--include-source-auth")) + source, ok := resp["source"].(map[string]interface{}) + require.True(t, ok, "connection response must include source") + config, ok := source["config"].(map[string]interface{}) + require.True(t, ok, "source must include config") + authType, _ := config["auth_type"].(string) + return authType +} + +// TestConnectionUpsertWebhookSourceAuthFlags covers --source-* auth flags on a WEBHOOK source. +// The API rejects config.auth on WEBHOOK without config.auth_type ("source.config.auth is not +// allowed"), so the CLI must send it - on create, and on a partial update of an existing +// connection, where the stored auth_type comes back without the credentials. +func TestConnectionUpsertWebhookSourceAuthFlags(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + timestamp := generateTimestamp() + connName := "test-webhook-auth-conn-" + timestamp + + var conn Connection + err := cli.RunJSON(&conn, "gateway", "connection", "upsert", connName, + "--source-name", "test-webhook-auth-src-"+timestamp, + "--source-type", "WEBHOOK", + "--source-api-key", "test_key_abc123", + "--destination-name", "test-webhook-auth-dst-"+timestamp, + "--destination-type", "HTTP", + "--destination-url", "https://api.example.com/webhook") + require.NoError(t, err, "WEBHOOK source with --source-api-key should be accepted") + require.NotEmpty(t, conn.ID) + t.Cleanup(func() { deleteConnection(t, cli, conn.ID) }) + assert.Equal(t, "API_KEY", connectionSourceAuthType(t, cli, conn.ID)) + + // Partial update: only source auth flags, no --source-name/--source-type. + err = cli.RunJSON(&conn, "gateway", "connection", "upsert", connName, + "--source-basic-auth-user", "user", "--source-basic-auth-pass", "pass") + require.NoError(t, err, "switching the source's auth method on an existing connection should be accepted") + assert.Equal(t, "BASIC_AUTH", connectionSourceAuthType(t, cli, conn.ID)) + + // Partial update of a non-auth field keeps the stored method. + err = cli.RunJSON(&conn, "gateway", "connection", "upsert", connName, + "--source-allowed-http-methods", "POST,PUT") + require.NoError(t, err, "a non-auth source update on an authenticated source should be accepted") + assert.Equal(t, "BASIC_AUTH", connectionSourceAuthType(t, cli, conn.ID)) +} + +// TestConnectionRetryResponseStatusCodeExpressions verifies --rule-retry-response-status-codes +// accepts the API's expressions (ranges, exclusions), not only integer codes. +func TestConnectionRetryResponseStatusCodeExpressions(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + timestamp := generateTimestamp() + + var conn Connection + err := cli.RunJSON(&conn, "gateway", "connection", "create", + "--name", "test-retry-expr-"+timestamp, + "--source-name", "test-retry-expr-src-"+timestamp, + "--source-type", "WEBHOOK", + "--destination-name", "test-retry-expr-dst-"+timestamp, + "--destination-type", "HTTP", + "--destination-url", "https://api.example.com/webhook", + "--rule-retry-strategy", "linear", + "--rule-retry-count", "3", + "--rule-retry-interval", "5000", + "--rule-retry-response-status-codes", "429,500-599,!501") + require.NoError(t, err, "retry status code expressions should be accepted") + require.NotEmpty(t, conn.ID) + t.Cleanup(func() { deleteConnection(t, cli, conn.ID) }) + + for _, rule := range conn.Rules { + if rule["type"] == "retry" { + assertResponseStatusCodesMatch(t, rule["response_status_codes"], "429", "500-599", "!501") + return + } + } + t.Fatal("expected a retry rule") +} diff --git a/test/acceptance/connection_update_ignored_changes_test.go b/test/acceptance/connection_update_ignored_changes_test.go new file mode 100644 index 00000000..39dca1a2 --- /dev/null +++ b/test/acceptance/connection_update_ignored_changes_test.go @@ -0,0 +1,62 @@ +//go:build connection_update + +package acceptance + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConnectionUpdateRejectsChangedSides covers #466: PUT /connections/{id} +// discards source_id and destination_id, so update used to print success and the +// old destination for a change that never happened. +func TestConnectionUpdateRejectsChangedSides(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + + connID := createTestConnection(t, cli) + t.Cleanup(func() { deleteConnection(t, cli, connID) }) + + var conn Connection + require.NoError(t, cli.RunJSON(&conn, "gateway", "connection", "get", connID)) + + otherDestID := createTestDestination(t, cli) + t.Cleanup(func() { deleteDestination(t, cli, otherDestID) }) + otherSourceID := createTestSource(t, cli) + t.Cleanup(func() { deleteSource(t, cli, otherSourceID) }) + + t.Run("a different destination ID is rejected", func(t *testing.T) { + stdout, stderr, err := cli.Run("gateway", "connection", "update", connID, "--destination-id", otherDestID) + require.Error(t, err, "stdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Equal(t, conn.Destination.ID, after.Destination.ID) + }) + + t.Run("a different source ID is rejected", func(t *testing.T) { + stdout, stderr, err := cli.Run("gateway", "connection", "update", connID, "--source-id", otherSourceID) + require.Error(t, err, "stdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Equal(t, conn.Source.ID, after.Source.ID) + }) + + t.Run("the stored IDs are accepted and other changes still apply", func(t *testing.T) { + // Negative control: the guard rejects a difference, not the flags. + var updated Connection + require.NoError(t, cli.RunJSON(&updated, "gateway", "connection", "update", connID, + "--destination-id", conn.Destination.ID, "--source-id", conn.Source.ID, + "--description", "same sides")) + assert.Equal(t, "same sides", updated.Description) + assert.Equal(t, conn.Destination.ID, updated.Destination.ID) + }) +} diff --git a/test/acceptance/connection_upsert_empty_rules_test.go b/test/acceptance/connection_upsert_empty_rules_test.go new file mode 100644 index 00000000..a053d1cf --- /dev/null +++ b/test/acceptance/connection_upsert_empty_rules_test.go @@ -0,0 +1,76 @@ +//go:build connection_upsert + +package acceptance + +import ( + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConnectionUpsertEmptyRulesClearsRules covers #472: --rules '[]' has to +// reach the API as an empty array, as it does for `connection update`. +func TestConnectionUpsertEmptyRulesClearsRules(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + + connID := createTestConnection(t, cli) + t.Cleanup(func() { deleteConnection(t, cli, connID) }) + + var conn Connection + require.NoError(t, cli.RunJSON(&conn, "gateway", "connection", "get", connID)) + + rulesJSON := `[{"type":"retry","strategy":"linear","count":2,"interval":60000}]` + require.NoError(t, cli.RunJSON(&Connection{}, "gateway", "connection", "upsert", conn.Name, "--rules", rulesJSON)) + + var withRules Connection + require.NoError(t, cli.RunJSON(&withRules, "gateway", "connection", "get", connID)) + require.Len(t, withRules.Rules, 1, "setup: the connection must have a rule to clear") + + t.Run("dry-run says the rules will be cleared and changes nothing", func(t *testing.T) { + stdout := cli.RunExpectSuccess("gateway", "connection", "upsert", conn.Name, "--rules", "[]", "--dry-run") + assert.Contains(t, stdout, "will be cleared") + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Len(t, after.Rules, 1, "a dry run must not clear the rules") + }) + + t.Run("an upsert without a rules flag leaves the rules alone", func(t *testing.T) { + // Negative control: only an explicit empty array clears. + require.NoError(t, cli.RunJSON(&Connection{}, "gateway", "connection", "upsert", conn.Name, "--description", "no rules flag")) + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Len(t, after.Rules, 1, "omitting --rules must keep the stored rules") + }) + + t.Run("--rules '[]' clears them", func(t *testing.T) { + require.NoError(t, cli.RunJSON(&Connection{}, "gateway", "connection", "upsert", conn.Name, "--rules", "[]")) + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Empty(t, after.Rules, "the empty array must clear the ruleset") + }) + + t.Run("--rules-file with an empty array clears them", func(t *testing.T) { + require.NoError(t, cli.RunJSON(&Connection{}, "gateway", "connection", "upsert", conn.Name, "--rules", rulesJSON)) + var restored Connection + require.NoError(t, cli.RunJSON(&restored, "gateway", "connection", "get", connID)) + require.Len(t, restored.Rules, 1, "setup: the rule must be back") + + path := t.TempDir() + "/rules.json" + require.NoError(t, os.WriteFile(path, []byte("[]"), 0644)) + require.NoError(t, cli.RunJSON(&Connection{}, "gateway", "connection", "upsert", conn.Name, "--rules-file", path)) + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Empty(t, after.Rules, fmt.Sprintf("--rules-file with [] must clear the ruleset: %+v", after.Rules)) + }) +} diff --git a/test/acceptance/connection_upsert_ignored_changes_test.go b/test/acceptance/connection_upsert_ignored_changes_test.go new file mode 100644 index 00000000..94377b5c --- /dev/null +++ b/test/acceptance/connection_upsert_ignored_changes_test.go @@ -0,0 +1,132 @@ +//go:build connection_upsert + +package acceptance + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// listDestinationsByName returns the destinations the API lists for an exact +// name filter. +func listDestinationsByName(t *testing.T, cli *CLIRunner, name string) []Destination { + t.Helper() + var resp struct { + Models []Destination `json:"models"` + } + require.NoError(t, cli.RunJSON(&resp, "gateway", "destination", "list", "--name", name)) + return resp.Models +} + +// TestConnectionUpsertRejectsChangedDestination covers #466: the API never +// changes an existing connection's destination, so upsert has to fail rather +// than report success, and it has to fail before the inline destination is +// upserted, or that destination is left behind attached to nothing. +func TestConnectionUpsertRejectsChangedDestination(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + + connID := createTestConnection(t, cli) + t.Cleanup(func() { deleteConnection(t, cli, connID) }) + + var conn Connection + require.NoError(t, cli.RunJSON(&conn, "gateway", "connection", "get", connID)) + + t.Run("inline destination with a different name creates no orphan", func(t *testing.T) { + orphanName := "test-orphan-dst-" + generateTimestamp() + + stdout, stderr, err := cli.Run("gateway", "connection", "upsert", conn.Name, + "--source-name", conn.Source.Name, "--source-type", "WEBHOOK", + "--destination-name", orphanName, "--destination-type", "CLI", + "--destination-cli-path", "/elsewhere") + require.Error(t, err, "changing the destination must fail\nstdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + + // The destination was not created ... + assert.Empty(t, listDestinationsByName(t, cli, orphanName), "no orphan destination may be created") + // ... and the filter does find a destination that exists, so the empty + // result above is not the filter matching nothing. + assert.Len(t, listDestinationsByName(t, cli, conn.Destination.Name), 1, + "negative control: the stored destination must be listed by the same filter") + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Equal(t, conn.Destination.ID, after.Destination.ID, "destination must be unchanged") + }) + + t.Run("a different destination ID is rejected", func(t *testing.T) { + otherID := createTestDestination(t, cli) + t.Cleanup(func() { deleteDestination(t, cli, otherID) }) + + stdout, stderr, err := cli.Run("gateway", "connection", "upsert", conn.Name, + "--source-id", conn.Source.ID, "--destination-id", otherID) + require.Error(t, err, "changing the destination must fail\nstdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + + var after Connection + require.NoError(t, cli.RunJSON(&after, "gateway", "connection", "get", connID)) + assert.Equal(t, conn.Destination.ID, after.Destination.ID, "destination must be unchanged") + }) + + t.Run("a different destination ID alone is rejected", func(t *testing.T) { + otherID := createTestDestination(t, cli) + t.Cleanup(func() { deleteDestination(t, cli, otherID) }) + + // Before the fix this reached the API without a source and came back as a + // 422 about source_id. + stdout, stderr, err := cli.Run("gateway", "connection", "upsert", conn.Name, "--destination-id", otherID) + require.Error(t, err, "stdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + }) + + t.Run("dry-run reports the problem too", func(t *testing.T) { + otherID := createTestDestination(t, cli) + t.Cleanup(func() { deleteDestination(t, cli, otherID) }) + + stdout, stderr, err := cli.Run("gateway", "connection", "upsert", conn.Name, + "--source-id", conn.Source.ID, "--destination-id", otherID, "--dry-run") + require.Error(t, err, "stdout: %s", stdout) + assert.Contains(t, stderr+stdout, "cannot be changed") + }) + + t.Run("a different source is a different connection and is not refused", func(t *testing.T) { + // Negative control for the whole guard. A connection name is only unique + // per source, so upsert with another source creates a second connection + // with the same name; it does not re-point the stored one, and refusing + // it would block a working feature. + newSource := "test-upsert-newsrc-" + generateTimestamp() + var created Connection + require.NoError(t, cli.RunJSON(&created, "gateway", "connection", "upsert", conn.Name, + "--source-name", newSource, "--source-type", "WEBHOOK")) + t.Cleanup(func() { deleteConnection(t, cli, created.ID) }) + + assert.NotEqual(t, connID, created.ID, "a different source must not re-point the stored connection") + assert.Equal(t, newSource, created.Source.Name) + + var stored Connection + require.NoError(t, cli.RunJSON(&stored, "gateway", "connection", "get", connID)) + assert.Equal(t, conn.Source.ID, stored.Source.ID, "the stored connection keeps its source") + }) + + t.Run("the stored destination is still accepted", func(t *testing.T) { + // Negative control: the guard rejects a difference, not every upsert that + // names a destination. + var upserted Connection + require.NoError(t, cli.RunJSON(&upserted, "gateway", "connection", "upsert", conn.Name, + "--source-id", conn.Source.ID, "--destination-id", conn.Destination.ID, + "--description", "same destination")) + assert.Equal(t, conn.Destination.ID, upserted.Destination.ID) + + var byName Connection + require.NoError(t, cli.RunJSON(&byName, "gateway", "connection", "upsert", conn.Name, + "--source-name", conn.Source.Name, "--source-type", "WEBHOOK", + "--destination-name", conn.Destination.Name, "--destination-type", "CLI", + "--destination-cli-path", "/updated")) + assert.Equal(t, conn.Destination.ID, byName.Destination.ID) + }) +} diff --git a/test/acceptance/connection_upsert_test.go b/test/acceptance/connection_upsert_test.go index d7b54716..eff88609 100644 --- a/test/acceptance/connection_upsert_test.go +++ b/test/acceptance/connection_upsert_test.go @@ -376,6 +376,67 @@ func TestConnectionUpsertPartialUpdates(t *testing.T) { t.Logf("Successfully upserted connection %s with source-name only", connID) }) + // An inline source (name + type + auth) with no destination flags used to + // skip the connection lookup, so the PUT carried no destination and the API + // answered 422 "value must contain at least one of [destination_id, destination]". + t.Run("UpsertInlineSourceWithoutDestinationFlagsKeepsDestination", func(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + timestamp := generateTimestamp() + + connName := "test-upsert-srcinline-" + timestamp + sourceName := "test-upsert-src-si-" + timestamp + destName := "test-upsert-dst-si-" + timestamp + destURL := "https://api.example.com/webhook" + + var createResp map[string]interface{} + err := cli.RunJSON(&createResp, + "gateway", "connection", "create", + "--name", connName, + "--source-type", "WEBHOOK", + "--source-name", sourceName, + "--destination-type", "HTTP", + "--destination-name", destName, + "--destination-url", destURL, + ) + require.NoError(t, err, "Should create connection") + + connID, ok := createResp["id"].(string) + require.True(t, ok && connID != "", "Expected connection ID") + + t.Cleanup(func() { + deleteConnection(t, cli, connID) + }) + + createDest, ok := createResp["destination"].(map[string]interface{}) + require.True(t, ok, "Expected destination in create response") + destID, ok := createDest["id"].(string) + require.True(t, ok && destID != "", "Expected destination ID") + + var upsertResp map[string]interface{} + err = cli.RunJSON(&upsertResp, + "gateway", "connection", "upsert", connName, + "--source-name", sourceName, + "--source-type", "WEBHOOK", + "--source-hmac-secret", "s3cret", + ) + require.NoError(t, err, "Should upsert an inline source without destination flags") + + upsertDest, ok := upsertResp["destination"].(map[string]interface{}) + require.True(t, ok, "Expected destination in upsert response") + assert.Equal(t, destID, upsertDest["id"], "Destination should be the stored one") + upsertDestConfig, ok := upsertDest["config"].(map[string]interface{}) + require.True(t, ok, "Expected destination config in upsert response") + assert.Equal(t, destURL, upsertDestConfig["url"], "Destination URL should be unchanged") + + upsertSource, ok := upsertResp["source"].(map[string]interface{}) + require.True(t, ok, "Expected source in upsert response") + assert.Equal(t, sourceName, upsertSource["name"], "Source name should be unchanged") + }) + // Regression test for https://github.com/hookdeck/hookdeck-cli/issues/192: // --rule-filter-headers should store JSON as a parsed object with exact values preserved. t.Run("FilterHeadersJSONExactValues", func(t *testing.T) { diff --git a/test/acceptance/destination_omitted_type_test.go b/test/acceptance/destination_omitted_type_test.go new file mode 100644 index 00000000..52dfe5c1 --- /dev/null +++ b/test/acceptance/destination_omitted_type_test.go @@ -0,0 +1,94 @@ +//go:build destination + +package acceptance + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// configString reads a string field from a destination's decoded config. +func configString(t *testing.T, dst Destination, key string) string { + t.Helper() + cfg, ok := dst.Config.(map[string]interface{}) + require.True(t, ok, "destination config should be an object, got %T", dst.Config) + v, _ := cfg[key].(string) + return v +} + +// TestDestinationUpdateAppliesTypeSpecificFlagsWithoutType covers #406: --type +// is normally omitted on update because the type is already stored, and +// --url / --cli-path used to be dropped from the request while the command +// exited 0. Every case reads the destination back, because the exit code and +// the success message were the part that was already "right". +func TestDestinationUpdateAppliesTypeSpecificFlagsWithoutType(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + + t.Run("update --url on an HTTP destination", func(t *testing.T) { + name := "test-dst-406-http-" + generateTimestamp() + var dst Destination + require.NoError(t, cli.RunJSON(&dst, "gateway", "destination", "create", + "--name", name, "--type", "HTTP", "--url", "https://example.com/old")) + t.Cleanup(func() { deleteDestination(t, cli, dst.ID) }) + + // Negative control: a change with no --url must leave the URL alone, so a + // changed URL below can only come from --url. + cli.RunExpectSuccess("gateway", "destination", "update", dst.ID, "--description", "no url flag") + var untouched Destination + require.NoError(t, cli.RunJSON(&untouched, "gateway", "destination", "get", dst.ID)) + require.Equal(t, "https://example.com/old", configString(t, untouched, "url")) + + cli.RunExpectSuccess("gateway", "destination", "update", dst.ID, "--url", "https://example.com/new") + + var after Destination + require.NoError(t, cli.RunJSON(&after, "gateway", "destination", "get", dst.ID)) + assert.Equal(t, "https://example.com/new", configString(t, after, "url"), "--url without --type must change the URL") + assert.Equal(t, "HTTP", after.Type, "the type must not be changed by resolving it") + }) + + t.Run("update --cli-path on a CLI destination", func(t *testing.T) { + name := "test-dst-406-cli-" + generateTimestamp() + var dst Destination + require.NoError(t, cli.RunJSON(&dst, "gateway", "destination", "create", + "--name", name, "--type", "CLI", "--cli-path", "/old")) + t.Cleanup(func() { deleteDestination(t, cli, dst.ID) }) + + cli.RunExpectSuccess("gateway", "destination", "update", dst.ID, "--cli-path", "/new") + + var after Destination + require.NoError(t, cli.RunJSON(&after, "gateway", "destination", "get", dst.ID)) + assert.Equal(t, "/new", configString(t, after, "path"), "--cli-path without --type must change the path") + }) + + t.Run("update --url on a CLI destination is refused, not dropped", func(t *testing.T) { + name := "test-dst-406-mismatch-" + generateTimestamp() + var dst Destination + require.NoError(t, cli.RunJSON(&dst, "gateway", "destination", "create", + "--name", name, "--type", "CLI", "--cli-path", "/keep")) + t.Cleanup(func() { deleteDestination(t, cli, dst.ID) }) + + stdout, stderr, err := cli.Run("gateway", "destination", "update", dst.ID, "--url", "https://example.com/x") + require.Error(t, err, "a flag the stored type has no field for must not be silently ignored\nstdout: %s", stdout) + assert.Contains(t, stderr+stdout, "--url") + }) + + t.Run("upsert --url on an existing HTTP destination", func(t *testing.T) { + name := "test-dst-406-upsert-" + generateTimestamp() + var dst Destination + require.NoError(t, cli.RunJSON(&dst, "gateway", "destination", "create", + "--name", name, "--type", "HTTP", "--url", "https://example.com/old")) + t.Cleanup(func() { deleteDestination(t, cli, dst.ID) }) + + cli.RunExpectSuccess("gateway", "destination", "upsert", name, "--url", "https://example.com/new") + + var after Destination + require.NoError(t, cli.RunJSON(&after, "gateway", "destination", "get", dst.ID)) + assert.Equal(t, "https://example.com/new", configString(t, after, "url"), "upsert --url without --type must change the URL") + }) +} diff --git a/test/acceptance/source_auth_flags_test.go b/test/acceptance/source_auth_flags_test.go new file mode 100644 index 00000000..41351ccc --- /dev/null +++ b/test/acceptance/source_auth_flags_test.go @@ -0,0 +1,171 @@ +//go:build source + +package acceptance + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// postSigned POSTs body to url with the given headers and returns the status code. +func postSigned(t *testing.T, url, body string, headers map[string]string) int { + t.Helper() + req, err := http.NewRequest(http.MethodPost, url, bytes.NewBufferString(body)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req) + require.NoError(t, err) + defer resp.Body.Close() + return resp.StatusCode +} + +func hmacSHA256Hex(secret, body string) string { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(body)) + return hex.EncodeToString(mac.Sum(nil)) +} + +// verification is what the API recorded for the request whose body is body. +type verification struct { + Verified bool + RejectionCause string +} + +// waitForRequestVerification polls the source's requests until one carrying marker in its raw +// body appears, and returns how the API judged its signature. +func waitForRequestVerification(t *testing.T, cli *CLIRunner, sourceID, marker string) verification { + t.Helper() + for i := 0; i < propagationAttempts; i++ { + time.Sleep(propagationInterval) + var list struct { + Models []map[string]interface{} `json:"models"` + } + require.NoError(t, cli.RunJSON(&list, "gateway", "request", "list", "--source-id", sourceID, "--limit", "20")) + for _, m := range list.Models { + id, _ := m["id"].(string) + stdout := cli.RunExpectSuccess("gateway", "request", "raw-body", id) + if !strings.Contains(stdout, marker) { + continue + } + var req map[string]interface{} + require.NoError(t, cli.RunJSON(&req, "gateway", "request", "get", id)) + v, _ := req["verified"].(bool) + cause, _ := req["rejection_cause"].(string) + return verification{Verified: v, RejectionCause: cause} + } + } + require.Failf(t, "request not found", "no request on source %s carried %q", sourceID, marker) + return verification{} +} + +// TestSourceCreateVAPIWebhookSecretVerifiesProviderSignatures is the regression for --webhook-secret +// sending a generic header_key. The API lays the stored config.auth over the provider's defaults, +// so the generic x-webhook-signature header replaced VAPI's x-signature and every real VAPI +// request was rejected. The request is signed the way VAPI signs it (HMAC-SHA256, hex, in +// x-signature), and the negative controls show verification is really happening. +func TestSourceCreateVAPIWebhookSecretVerifiesProviderSignatures(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + secret := "vapi_secret_" + generateTimestamp() + + var src Source + require.NoError(t, cli.RunJSON(&src, "gateway", "source", "create", + "--name", "test-vapi-auth-"+generateTimestamp(), "--type", "VAPI", "--webhook-secret", secret)) + require.NotEmpty(t, src.ID) + require.NotEmpty(t, src.URL) + t.Cleanup(func() { deleteSource(t, cli, src.ID) }) + + // The stored auth is the bare secret: nothing the CLI added can override VAPI's header. + var got map[string]interface{} + require.NoError(t, cli.RunJSON(&got, "gateway", "source", "get", src.ID, "--include-auth")) + config, _ := got["config"].(map[string]interface{}) + auth, _ := config["auth"].(map[string]interface{}) + assert.NotContains(t, auth, "header_key", "the CLI must not override VAPI's own header") + + send := func(marker string, headers map[string]string) { + body := fmt.Sprintf(`{"marker":%q}`, marker) + for k, v := range headers { + if v == "sign" { + headers[k] = hmacSHA256Hex(secret, body) + } + if v == "sign-wrong" { + headers[k] = hmacSHA256Hex(secret+"x", body) + } + } + require.Less(t, postSigned(t, src.URL, body, headers), 500) + } + + good := "good-" + generateTimestamp() + send(good, map[string]string{"x-signature": "sign"}) + bad := "bad-" + generateTimestamp() + send(bad, map[string]string{"x-signature": "sign-wrong"}) + generic := "generic-" + generateTimestamp() + send(generic, map[string]string{"x-webhook-signature": "sign"}) + + v := waitForRequestVerification(t, cli, src.ID, good) + assert.True(t, v.Verified, "a request signed in x-signature must verify; rejection_cause=%q", v.RejectionCause) + + v = waitForRequestVerification(t, cli, src.ID, bad) + assert.False(t, v.Verified, "a wrong signature must not verify") + assert.Equal(t, "VERIFICATION_FAILED", v.RejectionCause) + + v = waitForRequestVerification(t, cli, src.ID, generic) + assert.False(t, v.Verified, "the generic header must not be what VAPI sources verify") +} + +// TestSourceCreateChoiceOfMethodTypesWithAuthFlags: GITLAB offers a choice of method, and the +// generic shape --webhook-secret used to send fitted none of them, so the API answered 422 +// "config.auth is not allowed". Flags that no method of a type can express are refused locally. +func TestSourceCreateChoiceOfMethodTypesWithAuthFlags(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + + authType := func(id string) string { + t.Helper() + var got map[string]interface{} + require.NoError(t, cli.RunJSON(&got, "gateway", "source", "get", id, "--include-auth")) + config, _ := got["config"].(map[string]interface{}) + v, _ := config["auth_type"].(string) + return v + } + + var secretSrc Source + require.NoError(t, cli.RunJSON(&secretSrc, "gateway", "source", "create", + "--name", "test-gitlab-secret-"+generateTimestamp(), "--type", "GITLAB", "--webhook-secret", "whsec_acceptance")) + require.NotEmpty(t, secretSrc.ID) + t.Cleanup(func() { deleteSource(t, cli, secretSrc.ID) }) + assert.Equal(t, "STANDARD_WEBHOOKS", authType(secretSrc.ID)) + + var keySrc Source + require.NoError(t, cli.RunJSON(&keySrc, "gateway", "source", "create", + "--name", "test-gitlab-key-"+generateTimestamp(), "--type", "GITLAB", "--api-key", "glpat_acceptance")) + require.NotEmpty(t, keySrc.ID) + t.Cleanup(func() { deleteSource(t, cli, keySrc.ID) }) + assert.Equal(t, "GITLAB", authType(keySrc.ID)) + + // A type whose API key needs its own header name has no flag for it: refused, nothing created. + name := "test-ordinal-key-" + generateTimestamp() + stdout, stderr, err := cli.Run("gateway", "source", "create", "--name", name, "--type", "ORDINAL", "--api-key", "k") + require.Error(t, err) + assert.Contains(t, stdout+stderr, "header_key") + assert.Contains(t, stdout+stderr, "--config") +} diff --git a/test/acceptance/source_test.go b/test/acceptance/source_test.go index 0a4106b9..d9143f8e 100644 --- a/test/acceptance/source_test.go +++ b/test/acceptance/source_test.go @@ -126,6 +126,42 @@ func TestSourceUpsertUpdate(t *testing.T) { assert.Contains(t, stdout, newDesc) } +// TestSourceUpsertWithoutTypeKeepsTypeAndAuth: PUT /sources defaults a missing +// type to WEBHOOK, so an upsert without --type used to convert an existing +// STRIPE source into a WEBHOOK source and drop its verification. The CLI now +// sends the stored type; read the source back to prove both survived. +func TestSourceUpsertWithoutTypeKeepsTypeAndAuth(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + name := "test-src-upsert-keep-type-" + generateTimestamp() + webhookSecret := "whsec_acceptance_keep_type" + + var src Source + err := cli.RunJSON(&src, "gateway", "source", "upsert", name, + "--type", "STRIPE", "--webhook-secret", webhookSecret) + require.NoError(t, err) + require.NotEmpty(t, src.ID) + t.Cleanup(func() { deleteSource(t, cli, src.ID) }) + require.Equal(t, "STRIPE", src.Type) + + var updated Source + err = cli.RunJSON(&updated, "gateway", "source", "upsert", name, "--description", "kept") + require.NoError(t, err) + assert.Equal(t, src.ID, updated.ID) + assert.Equal(t, "STRIPE", updated.Type, "upsert without --type must keep the existing type") + + stdout, _, err := cli.Run("gateway", "source", "get", src.ID, "--output", "json", "--include-auth") + require.NoError(t, err) + var got map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(stdout), &got)) + assert.Equal(t, "STRIPE", got["type"]) + assert.Equal(t, "kept", got["description"]) + assert.Contains(t, stdout, webhookSecret, "upsert without --type must keep the existing verification") +} + func TestSourceEnableDisable(t *testing.T) { if testing.Short() { t.Skip("Skipping acceptance test in short mode") @@ -614,3 +650,41 @@ func TestSourceDeleteWithoutForceFailsNonInteractively(t *testing.T) { require.NoError(t, cli.RunJSON(&check, "gateway", "source", "get", src.ID)) assert.Equal(t, src.ID, check.ID, "source must not have been deleted") } + +// TestSourceUpsertWebhookAuthFlags covers auth flags on WEBHOOK sources, which the API rejects +// without config.auth_type ("config.auth is not allowed") - including upsert and update without +// --type, which must both send the stored type. +func TestSourceUpsertWebhookAuthFlags(t *testing.T) { + if testing.Short() { + t.Skip("Skipping acceptance test in short mode") + } + + cli := NewCLIRunner(t) + name := "test-src-webhook-auth-" + generateTimestamp() + + authType := func(id string) string { + t.Helper() + var resp map[string]interface{} + require.NoError(t, cli.RunJSON(&resp, "gateway", "source", "get", id, "--include-auth")) + config, ok := resp["config"].(map[string]interface{}) + require.True(t, ok, "source must include config") + v, _ := config["auth_type"].(string) + return v + } + + var src Source + err := cli.RunJSON(&src, "gateway", "source", "upsert", name, "--type", "WEBHOOK", "--api-key", "test_key_abc123") + require.NoError(t, err, "source upsert --type WEBHOOK --api-key should be accepted") + require.NotEmpty(t, src.ID) + t.Cleanup(func() { deleteSource(t, cli, src.ID) }) + assert.Equal(t, "API_KEY", authType(src.ID)) + + err = cli.RunJSON(&src, "gateway", "source", "upsert", name, "--basic-auth-user", "user", "--basic-auth-pass", "pass") + require.NoError(t, err, "source upsert without --type should be accepted") + assert.Equal(t, "WEBHOOK", strings.ToUpper(src.Type)) + assert.Equal(t, "BASIC_AUTH", authType(src.ID)) + + err = cli.RunJSON(&src, "gateway", "source", "update", src.ID, "--api-key", "test_key_def456") + require.NoError(t, err, "source update without --type should be accepted") + assert.Equal(t, "API_KEY", authType(src.ID)) +}