From 8ee91237f926d718972fc4fca855261c0fc5ff05 Mon Sep 17 00:00:00 2001 From: SomeoneWithOptions Date: Wed, 21 Oct 2026 17:49:17 -0500 Subject: [PATCH] feat(promotion): add gitlab providers, apply status, and project scope --- docs/n8n_promotion.md | 15 +- docs/n8n_promotion_apply.md | 31 +- docs/n8n_promotion_connection_create.md | 4 + docs/n8n_promotion_project.md | 4 +- docs/n8n_promotion_project_add.md | 5 +- docs/n8n_promotion_project_list.md | 5 +- docs/n8n_promotion_project_remove.md | 3 +- docs/n8n_promotion_promote.md | 11 +- docs/n8n_promotion_provider_create.md | 52 +- docs/n8n_promotion_provider_update.md | 12 +- internal/cli/cli.go | 15 +- internal/cli/promotion.go | 628 +++++++++++++++++++----- internal/cli/promotion_apply_test.go | 349 +++++++++++++ internal/cli/promotion_test.go | 4 +- internal/n8n/promotion.go | 416 ++++++++++++++-- internal/n8n/promotion_apply_test.go | 366 ++++++++++++++ internal/n8n/promotion_test.go | 10 +- 17 files changed, 1726 insertions(+), 204 deletions(-) create mode 100644 internal/cli/promotion_apply_test.go create mode 100644 internal/n8n/promotion_apply_test.go diff --git a/docs/n8n_promotion.md b/docs/n8n_promotion.md index 271a415..705e9a0 100644 --- a/docs/n8n_promotion.md +++ b/docs/n8n_promotion.md @@ -8,12 +8,15 @@ Manage the upstream-only Promotions generation of Git sync. Start with 'provider list' to find a provider, then 'connection list' to find a connection. Create a provider first, then a connection on it, then a config per direction under 'config', clone each checkout -under 'checkout', link team projects under 'project', then 'promote' -local projects to the remote or 'apply' the remote into the instance. - -'promote' commits and pushes every team project to the remote; -'apply' resets the apply checkout and imports with overwrite behavior, -creating, updating, or removing content to match. Both mutate versioned +under 'checkout', link team projects to a projects-scope connection +under 'project', then 'promote' the instance to the remote or 'apply' +the remote into the instance. + +'promote' and 'apply' run on the instance connection. 'promote' +commits and pushes every team project to the remote; 'apply' checks the +package and imports with overwrite behavior, creating, updating, or +removing content to match, or reports why it is blocked and writes +nothing. Both mutate versioned content and ask for confirmation. Config and connection removal can remove local checkouts. This is the upstream Promotions generation: an instance that serves GitConnections instead answers 404 or 503, which diff --git a/docs/n8n_promotion_apply.md b/docs/n8n_promotion_apply.md index c25b0df..98b1104 100644 --- a/docs/n8n_promotion_apply.md +++ b/docs/n8n_promotion_apply.md @@ -4,16 +4,29 @@ Apply the Git remote into this instance ### Synopsis -Reset the apply checkout to the branch tip and import projects into -the instance, overwriting to match. The apply checkout must be cloned -first. Preview what is linked with 'n8n promotion project list'. - -This rewrites instance content from the remote and cannot be undone: -workflows, folders, credentials, data tables, variables, and tags are -created, updated, or removed to match the branch, and credential gaps -become stubs. Interactive runs ask for confirmation and +Check the full package at the apply branch tip and import it into the +instance, overwriting to match. Runs on the instance connection; the +apply checkout must be cloned first. + +The server answers one of three statuses, and only one writes: + applied content was imported; counts and warnings follow. + blocked preflight stopped before any write: missing projects, + missing credential or variable bindings, access + requirements, or conflicts (including project-deletion + and data-table destructive-change). Nothing was applied. + source-changed the branch moved since it was reviewed. Nothing was + applied. + +An applied run rewrites instance content from the remote and cannot be +undone: workflows, folders, credentials, data tables, variables, and +tags are created, updated, or removed to match the branch, and +credential gaps become stubs. Interactive runs ask for confirmation and non-interactive runs require --yes. Requires gitConnection:pull. +Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 any other error +or an unknown status. --output json prints the full result on stdout +in every status; the next step goes to stderr. + ``` n8n promotion apply [flags] ``` @@ -31,7 +44,7 @@ n8n promotion apply [flags] ``` --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for apply - --output string output format: text or json (JSON is the apply result with counts and commit) (default "text") + --output string output format: text or json (JSON is the full apply result: status, git, and counts or preflight) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) --yes confirm overwriting instance content from the remote without prompting (required when stdin is not interactive) ``` diff --git a/docs/n8n_promotion_connection_create.md b/docs/n8n_promotion_connection_create.md index a4e7af4..2d4a29f 100644 --- a/docs/n8n_promotion_connection_create.md +++ b/docs/n8n_promotion_connection_create.md @@ -12,6 +12,10 @@ config {"settings":{"schemaVersion":1,"branchName":"main"}} and the promote config {"settings":{"schemaVersion":1, "baseBranchName":"main","createBranchOnPromotion":false}}. +On a gitlab provider the remote URL must belong to the provider: the +connection stores only the repository path (reported read-only as +target.repositoryPath, never sent) and derives remoteUrl from the +provider base URL. Only one instance-scope connection can exist. Unknown fields and trailing JSON documents are refused before transport. Requires gitConnection:create. Follow with 'n8n promotion config apply set' and 'n8n promotion config promote diff --git a/docs/n8n_promotion_project.md b/docs/n8n_promotion_project.md index 61777c1..8daa561 100644 --- a/docs/n8n_promotion_project.md +++ b/docs/n8n_promotion_project.md @@ -4,7 +4,9 @@ Manage projects linked to a promotion connection ### Synopsis -Manage which team projects one promotion connection syncs. Start with +Manage which team projects a projects-scope promotion connection +syncs; a project's own connection takes precedence over the instance +connection for project-level sync. Start with 'list' to see the linked project IDs, then 'add' a project or 'remove' one. diff --git a/docs/n8n_promotion_project_add.md b/docs/n8n_promotion_project_add.md index 114da46..f3ea527 100644 --- a/docs/n8n_promotion_project_add.md +++ b/docs/n8n_promotion_project_add.md @@ -4,8 +4,9 @@ Add a project to a promotion connection ### Synopsis -Add one team project to one promotion connection so promote and apply -include it. A project can belong to only one connection: adding a +Link one team project to one projects-scope promotion connection, so +project-level sync uses that connection instead of the instance +connection. A project can belong to only one connection: adding a project that is already linked elsewhere answers 409. The checkout must be cloned first. Requires gitConnection:manageProjects. diff --git a/docs/n8n_promotion_project_list.md b/docs/n8n_promotion_project_list.md index 074f9b2..d98be7c 100644 --- a/docs/n8n_promotion_project_list.md +++ b/docs/n8n_promotion_project_list.md @@ -4,8 +4,9 @@ List projects linked to a promotion connection ### Synopsis -List the team projects added to one promotion connection. These are -the projects 'promote' exports and 'apply' overwrites. Find the +List the team projects linked to one projects-scope promotion +connection. Connection-level 'promote' and 'apply' run on the instance +connection and do not use these links. Find the connection ID with 'n8n promotion connection list'. Requires gitConnection:read. diff --git a/docs/n8n_promotion_project_remove.md b/docs/n8n_promotion_project_remove.md index 4cf5084..30bcaf2 100644 --- a/docs/n8n_promotion_project_remove.md +++ b/docs/n8n_promotion_project_remove.md @@ -6,7 +6,8 @@ Remove a project from a promotion connection Unlink one project from one promotion connection. The project itself and its instance content are untouched; only the sync link goes away, -so later promotes and applies skip it. Re-add it later with 'n8n +so project-level sync falls back to the instance connection. Re-add it +later with 'n8n promotion project add'. Interactive runs ask for confirmation; non-interactive runs require diff --git a/docs/n8n_promotion_promote.md b/docs/n8n_promotion_promote.md index 75c10b2..3da258e 100644 --- a/docs/n8n_promotion_promote.md +++ b/docs/n8n_promotion_promote.md @@ -4,10 +4,13 @@ Promote team projects to the Git remote ### Synopsis -Export all team projects, commit them, and push to the promote -checkout's branch. The promote checkout must be cloned first: run 'n8n -promotion checkout clone CONNECTION_ID promote' and link projects -with 'n8n promotion project add'. +Export every team project, commit it, and push to the configured base +branch or a new timestamped branch (the result names it). Personal +projects are ignored. This runs on the instance connection only, so +project links from 'n8n promotion project add' do not select what is +promoted. The promote checkout must be cloned first: run 'n8n promotion +checkout clone CONNECTION_ID promote'. When workflows reference +variables, the API key also needs variable:list. Pass --commit-message once (1 to 1000 characters). Without --force a promote the remote would reject is refused with 409 and nothing is diff --git a/docs/n8n_promotion_provider_create.md b/docs/n8n_promotion_provider_create.md index cb20d83..83de40d 100644 --- a/docs/n8n_promotion_provider_create.md +++ b/docs/n8n_promotion_provider_create.md @@ -4,16 +4,27 @@ Create a promotion provider ### Synopsis -Create one promotion provider from strict JSON supplied by --input. -Required fields are name (at most 128 characters), type (git), and an -auth object: {"authType":"ssh-key"} with an optional keyType -(ed25519 or rsa, default ed25519), or {"authType":"token", -"username":"...", "password":"..."}. - -Credentials travel only as --input because secrets are never flags: -process lists and shell history can expose argv. Unknown fields and -trailing JSON documents are refused before transport. Requires -gitConnection:create. Follow with 'n8n promotion connection create'. +Create one promotion provider from flags or from strict JSON supplied by +--input; the two ways are mutually exclusive and one is required. + +Type git is a plain Git remote. Type gitlab is a Git host provider: the +server checks API access before saving and can list repositories. Pass +--base-url for self-managed GitLab; it becomes config {"schemaVersion":1, +"baseUrl":"..."} and applies to gitlab providers only. + +Auth is ssh-key (the response carries the generated public key; add it +to the remote as a deploy key) or token. A token is never a flag: the +flag way asks for it without echo, or reads it from stdin with +--password-stdin. A git provider needs --username with a token; GitLab +ignores the username and uses n8n for Git transport. + +The --input document has name (at most 128 characters), type (git or +gitlab), auth {"authType":"ssh-key"} with an optional keyType +(ed25519 or rsa, default ed25519) or {"authType":"token", +"password":"..."} plus username for git, and the optional config. +Unknown fields and trailing JSON documents are refused before +transport. Requires gitConnection:create. Follow with 'n8n promotion +connection create'. ``` n8n promotion provider create [flags] @@ -22,19 +33,26 @@ n8n promotion provider create [flags] ### Examples ``` - n8n promotion provider create --input provider.json - printf '%s\n' '{"name":"github","type":"git","auth":{"authType":"ssh-key"}}' | n8n promotion provider create --input - + n8n promotion provider create --name github --type git --auth-type ssh-key + printf '%s\n' "$GITLAB_TOKEN" | n8n promotion provider create --name gitlab --type gitlab --base-url https://gitlab.example.com --auth-type token --password-stdin n8n promotion provider create --input provider.json --output json ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for create - --input string promotion provider JSON file path, or - for stdin (required; maximum 1 MiB) - --output string output format: text or json (JSON is the provider returned by the API) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --auth-type string auth type: ssh-key or token (default: ssh-key) + --base-url string GitLab base URL for self-managed GitLab, e.g. https://gitlab.example.com; gitlab only (default: none, no config is sent) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for create + --input string promotion provider JSON file path, or - for stdin (maximum 1 MiB; default: build the document from --name and the other flags) + --key-type string SSH key type for ssh-key auth: ed25519 or rsa (default: the server's ed25519) + --name string provider name, 1 to 128 characters (required without --input) + --output string output format: text or json (JSON is the creation result: provider plus publicKey) (default "text") + --password-stdin read the token for token auth from stdin instead of prompting without echo (default false; required when stdin is not a terminal) + --type string provider type: git or gitlab (default: git) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --username string Git username for token auth; required for git, ignored by gitlab (default: none) ``` ### SEE ALSO diff --git a/docs/n8n_promotion_provider_update.md b/docs/n8n_promotion_provider_update.md index be345e3..bd7c7bd 100644 --- a/docs/n8n_promotion_provider_update.md +++ b/docs/n8n_promotion_provider_update.md @@ -5,14 +5,18 @@ Update a promotion provider ### Synopsis Update one promotion provider from strict JSON supplied by --input. -Only the fields present are changed; at least one of name or auth is -required. Auth follows the create shape: ssh-key with an optional key -type, or token with a username and password. +Only the fields present are changed; at least one of name, auth, or +config is required. Auth follows the create shape: ssh-key with an +optional key type, or token with a password (plus username for git +providers). The auth type cannot change. A gitlab provider can change +its base URL with config {"schemaVersion":1,"baseUrl":"..."}; a +different API destination needs auth in the same document. Replacing the credential affects every connection attached to this provider, so interactive runs ask for confirmation and non-interactive runs require --yes. Credentials travel only as --input because secrets -are never flags. Requires gitConnection:update. +are never flags. A 409 means another request changed the provider +first: reload it and retry. Requires gitConnection:update. ``` n8n promotion provider update [flags] diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b413882..aa6c042 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -26,7 +26,13 @@ const ( ExitError = 1 // ExitDiffError distinguishes a failed comparison from detected differences. ExitDiffError = 2 - ExitCanceled = 130 + // ExitPromotionBlocked is a promotion apply the server stopped at + // preflight: the result was printed and nothing was written. + ExitPromotionBlocked = 3 + // ExitPromotionSourceChanged is a promotion apply whose branch moved since + // the review: the result was printed and nothing was written. + ExitPromotionSourceChanged = 4 + ExitCanceled = 130 ) // Streams are the three standard streams a command tree reads and writes. @@ -159,6 +165,13 @@ func Run(ctx context.Context, args []string, opts Options) int { fmt.Fprintf(opts.Streams.Err, "n8n: %v\n", err) return ExitError } + var stoppedApply *promotionApplyStoppedError + if errors.As(err, &stoppedApply) { + // The result and the next step were printed; say why the exit code is + // not zero without the usage hint a real error gets. + fmt.Fprintf(opts.Streams.Err, "n8n: %v\n", err) + return stoppedApply.exitCode() + } code := report(opts.Streams.Err, err) if code == ExitError && cmd != nil && cmd.Annotations["diffExitCodes"] == "true" { return ExitDiffError diff --git a/internal/cli/promotion.go b/internal/cli/promotion.go index 53bc6cd..5be8747 100644 --- a/internal/cli/promotion.go +++ b/internal/cli/promotion.go @@ -2,8 +2,10 @@ package cli import ( "bytes" + "cmp" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -31,11 +33,14 @@ func newPromotionCommand(opts Options) *cobra.Command { "Start with 'provider list' to find a provider, then 'connection list'\n" + "to find a connection. Create a provider first, then a connection on\n" + "it, then a config per direction under 'config', clone each checkout\n" + - "under 'checkout', link team projects under 'project', then 'promote'\n" + - "local projects to the remote or 'apply' the remote into the instance.\n\n" + - "'promote' commits and pushes every team project to the remote;\n" + - "'apply' resets the apply checkout and imports with overwrite behavior,\n" + - "creating, updating, or removing content to match. Both mutate versioned\n" + + "under 'checkout', link team projects to a projects-scope connection\n" + + "under 'project', then 'promote' the instance to the remote or 'apply'\n" + + "the remote into the instance.\n\n" + + "'promote' and 'apply' run on the instance connection. 'promote'\n" + + "commits and pushes every team project to the remote; 'apply' checks the\n" + + "package and imports with overwrite behavior, creating, updating, or\n" + + "removing content to match, or reports why it is blocked and writes\n" + + "nothing. Both mutate versioned\n" + "content and ask for confirmation. Config and connection removal can\n" + "remove local checkouts. This is the upstream Promotions generation: an\n" + "instance that serves GitConnections instead answers 404 or 503, which\n" + @@ -151,7 +156,7 @@ func runPromotionProviderList(ctx context.Context, opts Options, f promotionProv page, err = client.ListPromotionProviders(ctx, listOpts) } if err != nil { - return promotionAPIError(err, resolution, "provider list") + return promotionAPIError(err, resolution, "provider list", promotionSubject{}) } if f.output == outputJSON { err = writePageJSON(opts.Streams.Out, page, collection) @@ -185,51 +190,89 @@ func writePromotionProviderListText(opts Options, resolution config.Resolution, return nil } -type promotionProviderInputFlags struct { - instance instanceFlags - input string - output string +type promotionProviderCreateFlags struct { + instance instanceFlags + input string + name string + providerType string + baseURL string + authType string + keyType string + username string + passwordStdin bool + output string } -func (f *promotionProviderInputFlags) register(cmd *cobra.Command) { - f.instance.register(cmd) - cmd.Flags().StringVar(&f.input, "input", "", "promotion provider JSON file path, or - for stdin (required; maximum 1 MiB)") - cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the provider returned by the API)") +// documentFlagsSet reports whether any flag that builds the creation document +// was passed; those flags and --input are mutually exclusive. +func (f promotionProviderCreateFlags) documentFlagsSet() bool { + return f.name != "" || f.providerType != "" || f.baseURL != "" || f.authType != "" || + f.keyType != "" || f.username != "" || f.passwordStdin } func newPromotionProviderCreateCommand(opts Options) *cobra.Command { - var f promotionProviderInputFlags + var f promotionProviderCreateFlags cmd := &cobra.Command{ Use: "create", Short: "Create a promotion provider", - Long: "Create one promotion provider from strict JSON supplied by --input.\n" + - "Required fields are name (at most 128 characters), type (git), and an\n" + - "auth object: {\"authType\":\"ssh-key\"} with an optional keyType\n" + - "(ed25519 or rsa, default ed25519), or {\"authType\":\"token\",\n" + - "\"username\":\"...\", \"password\":\"...\"}.\n\n" + - "Credentials travel only as --input because secrets are never flags:\n" + - "process lists and shell history can expose argv. Unknown fields and\n" + - "trailing JSON documents are refused before transport. Requires\n" + - "gitConnection:create. Follow with 'n8n promotion connection create'.", - Example: " n8n promotion provider create --input provider.json\n" + - " printf '%s\\n' '{\"name\":\"github\",\"type\":\"git\",\"auth\":{\"authType\":\"ssh-key\"}}' | n8n promotion provider create --input -\n" + + Long: "Create one promotion provider from flags or from strict JSON supplied by\n" + + "--input; the two ways are mutually exclusive and one is required.\n\n" + + "Type git is a plain Git remote. Type gitlab is a Git host provider: the\n" + + "server checks API access before saving and can list repositories. Pass\n" + + "--base-url for self-managed GitLab; it becomes config {\"schemaVersion\":1,\n" + + "\"baseUrl\":\"...\"} and applies to gitlab providers only.\n\n" + + "Auth is ssh-key (the response carries the generated public key; add it\n" + + "to the remote as a deploy key) or token. A token is never a flag: the\n" + + "flag way asks for it without echo, or reads it from stdin with\n" + + "--password-stdin. A git provider needs --username with a token; GitLab\n" + + "ignores the username and uses n8n for Git transport.\n\n" + + "The --input document has name (at most 128 characters), type (git or\n" + + "gitlab), auth {\"authType\":\"ssh-key\"} with an optional keyType\n" + + "(ed25519 or rsa, default ed25519) or {\"authType\":\"token\",\n" + + "\"password\":\"...\"} plus username for git, and the optional config.\n" + + "Unknown fields and trailing JSON documents are refused before\n" + + "transport. Requires gitConnection:create. Follow with 'n8n promotion\n" + + "connection create'.", + Example: " n8n promotion provider create --name github --type git --auth-type ssh-key\n" + + " printf '%s\\n' \"$GITLAB_TOKEN\" | n8n promotion provider create --name gitlab --type gitlab --base-url https://gitlab.example.com --auth-type token --password-stdin\n" + " n8n promotion provider create --input provider.json --output json", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return runPromotionProviderCreate(cmd.Context(), opts, f) }, } - f.register(cmd) + f.instance.register(cmd) + cmd.Flags().StringVar(&f.input, "input", "", "promotion provider JSON file path, or - for stdin (maximum 1 MiB; default: build the document from --name and the other flags)") + cmd.Flags().StringVar(&f.name, "name", "", "provider name, 1 to 128 characters (required without --input)") + cmd.Flags().StringVar(&f.providerType, "type", "", "provider type: git or gitlab (default: git)") + cmd.Flags().StringVar(&f.baseURL, "base-url", "", "GitLab base URL for self-managed GitLab, e.g. https://gitlab.example.com; gitlab only (default: none, no config is sent)") + cmd.Flags().StringVar(&f.authType, "auth-type", "", "auth type: ssh-key or token (default: ssh-key)") + cmd.Flags().StringVar(&f.keyType, "key-type", "", "SSH key type for ssh-key auth: ed25519 or rsa (default: the server's ed25519)") + cmd.Flags().StringVar(&f.username, "username", "", "Git username for token auth; required for git, ignored by gitlab (default: none)") + cmd.Flags().BoolVar(&f.passwordStdin, "password-stdin", false, "read the token for token auth from stdin instead of prompting without echo (default false; required when stdin is not a terminal)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the creation result: provider plus publicKey)") return cmd } -func runPromotionProviderCreate(ctx context.Context, opts Options, f promotionProviderInputFlags) error { +func runPromotionProviderCreate(ctx context.Context, opts Options, f promotionProviderCreateFlags) error { if err := validateOutput(f.output); err != nil { return err } var request n8n.CreatePromotionProviderRequest - if err := readPromotionDocument(opts, f.input, &request); err != nil { - return err + switch { + case f.input != "" && f.documentFlagsSet(): + return fmt.Errorf("--input and the document flags (--name, --type, --base-url, --auth-type, --key-type, --username, --password-stdin) are mutually exclusive: pass one way") + case f.input != "": + if err := readPromotionDocument(opts, f.input, &request); err != nil { + return err + } + case f.documentFlagsSet(): + var err error + if request, err = promotionProviderFromFlags(opts, f); err != nil { + return err + } + default: + return fmt.Errorf("a provider document is required: pass --name with --type and --auth-type, or --input FILE (--input - for stdin)") } if err := request.Validate(); err != nil { return err @@ -240,7 +283,7 @@ func runPromotionProviderCreate(ctx context.Context, opts Options, f promotionPr } created, err := client.CreatePromotionProvider(ctx, request) if err != nil { - return promotionAPIError(err, resolution, "provider create") + return promotionAPIError(err, resolution, "provider create", promotionSubject{}) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, created) @@ -248,6 +291,53 @@ func runPromotionProviderCreate(ctx context.Context, opts Options, f promotionPr return writePromotionProviderResult(opts, resolution, "Created", &created.Provider, f.output) } +// promotionProviderFromFlags builds the creation document from flags. The +// document is checked before the token is read, so a typo never costs a +// prompt; the token itself comes from stdin or a no-echo prompt, never argv. +func promotionProviderFromFlags(opts Options, f promotionProviderCreateFlags) (n8n.CreatePromotionProviderRequest, error) { + request := n8n.CreatePromotionProviderRequest{ + Name: f.name, + Type: cmp.Or(f.providerType, n8n.PromotionProviderTypeGit), + Auth: n8n.PromotionProviderAuth{ + AuthType: cmp.Or(f.authType, n8n.PromotionAuthTypeSSHKey), + KeyType: f.keyType, + Username: f.username, + }, + } + if f.baseURL != "" { + request.Config = &n8n.PromotionProviderHostConfig{SchemaVersion: 1, BaseURL: f.baseURL} + } + token := request.Auth.AuthType == n8n.PromotionAuthTypeToken + if f.passwordStdin && !token { + return request, fmt.Errorf("--password-stdin needs --auth-type token") + } + probe := request + if token { + probe.Auth.Password = "unread" // stands in until the token is read + } + if err := probe.Validate(); err != nil { + return request, err + } + if !token { + return request, nil + } + var secret n8n.Secret + var err error + switch { + case f.passwordStdin: + secret, err = readSecretFrom(opts.Streams.In) + case opts.interactive(): + secret, err = opts.prompter().PromptSecret("Git provider token: ") + default: + return request, fmt.Errorf("no terminal available to read the provider token: pipe it with --password-stdin") + } + if err != nil { + return request, err + } + request.Auth.Password = secret.Reveal() + return request, nil +} + type promotionProviderGetFlags struct { instance instanceFlags output string @@ -290,7 +380,7 @@ func runPromotionProviderGet(ctx context.Context, opts Options, id string, f pro } provider, err := client.GetPromotionProvider(ctx, id) if err != nil { - return promotionAPIError(err, resolution, "provider get") + return promotionAPIError(err, resolution, "provider get", promotionProviderSubject(id)) } return writePromotionProviderResult(opts, resolution, "Provider", provider, f.output) } @@ -308,13 +398,17 @@ func newPromotionProviderUpdateCommand(opts Options) *cobra.Command { Use: "update ", Short: "Update a promotion provider", Long: "Update one promotion provider from strict JSON supplied by --input.\n" + - "Only the fields present are changed; at least one of name or auth is\n" + - "required. Auth follows the create shape: ssh-key with an optional key\n" + - "type, or token with a username and password.\n\n" + + "Only the fields present are changed; at least one of name, auth, or\n" + + "config is required. Auth follows the create shape: ssh-key with an\n" + + "optional key type, or token with a password (plus username for git\n" + + "providers). The auth type cannot change. A gitlab provider can change\n" + + "its base URL with config {\"schemaVersion\":1,\"baseUrl\":\"...\"}; a\n" + + "different API destination needs auth in the same document.\n\n" + "Replacing the credential affects every connection attached to this\n" + "provider, so interactive runs ask for confirmation and non-interactive\n" + "runs require --yes. Credentials travel only as --input because secrets\n" + - "are never flags. Requires gitConnection:update.", + "are never flags. A 409 means another request changed the provider\n" + + "first: reload it and retry. Requires gitConnection:update.", Example: " n8n promotion provider update PROVIDER_ID --input provider-update.json\n" + " printf '%s\\n' '{\"name\":\"github-new\"}' | n8n promotion provider update PROVIDER_ID --input -\n" + " n8n promotion provider update PROVIDER_ID --input provider-update.json --yes --output json", @@ -360,7 +454,7 @@ func runPromotionProviderUpdate(ctx context.Context, opts Options, id string, f } updated, err := client.UpdatePromotionProvider(ctx, id, request) if err != nil { - return promotionAPIError(err, resolution, "provider update") + return promotionAPIError(err, resolution, "provider update", promotionProviderSubject(id)) } return writePromotionProviderResult(opts, resolution, "Updated", updated, f.output) } @@ -414,7 +508,7 @@ func runPromotionProviderDelete(ctx context.Context, opts Options, id string, f return err } if err := client.DeletePromotionProvider(ctx, id); err != nil { - return promotionAPIError(err, resolution, "provider delete") + return promotionAPIError(err, resolution, "provider delete", promotionProviderSubject(id)) } return writePromotionMutation(opts, resolution, promotionMutation{Action: "deleted", ProviderID: id}, f.output) } @@ -523,7 +617,7 @@ func runPromotionConnectionList(ctx context.Context, opts Options, f promotionCo page, err = client.ListPromotionConnections(ctx, listOpts) } if err != nil { - return promotionAPIError(err, resolution, "connection list") + return promotionAPIError(err, resolution, "connection list", promotionSubject{}) } if f.output == outputJSON { err = writePageJSON(opts.Streams.Out, page, collection) @@ -582,6 +676,10 @@ func newPromotionConnectionCreateCommand(opts Options) *cobra.Command { "config {\"settings\":{\"schemaVersion\":1,\"branchName\":\"main\"}} and\n" + "the promote config {\"settings\":{\"schemaVersion\":1,\n" + "\"baseBranchName\":\"main\",\"createBranchOnPromotion\":false}}.\n\n" + + "On a gitlab provider the remote URL must belong to the provider: the\n" + + "connection stores only the repository path (reported read-only as\n" + + "target.repositoryPath, never sent) and derives remoteUrl from the\n" + + "provider base URL. Only one instance-scope connection can exist.\n" + "Unknown fields and trailing JSON documents are refused before\n" + "transport. Requires gitConnection:create. Follow with\n" + "'n8n promotion config apply set' and 'n8n promotion config promote\n" + @@ -614,7 +712,7 @@ func runPromotionConnectionCreate(ctx context.Context, opts Options, f promotion } created, err := client.CreatePromotionConnection(ctx, request) if err != nil { - return promotionAPIError(err, resolution, "connection create") + return promotionAPIError(err, resolution, "connection create", promotionProviderSubject(request.ProviderID)) } return writePromotionConnectionResult(opts, resolution, "Created", created, f.output) } @@ -661,7 +759,7 @@ func runPromotionConnectionGet(ctx context.Context, opts Options, id string, f p } connection, err := client.GetPromotionConnection(ctx, id) if err != nil { - return promotionAPIError(err, resolution, "connection get") + return promotionAPIError(err, resolution, "connection get", promotionConnectionSubject(id)) } return writePromotionConnectionResult(opts, resolution, "Connection", connection, f.output) } @@ -711,7 +809,7 @@ func runPromotionConnectionUpdate(ctx context.Context, opts Options, id string, } updated, err := client.UpdatePromotionConnection(ctx, id, request) if err != nil { - return promotionAPIError(err, resolution, "connection update") + return promotionAPIError(err, resolution, "connection update", promotionConnectionSubject(id)) } return writePromotionConnectionResult(opts, resolution, "Updated", updated, f.output) } @@ -766,7 +864,7 @@ func runPromotionConnectionDelete(ctx context.Context, opts Options, id string, return err } if err := client.DeletePromotionConnection(ctx, id); err != nil { - return promotionAPIError(err, resolution, "connection delete") + return promotionAPIError(err, resolution, "connection delete", promotionConnectionSubject(id)) } return writePromotionMutation(opts, resolution, promotionMutation{Action: "deleted", ConnectionID: id}, f.output) } @@ -891,7 +989,7 @@ func runPromotionConfigApplySet(ctx context.Context, opts Options, id string, f } config, err := client.UpsertPromotionApplyConfig(ctx, id, request) if err != nil { - return promotionAPIError(err, resolution, "config apply set") + return promotionAPIError(err, resolution, "config apply set", promotionConnectionSubject(id)) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, config) @@ -959,7 +1057,7 @@ func runPromotionConfigPromoteSet(ctx context.Context, opts Options, id string, } config, err := client.UpsertPromotionPromoteConfig(ctx, id, request) if err != nil { - return promotionAPIError(err, resolution, "config promote set") + return promotionAPIError(err, resolution, "config promote set", promotionConnectionSubject(id)) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, config) @@ -1025,7 +1123,7 @@ func runPromotionConfigDelete(ctx context.Context, opts Options, id, direction s return err } if err := client.DeletePromotionConfig(ctx, id, direction); err != nil { - return promotionAPIError(err, resolution, "config delete") + return promotionAPIError(err, resolution, "config delete", promotionConnectionSubject(id)) } return writePromotionMutation(opts, resolution, promotionMutation{Action: "config deleted", ConnectionID: id, Direction: direction}, f.output) } @@ -1102,7 +1200,7 @@ func runPromotionCheckoutClone(ctx context.Context, opts Options, id, direction } checkout, err := client.ClonePromotionCheckout(ctx, id, direction) if err != nil { - return promotionAPIError(err, resolution, "checkout clone") + return promotionAPIError(err, resolution, "checkout clone", promotionConnectionSubject(id)) } return writePromotionCheckout(opts, resolution, "Cloned", checkout, f.output) } @@ -1162,7 +1260,7 @@ func runPromotionCheckoutDisconnect(ctx context.Context, opts Options, id, direc } checkout, err := client.DisconnectPromotionCheckout(ctx, id, direction) if err != nil { - return promotionAPIError(err, resolution, "checkout disconnect") + return promotionAPIError(err, resolution, "checkout disconnect", promotionConnectionSubject(id)) } return writePromotionCheckout(opts, resolution, "Disconnected", checkout, f.output) } @@ -1173,7 +1271,9 @@ func newPromotionProjectCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "project", Short: "Manage projects linked to a promotion connection", - Long: "Manage which team projects one promotion connection syncs. Start with\n" + + Long: "Manage which team projects a projects-scope promotion connection\n" + + "syncs; a project's own connection takes precedence over the instance\n" + + "connection for project-level sync. Start with\n" + "'list' to see the linked project IDs, then 'add' a project or\n" + "'remove' one.\n\n" + "A project can belong to only one connection, so adding a linked\n" + @@ -1205,8 +1305,9 @@ func newPromotionProjectListCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "list ", Short: "List projects linked to a promotion connection", - Long: "List the team projects added to one promotion connection. These are\n" + - "the projects 'promote' exports and 'apply' overwrites. Find the\n" + + Long: "List the team projects linked to one projects-scope promotion\n" + + "connection. Connection-level 'promote' and 'apply' run on the instance\n" + + "connection and do not use these links. Find the\n" + "connection ID with 'n8n promotion connection list'. Requires\n" + "gitConnection:read.", Example: " n8n promotion project list CONNECTION_ID\n" + @@ -1237,7 +1338,7 @@ func runPromotionProjectList(ctx context.Context, opts Options, id string, f pro } projects, err := client.ListPromotionConnectionProjects(ctx, id) if err != nil { - return promotionAPIError(err, resolution, "project list") + return promotionAPIError(err, resolution, "project list", promotionConnectionSubject(id)) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, projects) @@ -1271,8 +1372,9 @@ func newPromotionProjectAddCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "add ", Short: "Add a project to a promotion connection", - Long: "Add one team project to one promotion connection so promote and apply\n" + - "include it. A project can belong to only one connection: adding a\n" + + Long: "Link one team project to one projects-scope promotion connection, so\n" + + "project-level sync uses that connection instead of the instance\n" + + "connection. A project can belong to only one connection: adding a\n" + "project that is already linked elsewhere answers 409. The checkout\n" + "must be cloned first. Requires gitConnection:manageProjects.", Example: " n8n promotion project add CONNECTION_ID PROJECT_ID\n" + @@ -1303,7 +1405,7 @@ func runPromotionProjectAdd(ctx context.Context, opts Options, id, projectID str } link, err := client.AddProjectToPromotionConnection(ctx, id, projectID) if err != nil { - return promotionAPIError(err, resolution, "project add") + return promotionAPIError(err, resolution, "project add", promotionProjectLinkSubject(id, projectID)) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, link) @@ -1328,7 +1430,8 @@ func newPromotionProjectRemoveCommand(opts Options) *cobra.Command { Short: "Remove a project from a promotion connection", Long: "Unlink one project from one promotion connection. The project itself\n" + "and its instance content are untouched; only the sync link goes away,\n" + - "so later promotes and applies skip it. Re-add it later with 'n8n\n" + + "so project-level sync falls back to the instance connection. Re-add it\n" + + "later with 'n8n\n" + "promotion project add'.\n\n" + "Interactive runs ask for confirmation; non-interactive runs require\n" + "--yes. Requires gitConnection:manageProjects.", @@ -1359,12 +1462,12 @@ func runPromotionProjectRemove(ctx context.Context, opts Options, id, projectID if err != nil { return err } - question := fmt.Sprintf("Remove project %q from promotion connection %q on %s? The project content stays; later promotes and applies skip it.", projectID, id, resolution.URL) + question := fmt.Sprintf("Remove project %q from promotion connection %q on %s? The project content stays; project-level sync falls back to the instance connection.", projectID, id, resolution.URL) if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } if err := client.RemoveProjectFromPromotionConnection(ctx, id, projectID); err != nil { - return promotionAPIError(err, resolution, "project remove") + return promotionAPIError(err, resolution, "project remove", promotionProjectLinkSubject(id, projectID)) } return writePromotionMutation(opts, resolution, promotionMutation{Action: "project removed", ConnectionID: id, ProjectID: projectID}, f.output) } @@ -1384,10 +1487,13 @@ func newPromotionPromoteCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "promote ", Short: "Promote team projects to the Git remote", - Long: "Export all team projects, commit them, and push to the promote\n" + - "checkout's branch. The promote checkout must be cloned first: run 'n8n\n" + - "promotion checkout clone CONNECTION_ID promote' and link projects\n" + - "with 'n8n promotion project add'.\n\n" + + Long: "Export every team project, commit it, and push to the configured base\n" + + "branch or a new timestamped branch (the result names it). Personal\n" + + "projects are ignored. This runs on the instance connection only, so\n" + + "project links from 'n8n promotion project add' do not select what is\n" + + "promoted. The promote checkout must be cloned first: run 'n8n promotion\n" + + "checkout clone CONNECTION_ID promote'. When workflows reference\n" + + "variables, the API key also needs variable:list.\n\n" + "Pass --commit-message once (1 to 1000 characters). Without --force a\n" + "promote the remote would reject is refused with 409 and nothing is\n" + "pushed; --force pushes anyway and rewrites remote history. This\n" + @@ -1436,7 +1542,7 @@ func runPromotionPromote(ctx context.Context, opts Options, id string, f promoti } result, err := client.PromotePackage(ctx, id, request) if err != nil { - return promotionAPIError(err, resolution, "promote") + return promotionAPIError(err, resolution, "promote", promotionConnectionSubject(id)) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, result) @@ -1455,14 +1561,25 @@ func newPromotionApplyCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "apply ", Short: "Apply the Git remote into this instance", - Long: "Reset the apply checkout to the branch tip and import projects into\n" + - "the instance, overwriting to match. The apply checkout must be cloned\n" + - "first. Preview what is linked with 'n8n promotion project list'.\n\n" + - "This rewrites instance content from the remote and cannot be undone:\n" + - "workflows, folders, credentials, data tables, variables, and tags are\n" + - "created, updated, or removed to match the branch, and credential gaps\n" + - "become stubs. Interactive runs ask for confirmation and\n" + - "non-interactive runs require --yes. Requires gitConnection:pull.", + Long: "Check the full package at the apply branch tip and import it into the\n" + + "instance, overwriting to match. Runs on the instance connection; the\n" + + "apply checkout must be cloned first.\n\n" + + "The server answers one of three statuses, and only one writes:\n" + + " applied content was imported; counts and warnings follow.\n" + + " blocked preflight stopped before any write: missing projects,\n" + + " missing credential or variable bindings, access\n" + + " requirements, or conflicts (including project-deletion\n" + + " and data-table destructive-change). Nothing was applied.\n" + + " source-changed the branch moved since it was reviewed. Nothing was\n" + + " applied.\n\n" + + "An applied run rewrites instance content from the remote and cannot be\n" + + "undone: workflows, folders, credentials, data tables, variables, and\n" + + "tags are created, updated, or removed to match the branch, and\n" + + "credential gaps become stubs. Interactive runs ask for confirmation and\n" + + "non-interactive runs require --yes. Requires gitConnection:pull.\n\n" + + "Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 any other error\n" + + "or an unknown status. --output json prints the full result on stdout\n" + + "in every status; the next step goes to stderr.", Example: " n8n promotion apply CONNECTION_ID\n" + " n8n promotion apply CONNECTION_ID --yes\n" + " n8n promotion apply CONNECTION_ID --yes --output json", @@ -1473,7 +1590,7 @@ func newPromotionApplyCommand(opts Options) *cobra.Command { } f.instance.register(cmd) cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm overwriting instance content from the remote without prompting (required when stdin is not interactive)") - cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the apply result with counts and commit)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the full apply result: status, git, and counts or preflight)") return cmd } @@ -1497,12 +1614,83 @@ func runPromotionApply(ctx context.Context, opts Options, id string, f promotion } result, err := client.ApplyPackage(ctx, id) if err != nil { - return promotionAPIError(err, resolution, "apply") + return promotionAPIError(err, resolution, "apply", promotionConnectionSubject(id)) } if f.output == outputJSON { - return writeJSON(opts.Streams.Out, result) + err = writeJSON(opts.Streams.Out, result) + } else { + err = writePromotionApplyResult(opts, resolution, result) + } + if err != nil { + return err + } + return finishPromotionApply(opts, id, result) +} + +// promotionApplyStoppedError is returned after an apply answered 200 without +// importing: blocked at preflight, the source moved, or a status this CLI does +// not know. The result was already printed; Run reports the message and maps +// the status to its own exit code so scripts can tell these apart from +// transport and validation errors. +type promotionApplyStoppedError struct { + connectionID, status string +} + +func (e *promotionApplyStoppedError) Error() string { + switch e.status { + case n8n.PromotionApplyStatusBlocked: + return fmt.Sprintf("promotion apply of connection %s was blocked at preflight; nothing was applied", e.connectionID) + case n8n.PromotionApplyStatusSourceChanged: + return fmt.Sprintf("promotion apply of connection %s stopped because the source branch moved; nothing was applied", e.connectionID) + default: + return fmt.Sprintf("promotion apply of connection %s answered unknown status %q; check the instance before assuming anything was applied", e.connectionID, e.status) + } +} + +func (e *promotionApplyStoppedError) exitCode() int { + switch e.status { + case n8n.PromotionApplyStatusBlocked: + return ExitPromotionBlocked + case n8n.PromotionApplyStatusSourceChanged: + return ExitPromotionSourceChanged + default: + return ExitError + } +} + +// finishPromotionApply writes the next-step hint for a result that wrote +// nothing and returns the matching error; an applied result returns nil. +func finishPromotionApply(opts Options, id string, result *n8n.ApplyPromotionResult) error { + if result.Applied() { + return nil + } + source := result.ExpectedSource() + switch result.Status { + case n8n.PromotionApplyStatusBlocked: + fmt.Fprintln(opts.Streams.Err, "Nothing was applied: preflight found items to resolve first. Create the missing projects, bind the missing credentials and variables, and grant the listed access.") + if promotionNeedsConfirmation(result.Preflight) { + fmt.Fprintln(opts.Streams.Err, "project-deletion and destructive-change conflicts are applied only with explicit confirmation when the apply is continued.") + } + fmt.Fprintf(opts.Streams.Err, "Then continue the apply with expected source configId=%s branchName=%s commitSha=%s (an 'apply-continue' command is upcoming in this CLI).\n", + emptyDash(source.ConfigID), emptyDash(source.BranchName), emptyDash(source.CommitSHA)) + case n8n.PromotionApplyStatusSourceChanged: + fmt.Fprintf(opts.Streams.Err, "Nothing was applied: the branch moved since it was reviewed. Review the branch again, then re-run 'n8n promotion apply %s'.\n", id) + default: + fmt.Fprintln(opts.Streams.Err, "This CLI does not know the apply status; read the full result with --output json.") + } + return &promotionApplyStoppedError{connectionID: id, status: result.Status} +} + +func promotionNeedsConfirmation(preflight *n8n.PromotionApplyPreflight) bool { + if preflight == nil { + return false + } + for _, conflict := range preflight.Conflicts { + if conflict.Code == n8n.PromotionConflictProjectDeletion || conflict.Code == n8n.PromotionConflictDestructiveChange { + return true + } } - return writePromotionApplyResult(opts, resolution, result) + return false } // Shared helpers. @@ -1554,6 +1742,9 @@ func writePromotionProviderResult(opts Options, resolution config.Resolution, ac if provider.Config != nil && provider.Config.PublicKey != nil { fmt.Fprintf(tw, "Public key:\t%s\n", truncatedPromotionSecret(*provider.Config.PublicKey)) } + if provider.Config != nil && provider.Config.BaseURL != nil { + fmt.Fprintf(tw, "Base URL:\t%s\n", emptyDash(*provider.Config.BaseURL)) + } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) if provider.CreatedAt != "" { fmt.Fprintf(tw, "Created:\t%s\n", provider.CreatedAt) @@ -1573,12 +1764,21 @@ func writePromotionConnectionResult(opts Options, resolution config.Resolution, fmt.Fprintf(tw, "Name:\t%s\n", emptyDash(connection.Name)) fmt.Fprintf(tw, "Scope:\t%s\n", emptyDash(connection.Scope)) fmt.Fprintf(tw, "Remote:\t%s\n", emptyDash(connection.Target.RemoteURL)) + if connection.Target.RepositoryPath != "" { + fmt.Fprintf(tw, "Repository path:\t%s\n", connection.Target.RepositoryPath) + } fmt.Fprintf(tw, "Provider:\t%s\n", emptyDash(connection.Provider.Name)) if connection.Configs.Apply != nil { fmt.Fprintf(tw, "Apply branch:\t%s\n", emptyDash(connection.Configs.Apply.Settings.BranchName)) + if checkout := connection.Configs.Apply.Checkout; checkout != nil { + fmt.Fprintf(tw, "Apply checkout:\t%s\n", promotionCheckoutState(*checkout)) + } } if connection.Configs.Promote != nil { fmt.Fprintf(tw, "Promote base:\t%s\n", emptyDash(connection.Configs.Promote.Settings.BaseBranchName)) + if checkout := connection.Configs.Promote.Checkout; checkout != nil { + fmt.Fprintf(tw, "Promote checkout:\t%s\n", promotionCheckoutState(*checkout)) + } } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) if connection.CreatedAt != "" { @@ -1590,6 +1790,19 @@ func writePromotionConnectionResult(opts Options, resolution config.Resolution, return tw.Flush() } +// promotionCheckoutState says whether a direction is cloned and whether the +// clone still matches its config (a stale clone needs 'checkout clone' again). +func promotionCheckoutState(checkout n8n.PromotionConfigCheckout) string { + switch { + case !checkout.HasCheckout: + return "not cloned" + case checkout.MatchesConfig: + return "cloned" + default: + return "cloned, does not match the config; clone again" + } +} + type promotionMutation struct { Action string `json:"action"` ProviderID string `json:"providerId,omitempty"` @@ -1650,55 +1863,198 @@ func writePromotionPromoteResult(opts Options, resolution config.Resolution, res } func writePromotionApplyResult(opts Options, resolution config.Resolution, result *n8n.ApplyPromotionResult) error { - tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) - fmt.Fprintf(tw, "Applied:\t%s\n", result.ConnectionID) + switch { + case result.Applied(): + return writePromotionAppliedResult(opts, resolution, result) + case result.Status == n8n.PromotionApplyStatusBlocked: + return writePromotionBlockedResult(opts, resolution, result) + default: + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + writePromotionApplyHeader(tw, resolution, result) + return tw.Flush() + } +} + +func writePromotionApplyHeader(tw *tabwriter.Writer, resolution config.Resolution, result *n8n.ApplyPromotionResult) { + label := "Not applied" + if result.Applied() { + label = "Applied" + } + fmt.Fprintf(tw, "%s:\t%s\n", label, result.ConnectionID) + fmt.Fprintf(tw, "Status:\t%s\n", emptyDash(result.Status)) + fmt.Fprintf(tw, "Config:\t%s\n", emptyDash(result.ConfigID)) fmt.Fprintf(tw, "Commit:\t%s\n", emptyDash(result.Git.CommitSHA)) fmt.Fprintf(tw, "Branch:\t%s\n", emptyDash(result.Git.BranchName)) fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) +} + +func writePromotionAppliedResult(opts Options, resolution config.Resolution, result *n8n.ApplyPromotionResult) error { + var counts n8n.PromotionApplyCounts + if result.Counts != nil { + counts = *result.Counts + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + writePromotionApplyHeader(tw, resolution, result) fmt.Fprintln(tw, "\nENTITY\tDETAIL\tCOUNT") - fmt.Fprintf(tw, "projects\tcreated\t%d\n", result.Counts.Projects.Created) - fmt.Fprintf(tw, "projects\tupdated\t%d\n", result.Counts.Projects.Updated) - fmt.Fprintf(tw, "projects\tskipped\t%d\n", result.Counts.Projects.Skipped) - fmt.Fprintf(tw, "projects\tdeleted\t%d\n", result.Counts.Projects.Deleted) - fmt.Fprintf(tw, "folders\tcreated\t%d\n", result.Counts.Folders.Created) - fmt.Fprintf(tw, "folders\tskipped\t%d\n", result.Counts.Folders.Skipped) - fmt.Fprintf(tw, "folders\tremoved\t%d\n", result.Counts.Folders.Removed) - fmt.Fprintf(tw, "workflows\tcreated\t%d\n", result.Counts.Workflows.Created) - fmt.Fprintf(tw, "workflows\tupdated\t%d\n", result.Counts.Workflows.Updated) - fmt.Fprintf(tw, "workflows\tskipped\t%d\n", result.Counts.Workflows.Skipped) - fmt.Fprintf(tw, "workflows\tarchived\t%d\n", result.Counts.Workflows.Archived) - fmt.Fprintf(tw, "workflows\tdeleted\t%d\n", result.Counts.Workflows.Deleted) - fmt.Fprintf(tw, "workflows\tpublished\t%d\n", result.Counts.Workflows.Publishing.Published) - fmt.Fprintf(tw, "workflows\tunpublished\t%d\n", result.Counts.Workflows.Publishing.Unpublished) - fmt.Fprintf(tw, "workflows\tunchanged\t%d\n", result.Counts.Workflows.Publishing.Unchanged) - fmt.Fprintf(tw, "workflows\tblocked\t%d\n", result.Counts.Workflows.Publishing.Blocked) - fmt.Fprintf(tw, "workflows\tfailed\t%d\n", result.Counts.Workflows.Publishing.Failed) - fmt.Fprintf(tw, "credentials\tmatched\t%d\n", result.Counts.Credentials.Matched) - fmt.Fprintf(tw, "credentials\tstubbed\t%d\n", result.Counts.Credentials.Stubbed) - fmt.Fprintf(tw, "dataTables\tmatched\t%d\n", result.Counts.DataTables.Matched) - fmt.Fprintf(tw, "dataTables\tcreated\t%d\n", result.Counts.DataTables.Created) - fmt.Fprintf(tw, "variables\tmatched\t%d\n", result.Counts.Variables.Matched) - fmt.Fprintf(tw, "variables\tcreated\t%d\n", result.Counts.Variables.Created) - fmt.Fprintf(tw, "variables\tupdated\t%d\n", result.Counts.Variables.Updated) - fmt.Fprintf(tw, "variables\tstubbed\t%d\n", result.Counts.Variables.Stubbed) - fmt.Fprintf(tw, "variables\tmissing\t%d\n", result.Counts.Variables.Missing) - fmt.Fprintf(tw, "tags\tmatched\t%d\n", result.Counts.Tags.Matched) - fmt.Fprintf(tw, "tags\tcreated\t%d\n", result.Counts.Tags.Created) - fmt.Fprintf(tw, "tags\trenamed\t%d\n", result.Counts.Tags.Renamed) - fmt.Fprintf(tw, "tags\treconciled\t%d\n", result.Counts.Tags.Reconciled) - fmt.Fprintf(tw, "tags\tskipped\t%d\n", result.Counts.Tags.Skipped) + fmt.Fprintf(tw, "projects\tcreated\t%d\n", counts.Projects.Created) + fmt.Fprintf(tw, "projects\tupdated\t%d\n", counts.Projects.Updated) + fmt.Fprintf(tw, "projects\tskipped\t%d\n", counts.Projects.Skipped) + fmt.Fprintf(tw, "projects\tdeleted\t%d\n", counts.Projects.Deleted) + fmt.Fprintf(tw, "folders\tcreated\t%d\n", counts.Folders.Created) + fmt.Fprintf(tw, "folders\tskipped\t%d\n", counts.Folders.Skipped) + fmt.Fprintf(tw, "folders\tremoved\t%d\n", counts.Folders.Removed) + fmt.Fprintf(tw, "workflows\tcreated\t%d\n", counts.Workflows.Created) + fmt.Fprintf(tw, "workflows\tupdated\t%d\n", counts.Workflows.Updated) + fmt.Fprintf(tw, "workflows\tskipped\t%d\n", counts.Workflows.Skipped) + fmt.Fprintf(tw, "workflows\tarchived\t%d\n", counts.Workflows.Archived) + fmt.Fprintf(tw, "workflows\tdeleted\t%d\n", counts.Workflows.Deleted) + fmt.Fprintf(tw, "workflows\tpublished\t%d\n", counts.Workflows.Publishing.Published) + fmt.Fprintf(tw, "workflows\tunpublished\t%d\n", counts.Workflows.Publishing.Unpublished) + fmt.Fprintf(tw, "workflows\tunchanged\t%d\n", counts.Workflows.Publishing.Unchanged) + fmt.Fprintf(tw, "workflows\tblocked\t%d\n", counts.Workflows.Publishing.Blocked) + fmt.Fprintf(tw, "workflows\tfailed\t%d\n", counts.Workflows.Publishing.Failed) + fmt.Fprintf(tw, "credentials\tmatched\t%d\n", counts.Credentials.Matched) + fmt.Fprintf(tw, "credentials\tstubbed\t%d\n", counts.Credentials.Stubbed) + fmt.Fprintf(tw, "dataTables\tmatched\t%d\n", counts.DataTables.Matched) + fmt.Fprintf(tw, "dataTables\tcreated\t%d\n", counts.DataTables.Created) + fmt.Fprintf(tw, "dataTables\tupdated\t%d\n", counts.DataTables.Updated) + fmt.Fprintf(tw, "variables\tmatched\t%d\n", counts.Variables.Matched) + fmt.Fprintf(tw, "variables\tcreated\t%d\n", counts.Variables.Created) + fmt.Fprintf(tw, "variables\tupdated\t%d\n", counts.Variables.Updated) + fmt.Fprintf(tw, "variables\tstubbed\t%d\n", counts.Variables.Stubbed) + fmt.Fprintf(tw, "variables\tmissing\t%d\n", counts.Variables.Missing) + fmt.Fprintf(tw, "tags\tmatched\t%d\n", counts.Tags.Matched) + fmt.Fprintf(tw, "tags\tcreated\t%d\n", counts.Tags.Created) + fmt.Fprintf(tw, "tags\trenamed\t%d\n", counts.Tags.Renamed) + fmt.Fprintf(tw, "tags\treconciled\t%d\n", counts.Tags.Reconciled) + fmt.Fprintf(tw, "tags\tskipped\t%d\n", counts.Tags.Skipped) + writePromotionIssues(tw, "Warnings", result.Warnings) if err := tw.Flush(); err != nil { return err } - if result.Counts.Variables.Missing > 0 { - fmt.Fprintf(opts.Streams.Err, "%d variable(s) still unresolved: workflows referencing them may fail until the variables exist.\n", result.Counts.Variables.Missing) + if counts.Variables.Missing > 0 { + fmt.Fprintf(opts.Streams.Err, "%d variable(s) still unresolved: workflows referencing them may fail until the variables exist.\n", counts.Variables.Missing) } - if result.Counts.Workflows.Publishing.Failed > 0 || result.Counts.Workflows.Publishing.Blocked > 0 { + if counts.Workflows.Publishing.Failed > 0 || counts.Workflows.Publishing.Blocked > 0 { fmt.Fprintln(opts.Streams.Err, "Some workflows did not publish: see the publishing counts in --output json.") } + if len(result.Warnings) > 0 { + fmt.Fprintf(opts.Streams.Err, "The apply finished with %d warning(s): see the WARNINGS table.\n", len(result.Warnings)) + } return nil } +func writePromotionBlockedResult(opts Options, resolution config.Resolution, result *n8n.ApplyPromotionResult) error { + var preflight n8n.PromotionApplyPreflight + if result.Preflight != nil { + preflight = *result.Preflight + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + writePromotionApplyHeader(tw, resolution, result) + if len(preflight.MissingProjects) > 0 { + fmt.Fprintf(tw, "\nMISSING PROJECTS (%d)\nID\tNAME\n", len(preflight.MissingProjects)) + for _, project := range preflight.MissingProjects { + fmt.Fprintf(tw, "%s\t%s\n", emptyDash(project.ID), emptyDash(project.Name)) + } + } + writePromotionIssues(tw, "Missing bindings", preflight.MissingBindings) + writePromotionIssues(tw, "Access requirements", preflight.AccessRequirements) + writePromotionIssues(tw, "Conflicts", preflight.Conflicts) + writePromotionIssues(tw, "Warnings", preflight.Warnings) + if preflight.Empty() { + fmt.Fprintln(tw, "\nPreflight:\tno items reported") + } + return tw.Flush() +} + +// writePromotionIssues renders one preflight group as a table: kind, code, +// name, a one-line detail, and which workflows use the item. +func writePromotionIssues(tw *tabwriter.Writer, title string, issues []n8n.PromotionApplyIssue) { + if len(issues) == 0 { + return + } + fmt.Fprintf(tw, "\n%s (%d)\nKIND\tCODE\tNAME\tDETAIL\tUSED BY\n", strings.ToUpper(title), len(issues)) + for _, issue := range issues { + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", emptyDash(issue.Kind), emptyDash(issue.Code), + emptyDash(promotionIssueName(issue)), emptyDash(promotionIssueDetail(issue)), emptyDash(promotionIssueConsumers(issue))) + } +} + +func promotionIssueName(issue n8n.PromotionApplyIssue) string { + if issue.Name == "" && issue.Project != nil { + return issue.Project.Name + } + return issue.Name +} + +func promotionIssueDetail(issue n8n.PromotionApplyIssue) string { + var parts []string + switch issue.Code { + case n8n.PromotionConflictProjectDeletion: + parts = append(parts, "the apply deletes this team project and everything in it") + case n8n.PromotionConflictDestructiveChange: + for _, change := range issue.Changes { + if change.Destructive { + parts = append(parts, promotionChangeText(change)) + } + } + } + if issue.CredentialType != "" { + parts = append(parts, "type "+issue.CredentialType) + } + if len(issue.ExpectedTypes) > 0 { + parts = append(parts, "expected "+strings.Join(issue.ExpectedTypes, "|")) + } + if issue.TargetType != "" { + parts = append(parts, "instance has "+issue.TargetType) + } + if issue.UsageScope != "" { + parts = append(parts, "usage scope "+issue.UsageScope) + } + if issue.Scope != nil { + scope := issue.Scope.Kind + if issue.Scope.Project != nil { + scope += " " + issue.Scope.Project.Name + } + parts = append(parts, "scope "+scope) + } + if issue.SourceID != nil && *issue.SourceID != "" { + parts = append(parts, "source ID "+*issue.SourceID) + } + if issue.Project != nil && issue.Code != n8n.PromotionConflictProjectDeletion { + parts = append(parts, "project "+issue.Project.ID) + } + if issue.OwnerProject != nil { + parts = append(parts, "owner "+issue.OwnerProject.Name) + } + return strings.Join(parts, "; ") +} + +func promotionChangeText(change n8n.PromotionDataTableChange) string { + switch { + case change.Column != "" && change.From != "" && change.To != "": + return fmt.Sprintf("%s %s %s->%s", change.Kind, change.Column, change.From, change.To) + case change.Column != "": + return fmt.Sprintf("%s %s", change.Kind, change.Column) + default: + return change.Kind + } +} + +func promotionIssueConsumers(issue n8n.PromotionApplyIssue) string { + workflows := len(issue.Workflows) + for _, consumer := range issue.Consumers { + workflows += len(consumer.Workflows) + } + if workflows == 0 { + return "" + } + if len(issue.Consumers) == 0 { + return fmt.Sprintf("%d workflow(s)", workflows) + } + return fmt.Sprintf("%d workflow(s) in %d project(s)", workflows, len(issue.Consumers)) +} + // truncatedPromotionSecret keeps public keys out of full display: text output // shows only a prefix while JSON keeps the complete value for scripting. func truncatedPromotionSecret(value string) string { @@ -1712,12 +2068,37 @@ func truncatedPromotionSecret(value string) string { return value[:prefix] + "…" } -func promotionAPIError(err error, resolution config.Resolution, action string) error { +// promotionSubject names what one promotion route addresses, so a 404 can say +// which ID is missing. The zero value is a collection route, where a 404 can +// only mean the instance does not serve the module. +type promotionSubject struct { + what string // e.g. promotion connection "conn-1" + find string // the command that lists valid IDs +} + +func promotionProviderSubject(id string) promotionSubject { + return promotionSubject{what: fmt.Sprintf("promotion provider %q", id), find: "'n8n promotion provider list'"} +} + +func promotionConnectionSubject(id string) promotionSubject { + return promotionSubject{what: fmt.Sprintf("promotion connection %q", id), find: "'n8n promotion connection list'"} +} + +func promotionProjectLinkSubject(id, projectID string) promotionSubject { + return promotionSubject{ + what: fmt.Sprintf("promotion connection %q or project %q", id, projectID), + find: "'n8n promotion connection list' and 'n8n project list'", + } +} + +func promotionAPIError(err error, resolution config.Resolution, action string, subject promotionSubject) error { switch { case n8n.IsConflict(err) && action == "provider delete": return fmt.Errorf("%s rejected the promotion provider delete (409): the provider still has attached connections, so nothing changed; remove them first, then delete the provider: %w", resolution.URL, err) case n8n.IsConflict(err) && action == "project add": return fmt.Errorf("%s rejected the promotion project add (409): the project is already linked to a connection, so nothing changed; remove it there first, then add it here: %w", resolution.URL, err) + case n8n.IsConflict(err) && action == "provider update": + return fmt.Errorf("%s rejected the promotion provider update (409): another request changed the provider's credential or configuration first, so nothing changed; reload it with 'n8n promotion provider get' and retry: %w", resolution.URL, err) case n8n.IsConflict(err): return fmt.Errorf("%s rejected the promotion %s (409): the connection or project is in a conflicting state, so nothing changed; list the current state and retry: %w", resolution.URL, action, err) case n8n.IsStatus(err, http.StatusBadRequest): @@ -1726,6 +2107,11 @@ func promotionAPIError(err error, resolution config.Resolution, action string) e return fmt.Errorf("%s rejected the promotion %s (422): the remote content cannot be imported as-is (missing references or unresolvable content); resolve the references and retry: %w", resolution.URL, action, err) case n8n.IsForbidden(err): return forbiddenScopeError(err, resolution, "promotion "+action, allOf(promotionScope(action)), "", promotionResource) + case n8n.IsNotFound(err) && subject.what != "" && !promotionRouteMissing(err): + return fmt.Errorf("%s has no %s (404): check the ID with %s: %w", resolution.URL, subject.what, subject.find, err) + case n8n.IsNotFound(err) && subject.what != "": + return fmt.Errorf("%s answered 404 for %s: either the ID does not exist (check it with %s) or the instance does not serve promotions (run %s): %w", + resolution.URL, subject.what, subject.find, discoverHint(promotionResource), err) case n8n.IsNotFound(err), n8n.IsStatus(err, http.StatusServiceUnavailable): return fmt.Errorf("%s does not serve promotions (%d): it needs the Promotions module (a GitConnections-generation instance answers here instead); run %s to see what this instance offers: %w", resolution.URL, n8n.StatusCodeOf(err), discoverHint(promotionResource), err) @@ -1734,6 +2120,22 @@ func promotionAPIError(err error, resolution config.Resolution, action string) e } } +// promotionRouteMissing reports whether a 404 carries nothing beyond the +// status: no code and no message, or only a generic "not found" or framework +// "Cannot POST ..." text. That is what an unmounted route answers; a missing +// connection, provider or project answers with its own message. +func promotionRouteMissing(err error) bool { + apiErr, ok := errors.AsType[*n8n.APIError](err) + if !ok { + return true + } + if apiErr.Code != "" { + return false + } + message := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(apiErr.Message), ".")) + return message == "" || message == "not found" || strings.HasPrefix(message, "cannot ") +} + func promotionScope(action string) string { switch action { case "provider list", "connection list": @@ -1754,6 +2156,8 @@ func promotionScope(action string) string { return "gitConnection:push" case "apply": return "gitConnection:pull" + case "provider repositories", "provider branches": + return "gitConnection:discover" default: return "gitConnection:*" } diff --git a/internal/cli/promotion_apply_test.go b/internal/cli/promotion_apply_test.go new file mode 100644 index 0000000..9f7dea4 --- /dev/null +++ b/internal/cli/promotion_apply_test.go @@ -0,0 +1,349 @@ +package cli + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +const cliPromotionAppliedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"0123456789abcdef0123456789abcdef01234567","branchName":"main"}, + "status":"applied", + "counts":{ + "projects":{"created":1,"updated":0,"skipped":0,"deleted":0}, + "folders":{"created":0,"skipped":0,"removed":0}, + "workflows":{"created":1,"updated":0,"skipped":0,"archived":0,"deleted":0,"publishing":{"published":1,"unpublished":0,"unchanged":0,"blocked":0,"failed":0}}, + "credentials":{"matched":1,"stubbed":0}, + "dataTables":{"matched":0,"created":0,"updated":2}, + "variables":{"matched":0,"created":0,"updated":0,"stubbed":0,"missing":0}, + "tags":{"matched":0,"created":0,"renamed":0,"reconciled":0,"skipped":0} + }, + "warnings":[ + {"kind":"variable","code":"variable-shadowed","name":"API_URL","scope":{"kind":"global"}, + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-1","name":"Sync"}]}]} + ] +}` + +const cliPromotionBlockedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"0123456789abcdef0123456789abcdef01234567","branchName":"main"}, + "status":"blocked", + "preflight":{ + "missingProjects":[{"id":"p-9","name":"Ops"}], + "missingBindings":[ + {"kind":"credential","sourceId":"cred-1","name":"Slack","credentialType":"slackApi", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-1","name":"Sync"},{"id":"wf-2","name":"Notify"}]}], + "ownerProject":{"id":"p-1","name":"Sales"}} + ], + "accessRequirements":[ + {"kind":"credential","sourceId":"cred-2","name":"Postgres","credentialType":"postgres","code":"access-required", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-3","name":"Load"}]}]} + ], + "conflicts":[ + {"kind":"project","code":"project-deletion","project":{"id":"p-7","name":"Legacy"}}, + {"kind":"data-table","code":"destructive-change","id":"dt-1","name":"Orders", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-5","name":"Orders"}]}], + "changes":[{"kind":"remove-column","column":"total","type":"number","destructive":true}, + {"kind":"rename-table","from":"orders","to":"Orders","destructive":false}]} + ], + "warnings":[] + } +}` + +const cliPromotionSourceChangedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"fedcba9876543210fedcba9876543210fedcba98","branchName":"main"}, + "status":"source-changed" +}` + +func sameJSON(t *testing.T, got, want string) bool { + t.Helper() + var a, b bytes.Buffer + if err := json.Compact(&a, []byte(got)); err != nil { + t.Errorf("stdout is not JSON: %v\n%s", err, got) + return false + } + if err := json.Compact(&b, []byte(want)); err != nil { + t.Fatalf("fixture is not JSON: %v", err) + } + return a.String() == b.String() +} + +func TestPromotionApplyBlocked(t *testing.T) { + f := promotionFixture(t, cliPromotionBlockedBody) + + got := f.run("promotion", "apply", "conn-1", "--yes", "--output", "json") + if got.code != ExitPromotionBlocked { + t.Fatalf("exit = %d, want %d (stderr: %s)", got.code, ExitPromotionBlocked, got.stderr) + } + if !sameJSON(t, got.stdout, cliPromotionBlockedBody) { + t.Errorf("stdout = %s, want the full blocked result", got.stdout) + } + for _, want := range []string{"Nothing was applied", "configId=cfg-apply", "branchName=main", "commitSha=0123456789abcdef0123456789abcdef01234567", "explicit confirmation", "blocked at preflight"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, got.stderr) + } + } + if strings.Contains(got.stderr, "Run 'n8n --help'") { + t.Errorf("stderr = %q, want no usage hint for a reported outcome", got.stderr) + } + + got = f.run("promotion", "apply", "conn-1", "--yes") + if got.code != ExitPromotionBlocked { + t.Fatalf("text exit = %d, want %d (stderr: %s)", got.code, ExitPromotionBlocked, got.stderr) + } + for _, want := range []string{ + "Not applied:", "blocked", + "MISSING PROJECTS (1)", "p-9", "Ops", + "MISSING BINDINGS (1)", "Slack", "type slackApi", "2 workflow(s) in 1 project(s)", + "ACCESS REQUIREMENTS (1)", "access-required", "Postgres", + "CONFLICTS (2)", "project-deletion", "Legacy", "deletes this team project", + "destructive-change", "Orders", "remove-column total", + } { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + if strings.Contains(got.stdout, "Applied:") || strings.Contains(got.stdout, "ENTITY") || strings.Contains(got.stdout, "rename-table") { + t.Errorf("stdout = %s, want no applied counts and only destructive changes", got.stdout) + } +} + +func TestPromotionApplySourceChanged(t *testing.T) { + f := promotionFixture(t, cliPromotionSourceChangedBody) + + got := f.run("promotion", "apply", "conn-1", "--yes", "--output", "json") + if got.code != ExitPromotionSourceChanged { + t.Fatalf("exit = %d, want %d (stderr: %s)", got.code, ExitPromotionSourceChanged, got.stderr) + } + if !sameJSON(t, got.stdout, cliPromotionSourceChangedBody) { + t.Errorf("stdout = %s, want the full result", got.stdout) + } + if !strings.Contains(got.stderr, "branch moved") || !strings.Contains(got.stderr, "Nothing was applied") || !strings.Contains(got.stderr, "n8n promotion apply conn-1") { + t.Errorf("stderr = %q, want the re-run hint", got.stderr) + } + + got = f.run("promotion", "apply", "conn-1", "--yes") + if got.code != ExitPromotionSourceChanged || !strings.Contains(got.stdout, "source-changed") || strings.Contains(got.stdout, "ENTITY") { + t.Errorf("text result = %+v, want the status without counts", got) + } +} + +func TestPromotionApplyUnknownStatusIsNotSuccess(t *testing.T) { + body := `{"connectionId":"conn-1","configId":"cfg-apply","git":{"commitSha":"abc","branchName":"main"},"status":"queued","queue":{"position":1}}` + f := promotionFixture(t, body) + + got := f.run("promotion", "apply", "conn-1", "--yes", "--output", "json") + if got.code != ExitError { + t.Fatalf("exit = %d, want %d (stderr: %s)", got.code, ExitError, got.stderr) + } + if !sameJSON(t, got.stdout, body) { + t.Errorf("stdout = %s, want the unknown result kept intact", got.stdout) + } + if !strings.Contains(got.stderr, `unknown status "queued"`) { + t.Errorf("stderr = %q, want the unknown status named", got.stderr) + } +} + +func TestPromotionApplyAppliedWithWarnings(t *testing.T) { + f := promotionFixture(t, cliPromotionAppliedBody) + + got := f.run("promotion", "apply", "conn-1", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Applied:", "conn-1", "dataTables updated 2", "WARNINGS (1)", "variable-shadowed", "API_URL", "scope global"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + if !strings.Contains(got.stderr, "1 warning(s)") { + t.Errorf("stderr = %q, want the warning hint", got.stderr) + } + + got = f.run("promotion", "apply", "conn-1", "--yes", "--output", "json") + if got.code != ExitSuccess || !sameJSON(t, got.stdout, cliPromotionAppliedBody) { + t.Errorf("json result = %+v, want the verbatim applied result", got) + } +} + +func TestPromotionProviderCreateGitLabFromFlags(t *testing.T) { + f := promotionFixture(t, `{"provider":{"id":"prov-2","name":"gitlab","type":"gitlab","authType":"token", + "config":{"schemaVersion":1,"baseUrl":"https://gitlab.example.com"},"createdAt":"t","updatedAt":"t"},"publicKey":null}`) + + f.stdin = "glpat-super-secret\n" + got := f.run("promotion", "provider", "create", "--name", "gitlab", "--type", "gitlab", + "--base-url", "https://gitlab.example.com", "--auth-type", "token", "--password-stdin") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var sent map[string]json.RawMessage + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body: %v", err) + } + if string(sent["type"]) != `"gitlab"` || string(sent["config"]) != `{"schemaVersion":1,"baseUrl":"https://gitlab.example.com"}` { + t.Errorf("request = %s, want gitlab with config", f.lastBody()) + } + if string(sent["auth"]) != `{"authType":"token","password":"glpat-super-secret"}` { + t.Errorf("auth = %s, want the token without a username", sent["auth"]) + } + if !strings.Contains(got.stdout, "Base URL:") || !strings.Contains(got.stdout, "https://gitlab.example.com") { + t.Errorf("stdout = %s, want the base URL", got.stdout) + } + if strings.Contains(got.stdout+got.stderr, "glpat") { + t.Errorf("token leaked into output:\n%s\n%s", got.stdout, got.stderr) + } + + // Interactive token auth asks without echo. + f.prompt.secret = "prompted-token" + f.prompt.prompts = nil + got = f.run("promotion", "provider", "create", "--name", "gitlab", "--type", "gitlab", "--auth-type", "token") + if got.code != ExitSuccess || len(f.prompt.prompts) != 1 || !strings.Contains(f.lastBody(), "prompted-token") { + t.Errorf("prompted result = %+v, prompts = %q, body = %s", got, f.prompt.prompts, f.lastBody()) + } + + // SSH-key auth on a git provider needs no secret at all. + f.prompt.prompts = nil + got = f.run("promotion", "provider", "create", "--name", "github") + if got.code != ExitSuccess || len(f.prompt.prompts) != 0 || !strings.Contains(f.lastBody(), `"type":"git"`) || !strings.Contains(f.lastBody(), `"authType":"ssh-key"`) { + t.Errorf("ssh-key result = %+v, body = %s", got, f.lastBody()) + } +} + +func TestPromotionProviderCreateFlagErrorsBeforeTransport(t *testing.T) { + f := promotionFixture(t, cliPromotionProviderCreateBody) + before := f.requestCount() + path := writePromotionInput(t, f, "provider.json", `{"name":"github","type":"git","auth":{"authType":"ssh-key"}}`) + + f.prompt.prompts = nil + for _, tc := range []struct { + args []string + interactive bool + want string + }{ + {[]string{"--input", path, "--name", "x"}, true, "mutually exclusive"}, + {[]string{"--name", "x", "--type", "git", "--base-url", "https://gitlab.example.com"}, true, "gitlab providers only"}, + {[]string{"--name", "x", "--type", "gitlab", "--base-url", "gitlab.example.com"}, true, "absolute http or https URL"}, + {[]string{"--name", "x", "--auth-type", "token"}, true, "username is required"}, + {[]string{"--name", "x", "--password-stdin"}, true, "needs --auth-type token"}, + {[]string{"--name", "x", "--type", "gitlab", "--auth-type", "token"}, false, "pipe it with --password-stdin"}, + {[]string{"--type", "bitbucket", "--name", "x"}, true, "unknown provider type"}, + } { + f.interactive = tc.interactive + got := f.run(append([]string{"promotion", "provider", "create"}, tc.args...)...) + if got.code != ExitError || !strings.Contains(got.stderr, tc.want) { + t.Errorf("%v result = %+v, want %q", tc.args, got, tc.want) + } + } + if f.requestCount() != before || len(f.prompt.prompts) != 0 { + t.Errorf("requests = %d want %d, prompts = %q: want refusal before the token prompt and transport", f.requestCount(), before, f.prompt.prompts) + } +} + +func TestPromotionGitLabTokenInputNeedsNoUsername(t *testing.T) { + f := promotionFixture(t, cliPromotionProviderCreateBody) + + path := writePromotionInput(t, f, "gitlab.json", `{"name":"gl","type":"gitlab","auth":{"authType":"token","password":"secret"},"config":{"schemaVersion":1,"baseUrl":"https://gitlab.example.com"}}`) + if got := f.run("promotion", "provider", "create", "--input", path); got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(f.lastBody(), `"config":{"schemaVersion":1,"baseUrl":"https://gitlab.example.com"}`) { + t.Errorf("body = %s, want the config forwarded", f.lastBody()) + } + + f.body = cliPromotionProviderBody + update := writePromotionInput(t, f, "gitlab-update.json", `{"config":{"schemaVersion":1,"baseUrl":"https://gitlab2.example.com"},"auth":{"authType":"token","password":"new"}}`) + if got := f.run("promotion", "provider", "update", "prov-1", "--input", update, "--yes"); got.code != ExitSuccess { + t.Fatalf("update exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(f.lastBody(), "gitlab2.example.com") { + t.Errorf("update body = %s, want the new base URL", f.lastBody()) + } +} + +func TestPromotionConnectionTargetRepositoryPath(t *testing.T) { + body := `{"id":"conn-2","name":"gl","scope":"instance", + "target":{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git","repositoryPath":"org/repo"}, + "provider":{"id":"prov-2","name":"gitlab","type":"gitlab","authType":"token","createdAt":"t","updatedAt":"t"}, + "configs":{"apply":{"id":"cfg-a","name":"Apply","createdAt":"t","updatedAt":"t","checkout":{"hasCheckout":true,"matchesConfig":false},"settings":{"schemaVersion":1,"branchName":"main"}}}, + "createdAt":"t","updatedAt":"t"}` + f := promotionFixture(t, body) + + got := f.run("promotion", "connection", "get", "conn-2", "--output", "json") + if got.code != ExitSuccess || !sameJSON(t, got.stdout, body) { + t.Errorf("json result = %+v, want the connection with repositoryPath and checkout intact", got) + } + got = f.run("promotion", "connection", "get", "conn-2") + for _, want := range []string{"Repository path:", "org/repo", "Apply checkout:", "does not match"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + + before := f.requestCount() + path := writePromotionInput(t, f, "conn-update.json", `{"target":{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git","repositoryPath":"org/repo"}}`) + got = f.run("promotion", "connection", "update", "conn-2", "--input", path) + if got.code != ExitError || !strings.Contains(got.stderr, "repositoryPath is read-only") || f.requestCount() != before { + t.Errorf("read-only update result = %+v, requests = %d want %d", got, f.requestCount(), before) + } +} + +func TestPromotionNotFoundNamesTheMissingResource(t *testing.T) { + f := promotionFixture(t, `{}`) + notFound := func(body string) func(*http.Request, int) (int, string) { + return func(*http.Request, int) (int, string) { return http.StatusNotFound, body } + } + + f.route = notFound(`{"message":"Promotion connection conn-1 not found"}`) + got := f.run("promotion", "connection", "get", "conn-1") + if got.code != ExitError || !strings.Contains(got.stderr, `has no promotion connection "conn-1" (404)`) || !strings.Contains(got.stderr, "n8n promotion connection list") { + t.Errorf("specific 404 = %+v, want the missing connection named", got) + } + if strings.Contains(got.stderr, "does not serve promotions") { + t.Errorf("specific 404 = %q, want no module diagnostic", got.stderr) + } + + f.route = notFound(`{"message":"not found"}`) + got = f.run("promotion", "provider", "get", "prov-1") + if got.code != ExitError || !strings.Contains(got.stderr, `promotion provider "prov-1"`) || !strings.Contains(got.stderr, "does not serve promotions") { + t.Errorf("generic 404 on an ID route = %+v, want both causes", got) + } + + got = f.run("promotion", "project", "add", "conn-1", "proj-1") + if got.code != ExitError || !strings.Contains(got.stderr, `project "proj-1"`) || !strings.Contains(got.stderr, "n8n project list") { + t.Errorf("project add 404 = %+v, want both IDs named", got) + } + + got = f.run("promotion", "connection", "list") + if got.code != ExitError || !strings.Contains(got.stderr, "does not serve promotions (404)") || !strings.Contains(got.stderr, "n8n discover --resource promotions") { + t.Errorf("collection 404 = %+v, want the module diagnostic", got) + } +} + +func TestPromotionScopeCoversDiscover(t *testing.T) { + for _, action := range []string{"provider repositories", "provider branches"} { + if got := promotionScope(action); got != "gitConnection:discover" { + t.Errorf("promotionScope(%q) = %q, want gitConnection:discover", action, got) + } + } +} + +func TestPromotionApplyStoppedErrorExitCodes(t *testing.T) { + for status, want := range map[string]int{ + n8n.PromotionApplyStatusBlocked: ExitPromotionBlocked, + n8n.PromotionApplyStatusSourceChanged: ExitPromotionSourceChanged, + "queued": ExitError, + } { + if got := (&promotionApplyStoppedError{connectionID: "c", status: status}).exitCode(); got != want { + t.Errorf("exit code for %q = %d, want %d", status, got, want) + } + } +} diff --git a/internal/cli/promotion_test.go b/internal/cli/promotion_test.go index 3e560f0..129ff16 100644 --- a/internal/cli/promotion_test.go +++ b/internal/cli/promotion_test.go @@ -650,11 +650,13 @@ func TestPromotionDenialsAreReported(t *testing.T) { t.Errorf("403 result = %+v, want scope and discover hint", got) } - f.status = http.StatusNotFound + // A bare 404 on an ID route names both causes: missing ID or module. + f.route = func(*http.Request, int) (int, string) { return http.StatusNotFound, `{"message":"not found"}` } got = f.run("promotion", "apply", "conn-1", "--yes") if got.code != ExitError || !strings.Contains(got.stderr, "does not serve promotions") || !strings.Contains(got.stderr, "n8n discover --resource promotions") { t.Errorf("404 result = %+v, want the availability hint", got) } + f.route = nil f.status = http.StatusServiceUnavailable got = f.run("promotion", "provider", "get", "prov-1") diff --git a/internal/n8n/promotion.go b/internal/n8n/promotion.go index 66a5091..4af11c3 100644 --- a/internal/n8n/promotion.go +++ b/internal/n8n/promotion.go @@ -1,11 +1,15 @@ package n8n import ( + "bytes" "context" + "encoding/json" "errors" "fmt" + "maps" "net/http" "net/url" + "regexp" "slices" "strings" "unicode/utf8" @@ -34,10 +38,16 @@ const ( var promotionDirections = []string{PromotionDirectionApply, PromotionDirectionPromote} +// Provider types. A gitlab provider is a Git host provider: it talks to the +// GitLab API, so it can list repositories and carries an optional base URL for +// self-managed GitLab. A git provider is a plain Git remote. const ( - PromotionProviderTypeGit = "git" + PromotionProviderTypeGit = "git" + PromotionProviderTypeGitLab = "gitlab" ) +var promotionProviderTypes = []string{PromotionProviderTypeGit, PromotionProviderTypeGitLab} + const ( PromotionAuthTypeSSHKey = "ssh-key" PromotionAuthTypeToken = "token" @@ -62,12 +72,36 @@ const ( ) // PromotionProviderConfig is the public provider configuration. SSH providers -// report their public key and key type; token providers report only the schema -// version because the secret stays server-side. +// report their public key and key type; GitLab providers report their base +// URL; token providers otherwise report only the schema version because the +// secret stays server-side. type PromotionProviderConfig struct { SchemaVersion int `json:"schemaVersion"` PublicKey *string `json:"publicKey,omitempty"` KeyType *string `json:"keyType,omitempty"` + BaseURL *string `json:"baseUrl,omitempty"` +} + +// PromotionProviderHostConfig is the write document for a Git host provider +// configuration: the base URL of a self-managed GitLab. +type PromotionProviderHostConfig struct { + SchemaVersion int `json:"schemaVersion"` + BaseURL string `json:"baseUrl"` +} + +// Validate rejects a host configuration the API would reject before transport. +func (c PromotionProviderHostConfig) Validate() error { + if c.SchemaVersion != promotionTargetSchemaVersion { + return fmt.Errorf("config schemaVersion must be %d, got %d", promotionTargetSchemaVersion, c.SchemaVersion) + } + if strings.TrimSpace(c.BaseURL) == "" { + return fmt.Errorf("config baseUrl is required: pass the GitLab URL, e.g. https://gitlab.example.com") + } + parsed, err := url.Parse(c.BaseURL) + if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Host == "" { + return fmt.Errorf("config baseUrl %q must be an absolute http or https URL, e.g. https://gitlab.example.com", c.BaseURL) + } + return nil } // PromotionProvider is one promotion provider as list, get and update report @@ -91,7 +125,8 @@ type PromotionProviderCreateResult struct { // PromotionProviderAuth carries one provider credential document. SSH-key auth // takes an optional key type and no username or password; token auth takes a -// username and password and no key type. +// password (the token) and no key type. A git provider also needs a username +// for token auth; GitLab ignores it. type PromotionProviderAuth struct { AuthType string `json:"authType"` KeyType string `json:"keyType,omitempty"` @@ -114,8 +149,8 @@ func (a PromotionProviderAuth) Validate() error { if a.KeyType != "" { return fmt.Errorf("token auth takes no key type: use ssh-key auth for key types") } - if strings.TrimSpace(a.Username) == "" { - return fmt.Errorf("username is required for token auth") + if a.Username != "" && strings.TrimSpace(a.Username) == "" { + return fmt.Errorf("username must not be blank: omit it or pass the Git username") } if a.Password == "" { return fmt.Errorf("password is required for token auth") @@ -126,11 +161,13 @@ func (a PromotionProviderAuth) Validate() error { } } -// CreatePromotionProviderRequest creates one promotion provider. +// CreatePromotionProviderRequest creates one promotion provider. Config is +// the optional Git host configuration (GitLab base URL). type CreatePromotionProviderRequest struct { - Name string `json:"name"` - Type string `json:"type"` - Auth PromotionProviderAuth `json:"auth"` + Name string `json:"name"` + Type string `json:"type"` + Auth PromotionProviderAuth `json:"auth"` + Config *PromotionProviderHostConfig `json:"config,omitempty"` } // Validate rejects a creation document the API would reject before transport. @@ -138,27 +175,47 @@ func (r CreatePromotionProviderRequest) Validate() error { if err := validatePromotionName(r.Name); err != nil { return err } - if r.Type != PromotionProviderTypeGit { - return fmt.Errorf("unknown provider type %q: use %q", r.Type, PromotionProviderTypeGit) + if !slices.Contains(promotionProviderTypes, r.Type) { + return fmt.Errorf("unknown provider type %q: use %s", r.Type, strings.Join(promotionProviderTypes, ", ")) } if err := r.Auth.Validate(); err != nil { return err } + if r.Type == PromotionProviderTypeGit && r.Auth.AuthType == PromotionAuthTypeToken && r.Auth.Username == "" { + return fmt.Errorf("username is required for token auth on a git provider (GitLab providers ignore it)") + } + if r.Config != nil { + if r.Type != PromotionProviderTypeGitLab { + return fmt.Errorf("config (baseUrl) applies to gitlab providers only, not %q", r.Type) + } + if err := r.Config.Validate(); err != nil { + return err + } + } return nil } -// UpdatePromotionProviderRequest replaces the name and/or credential of one -// provider. At least one field is required. Sending auth replaces the stored -// credential for every connection attached to the provider. +// UpdatePromotionProviderRequest replaces the name, credential and/or host +// configuration of one provider. At least one field is required. Sending auth +// replaces the stored credential for every connection attached to the +// provider; a changed base URL needs auth in the same request. type UpdatePromotionProviderRequest struct { - Name *string `json:"name,omitempty"` - Auth *PromotionProviderAuth `json:"auth,omitempty"` + Name *string `json:"name,omitempty"` + Auth *PromotionProviderAuth `json:"auth,omitempty"` + Config *PromotionProviderHostConfig `json:"config,omitempty"` } // Validate rejects an empty or malformed update document before transport. +// The provider type is not known here, so a missing token username is left to +// the server. func (r UpdatePromotionProviderRequest) Validate() error { - if r.Name == nil && r.Auth == nil { - return fmt.Errorf("promotion provider update is empty: set name and/or auth") + if r.Name == nil && r.Auth == nil && r.Config == nil { + return fmt.Errorf("promotion provider update is empty: set at least one of name, auth, or config") + } + if r.Config != nil { + if err := r.Config.Validate(); err != nil { + return err + } } if r.Name != nil { if err := validatePromotionName(*r.Name); err != nil { @@ -173,14 +230,52 @@ func (r UpdatePromotionProviderRequest) Validate() error { return nil } -// PromotionTarget is the remote a connection syncs through. +// PromotionTarget is the remote a connection syncs through, as the API +// reports it. GitLab connections also report the stored repository path, +// which is read-only: write documents use [PromotionTargetDocument]. type PromotionTarget struct { + SchemaVersion int `json:"schemaVersion"` + RemoteURL string `json:"remoteUrl"` + RepositoryPath string `json:"repositoryPath,omitempty"` +} + +// Document returns the writable part of the target. +func (t PromotionTarget) Document() PromotionTargetDocument { + return PromotionTargetDocument{SchemaVersion: t.SchemaVersion, RemoteURL: t.RemoteURL} +} + +// PromotionTargetDocument is the target a connection create or update sends. +// For GitLab the remote URL must belong to the provider; the server stores +// only the repository path and derives remoteUrl from the provider base URL. +type PromotionTargetDocument struct { SchemaVersion int `json:"schemaVersion"` RemoteURL string `json:"remoteUrl"` } +// UnmarshalJSON decodes strictly and names the read-only repositoryPath, so a +// target copied from 'connection get' fails with the fix instead of a bare +// unknown-field error. +func (t *PromotionTargetDocument) UnmarshalJSON(data []byte) error { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if _, ok := fields["repositoryPath"]; ok { + return fmt.Errorf("target.repositoryPath is read-only: send only schemaVersion and remoteUrl") + } + type plain PromotionTargetDocument + var decoded plain + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&decoded); err != nil { + return err + } + *t = PromotionTargetDocument(decoded) + return nil +} + // Validate rejects a target the API would reject before transport. -func (t PromotionTarget) Validate() error { +func (t PromotionTargetDocument) Validate() error { if t.SchemaVersion != promotionTargetSchemaVersion { return fmt.Errorf("target schemaVersion must be %d, got %d", promotionTargetSchemaVersion, t.SchemaVersion) } @@ -213,21 +308,32 @@ type PromotionPromoteSettings struct { CreateBranchOnPromote bool `json:"createBranchOnPromotion"` } -// PromotionApplyConfig is one stored apply direction config. +// PromotionConfigCheckout is the local checkout state of one direction config: +// whether it is cloned and whether the clone still matches the config. +type PromotionConfigCheckout struct { + HasCheckout bool `json:"hasCheckout"` + MatchesConfig bool `json:"matchesConfig"` +} + +// PromotionApplyConfig is one stored apply direction config. Checkout is nil +// on connection list rows, which omit it. type PromotionApplyConfig struct { - ID string `json:"id"` - Name string `json:"name"` - CreatedAt string `json:"createdAt"` - UpdatedAt string `json:"updatedAt"` - Settings PromotionApplySettings `json:"settings"` + ID string `json:"id"` + Name string `json:"name"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` + Checkout *PromotionConfigCheckout `json:"checkout,omitempty"` + Settings PromotionApplySettings `json:"settings"` } -// PromotionPromoteConfig is one stored promote direction config. +// PromotionPromoteConfig is one stored promote direction config. Checkout is +// nil on connection list rows, which omit it. type PromotionPromoteConfig struct { ID string `json:"id"` Name string `json:"name"` CreatedAt string `json:"createdAt"` UpdatedAt string `json:"updatedAt"` + Checkout *PromotionConfigCheckout `json:"checkout,omitempty"` Settings PromotionPromoteSettings `json:"settings"` } @@ -278,7 +384,7 @@ type CreatePromotionConnectionRequest struct { Name string `json:"name"` Scope string `json:"scope"` ProviderID string `json:"providerId"` - Target PromotionTarget `json:"target"` + Target PromotionTargetDocument `json:"target"` Configs *CreatePromotionConnectionConfigs `json:"configs,omitempty"` } @@ -314,9 +420,9 @@ func (r CreatePromotionConnectionRequest) Validate() error { // UpdatePromotionConnectionRequest patches a connection. Only the supplied // fields change; at least one is required. type UpdatePromotionConnectionRequest struct { - Name *string `json:"name,omitempty"` - Target *PromotionTarget `json:"target,omitempty"` - ProviderID *string `json:"providerId,omitempty"` + Name *string `json:"name,omitempty"` + Target *PromotionTargetDocument `json:"target,omitempty"` + ProviderID *string `json:"providerId,omitempty"` } // Validate rejects an empty or malformed update document before transport. @@ -511,10 +617,11 @@ type PromotionApplyCredentialCounts struct { Stubbed int `json:"stubbed"` } -// PromotionApplyDataTableCounts counts data tables matched or created. +// PromotionApplyDataTableCounts counts data tables matched, created or updated. type PromotionApplyDataTableCounts struct { Matched int `json:"matched"` Created int `json:"created"` + Updated int `json:"updated"` } // PromotionApplyVariableCounts counts variables by outcome of one apply. @@ -546,13 +653,244 @@ type PromotionApplyCounts struct { Tags PromotionApplyTagCounts `json:"tags"` } -// ApplyPromotionResult is the apply acknowledgement: what the checkout -// overwrote and the commit it now matches. +// Apply outcomes. The apply response is a union on status: only applied +// wrote anything. An unknown status is kept as sent so a newer server never +// fails the decode. +const ( + PromotionApplyStatusApplied = "applied" + PromotionApplyStatusBlocked = "blocked" + PromotionApplyStatusSourceChanged = "source-changed" +) + +// Preflight conflict codes that need explicit confirmation at continue time. +const ( + PromotionConflictProjectDeletion = "project-deletion" + PromotionConflictDestructiveChange = "destructive-change" +) + +// PromotionRef names one project or workflow in a preflight item. +type PromotionRef struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// PromotionConsumer is one project and the workflows in it that reference a +// preflight item. +type PromotionConsumer struct { + Project PromotionRef `json:"project"` + Workflows []PromotionRef `json:"workflows"` +} + +// PromotionVariableScope is the scope of a variable binding: global, or one +// project. +type PromotionVariableScope struct { + Kind string `json:"kind"` + Project *PromotionRef `json:"project,omitempty"` +} + +// PromotionDataTableChange is one column or table change a data-table +// destructive-change conflict reports. Destructive changes drop column values. +type PromotionDataTableChange struct { + Kind string `json:"kind"` + Column string `json:"column,omitempty"` + Type string `json:"type,omitempty"` + From string `json:"from,omitempty"` + To string `json:"to,omitempty"` + Destructive bool `json:"destructive"` +} + +// PromotionApplyIssue is one preflight item or warning: a missing binding, +// an access requirement, a conflict, or a warning. Kind (credential, variable, +// project, data-table) and Code discriminate; the remaining fields are the +// union of the documented variants, and only those a variant carries are set. +// The full document is preserved verbatim so new variants survive without a +// client change. +type PromotionApplyIssue struct { + Kind string `json:"kind"` + Code string `json:"code,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + SourceID *string `json:"sourceId,omitempty"` + CredentialType string `json:"credentialType,omitempty"` + ExpectedTypes []string `json:"expectedTypes,omitempty"` + TargetType string `json:"targetType,omitempty"` + UsageScope string `json:"usageScope,omitempty"` + VariableType string `json:"variableType,omitempty"` + Scope *PromotionVariableScope `json:"scope,omitempty"` + Project *PromotionRef `json:"project,omitempty"` + OwnerProject *PromotionRef `json:"ownerProject,omitempty"` + FilePath string `json:"filePath,omitempty"` + ReferenceFiles []string `json:"referenceFiles,omitempty"` + Workflows []PromotionRef `json:"workflows,omitempty"` + Consumers []PromotionConsumer `json:"consumers,omitempty"` + Changes []PromotionDataTableChange `json:"changes,omitempty"` + Raw json.RawMessage `json:"-"` +} + +// UnmarshalJSON decodes the typed view and keeps the verbatim document. +func (i *PromotionApplyIssue) UnmarshalJSON(data []byte) error { + type plain PromotionApplyIssue + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *i = PromotionApplyIssue(decoded) + i.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// MarshalJSON re-emits the verbatim document when present. +func (i PromotionApplyIssue) MarshalJSON() ([]byte, error) { + if len(i.Raw) > 0 { + return i.Raw, nil + } + type plain PromotionApplyIssue + return json.Marshal(plain(i)) +} + +// PromotionMissingProject is one package project that does not exist on the +// instance. Icon and telemetry tags stay raw: they are display metadata. +type PromotionMissingProject struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Icon json.RawMessage `json:"icon,omitempty"` + CustomTelemetryTags json.RawMessage `json:"customTelemetryTags,omitempty"` +} + +// PromotionApplyPreflight lists why a blocked apply wrote nothing. +type PromotionApplyPreflight struct { + MissingProjects []PromotionMissingProject `json:"missingProjects"` + MissingBindings []PromotionApplyIssue `json:"missingBindings"` + AccessRequirements []PromotionApplyIssue `json:"accessRequirements"` + Conflicts []PromotionApplyIssue `json:"conflicts"` + Warnings []PromotionApplyIssue `json:"warnings"` +} + +// Empty reports whether the preflight lists nothing at all. +func (p PromotionApplyPreflight) Empty() bool { + return len(p.MissingProjects) == 0 && len(p.MissingBindings) == 0 && + len(p.AccessRequirements) == 0 && len(p.Conflicts) == 0 && len(p.Warnings) == 0 +} + +// PromotionExpectedSource pins the source an apply or continue may import: +// the config, branch and full commit a review saw. A mismatch answers status +// source-changed and writes nothing. +type PromotionExpectedSource struct { + ConfigID string `json:"configId"` + BranchName string `json:"branchName"` + CommitSHA string `json:"commitSha"` +} + +var promotionCommitSHA = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) + +// Validate rejects an expected source the API would reject before transport. +func (s PromotionExpectedSource) Validate() error { + if err := validatePromotionID(s.ConfigID, "expected source config ID"); err != nil { + return err + } + if strings.TrimSpace(s.BranchName) == "" { + return fmt.Errorf("expected source branch name is required") + } + if !promotionCommitSHA.MatchString(s.CommitSHA) { + return fmt.Errorf("expected source commit %q must be a full lowercase SHA-1 (40 hex) or SHA-256 (64 hex)", s.CommitSHA) + } + return nil +} + +// ApplyPromotionResult is the apply acknowledgement. Inspect Status before +// reading anything else: applied carries Counts and Warnings; blocked carries +// Preflight and wrote nothing; source-changed carries neither and wrote +// nothing. ConfigID and Git identify the source for a later continue. +// +// Extra holds top-level fields this type does not name. JSON encoding +// re-emits the verbatim response, so --output json is lossless even for +// fields and variants newer than the client. type ApplyPromotionResult struct { - ConnectionID string `json:"connectionId"` - ConfigID string `json:"configId"` - Counts PromotionApplyCounts `json:"counts"` - Git PromotionGit `json:"git"` + ConnectionID string `json:"connectionId"` + ConfigID string `json:"configId"` + Status string `json:"status,omitempty"` + Git PromotionGit `json:"git"` + Counts *PromotionApplyCounts `json:"counts,omitempty"` + Warnings []PromotionApplyIssue `json:"warnings,omitempty"` + Preflight *PromotionApplyPreflight `json:"preflight,omitempty"` + Extra map[string]json.RawMessage `json:"-"` + raw json.RawMessage +} + +// applyPromotionResultFields are the field names [ApplyPromotionResult] +// decodes itself. Anything else lands in Extra. +var applyPromotionResultFields = []string{ + "connectionId", "configId", "status", "git", "counts", "warnings", "preflight", +} + +// UnmarshalJSON decodes by shape, keeps unknown fields in Extra, and keeps the +// verbatim response for re-encoding. +func (r *ApplyPromotionResult) UnmarshalJSON(data []byte) error { + type plain ApplyPromotionResult + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + var rest map[string]json.RawMessage + if err := json.Unmarshal(data, &rest); err != nil { + return err + } + for _, known := range applyPromotionResultFields { + delete(rest, known) + } + *r = ApplyPromotionResult(decoded) + r.Extra = nil + if len(rest) > 0 { + r.Extra = rest + } + r.raw = append(json.RawMessage(nil), data...) + return nil +} + +// MarshalJSON re-emits the verbatim response when present; otherwise the +// named fields followed by Extra in sorted order. +func (r ApplyPromotionResult) MarshalJSON() ([]byte, error) { + if len(r.raw) > 0 { + return r.raw, nil + } + type plain ApplyPromotionResult + base, err := json.Marshal(plain(r)) + if err != nil { + return nil, err + } + if len(r.Extra) == 0 { + return base, nil + } + var b bytes.Buffer + b.Write(bytes.TrimSuffix(base, []byte("}"))) + for i, name := range slices.Sorted(maps.Keys(r.Extra)) { + if i > 0 || len(base) > 2 { + b.WriteByte(',') + } + key, err := json.Marshal(name) + if err != nil { + return nil, err + } + b.Write(key) + b.WriteByte(':') + b.Write(r.Extra[name]) + } + b.WriteByte('}') + return b.Bytes(), nil +} + +// Applied reports whether the apply wrote content. A response without status +// but with counts comes from a server older than the status union and is +// treated as applied. +func (r ApplyPromotionResult) Applied() bool { + return r.Status == PromotionApplyStatusApplied || (r.Status == "" && r.Counts != nil) +} + +// ExpectedSource returns the source a continue must name: the config and the +// branch and commit this result was checked against. +func (r ApplyPromotionResult) ExpectedSource() PromotionExpectedSource { + return PromotionExpectedSource{ConfigID: r.ConfigID, BranchName: r.Git.BranchName, CommitSHA: r.Git.CommitSHA} } // ListPromotionProviders returns one cursor-paginated page of providers. diff --git a/internal/n8n/promotion_apply_test.go b/internal/n8n/promotion_apply_test.go new file mode 100644 index 0000000..183d8b2 --- /dev/null +++ b/internal/n8n/promotion_apply_test.go @@ -0,0 +1,366 @@ +package n8n + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "strings" + "testing" +) + +// Apply result fixtures follow applyPackageResultDto in the upstream 1.1.1 +// contract: one per status of the union. +const promotionAppliedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"0123456789abcdef0123456789abcdef01234567","branchName":"main"}, + "status":"applied", + "counts":{ + "projects":{"created":1,"updated":0,"skipped":0,"deleted":0}, + "folders":{"created":1,"skipped":0,"removed":0}, + "workflows":{"created":1,"updated":0,"skipped":0,"archived":0,"deleted":0,"publishing":{"published":1,"unpublished":0,"unchanged":0,"blocked":0,"failed":0}}, + "credentials":{"matched":1,"stubbed":0}, + "dataTables":{"matched":0,"created":0,"updated":2}, + "variables":{"matched":0,"created":0,"updated":0,"stubbed":0,"missing":0}, + "tags":{"matched":1,"created":0,"renamed":0,"reconciled":0,"skipped":0} + }, + "warnings":[ + {"kind":"variable","code":"variable-shadowed","name":"API_URL","scope":{"kind":"global"}, + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-1","name":"Sync"}]}]} + ] +}` + +const promotionBlockedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"0123456789abcdef0123456789abcdef01234567","branchName":"main"}, + "status":"blocked", + "preflight":{ + "missingProjects":[{"id":"p-9","name":"Ops","icon":{"type":"emoji","value":"x"},"customTelemetryTags":[{"key":"team","value":"ops"}]}], + "missingBindings":[ + {"kind":"credential","sourceId":"cred-1","name":"Slack","credentialType":"slackApi", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-1","name":"Sync"},{"id":"wf-2","name":"Notify"}]}], + "ownerProject":{"id":"p-1","name":"Sales"},"expressionData":{"token":"={{ $env.X }}"}}, + {"kind":"variable","name":"API_URL","variableType":"string","scope":{"kind":"project","project":{"id":"p-1","name":"Sales"}}, + "sourceValue":"https://api.example.com","consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-1","name":"Sync"}]}]} + ], + "accessRequirements":[ + {"kind":"credential","sourceId":"cred-2","name":"Postgres","credentialType":"postgres","code":"access-required", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-3","name":"Load"}]}]} + ], + "conflicts":[ + {"kind":"credential","sourceId":null,"name":"Mail","expectedTypes":["smtp"],"referenceFiles":["workflows/wf-4.json"],"code":"missing-id", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-4","name":"Mail"}]}]}, + {"kind":"project","code":"project-deletion","project":{"id":"p-7","name":"Legacy"}}, + {"kind":"data-table","code":"destructive-change","id":"dt-1","name":"Orders", + "consumers":[{"project":{"id":"p-1","name":"Sales"},"workflows":[{"id":"wf-5","name":"Orders"}]}], + "changes":[{"kind":"remove-column","column":"total","type":"number","destructive":true}, + {"kind":"change-column-type","column":"date","from":"string","to":"date","destructive":true}, + {"kind":"rename-table","from":"orders","to":"Orders","destructive":false}]} + ], + "warnings":[] + } +}` + +const promotionSourceChangedBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"fedcba9876543210fedcba9876543210fedcba98","branchName":"main"}, + "status":"source-changed" +}` + +// promotionUnknownStatusBody is a status and a field this client does not +// know; neither may fail the decode or be dropped from JSON output. +const promotionUnknownStatusBody = `{ + "connectionId":"conn-1", + "configId":"cfg-apply", + "git":{"commitSha":"fedcba9876543210fedcba9876543210fedcba98","branchName":"main"}, + "status":"queued", + "queue":{"position":3} +}` + +func decodeApplyResult(t *testing.T, body string) *ApplyPromotionResult { + t.Helper() + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + result, err := server.client(t).ApplyPackage(context.Background(), "conn-1") + if err != nil { + t.Fatalf("ApplyPackage: %v", err) + } + return result +} + +func assertLosslessJSON(t *testing.T, v any, body string) { + t.Helper() + encoded, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var want, got bytes.Buffer + if err := json.Compact(&want, []byte(body)); err != nil { + t.Fatalf("compact fixture: %v", err) + } + if err := json.Compact(&got, encoded); err != nil { + t.Fatalf("compact output: %v", err) + } + if got.String() != want.String() { + t.Errorf("JSON round trip lost data:\n got %s\nwant %s", got.String(), want.String()) + } +} + +func TestApplyPackageApplied(t *testing.T) { + result := decodeApplyResult(t, promotionAppliedBody) + if result.Status != PromotionApplyStatusApplied || !result.Applied() { + t.Errorf("status = %q, applied = %v, want applied", result.Status, result.Applied()) + } + if result.Counts == nil || result.Counts.DataTables.Updated != 2 || result.Counts.Projects.Created != 1 { + t.Errorf("counts = %+v, want the decoded counts with dataTables.updated", result.Counts) + } + if len(result.Warnings) != 1 || result.Warnings[0].Code != "variable-shadowed" || result.Warnings[0].Scope == nil || result.Warnings[0].Scope.Kind != "global" { + t.Errorf("warnings = %+v, want the shadowed variable", result.Warnings) + } + if result.Preflight != nil || result.Extra != nil { + t.Errorf("preflight = %+v, extra = %v, want neither", result.Preflight, result.Extra) + } + assertLosslessJSON(t, result, promotionAppliedBody) +} + +func TestApplyPackageBlocked(t *testing.T) { + result := decodeApplyResult(t, promotionBlockedBody) + if result.Status != PromotionApplyStatusBlocked || result.Applied() { + t.Errorf("status = %q, applied = %v, want blocked and not applied", result.Status, result.Applied()) + } + if result.Counts != nil { + t.Errorf("counts = %+v, want none on a blocked apply", result.Counts) + } + p := result.Preflight + if p == nil || p.Empty() { + t.Fatalf("preflight = %+v, want items", p) + } + if len(p.MissingProjects) != 1 || p.MissingProjects[0].ID != "p-9" || len(p.MissingProjects[0].Icon) == 0 { + t.Errorf("missing projects = %+v", p.MissingProjects) + } + if len(p.MissingBindings) != 2 { + t.Fatalf("missing bindings = %+v, want credential and variable", p.MissingBindings) + } + credential, variable := p.MissingBindings[0], p.MissingBindings[1] + if credential.Kind != "credential" || credential.CredentialType != "slackApi" || credential.SourceID == nil || *credential.SourceID != "cred-1" || + credential.OwnerProject == nil || len(credential.Consumers) != 1 || len(credential.Consumers[0].Workflows) != 2 { + t.Errorf("credential binding = %+v", credential) + } + if variable.Kind != "variable" || variable.Scope == nil || variable.Scope.Project == nil || variable.Scope.Project.Name != "Sales" { + t.Errorf("variable binding = %+v", variable) + } + if len(p.AccessRequirements) != 1 || p.AccessRequirements[0].Code != "access-required" { + t.Errorf("access requirements = %+v", p.AccessRequirements) + } + if len(p.Conflicts) != 3 { + t.Fatalf("conflicts = %+v, want three", p.Conflicts) + } + if missing := p.Conflicts[0]; missing.SourceID != nil || len(missing.ExpectedTypes) != 1 || len(missing.ReferenceFiles) != 1 { + t.Errorf("missing-id conflict = %+v, want a null source ID kept as nil", missing) + } + if deletion := p.Conflicts[1]; deletion.Code != PromotionConflictProjectDeletion || deletion.Project == nil || deletion.Project.ID != "p-7" { + t.Errorf("project-deletion conflict = %+v", deletion) + } + if change := p.Conflicts[2]; change.Code != PromotionConflictDestructiveChange || len(change.Changes) != 3 || !change.Changes[0].Destructive || change.Changes[2].Destructive { + t.Errorf("destructive-change conflict = %+v", change) + } + if got := result.ExpectedSource(); got != (PromotionExpectedSource{ConfigID: "cfg-apply", BranchName: "main", CommitSHA: "0123456789abcdef0123456789abcdef01234567"}) { + t.Errorf("expected source = %+v", got) + } else if err := got.Validate(); err != nil { + t.Errorf("expected source from a blocked result: %v", err) + } + assertLosslessJSON(t, result, promotionBlockedBody) +} + +func TestApplyPackageSourceChanged(t *testing.T) { + result := decodeApplyResult(t, promotionSourceChangedBody) + if result.Status != PromotionApplyStatusSourceChanged || result.Applied() || result.Counts != nil || result.Preflight != nil { + t.Errorf("result = %+v, want source-changed with neither counts nor preflight", result) + } + assertLosslessJSON(t, result, promotionSourceChangedBody) +} + +func TestApplyPackageKeepsUnknownStatus(t *testing.T) { + result := decodeApplyResult(t, promotionUnknownStatusBody) + if result.Status != "queued" || result.Applied() { + t.Errorf("status = %q, applied = %v, want the unknown status kept and not applied", result.Status, result.Applied()) + } + if string(result.Extra["queue"]) != `{"position":3}` { + t.Errorf("extra = %v, want the unknown queue field", result.Extra) + } + assertLosslessJSON(t, result, promotionUnknownStatusBody) +} + +func TestApplyPackageLegacyResultIsApplied(t *testing.T) { + // promotionApplyResultBody predates the status union: counts, no status. + result := decodeApplyResult(t, promotionApplyResultBody) + if result.Status != "" || !result.Applied() { + t.Errorf("status = %q, applied = %v, want a status-less result with counts treated as applied", result.Status, result.Applied()) + } +} + +func TestApplyPromotionResultMarshalsWithoutRaw(t *testing.T) { + result := ApplyPromotionResult{ + ConnectionID: "conn-1", ConfigID: "cfg-apply", Status: PromotionApplyStatusSourceChanged, + Git: PromotionGit{CommitSHA: "abc", BranchName: "main"}, + Extra: map[string]json.RawMessage{"zeta": json.RawMessage(`1`), "alpha": json.RawMessage(`"a"`)}, + } + encoded, err := json.Marshal(result) + if err != nil { + t.Fatalf("marshal: %v", err) + } + want := `{"connectionId":"conn-1","configId":"cfg-apply","status":"source-changed","git":{"commitSha":"abc","branchName":"main"},"alpha":"a","zeta":1}` + if string(encoded) != want { + t.Errorf("marshal = %s\nwant %s", encoded, want) + } +} + +func TestPromotionExpectedSourceValidate(t *testing.T) { + valid := PromotionExpectedSource{ConfigID: "cfg-1", BranchName: "main", CommitSHA: strings.Repeat("a", 40)} + if err := valid.Validate(); err != nil { + t.Errorf("SHA-1 source: %v", err) + } + sha256 := valid + sha256.CommitSHA = strings.Repeat("b", 64) + if err := sha256.Validate(); err != nil { + t.Errorf("SHA-256 source: %v", err) + } + for name, bad := range map[string]PromotionExpectedSource{ + "no config": {BranchName: "main", CommitSHA: valid.CommitSHA}, + "no branch": {ConfigID: "cfg-1", BranchName: " ", CommitSHA: valid.CommitSHA}, + "short sha": {ConfigID: "cfg-1", BranchName: "main", CommitSHA: "deadbeef"}, + "upper sha": {ConfigID: "cfg-1", BranchName: "main", CommitSHA: strings.Repeat("A", 40)}, + "52-char sha": {ConfigID: "cfg-1", BranchName: "main", CommitSHA: strings.Repeat("a", 52)}, + } { + if err := bad.Validate(); err == nil { + t.Errorf("%s: want a validation error", name) + } + } +} + +func TestCreateGitLabPromotionProvider(t *testing.T) { + const gitlabBody = `{"provider":{"id":"prov-2","name":"gitlab","type":"gitlab","authType":"token", + "config":{"schemaVersion":1,"baseUrl":"https://gitlab.example.com"}, + "createdAt":"2026-09-17T00:00:00.000Z","updatedAt":"2026-09-17T00:00:00.000Z"},"publicKey":null}` + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, gitlabBody)) + + created, err := server.client(t).CreatePromotionProvider(context.Background(), CreatePromotionProviderRequest{ + Name: "gitlab", Type: PromotionProviderTypeGitLab, + Auth: PromotionProviderAuth{AuthType: PromotionAuthTypeToken, Password: "glpat-secret"}, + Config: &PromotionProviderHostConfig{SchemaVersion: 1, BaseURL: "https://gitlab.example.com"}, + }) + if err != nil { + t.Fatalf("CreatePromotionProvider without username: %v", err) + } + _, raw := server.last(t) + var sent struct { + Type string `json:"type"` + Auth map[string]json.RawMessage `json:"auth"` + Config map[string]any `json:"config"` + } + if err := json.Unmarshal([]byte(raw), &sent); err != nil { + t.Fatalf("request body: %v\n%s", err, raw) + } + if sent.Type != "gitlab" || sent.Config["baseUrl"] != "https://gitlab.example.com" || sent.Config["schemaVersion"] != float64(1) { + t.Errorf("request = %s, want gitlab with config", raw) + } + if _, ok := sent.Auth["username"]; ok { + t.Errorf("auth = %s, want no username", raw) + } + if created.Provider.Config == nil || created.Provider.Config.BaseURL == nil || *created.Provider.Config.BaseURL != "https://gitlab.example.com" { + t.Errorf("provider config = %+v, want the base URL", created.Provider.Config) + } +} + +func TestPromotionProviderHostValidation(t *testing.T) { + token := PromotionProviderAuth{AuthType: PromotionAuthTypeToken, Password: "secret"} + config := &PromotionProviderHostConfig{SchemaVersion: 1, BaseURL: "https://gitlab.example.com"} + for name, request := range map[string]CreatePromotionProviderRequest{ + "git token without username": {Name: "g", Type: PromotionProviderTypeGit, Auth: token}, + "config on git": {Name: "g", Type: PromotionProviderTypeGit, Auth: PromotionProviderAuth{AuthType: PromotionAuthTypeSSHKey}, Config: config}, + "relative base URL": {Name: "g", Type: PromotionProviderTypeGitLab, Auth: token, Config: &PromotionProviderHostConfig{SchemaVersion: 1, BaseURL: "gitlab.example.com"}}, + "blank base URL": {Name: "g", Type: PromotionProviderTypeGitLab, Auth: token, Config: &PromotionProviderHostConfig{SchemaVersion: 1, BaseURL: " "}}, + "config schema 2": {Name: "g", Type: PromotionProviderTypeGitLab, Auth: token, Config: &PromotionProviderHostConfig{SchemaVersion: 2, BaseURL: "https://gitlab.example.com"}}, + "blank username": {Name: "g", Type: PromotionProviderTypeGitLab, Auth: PromotionProviderAuth{AuthType: PromotionAuthTypeToken, Username: " ", Password: "secret"}}, + "unknown type": {Name: "g", Type: "github", Auth: token}, + } { + if err := request.Validate(); err == nil { + t.Errorf("%s: want a validation error", name) + } + } + if err := (CreatePromotionProviderRequest{Name: "g", Type: PromotionProviderTypeGitLab, Auth: token}).Validate(); err != nil { + t.Errorf("gitlab token without config or username: %v", err) + } + if err := (UpdatePromotionProviderRequest{Config: config}).Validate(); err != nil { + t.Errorf("config-only update: %v", err) + } + if err := (UpdatePromotionProviderRequest{Auth: &token}).Validate(); err != nil { + t.Errorf("token update without username: %v", err) + } +} + +func TestPromotionConnectionReadFields(t *testing.T) { + const body = `{ + "id":"conn-2","name":"gl","scope":"instance", + "target":{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git","repositoryPath":"org/repo"}, + "provider":{"id":"prov-2","name":"gitlab","type":"gitlab","authType":"token","createdAt":"t","updatedAt":"t"}, + "configs":{"apply":{"id":"cfg-a","name":"Apply","createdAt":"t","updatedAt":"t","checkout":{"hasCheckout":true,"matchesConfig":false},"settings":{"schemaVersion":1,"branchName":"main"}}}, + "createdAt":"t","updatedAt":"t"}` + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + + connection, err := server.client(t).GetPromotionConnection(context.Background(), "conn-2") + if err != nil { + t.Fatalf("GetPromotionConnection: %v", err) + } + if connection.Target.RepositoryPath != "org/repo" { + t.Errorf("repository path = %q, want org/repo", connection.Target.RepositoryPath) + } + if checkout := connection.Configs.Apply.Checkout; checkout == nil || !checkout.HasCheckout || checkout.MatchesConfig { + t.Errorf("apply checkout = %+v, want cloned and not matching", checkout) + } + assertLosslessJSON(t, connection, body) + + // The read-only path never travels back on a write. + if _, err := server.client(t).UpdatePromotionConnection(context.Background(), "conn-2", UpdatePromotionConnectionRequest{ + Target: new(connection.Target.Document()), + }); err != nil { + t.Fatalf("UpdatePromotionConnection: %v", err) + } + _, raw := server.last(t) + if strings.Contains(raw, "repositoryPath") || !strings.Contains(raw, "remoteUrl") { + t.Errorf("update body = %s, want remoteUrl without repositoryPath", raw) + } +} + +func TestPromotionTargetDocumentRejectsReadOnlyFields(t *testing.T) { + var doc PromotionTargetDocument + err := json.Unmarshal([]byte(`{"schemaVersion":1,"remoteUrl":"x","repositoryPath":"org/repo"}`), &doc) + if err == nil || !strings.Contains(err.Error(), "read-only") { + t.Errorf("repositoryPath error = %v, want the read-only explanation", err) + } + if err := json.Unmarshal([]byte(`{"schemaVersion":1,"remoteUrl":"x","other":1}`), &doc); err == nil { + t.Error("unknown target field: want a strict decode error") + } + if err := json.Unmarshal([]byte(`{"schemaVersion":1,"remoteUrl":"x"}`), &doc); err != nil || doc.RemoteURL != "x" { + t.Errorf("valid target = %+v (error %v)", doc, err) + } +} + +func TestUpsertPromotionConfigReportsCheckout(t *testing.T) { + const body = `{"id":"cfg-p","name":"Promote","createdAt":"t","updatedAt":"t", + "checkout":{"hasCheckout":false,"matchesConfig":false}, + "settings":{"schemaVersion":1,"baseBranchName":"main","createBranchOnPromotion":true}}` + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + config, err := server.client(t).UpsertPromotionPromoteConfig(context.Background(), "conn-1", UpsertPromotionPromoteConfigRequest{ + Settings: PromotionPromoteSettings{SchemaVersion: 1, BaseBranchName: "main", CreateBranchOnPromote: true}, + }) + if err != nil { + t.Fatalf("UpsertPromotionPromoteConfig: %v", err) + } + if config.Checkout == nil || config.Checkout.HasCheckout { + t.Errorf("checkout = %+v, want a reported, not-cloned checkout", config.Checkout) + } + assertLosslessJSON(t, config, body) +} diff --git a/internal/n8n/promotion_test.go b/internal/n8n/promotion_test.go index d82d052..659c177 100644 --- a/internal/n8n/promotion_test.go +++ b/internal/n8n/promotion_test.go @@ -352,7 +352,7 @@ func TestCreatePromotionConnection(t *testing.T) { created, err := server.client(t).CreatePromotionConnection(context.Background(), CreatePromotionConnectionRequest{ Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", - Target: PromotionTarget{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"}, + Target: PromotionTargetDocument{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"}, Configs: &CreatePromotionConnectionConfigs{ Apply: &CreatePromotionApplyConfig{Settings: PromotionApplySettings{SchemaVersion: 1, BranchName: "main"}}, }, @@ -380,13 +380,13 @@ func TestCreatePromotionConnectionValidation(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, promotionConnectionBody)) client := server.client(t) - validTarget := PromotionTarget{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"} + validTarget := PromotionTargetDocument{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"} cases := []CreatePromotionConnectionRequest{ {}, {Name: "prod", Scope: "global", ProviderID: "prov-1", Target: validTarget}, {Name: "prod", Scope: PromotionScopeProjects, ProviderID: " ", Target: validTarget}, - {Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", Target: PromotionTarget{SchemaVersion: 2, RemoteURL: "git@example.com:r.git"}}, - {Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", Target: PromotionTarget{SchemaVersion: 1, RemoteURL: " "}}, + {Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", Target: PromotionTargetDocument{SchemaVersion: 2, RemoteURL: "git@example.com:r.git"}}, + {Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", Target: PromotionTargetDocument{SchemaVersion: 1, RemoteURL: " "}}, {Name: "prod", Scope: PromotionScopeProjects, ProviderID: "prov-1", Target: validTarget, Configs: &CreatePromotionConnectionConfigs{ Apply: &CreatePromotionApplyConfig{Settings: PromotionApplySettings{SchemaVersion: 1, BranchName: ""}}, }}, @@ -449,7 +449,7 @@ func TestUpdatePromotionConnectionValidation(t *testing.T) { if _, err := client.UpdatePromotionConnection(context.Background(), "conn-1", UpdatePromotionConnectionRequest{}); err == nil { t.Error("empty update: want an error") } - badTarget := PromotionTarget{SchemaVersion: 9, RemoteURL: "git@example.com:r.git"} + badTarget := PromotionTargetDocument{SchemaVersion: 9, RemoteURL: "git@example.com:r.git"} if _, err := client.UpdatePromotionConnection(context.Background(), "conn-1", UpdatePromotionConnectionRequest{Target: &badTarget}); err == nil { t.Error("bad target: want an error") }