| 1 | |
| 2 | |
| 3 | |
| 4 | package limatmpl |
| 5 | |
| 6 | import ( |
| 7 | "cmp" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net/http" |
| 14 | "os" |
| 15 | "path" |
| 16 | "strings" |
| 17 | ) |
| 18 | |
| 19 | const defaultFilename = ".lima.yaml" |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | func transformGitHubURL(ctx context.Context, input string) (string, error) { |
| 30 | input, origBranch, _ := strings.Cut(input, "@") |
| 31 | |
| 32 | parts := strings.Split(input, "/") |
| 33 | for len(parts) < 2 { |
| 34 | parts = append(parts, "") |
| 35 | } |
| 36 | org := parts[0] |
| 37 | if org == "" { |
| 38 | return "", fmt.Errorf("github: URL must contain at least an ORG, got %#q", input) |
| 39 | } |
| 40 | |
| 41 | repo := cmp.Or(parts[1], org) |
| 42 | filePath := strings.Join(parts[2:], "/") |
| 43 | |
| 44 | |
| 45 | |
| 46 | if repo == ".." { |
| 47 | return "", fmt.Errorf("repo %#q in github: URL %#q escapes the org", repo, input) |
| 48 | } |
| 49 | if escapesRepo(filePath) { |
| 50 | return "", fmt.Errorf("path %#q in github: URL %#q escapes the repository", filePath, input) |
| 51 | } |
| 52 | if escapesRepo(origBranch) { |
| 53 | return "", fmt.Errorf("branch %#q in github: URL %#q escapes the repository", origBranch, input) |
| 54 | } |
| 55 | |
| 56 | if filePath == "" { |
| 57 | filePath = defaultFilename |
| 58 | } else { |
| 59 | |
| 60 | if strings.HasSuffix(filePath, "/") { |
| 61 | filePath += defaultFilename |
| 62 | } |
| 63 | |
| 64 | |
| 65 | filename := path.Base(filePath) |
| 66 | if !strings.Contains(filename[1:], ".") { |
| 67 | filePath += ".yaml" |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | |
| 72 | branch := origBranch |
| 73 | if branch == "" { |
| 74 | var err error |
| 75 | branch, err = getGitHubDefaultBranch(ctx, org, repo) |
| 76 | if err != nil { |
| 77 | return "", fmt.Errorf("failed to get default branch for %s/%s: %w", org, repo, err) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | |
| 82 | ext := strings.ToLower(path.Ext(filePath)) |
| 83 | if ext == ".yaml" || ext == ".yml" { |
| 84 | return resolveGitHubSymlink(ctx, org, repo, branch, filePath, origBranch) |
| 85 | } |
| 86 | return githubUserContentURL(org, repo, branch, filePath), nil |
| 87 | } |
| 88 | |
| 89 | func githubUserContentURL(org, repo, branch, filePath string) string { |
| 90 | |
| 91 | |
| 92 | return fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/%s", org, repo, branch, path.Clean(filePath)) |
| 93 | } |
| 94 | |
| 95 | func getGitHubUserContent(ctx context.Context, org, repo, branch, filePath string) (*http.Response, error) { |
| 96 | url := githubUserContentURL(org, repo, branch, filePath) |
| 97 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) |
| 98 | if err != nil { |
| 99 | return nil, fmt.Errorf("failed to create request: %w", err) |
| 100 | } |
| 101 | req.Header.Set("User-Agent", "lima") |
| 102 | return http.DefaultClient.Do(req) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | func getGitHubDefaultBranch(ctx context.Context, org, repo string) (string, error) { |
| 107 | apiURL := fmt.Sprintf("https://api.github.com/repos/%s/%s", org, repo) |
| 108 | |
| 109 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, http.NoBody) |
| 110 | if err != nil { |
| 111 | return "", fmt.Errorf("failed to create request: %w", err) |
| 112 | } |
| 113 | |
| 114 | req.Header.Set("User-Agent", "lima") |
| 115 | req.Header.Set("Accept", "application/vnd.github.v3+json") |
| 116 | |
| 117 | |
| 118 | token := cmp.Or(os.Getenv("GH_TOKEN"), os.Getenv("GITHUB_TOKEN")) |
| 119 | if token != "" { |
| 120 | req.Header.Set("Authorization", "token "+token) |
| 121 | } |
| 122 | |
| 123 | resp, err := http.DefaultClient.Do(req) |
| 124 | if err != nil { |
| 125 | return "", fmt.Errorf("failed to query GitHub API: %w", err) |
| 126 | } |
| 127 | defer resp.Body.Close() |
| 128 | |
| 129 | body, err := io.ReadAll(resp.Body) |
| 130 | if err != nil { |
| 131 | return "", fmt.Errorf("failed to read GitHub API response: %w", err) |
| 132 | } |
| 133 | if resp.StatusCode != http.StatusOK { |
| 134 | return "", fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, string(body)) |
| 135 | } |
| 136 | |
| 137 | var repoData struct { |
| 138 | DefaultBranch string `json:"default_branch"` |
| 139 | } |
| 140 | if err := json.Unmarshal(body, &repoData); err != nil { |
| 141 | return "", fmt.Errorf("failed to parse GitHub API response: %w", err) |
| 142 | } |
| 143 | if repoData.DefaultBranch == "" { |
| 144 | return "", fmt.Errorf("repository %s/%s has no default branch", org, repo) |
| 145 | } |
| 146 | return repoData.DefaultBranch, nil |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | func resolveGitHubSymlink(ctx context.Context, org, repo, branch, filePath, origBranch string) (string, error) { |
| 153 | resp, err := getGitHubUserContent(ctx, org, repo, branch, filePath) |
| 154 | if err != nil { |
| 155 | return "", fmt.Errorf("failed to fetch file: %w", err) |
| 156 | } |
| 157 | defer resp.Body.Close() |
| 158 | |
| 159 | |
| 160 | if resp.StatusCode == http.StatusNotFound && repo == org { |
| 161 | defaultBranch, err := getGitHubDefaultBranch(ctx, org, repo) |
| 162 | if err == nil { |
| 163 | return resolveGitHubRedirect(ctx, org, repo, defaultBranch, filePath, branch) |
| 164 | } |
| 165 | } |
| 166 | if resp.StatusCode != http.StatusOK { |
| 167 | return "", fmt.Errorf("file %#q not found or inaccessible: status %d", resp.Request.URL, resp.StatusCode) |
| 168 | } |
| 169 | |
| 170 | |
| 171 | buf := make([]byte, 1024) |
| 172 | n, err := resp.Body.Read(buf) |
| 173 | if err != nil && !errors.Is(err, io.EOF) { |
| 174 | return "", fmt.Errorf("failed to read %#q content: %w", resp.Request.URL, err) |
| 175 | } |
| 176 | content := string(buf[:n]) |
| 177 | |
| 178 | |
| 179 | if repo == org && strings.HasPrefix(content, "github:") { |
| 180 | return validateGitHubRedirect(content, org, origBranch, resp.Request.URL.String()) |
| 181 | } |
| 182 | |
| 183 | |
| 184 | if !(content == "" || strings.ContainsAny(content, "\n :")) { |
| 185 | |
| 186 | filePath, err = symlinkTarget(filePath, content) |
| 187 | if err != nil { |
| 188 | return "", err |
| 189 | } |
| 190 | } |
| 191 | return githubUserContentURL(org, repo, branch, filePath), nil |
| 192 | } |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | func symlinkTarget(filePath, target string) (string, error) { |
| 198 | resolved := path.Join(path.Dir(filePath), target) |
| 199 | if escapesRepo(resolved) { |
| 200 | return "", fmt.Errorf("symlink target %#q in %#q escapes the repository", target, filePath) |
| 201 | } |
| 202 | return resolved, nil |
| 203 | } |
| 204 | |
| 205 | |
| 206 | func escapesRepo(p string) bool { |
| 207 | p = path.Clean(p) |
| 208 | return p == ".." || strings.HasPrefix(p, "../") |
| 209 | } |
| 210 | |
| 211 | |
| 212 | |
| 213 | func resolveGitHubRedirect(ctx context.Context, org, repo, defaultBranch, filePath, origBranch string) (string, error) { |
| 214 | |
| 215 | resp, err := getGitHubUserContent(ctx, org, repo, defaultBranch, filePath) |
| 216 | if err != nil { |
| 217 | return "", fmt.Errorf("failed to fetch file: %w", err) |
| 218 | } |
| 219 | defer resp.Body.Close() |
| 220 | if resp.StatusCode != http.StatusOK { |
| 221 | return "", fmt.Errorf("file %#q not found or inaccessible: status %d", resp.Request.URL, resp.StatusCode) |
| 222 | } |
| 223 | body, err := io.ReadAll(resp.Body) |
| 224 | if err != nil { |
| 225 | return "", fmt.Errorf("failed to read %#q content: %w", resp.Request.URL, err) |
| 226 | } |
| 227 | return validateGitHubRedirect(string(body), org, origBranch, resp.Request.URL.String()) |
| 228 | } |
| 229 | |
| 230 | func validateGitHubRedirect(body, org, origBranch, url string) (string, error) { |
| 231 | redirect, _, _ := strings.Cut(body, "\n") |
| 232 | redirect = strings.TrimSpace(redirect) |
| 233 | |
| 234 | if !strings.HasPrefix(redirect, "github:"+org+"/") { |
| 235 | return "", fmt.Errorf("redirect %#q is not a `github:%s` URL (from %#q)", redirect, org, url) |
| 236 | } |
| 237 | if strings.ContainsRune(redirect, '@') { |
| 238 | return "", fmt.Errorf("redirect %#q must not include a branch/tag/sha (from %#q)", redirect, url) |
| 239 | } |
| 240 | |
| 241 | if origBranch != "" { |
| 242 | redirect += "@" + origBranch |
| 243 | } |
| 244 | return redirect, nil |
| 245 | } |