// Package github reads public repository metadata from the public GitHub // REST API. It is SSRF-safe by construction: the only origin it contacts is // https://api.github.com, a repository coordinate is validated by the domain // before it becomes a path, and a redirect to any other origin is refused. package github import ( "cmp" "context" "crypto/tls" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "regexp" "slices" "strconv" "strings" "time" "unicode/utf8" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) const ( // apiOrigin is the only origin the fetcher ever contacts. apiOrigin = "https://api.github.com" apiVersion = "2022-11-28" userAgent = "lincodex-repository-check" // Response caps: a repository document is a few KiB, the language map // smaller; a README is read only up to its excerpt budget. maxMetadataBytes = 1 << 20 maxReadmeBytes = 64 << 10 // maxRedirects bounds same-origin redirects, such as a renamed repository. maxRedirects = 3 // The stored bounds of candidate_project_repositories. maxDescriptionRunes = 1000 maxReadmeRunes = 4000 maxTopics = 20 // maxLanguages keeps the main languages by size. maxLanguages = 3 // Rate limit waits are clamped, so a wrong header cannot stall a check // for days or make it spin. minRateLimitWait = time.Minute maxRateLimitWait = time.Hour ) // Fetcher implements outbound.RepositoryMetadataFetcher. type Fetcher struct { client *http.Client origin string token string clock func() time.Time } var _ outbound.RepositoryMetadataFetcher = (*Fetcher)(nil) // NewFetcher builds a fetcher for api.github.com. token is optional; it is // sent only to that origin and never logged. func NewFetcher(timeout time.Duration, token string, clock func() time.Time) (*Fetcher, error) { return newFetcher(apiOrigin, timeout, token, clock, &http.Transport{ // No proxy from the environment: the request goes to GitHub directly. Proxy: nil, DialContext: (&net.Dialer{Timeout: timeout}).DialContext, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, TLSHandshakeTimeout: timeout, ResponseHeaderTimeout: timeout, MaxIdleConns: 4, IdleConnTimeout: time.Minute, ForceAttemptHTTP2: true, }) } // newFetcher lets tests point the fetcher at an httptest server; production // code reaches it only through NewFetcher with the fixed origin. func newFetcher(origin string, timeout time.Duration, token string, clock func() time.Time, transport http.RoundTripper) (*Fetcher, error) { if timeout <= 0 || clock == nil || transport == nil { return nil, errors.New("github.newFetcher - timeout, clock, and transport must be set") } parsed, err := url.Parse(origin) if err != nil || parsed.Host == "" || parsed.Path != "" { return nil, errors.New("github.newFetcher - origin is invalid") } return &Fetcher{ client: &http.Client{ Timeout: timeout, Transport: transport, CheckRedirect: func(request *http.Request, via []*http.Request) error { if len(via) >= maxRedirects { return errors.New("too many redirects") } if request.URL.Scheme != parsed.Scheme || request.URL.Host != parsed.Host { return errors.New("redirect to another origin") } return nil }, }, origin: parsed.Scheme + "://" + parsed.Host, token: token, clock: clock, }, nil } type repositoryDocument struct { ID int64 `json:"id"` Private bool `json:"private"` Visibility string `json:"visibility"` Description *string `json:"description"` Topics []string `json:"topics"` } // Fetch reads the repository, its languages, and its README. A repository // that does not exist or is not public is Found=false with no metadata. func (fetcher *Fetcher) Fetch( ctx context.Context, repository domain.GitHubRepository, previous outbound.RepositoryCheck, ) (outbound.RepositoryFetch, error) { if repository.IsZero() { return outbound.RepositoryFetch{}, fmt.Errorf("github.Fetcher.Fetch - repository is not set: %w", domain.ErrInvalidGitHubRepository) } base := "/repos/" + url.PathEscape(repository.Owner()) + "/" + url.PathEscape(repository.Name()) repositoryETag := "" if previous.State == outbound.RepositoryCheckVerified { repositoryETag = previous.RepositoryETag } response, err := fetcher.get(ctx, base, "application/vnd.github+json", repositoryETag, maxMetadataBytes) if err != nil { return outbound.RepositoryFetch{}, err } switch { case response.status == http.StatusNotModified && repositoryETag != "": return outbound.RepositoryFetch{ Found: true, NotModified: true, GitHubID: previous.GitHubID, Evidence: previous.Evidence, RepositoryETag: previous.RepositoryETag, ReadmeETag: previous.ReadmeETag, }, nil case response.status == http.StatusNotFound || response.status == http.StatusGone || response.status == http.StatusUnavailableForLegalReasons: return outbound.RepositoryFetch{Found: false}, nil case response.status != http.StatusOK: return outbound.RepositoryFetch{}, fetcher.statusError(response) } return fetcher.publicRepository(ctx, base, response) } // publicRepository reads the metadata of a repository document that GitHub // returned: a private or internal one is not found, a public one gets its // languages and README. func (fetcher *Fetcher) publicRepository(ctx context.Context, base string, response fetched) (outbound.RepositoryFetch, error) { var document repositoryDocument if err := json.Unmarshal(response.body, &document); err != nil || document.ID <= 0 { return outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse} } if document.Private || (document.Visibility != "" && document.Visibility != "public") { return outbound.RepositoryFetch{Found: false}, nil } languages, err := fetcher.languages(ctx, base) if err != nil { return outbound.RepositoryFetch{}, err } readme, readmeETag, err := fetcher.readme(ctx, base) if err != nil { return outbound.RepositoryFetch{}, err } description := "" if document.Description != nil { description = truncate(plainLine(*document.Description), maxDescriptionRunes) } return outbound.RepositoryFetch{ Found: true, GitHubID: document.ID, RepositoryETag: boundedETag(response.etag), ReadmeETag: readmeETag, Evidence: domain.RepositoryEvidence{ Description: description, Topics: cleanTopics(document.Topics), Languages: languages, ReadmeExcerpt: readme, }, }, nil } func (fetcher *Fetcher) languages(ctx context.Context, base string) ([]string, error) { response, err := fetcher.get(ctx, base+"/languages", "application/vnd.github+json", "", maxMetadataBytes) if err != nil { return nil, err } if response.status == http.StatusNotFound { return []string{}, nil } if response.status != http.StatusOK { return nil, fetcher.statusError(response) } var sizes map[string]int64 if err := json.Unmarshal(response.body, &sizes); err != nil { return nil, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse} } type language struct { name string bytes int64 } var ordered []language for name, size := range sizes { if clean := plainLine(name); clean != "" && utf8.RuneCountInString(clean) <= 50 { ordered = append(ordered, language{name: clean, bytes: size}) } } slices.SortFunc(ordered, func(left, right language) int { return cmp.Or(cmp.Compare(right.bytes, left.bytes), strings.Compare(left.name, right.name)) }) names := make([]string, 0, maxLanguages) for _, item := range ordered[:min(len(ordered), maxLanguages)] { names = append(names, item.name) } return names, nil } func (fetcher *Fetcher) readme(ctx context.Context, base string) (string, string, error) { response, err := fetcher.get(ctx, base+"/readme", "application/vnd.github.raw+json", "", maxReadmeBytes) if err != nil { return "", "", err } if response.status == http.StatusNotFound { return "", "", nil } if response.status != http.StatusOK { return "", "", fetcher.statusError(response) } // A cut body may end inside a multi-byte character; invalid bytes are // dropped instead of failing the check. text := strings.ToValidUTF8(string(response.body), "") return truncate(MarkdownToText(text), maxReadmeRunes), boundedETag(response.etag), nil } type fetched struct { status int etag string body []byte headers http.Header } func (fetcher *Fetcher) get(ctx context.Context, path, accept, etag string, limit int64) (fetched, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, fetcher.origin+path, nil) if err != nil { return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork} } request.Header.Set("Accept", accept) request.Header.Set("User-Agent", userAgent) request.Header.Set("X-GitHub-Api-Version", apiVersion) if etag != "" { request.Header.Set("If-None-Match", etag) } if fetcher.token != "" { request.Header.Set("Authorization", "Bearer "+fetcher.token) } response, err := fetcher.client.Do(request) if err != nil { // The error can carry the URL; only the class leaves this function. return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork} } defer func() { _ = response.Body.Close() }() body, err := io.ReadAll(io.LimitReader(response.Body, limit)) if err != nil { return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork} } return fetched{status: response.StatusCode, etag: response.Header.Get("ETag"), body: body, headers: response.Header}, nil } // statusError classifies an unexpected status. GitHub reports an exhausted // rate limit as 403 or 429 with x-ratelimit-remaining 0 or Retry-After. func (fetcher *Fetcher) statusError(response fetched) error { limited := response.status == http.StatusTooManyRequests || (response.status == http.StatusForbidden && (response.headers.Get("X-RateLimit-Remaining") == "0" || response.headers.Get("Retry-After") != "")) switch { case limited: return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: fetcher.rateLimitWait(response.headers)} case response.status >= http.StatusInternalServerError: return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureServerError} default: return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse} } } func (fetcher *Fetcher) rateLimitWait(headers http.Header) time.Duration { wait := minRateLimitWait if seconds, err := strconv.ParseInt(headers.Get("Retry-After"), 10, 64); err == nil && seconds > 0 { wait = time.Duration(seconds) * time.Second } else if reset, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64); err == nil { wait = time.Unix(reset, 0).Sub(fetcher.clock()) } return min(max(wait, minRateLimitWait), maxRateLimitWait) } func boundedETag(etag string) string { if etag == "" || len(etag) > 200 || strings.ContainsFunc(etag, func(character rune) bool { return character < 0x20 || character > 0x7e }) { return "" } return etag } func cleanTopics(topics []string) []string { cleaned := make([]string, 0, min(len(topics), maxTopics)) for _, topic := range topics { if len(cleaned) == maxTopics { break } if clean := plainLine(topic); clean != "" && utf8.RuneCountInString(clean) <= 50 { cleaned = append(cleaned, clean) } } return cleaned } // plainLine keeps printable text on one line. func plainLine(value string) string { value = strings.Map(func(character rune) rune { if character < 0x20 || character == 0x7f || character == '
' || character == '
' { return ' ' } return character }, value) return strings.Join(strings.Fields(value), " ") } func truncate(value string, limit int) string { if utf8.RuneCountInString(value) <= limit { return value } return strings.TrimSpace(string([]rune(value)[:limit])) } var ( fencedCodePattern = regexp.MustCompile("(?s)```.*?(```|$)|~~~.*?(~~~|$)") htmlCommentPatter = regexp.MustCompile(`(?s)`) htmlTagPattern = regexp.MustCompile(`(?s)<[^>]{0,500}>`) imagePattern = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`) linkPattern = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) referencePattern = regexp.MustCompile(`(?m)^\s*\[[^\]]+\]:\s*\S+.*$`) urlPattern = regexp.MustCompile(`https?://\S+`) headingPattern = regexp.MustCompile(`(?m)^\s{0,3}#{1,6}\s*`) listPattern = regexp.MustCompile(`(?m)^\s*(?:[-*+]|\d+[.)])\s+`) quotePattern = regexp.MustCompile(`(?m)^\s*>\s?`) emphasisPattern = regexp.MustCompile("[*_`~|]+") rulePattern = regexp.MustCompile(`(?m)^\s*[-=*_]{3,}\s*$`) ) // MarkdownToText turns a README into plain text for ranking: code blocks, // HTML, images, link targets, and bare URLs are removed and the markup // characters are dropped. The result is never rendered. func MarkdownToText(markdown string) string { text := strings.ReplaceAll(markdown, "\r\n", "\n") for _, step := range []struct { pattern *regexp.Regexp replacement string }{ {fencedCodePattern, " "}, {htmlCommentPatter, " "}, {imagePattern, " "}, {linkPattern, "$1"}, {referencePattern, " "}, {htmlTagPattern, " "}, {urlPattern, " "}, {rulePattern, " "}, {headingPattern, ""}, {listPattern, ""}, {quotePattern, ""}, {emphasisPattern, " "}, } { text = step.pattern.ReplaceAllString(text, step.replacement) } return plainLine(text) }