diff --git a/cmd/root.go b/cmd/root.go index 6791dde3..a56bd840 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -55,7 +55,7 @@ func init() { withShortHand("l"), ) boolFlag(flags, "persist-log-level", "Persists the set log level down to other module loggers.") - stringFlag(flags, "vcs-base-url", "VCS base url, useful if self hosting gitlab, enterprise github, etc.") + stringFlag(flags, "vcs-base-url", "VCS API base url, for self-hosted GitLab (https://) or GitHub Enterprise (https:///api/v3). Defaults to https://api.github.com or https://gitlab.com.") stringFlag(flags, "vcs-upload-url", "VCS upload url, required for enterprise github.") stringFlag(flags, "vcs-type", "VCS type. One of gitlab or github. Defaults to gitlab.", newStringOpts(). diff --git a/docs/usage.md b/docs/usage.md index 2c684160..02dbd432 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -162,7 +162,7 @@ The full list of supported environment variables is described below: |`KUBECHECKS_SCHEMAS_LOCATION`|Sets schema locations to be used for every check request. An absolute path on the host, or a git url in either git or http(s) format, is used as given. A relative path names a directory inside the repository being checked, so that schemas committed alongside the manifests that use them are found. Any location may be a kubeconform path template, such as ".github/schemas/{{ .ResourceKind }}_{{ .ResourceAPIVersion }}.json", when the files are not named "--.json".|`[]`| |`KUBECHECKS_SHOW_DEBUG_INFO`|Set to true to print debug info to the footer of MR comments.|`false`| |`KUBECHECKS_TIDY_OUTDATED_COMMENTS_MODE`|Sets the mode to use when tidying outdated comments. One of hide, delete.|`hide`| -|`KUBECHECKS_VCS_BASE_URL`|VCS base url, useful if self hosting gitlab, enterprise github, etc.|| +|`KUBECHECKS_VCS_BASE_URL`|VCS API base url, for self-hosted GitLab (https://) or GitHub Enterprise (https:///api/v3).|| |`KUBECHECKS_VCS_EMAIL`|VCS Email.|| |`KUBECHECKS_VCS_TOKEN`|VCS API token.|| |`KUBECHECKS_VCS_TYPE`|VCS type. One of gitlab or github.|`gitlab`| diff --git a/pkg/config/config.go b/pkg/config/config.go index 37ecfcda..cb5531e1 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -169,8 +169,17 @@ func NewWithViper(v *viper.Viper) (ServerConfig, error) { return cfg, errors.Wrap(err, "failed to read configuration") } + // vcs-type is documented as "one of gitlab or github", but that is help text only: + // a value from KUBECHECKS_VCS_TYPE reaches viper without flag-level validation. + // Reject unknown types here so they fail at config load, not later when a VCS + // client is created. An empty type (config not populated from the CLI) is left + // to the caller, which reports it when a client is actually needed. + if cfg.VcsType != "" && cfg.VcsType != "github" && cfg.VcsType != "gitlab" { + return cfg, fmt.Errorf("vcs-type must be one of github or gitlab, got %q", cfg.VcsType) + } + if cfg.VcsBaseUrl == "" { - cfg.VcsBaseUrl = fmt.Sprintf("https://%s.com", cfg.VcsType) + cfg.VcsBaseUrl = defaultVcsBaseUrl(cfg.VcsType) } // not set at all, which is the case when there are no flag defaults behind viper @@ -189,3 +198,19 @@ func NewWithViper(v *viper.Viper) (ServerConfig, error) { return cfg, nil } + +// defaultVcsBaseUrl is the API base for the public instance of each VCS, in the +// form every client expects of VcsBaseUrl: the GitHub client uses it as the API +// root, and the GitLab client appends /api/v4 to the instance root itself (the +// gitlab library's WithBaseURL does this). NewWithViper rejects unknown vcs types +// before calling this; an unset (empty) type yields an empty base URL. +func defaultVcsBaseUrl(vcsType string) string { + switch vcsType { + case "github": + return "https://api.github.com" + case "gitlab": + return "https://gitlab.com" + default: + return "" + } +} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 40136d04..b183febc 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -49,3 +49,36 @@ func TestNew_MaxCommentsPerCheck(t *testing.T) { require.ErrorContains(t, err, "max-comments-per-check", "%d", value) } } + +func TestNew_VcsBaseUrlDefault(t *testing.T) { + for vcsType, want := range map[string]string{ + "github": "https://api.github.com", + "gitlab": "https://gitlab.com", + } { + v := viper.New() + v.Set("vcs-type", vcsType) + + cfg, err := NewWithViper(v) + require.NoError(t, err, vcsType) + assert.Equal(t, want, cfg.VcsBaseUrl, vcsType) + } + + v := viper.New() + v.Set("vcs-type", "github") + v.Set("vcs-base-url", "https://github.example.com/api/v3") + + cfg, err := NewWithViper(v) + require.NoError(t, err) + assert.Equal(t, "https://github.example.com/api/v3", cfg.VcsBaseUrl, "an explicit base url is kept") +} + +func TestNew_InvalidVcsType(t *testing.T) { + // vcs-type is validated here because a value from KUBECHECKS_VCS_TYPE reaches + // viper without flag-level validation. + v := viper.New() + v.Set("vcs-type", "bitbucket") + + _, err := NewWithViper(v) + require.ErrorContains(t, err, "vcs-type must be one of github or gitlab") + require.ErrorContains(t, err, `"bitbucket"`) +} diff --git a/pkg/vcs/github_client/archive.go b/pkg/vcs/github_client/archive.go index 1fcb151d..2c72191c 100644 --- a/pkg/vcs/github_client/archive.go +++ b/pkg/vcs/github_client/archive.go @@ -18,6 +18,13 @@ func (c *Client) DownloadArchive(ctx context.Context, pr vcs.PullRequest) (strin ctx, span := tracer.Start(ctx, "DownloadArchive") defer span.End() + // VcsBaseUrl is the API base: https://api.github.com by default, and + // https:///api/v3 on GitHub Enterprise. pkg/config defaults it from + // vcs-type; fail loudly if a client was built without going through it. + if c.cfg.VcsBaseUrl == "" { + return "", errors.New("vcs-base-url is empty; expected pkg/config to default it from vcs-type") + } + // Retry configuration for waiting on GitHub to compute merge commit SHA. // This waits for a condition; for a call that fails, see retryConfig.do. rc := c.archiveRetry.withDefaults(10, 1*time.Second, 16*time.Second) @@ -131,21 +138,8 @@ func (c *Client) DownloadArchive(ctx context.Context, pr vcs.PullRequest) (strin // Go's http.Client strips the Authorization header on that cross-host redirect by // default, so the signed URL (already authenticated via query string) is fetched // without leaking the token. See issue #525. - // - // Enterprise detection mirrors createHttpClient: GHE requires both VcsBaseUrl and - // VcsUploadUrl to be set. VcsBaseUrl alone isn't a reliable signal because config - // defaults it to "https://github.com" when unset, so checking it would route - // cloud users into the enterprise branch and build a bogus - // `https://github.com/repos/...` URL that 404s. - var archiveURL string - if c.cfg.VcsUploadUrl != "" && c.cfg.VcsBaseUrl != "" { - // GitHub Enterprise: VcsBaseUrl is the API base (typically includes /api/v3). - baseURL := strings.TrimSuffix(c.cfg.VcsBaseUrl, "/") - archiveURL = fmt.Sprintf("%s/repos/%s/%s/zipball/%s", baseURL, pr.Owner, pr.Name, mergeCommitSHA) - } else { - // GitHub.com - archiveURL = fmt.Sprintf("https://api.github.com/repos/%s/%s/zipball/%s", pr.Owner, pr.Name, mergeCommitSHA) - } + baseURL := strings.TrimSuffix(c.cfg.VcsBaseUrl, "/") + archiveURL := fmt.Sprintf("%s/repos/%s/%s/zipball/%s", baseURL, pr.Owner, pr.Name, mergeCommitSHA) log.Debug(). Caller(). diff --git a/pkg/vcs/github_client/client.go b/pkg/vcs/github_client/client.go index 993276e7..4d83b312 100644 --- a/pkg/vcs/github_client/client.go +++ b/pkg/vcs/github_client/client.go @@ -137,14 +137,11 @@ func createHttpClient(ctx context.Context, cfg config.ServerConfig) (*http.Clien return nil, nil, errors.Wrap(err, "failed to create github app transport") } - // GitHub Enterprise: ghinstallation.Transport defaults its BaseURL to - // https://api.github.com. Unlike the go-github client (configured via - // WithEnterpriseURLs below), the App transport is never told about the - // Enterprise host, so installation-token requests go to api.github.com - // and 404. Point it at the configured Enterprise API base URL. - if cfg.VcsBaseUrl != "" { - appTransport.BaseURL = strings.TrimRight(cfg.VcsBaseUrl, "/") - } + // ghinstallation.Transport defaults its BaseURL to https://api.github.com + // and, unlike the go-github client (configured via WithEnterpriseURLs + // below), is never told about an Enterprise host. Point it at the + // configured API base, which pkg/config defaults to api.github.com. + appTransport.BaseURL = strings.TrimSuffix(cfg.VcsBaseUrl, "/") return &http.Client{Transport: appTransport}, appTransport, nil } diff --git a/pkg/vcs/github_client/client_test.go b/pkg/vcs/github_client/client_test.go index fcfe384e..c5cf7e2f 100644 --- a/pkg/vcs/github_client/client_test.go +++ b/pkg/vcs/github_client/client_test.go @@ -998,6 +998,7 @@ func TestClient_DownloadArchive_HappyPath(t *testing.T) { c := &Client{ googleClient: &GClient{PullRequests: mockPR}, + cfg: config.ServerConfig{VcsBaseUrl: "https://api.github.com"}, archiveRetry: fastRetry, } @@ -1036,6 +1037,7 @@ func TestClient_DownloadArchive_StaleMergeCommitThenReady(t *testing.T) { c := &Client{ googleClient: &GClient{PullRequests: mockPR}, + cfg: config.ServerConfig{VcsBaseUrl: "https://api.github.com"}, archiveRetry: fastRetry, } @@ -1068,6 +1070,7 @@ func TestClient_DownloadArchive_NotMergeable(t *testing.T) { c := &Client{ googleClient: &GClient{PullRequests: mockPR}, + cfg: config.ServerConfig{VcsBaseUrl: "https://api.github.com"}, archiveRetry: fastRetry, } @@ -1101,6 +1104,7 @@ func TestClient_DownloadArchive_ContextCancelled(t *testing.T) { c := &Client{ googleClient: &GClient{PullRequests: mockPR}, + cfg: config.ServerConfig{VcsBaseUrl: "https://api.github.com"}, archiveRetry: fastRetry, } @@ -1155,22 +1159,11 @@ func TestClient_DownloadArchive_GHEnterprise(t *testing.T) { mockPR.AssertExpectations(t) } -func TestClient_DownloadArchive_DefaultedVcsBaseUrl(t *testing.T) { - // pkg/config defaults VcsBaseUrl to "https://github.com" when unset, so a cloud - // configuration arrives at DownloadArchive with a non-empty VcsBaseUrl. The cloud - // branch must still fire (api.github.com), not the enterprise branch which would - // build a bogus `https://github.com/repos/...` URL. See issue #525 review. - mockPR := NewMockPullRequestsServicesWithGet(t, - prResponse{ - headSHA: "sha1", - mergeCommitSHA: "merge-sha", - mergeable: github.Ptr(true), - }, - ) - +func TestClient_DownloadArchive_EmptyVcsBaseUrl(t *testing.T) { + // A client built without going through pkg/config (which defaults VcsBaseUrl + // from vcs-type) must fail loudly instead of building a relative archive URL. c := &Client{ - googleClient: &GClient{PullRequests: mockPR}, - cfg: config.ServerConfig{VcsBaseUrl: "https://github.com"}, // no VcsUploadUrl + cfg: config.ServerConfig{}, archiveRetry: fastRetry, } @@ -1182,10 +1175,8 @@ func TestClient_DownloadArchive_DefaultedVcsBaseUrl(t *testing.T) { SHA: "sha1", } - url, err := c.DownloadArchive(context.Background(), pr) - require.NoError(t, err) - assert.Equal(t, "https://api.github.com/repos/owner/repo/zipball/merge-sha", url) - mockPR.AssertExpectations(t) + _, err := c.DownloadArchive(context.Background(), pr) + require.ErrorContains(t, err, "vcs-base-url is empty") } // --- test helpers --- @@ -1242,9 +1233,9 @@ func testRSAPrivateKeyPEM(t *testing.T) string { } // TestCreateHttpClientAppBaseURL verifies that for GitHub App auth the -// ghinstallation transport's BaseURL is pointed at the configured GitHub -// Enterprise API, not the default api.github.com. Without this, installation -// access-token requests go to api.github.com and 404 on Enterprise. +// ghinstallation transport's BaseURL is the configured API base: the +// Enterprise API on GHE, where api.github.com would 404, and pkg/config's +// github.com default otherwise. func TestCreateHttpClientAppBaseURL(t *testing.T) { key := testRSAPrivateKeyPEM(t) @@ -1264,8 +1255,8 @@ func TestCreateHttpClientAppBaseURL(t *testing.T) { expectedBaseURL: "https://github.example.com/api/v3", }, { - name: "no base url leaves the default (public github)", - vcsBaseURL: "", + name: "config's github default is the public api", + vcsBaseURL: "https://api.github.com", expectedBaseURL: "https://api.github.com", }, } diff --git a/pkg/vcs/gitlab_client/client.go b/pkg/vcs/gitlab_client/client.go index 10b1ea94..f7ddcc66 100644 --- a/pkg/vcs/gitlab_client/client.go +++ b/pkg/vcs/gitlab_client/client.go @@ -479,18 +479,7 @@ retryLoop: // Construct archive URL using GitLab API // IMPORTANT: Use the resolved SHA, not the ref path, for cache key extraction - // Format: https://gitlab.com/api/v4/projects/{project_path_encoded}/repository/archive.zip?sha={sha} - var archiveURL string - if c.cfg.VcsBaseUrl != "" { - // Self-hosted GitLab - baseURL := strings.TrimSuffix(c.cfg.VcsBaseUrl, "/") - archiveURL = fmt.Sprintf("%s/api/v4/projects/%s/repository/archive.zip?sha=%s", - baseURL, projectPathEncoded, mergeRefSHA) - } else { - // GitLab.com - archiveURL = fmt.Sprintf("https://gitlab.com/api/v4/projects/%s/repository/archive.zip?sha=%s", - projectPathEncoded, mergeRefSHA) - } + archiveURL := gitlabArchiveURL(c.cfg.VcsBaseUrl, projectPathEncoded, mergeRefSHA) log.Debug(). Caller(). @@ -505,6 +494,25 @@ retryLoop: return archiveURL, nil } +// gitlabArchiveURL builds the merge-ref archive endpoint URL for a resolved SHA: +// {instance}/api/v4/projects/{project_path_encoded}/repository/archive.zip?sha={sha}. +// instanceRoot is the GitLab instance root: https://gitlab.com by default (set by +// pkg/config), or https:// for self-hosted GitLab. Older configurations may +// carry the /api/v4 suffix explicitly, so it is appended exactly once, whichever +// form is given. +func gitlabArchiveURL(instanceRoot, projectPathEncoded, sha string) string { + baseURL := strings.TrimSuffix(instanceRoot, "/") + if baseURL == "" { + // Matches the gitlab library's own default; an empty VcsBaseUrl only + // happens when a client is built without going through pkg/config. + baseURL = "https://gitlab.com" + } + if !strings.HasSuffix(baseURL, "/api/v4") { + baseURL += "/api/v4" + } + return fmt.Sprintf("%s/projects/%s/repository/archive.zip?sha=%s", baseURL, projectPathEncoded, sha) +} + // MRReadinessStatus represents the readiness state of a merge request type MRReadinessStatus int diff --git a/pkg/vcs/gitlab_client/client_test.go b/pkg/vcs/gitlab_client/client_test.go index 5105f505..25462b73 100644 --- a/pkg/vcs/gitlab_client/client_test.go +++ b/pkg/vcs/gitlab_client/client_test.go @@ -556,3 +556,44 @@ func TestCreateGitlabClient_NoToken(t *testing.T) { }) assert.Equal(t, ErrNoToken, err) } + +func TestGitlabArchiveURL(t *testing.T) { + const path = "owner%2Frepo" + tests := []struct { + name string + instanceRoot string + want string + }{ + { + name: "empty falls back to gitlab.com", + instanceRoot: "", + want: "https://gitlab.com/api/v4/projects/owner%2Frepo/repository/archive.zip?sha=sha1", + }, + { + name: "instance root gets /api/v4 appended", + instanceRoot: "https://gitlab.example.com", + want: "https://gitlab.example.com/api/v4/projects/owner%2Frepo/repository/archive.zip?sha=sha1", + }, + { + name: "trailing slash is trimmed", + instanceRoot: "https://gitlab.example.com/", + want: "https://gitlab.example.com/api/v4/projects/owner%2Frepo/repository/archive.zip?sha=sha1", + }, + { + name: "existing /api/v4 suffix is not doubled", + instanceRoot: "https://gitlab.example.com/api/v4", + want: "https://gitlab.example.com/api/v4/projects/owner%2Frepo/repository/archive.zip?sha=sha1", + }, + { + name: "existing /api/v4 suffix with trailing slash is not doubled", + instanceRoot: "https://gitlab.example.com/api/v4/", + want: "https://gitlab.example.com/api/v4/projects/owner%2Frepo/repository/archive.zip?sha=sha1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, gitlabArchiveURL(tt.instanceRoot, path, "sha1")) + }) + } +}