|
| 1 | +package downloader |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/url" |
| 6 | + "path/filepath" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | + |
| 10 | + log "github.com/charmbracelet/log" |
| 11 | + "github.com/cloudposse/atmos/pkg/schema" |
| 12 | +) |
| 13 | + |
| 14 | +var ErrInvalidURL = fmt.Errorf("invalid URL") |
| 15 | + |
| 16 | +const schemeSeparator = "://" |
| 17 | + |
| 18 | +// CustomGitDetector intercepts Git URLs (for GitHub, Bitbucket, GitLab, etc.) |
| 19 | +// and transforms them into a proper URL for cloning, optionally injecting tokens. |
| 20 | +type CustomGitDetector struct { |
| 21 | + atmosConfig *schema.AtmosConfiguration |
| 22 | + source string |
| 23 | +} |
| 24 | + |
| 25 | +func NewCustomGitDetector(atmosConfig *schema.AtmosConfiguration, source string) *CustomGitDetector { |
| 26 | + return &CustomGitDetector{ |
| 27 | + atmosConfig: atmosConfig, |
| 28 | + source: source, |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// Detect implements the getter.Detector interface for go-getter v1. |
| 33 | +func (d *CustomGitDetector) Detect(src, _ string) (string, bool, error) { |
| 34 | + log.Debug("CustomGitDetector.Detect called") |
| 35 | + |
| 36 | + if len(src) == 0 { |
| 37 | + return "", false, nil |
| 38 | + } |
| 39 | + |
| 40 | + // Ensure the URL has an explicit scheme. |
| 41 | + src = d.ensureScheme(src) |
| 42 | + |
| 43 | + // Parse the URL to extract the host and path. |
| 44 | + parsedURL, err := url.Parse(src) |
| 45 | + if err != nil { |
| 46 | + maskedSrc, _ := maskBasicAuth(src) |
| 47 | + log.Debug("Failed to parse URL", keyURL, maskedSrc, "error", err) |
| 48 | + return "", false, fmt.Errorf("failed to parse URL %q: %w", maskedSrc, err) |
| 49 | + } |
| 50 | + |
| 51 | + // If no host is detected, this is likely a local file path. |
| 52 | + // Skip custom processing so that go getter handles it as is. |
| 53 | + if parsedURL.Host == "" { |
| 54 | + log.Debug("No host detected in URL, skipping custom git detection", keyURL, src) |
| 55 | + return "", false, nil |
| 56 | + } |
| 57 | + |
| 58 | + // Normalize the path. |
| 59 | + d.normalizePath(parsedURL) |
| 60 | + |
| 61 | + // Adjust host check to support GitHub, Bitbucket, GitLab, etc. |
| 62 | + host := strings.ToLower(parsedURL.Host) |
| 63 | + if host != hostGitHub && host != hostBitbucket && host != hostGitLab { |
| 64 | + log.Debug("Skipping token injection for an unsupported host", "host", parsedURL.Host) |
| 65 | + return "", false, nil |
| 66 | + } |
| 67 | + |
| 68 | + log.Debug("Reading config param", "InjectGithubToken", d.atmosConfig.Settings.InjectGithubToken) |
| 69 | + // Inject token if available. |
| 70 | + d.injectToken(parsedURL, host) |
| 71 | + |
| 72 | + // Adjust subdirectory if needed. |
| 73 | + d.adjustSubdir(parsedURL, d.source) |
| 74 | + |
| 75 | + // Set "depth=1" for a shallow clone if not specified. |
| 76 | + q := parsedURL.Query() |
| 77 | + if _, exists := q["depth"]; !exists { |
| 78 | + q.Set("depth", "1") |
| 79 | + } |
| 80 | + parsedURL.RawQuery = q.Encode() |
| 81 | + |
| 82 | + finalURL := "git::" + parsedURL.String() |
| 83 | + maskedFinal, err := maskBasicAuth(strings.TrimPrefix(finalURL, "git::")) |
| 84 | + if err != nil { |
| 85 | + log.Debug("Masking failed", "error", err) |
| 86 | + } else { |
| 87 | + log.Debug("Final transformation", "url", "git::"+maskedFinal) |
| 88 | + } |
| 89 | + |
| 90 | + return finalURL, true, nil |
| 91 | +} |
| 92 | + |
| 93 | +const ( |
| 94 | + // Named constants for regex match indices. |
| 95 | + matchIndexUser = 1 |
| 96 | + matchIndexHost = 3 |
| 97 | + matchIndexPath = 4 |
| 98 | + matchIndexSuffix = 5 |
| 99 | + matchIndexExtra = 6 |
| 100 | + |
| 101 | + keyURL = "url" |
| 102 | + |
| 103 | + hostGitHub = "github.com" |
| 104 | + hostGitLab = "gitlab.com" |
| 105 | + hostBitbucket = "bitbucket.org" |
| 106 | +) |
| 107 | + |
| 108 | +const GitPrefix = "git::" |
| 109 | + |
| 110 | +// ensureScheme checks for an explicit scheme and rewrites SCP-style URLs if needed. |
| 111 | +// Also removes any existing "git::" prefix (required for the dry-run mode to operate correctly). |
| 112 | +func (d *CustomGitDetector) ensureScheme(src string) string { |
| 113 | + // Strip any existing "git::" prefix |
| 114 | + src = strings.TrimPrefix(src, GitPrefix) |
| 115 | + |
| 116 | + if !strings.Contains(src, schemeSeparator) { |
| 117 | + if newSrc, rewritten := rewriteSCPURL(src); rewritten { |
| 118 | + maskedOld, _ := maskBasicAuth(src) |
| 119 | + maskedNew, _ := maskBasicAuth(newSrc) |
| 120 | + log.Debug("Rewriting SCP-style SSH URL", "old_url", maskedOld, "new_url", maskedNew) |
| 121 | + return newSrc |
| 122 | + } |
| 123 | + src = "https://" + src |
| 124 | + maskedSrc, _ := maskBasicAuth(src) |
| 125 | + log.Debug("Defaulting to https scheme", keyURL, maskedSrc) |
| 126 | + } |
| 127 | + return src |
| 128 | +} |
| 129 | + |
| 130 | +func rewriteSCPURL(src string) (string, bool) { |
| 131 | + scpPattern := regexp.MustCompile(`^(([\w.-]+)@)?([\w.-]+\.[\w.-]+):([\w./-]+)(\.git)?(.*)$`) |
| 132 | + if scpPattern.MatchString(src) { |
| 133 | + matches := scpPattern.FindStringSubmatch(src) |
| 134 | + newSrc := "ssh://" |
| 135 | + user := matches[matchIndexUser] // This includes the "@" if present. |
| 136 | + host := matches[matchIndexHost] |
| 137 | + // Only for SSH vendoring (i.e. when rewriting an SCP URL), inject default username (git) for known hosts. |
| 138 | + if user == "" && (strings.EqualFold(host, hostGitHub) || |
| 139 | + strings.EqualFold(host, hostGitLab) || |
| 140 | + strings.EqualFold(host, hostBitbucket)) { |
| 141 | + user = "git@" |
| 142 | + } |
| 143 | + newSrc += user + host + "/" + matches[matchIndexPath] |
| 144 | + if matches[matchIndexSuffix] != "" { |
| 145 | + newSrc += matches[matchIndexSuffix] |
| 146 | + } |
| 147 | + if matches[matchIndexExtra] != "" { |
| 148 | + newSrc += matches[matchIndexExtra] |
| 149 | + } |
| 150 | + return newSrc, true |
| 151 | + } |
| 152 | + return "", false |
| 153 | +} |
| 154 | + |
| 155 | +// normalizePath converts the URL path to use forward slashes. |
| 156 | +func (d *CustomGitDetector) normalizePath(parsedURL *url.URL) { |
| 157 | + unescapedPath, err := url.PathUnescape(parsedURL.Path) |
| 158 | + if err == nil { |
| 159 | + parsedURL.Path = filepath.ToSlash(unescapedPath) |
| 160 | + } else { |
| 161 | + parsedURL.Path = filepath.ToSlash(parsedURL.Path) |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +// injectToken injects a token into the URL if available. |
| 166 | +func (d *CustomGitDetector) injectToken(parsedURL *url.URL, host string) { |
| 167 | + token, tokenSource := d.resolveToken(host) |
| 168 | + if token != "" { |
| 169 | + defaultUsername := d.getDefaultUsername(host) |
| 170 | + parsedURL.User = url.UserPassword(defaultUsername, token) |
| 171 | + maskedURL, _ := maskBasicAuth(parsedURL.String()) |
| 172 | + log.Debug("Injected token", "env", tokenSource, keyURL, maskedURL) |
| 173 | + } else { |
| 174 | + log.Debug("No token found for injection") |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// resolveToken returns the token and its source based on the host. |
| 179 | +func (d *CustomGitDetector) resolveToken(host string) (string, string) { |
| 180 | + switch host { |
| 181 | + case hostGitHub: |
| 182 | + if d.atmosConfig.Settings.InjectGithubToken { |
| 183 | + return d.atmosConfig.Settings.AtmosGithubToken, "ATMOS_GITHUB_TOKEN" |
| 184 | + } |
| 185 | + return d.atmosConfig.Settings.GithubToken, "GITHUB_TOKEN" |
| 186 | + case hostBitbucket: |
| 187 | + if d.atmosConfig.Settings.InjectBitbucketToken { |
| 188 | + return d.atmosConfig.Settings.AtmosBitbucketToken, "ATMOS_BITBUCKET_TOKEN" |
| 189 | + } |
| 190 | + return d.atmosConfig.Settings.BitbucketToken, "BITBUCKET_TOKEN" |
| 191 | + case hostGitLab: |
| 192 | + if d.atmosConfig.Settings.InjectGitlabToken { |
| 193 | + return d.atmosConfig.Settings.AtmosGitlabToken, "ATMOS_GITLAB_TOKEN" |
| 194 | + } |
| 195 | + return d.atmosConfig.Settings.GitlabToken, "GITLAB_TOKEN" |
| 196 | + } |
| 197 | + return "", "" |
| 198 | +} |
| 199 | + |
| 200 | +// getDefaultUsername returns the default username for token injection based on the host. |
| 201 | +func (d *CustomGitDetector) getDefaultUsername(host string) string { |
| 202 | + switch host { |
| 203 | + case hostGitHub: |
| 204 | + return "x-access-token" |
| 205 | + case hostGitLab: |
| 206 | + return "oauth2" |
| 207 | + case hostBitbucket: |
| 208 | + defaultUsername := d.atmosConfig.Settings.BitbucketUsername |
| 209 | + if defaultUsername == "" { |
| 210 | + return "x-token-auth" |
| 211 | + } |
| 212 | + return defaultUsername |
| 213 | + default: |
| 214 | + return "x-access-token" |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +// adjustSubdir appends "//." to the path if no subdirectory is specified. |
| 219 | +func (d *CustomGitDetector) adjustSubdir(parsedURL *url.URL, source string) { |
| 220 | + normalizedSource := filepath.ToSlash(source) |
| 221 | + if normalizedSource != "" && !strings.Contains(normalizedSource, "//") { |
| 222 | + parts := strings.SplitN(parsedURL.Path, "/", 4) |
| 223 | + if strings.HasSuffix(parsedURL.Path, ".git") || len(parts) == 3 { |
| 224 | + maskedSrc, _ := maskBasicAuth(source) |
| 225 | + log.Debug("Detected top-level repo with no subdir: appending '//.'", keyURL, maskedSrc) |
| 226 | + parsedURL.Path += "//." |
| 227 | + } |
| 228 | + } |
| 229 | +} |
0 commit comments