Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dca260f582 | |||
| 921599542d | |||
| 71bb33b6fd | |||
| 55366b3431 | |||
| 3cd5ae594e |
@@ -5,6 +5,9 @@ import (
|
|||||||
"gitea.weiker.me/rodin/review-bot/vcs"
|
"gitea.weiker.me/rodin/review-bot/vcs"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Compile-time interface conformance assertion.
|
// Compile-time interface conformance assertions.
|
||||||
// Verifies github.Client satisfies vcs.PRReader.
|
// These verify github.Client satisfies vcs.PRReader and vcs.FileReader.
|
||||||
var _ vcs.PRReader = (*github.Client)(nil)
|
var (
|
||||||
|
_ vcs.PRReader = (*github.Client)(nil)
|
||||||
|
_ vcs.FileReader = (*github.Client)(nil)
|
||||||
|
)
|
||||||
|
|||||||
+108
-16
@@ -6,24 +6,36 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"gitea.weiker.me/rodin/review-bot/vcs"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetFileContent fetches a file from a repo at the given ref.
|
||||||
|
// Delegates to GetFileContentAtRef with the provided ref.
|
||||||
|
func (c *Client) GetFileContent(ctx context.Context, owner, repo, filePath, ref string) (string, error) {
|
||||||
|
return c.GetFileContentAtRef(ctx, owner, repo, filePath, ref)
|
||||||
|
}
|
||||||
|
|
||||||
// GetFileContentAtRef fetches a file at a specific ref from a repo.
|
// GetFileContentAtRef fetches a file at a specific ref from a repo.
|
||||||
// If ref is empty, the query parameter is omitted (uses default branch).
|
// If ref is empty, the query parameter is omitted (uses default branch).
|
||||||
//
|
//
|
||||||
// Note: dot-segments ("." and "..") in the path are silently removed to
|
// Returns an error if the path contains dot-segments (".", "..") or
|
||||||
// prevent path traversal. This means a path like "foo/../bar" resolves
|
// attempts to traverse above the repository root.
|
||||||
// to "foo/bar" rather than "bar".
|
func (c *Client) GetFileContentAtRef(ctx context.Context, owner, repo, filePath, ref string) (string, error) {
|
||||||
func (c *Client) GetFileContentAtRef(ctx context.Context, owner, repo, path, ref string) (string, error) {
|
escaped, err := escapePath(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("invalid file path: %w", err)
|
||||||
|
}
|
||||||
reqURL := fmt.Sprintf("%s/repos/%s/%s/contents/%s",
|
reqURL := fmt.Sprintf("%s/repos/%s/%s/contents/%s",
|
||||||
c.baseURL, url.PathEscape(owner), url.PathEscape(repo), escapePath(path))
|
c.baseURL, url.PathEscape(owner), url.PathEscape(repo), escaped)
|
||||||
if ref != "" {
|
if ref != "" {
|
||||||
reqURL += "?ref=" + url.QueryEscape(ref)
|
reqURL += "?ref=" + url.QueryEscape(ref)
|
||||||
}
|
}
|
||||||
body, err := c.doGet(ctx, reqURL)
|
body, err := c.doGet(ctx, reqURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("fetch file %s: %w", path, err)
|
return "", fmt.Errorf("fetch file %s: %w", filePath, err)
|
||||||
}
|
}
|
||||||
var resp struct {
|
var resp struct {
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
@@ -33,36 +45,116 @@ func (c *Client) GetFileContentAtRef(ctx context.Context, owner, repo, path, ref
|
|||||||
return "", fmt.Errorf("parse file content JSON: %w", err)
|
return "", fmt.Errorf("parse file content JSON: %w", err)
|
||||||
}
|
}
|
||||||
if resp.Encoding != "base64" {
|
if resp.Encoding != "base64" {
|
||||||
return "", fmt.Errorf("unexpected encoding %q for file %s", resp.Encoding, path)
|
return "", fmt.Errorf("unexpected encoding %q for file %s", resp.Encoding, filePath)
|
||||||
}
|
}
|
||||||
decoded, err := decodeBase64Content(resp.Content)
|
decoded, err := decodeBase64Content(resp.Content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("decode base64 content for %s: %w", path, err)
|
return "", fmt.Errorf("decode base64 content for %s: %w", filePath, err)
|
||||||
}
|
}
|
||||||
return decoded, nil
|
return decoded, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// escapePath encodes each segment of a slash-separated path, stripping
|
// ListContents lists files and directories at a given path in a repo.
|
||||||
// dot-segments to prevent path traversal.
|
// Returns the directory listing from the GitHub contents API.
|
||||||
func escapePath(p string) string {
|
// If the path points to a single file (not a directory), the API returns
|
||||||
parts := strings.Split(p, "/")
|
// a JSON object instead of an array; this is handled by returning a
|
||||||
var clean []string
|
// single-element slice.
|
||||||
|
func (c *Client) ListContents(ctx context.Context, owner, repo, filePath string) ([]vcs.ContentEntry, error) {
|
||||||
|
escaped, err := escapePath(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid file path: %w", err)
|
||||||
|
}
|
||||||
|
reqURL := fmt.Sprintf("%s/repos/%s/%s/contents/%s",
|
||||||
|
c.baseURL, url.PathEscape(owner), url.PathEscape(repo), escaped)
|
||||||
|
body, err := c.doGet(ctx, reqURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list contents %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// The GitHub contents API returns an array for directories and an object
|
||||||
|
// for single files. Try array first (common case), then fall back to object.
|
||||||
|
// An empty array ([]) is valid — it represents an empty directory — and
|
||||||
|
// results in a zero-length slice returned without error.
|
||||||
|
var entries []entry
|
||||||
|
if err := json.Unmarshal(body, &entries); err != nil {
|
||||||
|
var single entry
|
||||||
|
if err2 := json.Unmarshal(body, &single); err2 != nil {
|
||||||
|
return nil, fmt.Errorf("parse contents JSON: as array: %v; as object: %w", err, err2)
|
||||||
|
}
|
||||||
|
// Guard against empty objects ({}) or unexpected shapes that
|
||||||
|
// unmarshal successfully but carry no useful data.
|
||||||
|
if single.Name == "" && single.Path == "" && single.Type == "" {
|
||||||
|
return nil, fmt.Errorf("parse contents JSON: unexpected response format")
|
||||||
|
}
|
||||||
|
entries = []entry{single}
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]vcs.ContentEntry, len(entries))
|
||||||
|
for i, e := range entries {
|
||||||
|
result[i] = vcs.ContentEntry{
|
||||||
|
Name: e.Name,
|
||||||
|
Path: e.Path,
|
||||||
|
Type: e.Type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// escapePath validates and encodes a slash-separated file path for use in
|
||||||
|
// GitHub API URLs. Returns an error if the path contains dot-segments ("."
|
||||||
|
// or "..") or resolves to a path outside the repository root.
|
||||||
|
func escapePath(p string) (string, error) {
|
||||||
|
// Reject paths containing dot-segments rather than silently rewriting them.
|
||||||
|
for _, seg := range strings.Split(p, "/") {
|
||||||
|
if seg == "." || seg == ".." {
|
||||||
|
return "", fmt.Errorf("path contains dot-segment %q: %s", seg, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use path.Clean for canonical form, then verify it doesn't escape root.
|
||||||
|
cleaned := path.Clean(p)
|
||||||
|
if cleaned == "." || strings.HasPrefix(cleaned, "..") {
|
||||||
|
return "", fmt.Errorf("path resolves outside repository root: %s", p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode each segment individually.
|
||||||
|
parts := strings.Split(cleaned, "/")
|
||||||
|
var encoded []string
|
||||||
for _, part := range parts {
|
for _, part := range parts {
|
||||||
if part == "." || part == ".." || part == "" {
|
if part == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
clean = append(clean, url.PathEscape(part))
|
encoded = append(encoded, url.PathEscape(part))
|
||||||
}
|
}
|
||||||
return strings.Join(clean, "/")
|
return strings.Join(encoded, "/"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// maxFileContentSize is the maximum decoded file size (10 MB) to prevent
|
||||||
|
// resource exhaustion when decoding base64 content from the API.
|
||||||
|
const maxFileContentSize = 10 * 1024 * 1024
|
||||||
|
|
||||||
// decodeBase64Content decodes base64-encoded content from the GitHub contents API.
|
// decodeBase64Content decodes base64-encoded content from the GitHub contents API.
|
||||||
// GitHub returns base64 content with line breaks for formatting; we strip \r and \n before decoding.
|
// GitHub returns base64 content with line breaks for formatting; we strip \r and \n before decoding.
|
||||||
|
// Returns an error if the decoded content exceeds maxFileContentSize.
|
||||||
func decodeBase64Content(encoded string) (string, error) {
|
func decodeBase64Content(encoded string) (string, error) {
|
||||||
cleaned := strings.NewReplacer("\n", "", "\r", "").Replace(encoded)
|
cleaned := strings.NewReplacer("\n", "", "\r", "").Replace(encoded)
|
||||||
|
// Check estimated decoded size before allocating.
|
||||||
|
// Base64 encodes 3 bytes into 4 chars, so decoded ~ len*3/4.
|
||||||
|
if len(cleaned)*3/4 > maxFileContentSize {
|
||||||
|
return "", fmt.Errorf("file content too large: estimated %d bytes exceeds limit of %d", len(cleaned)*3/4, maxFileContentSize)
|
||||||
|
}
|
||||||
decoded, err := base64.StdEncoding.DecodeString(cleaned)
|
decoded, err := base64.StdEncoding.DecodeString(cleaned)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
if len(decoded) > maxFileContentSize {
|
||||||
|
return "", fmt.Errorf("file content too large: %d bytes exceeds limit of %d", len(decoded), maxFileContentSize)
|
||||||
|
}
|
||||||
return string(decoded), nil
|
return string(decoded), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,405 @@
|
|||||||
|
package github
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetFileContent_DelegatesToGetFileContentAtRef(t *testing.T) {
|
||||||
|
var gotRef string
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotRef = r.URL.Query().Get("ref")
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
|
"content": "dGVzdA==", // "test" in base64
|
||||||
|
"encoding": "base64",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
// Call with empty ref — should not include ref param
|
||||||
|
content, err := c.GetFileContent(context.Background(), "owner", "repo", "file.go", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if content != "test" {
|
||||||
|
t.Errorf("expected 'test', got %q", content)
|
||||||
|
}
|
||||||
|
if gotRef != "" {
|
||||||
|
t.Errorf("expected empty ref, got %q", gotRef)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContent_WithRef(t *testing.T) {
|
||||||
|
var gotRef string
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotRef = r.URL.Query().Get("ref")
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
|
"content": "dGVzdA==",
|
||||||
|
"encoding": "base64",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.GetFileContent(context.Background(), "owner", "repo", "file.go", "abc123")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if gotRef != "abc123" {
|
||||||
|
t.Errorf("expected ref 'abc123', got %q", gotRef)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContent_404(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
w.Write([]byte(`{"message":"Not Found"}`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.GetFileContent(context.Background(), "owner", "repo", "missing.go", "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for 404")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContent_401(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(401)
|
||||||
|
w.Write([]byte(`{"message":"Bad credentials"}`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.GetFileContent(context.Background(), "owner", "repo", "file.go", "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for 401")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContent_429Retry(t *testing.T) {
|
||||||
|
attempts := 0
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
attempts++
|
||||||
|
if attempts == 1 {
|
||||||
|
w.WriteHeader(429)
|
||||||
|
w.Write([]byte(`{"message":"rate limit"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
|
"content": "b2s=",
|
||||||
|
"encoding": "base64",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
if err := c.SetRetryBackoff([]time.Duration{1 * time.Millisecond, 1 * time.Millisecond}); err != nil {
|
||||||
|
t.Fatalf("SetRetryBackoff: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
content, err := c.GetFileContent(context.Background(), "owner", "repo", "file.go", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if content != "ok" {
|
||||||
|
t.Errorf("expected 'ok', got %q", content)
|
||||||
|
}
|
||||||
|
if attempts != 2 {
|
||||||
|
t.Errorf("expected 2 attempts, got %d", attempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContent_MalformedJSON(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(200)
|
||||||
|
w.Write([]byte(`not json`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.GetFileContent(context.Background(), "owner", "repo", "file.go", "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for malformed JSON")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_HappyPath(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/repos/owner/repo/contents/src" {
|
||||||
|
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode([]map[string]string{
|
||||||
|
{"name": "main.go", "path": "src/main.go", "type": "file"},
|
||||||
|
{"name": "lib", "path": "src/lib", "type": "dir"},
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
entries, err := c.ListContents(context.Background(), "owner", "repo", "src")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 2 {
|
||||||
|
t.Fatalf("expected 2 entries, got %d", len(entries))
|
||||||
|
}
|
||||||
|
if entries[0].Name != "main.go" {
|
||||||
|
t.Errorf("expected name 'main.go', got %q", entries[0].Name)
|
||||||
|
}
|
||||||
|
if entries[0].Path != "src/main.go" {
|
||||||
|
t.Errorf("expected path 'src/main.go', got %q", entries[0].Path)
|
||||||
|
}
|
||||||
|
if entries[0].Type != "file" {
|
||||||
|
t.Errorf("expected type 'file', got %q", entries[0].Type)
|
||||||
|
}
|
||||||
|
if entries[1].Name != "lib" {
|
||||||
|
t.Errorf("expected name 'lib', got %q", entries[1].Name)
|
||||||
|
}
|
||||||
|
if entries[1].Type != "dir" {
|
||||||
|
t.Errorf("expected type 'dir', got %q", entries[1].Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_404(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
w.Write([]byte(`{"message":"Not Found"}`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.ListContents(context.Background(), "owner", "repo", "missing")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for 404")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_401(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(401)
|
||||||
|
w.Write([]byte(`{"message":"Bad credentials"}`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.ListContents(context.Background(), "owner", "repo", "src")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for 401")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_429Retry(t *testing.T) {
|
||||||
|
attempts := 0
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
attempts++
|
||||||
|
if attempts == 1 {
|
||||||
|
w.WriteHeader(429)
|
||||||
|
w.Write([]byte(`{"message":"rate limit"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode([]map[string]string{
|
||||||
|
{"name": "file.go", "path": "file.go", "type": "file"},
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
if err := c.SetRetryBackoff([]time.Duration{1 * time.Millisecond, 1 * time.Millisecond}); err != nil {
|
||||||
|
t.Fatalf("SetRetryBackoff: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entries, err := c.ListContents(context.Background(), "owner", "repo", "src")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 1 {
|
||||||
|
t.Fatalf("expected 1 entry, got %d", len(entries))
|
||||||
|
}
|
||||||
|
if attempts != 2 {
|
||||||
|
t.Errorf("expected 2 attempts, got %d", attempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_MalformedJSON(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(200)
|
||||||
|
w.Write([]byte(`not json`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
|
||||||
|
_, err := c.ListContents(context.Background(), "owner", "repo", "src")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for malformed JSON")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListContents_SingleFile(t *testing.T) {
|
||||||
|
// GitHub Contents API returns a JSON object (not array) for single-file paths
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(200)
|
||||||
|
w.Write([]byte(`{"name":"README.md","path":"README.md","type":"file"}`))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
c.SetHTTPClient(srv.Client())
|
||||||
|
entries, err := c.ListContents(context.Background(), "owner", "repo", "README.md")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 1 {
|
||||||
|
t.Fatalf("expected 1 entry, got %d", len(entries))
|
||||||
|
}
|
||||||
|
if entries[0].Name != "README.md" {
|
||||||
|
t.Errorf("expected name 'README.md', got %q", entries[0].Name)
|
||||||
|
}
|
||||||
|
if entries[0].Type != "file" {
|
||||||
|
t.Errorf("expected type 'file', got %q", entries[0].Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEscapePath_ValidPaths(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"simple file", "file.go", "file.go"},
|
||||||
|
{"nested path", "path/to/file.go", "path/to/file.go"},
|
||||||
|
{"special chars", "path/to/my file.go", "path/to/my%20file.go"},
|
||||||
|
{"leading slash stripped", "/path/to/file.go", "path/to/file.go"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
got, err := escapePath(tt.path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("escapePath(%q) = %q, want %q", tt.path, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEscapePath_DotSegments(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
}{
|
||||||
|
{"single dot", "./file.go"},
|
||||||
|
{"double dot", "../file.go"},
|
||||||
|
{"dot in middle", "path/./file.go"},
|
||||||
|
{"parent traversal", "path/../file.go"},
|
||||||
|
{"only dots", ".."},
|
||||||
|
{"nested parent traversal", "a/b/../../c"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
_, err := escapePath(tt.path)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected error for path %q, got nil", tt.path)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "dot-segment") {
|
||||||
|
t.Errorf("expected error about dot-segment, got: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFileContentAtRef_DotSegmentError(t *testing.T) {
|
||||||
|
// Server should never be called — the error is caught before the request.
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Fatal("server should not have been called")
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := NewClient("token", srv.URL, AllowInsecureHTTP())
|
||||||
|
_, err := c.GetFileContentAtRef(context.Background(), "owner", "repo", "foo/../bar.go", "main")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for path with dot-segments")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "invalid file path") {
|
||||||
|
t.Errorf("expected 'invalid file path' error, got: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeBase64Content(t *testing.T) {
|
||||||
|
// Test with newlines (GitHub's format)
|
||||||
|
encoded := "cGFja2FnZSBt\nYWlu"
|
||||||
|
decoded, err := decodeBase64Content(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if decoded != "package main" {
|
||||||
|
t.Errorf("expected 'package main', got %q", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeBase64Content_Invalid(t *testing.T) {
|
||||||
|
_, err := decodeBase64Content("not!!!valid!!!base64")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for invalid base64")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeBase64Content_CRLF(t *testing.T) {
|
||||||
|
// Base64 of "hello world" with CRLF line breaks inserted
|
||||||
|
encoded := "aGVs\r\nbG8g\r\nd29y\r\nbGQ="
|
||||||
|
decoded, err := decodeBase64Content(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if decoded != "hello world" {
|
||||||
|
t.Errorf("expected 'hello world', got %q", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeBase64Content_SizeLimit(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
// Create base64 content that would decode to > maxFileContentSize.
|
||||||
|
// maxFileContentSize is 10MB. Base64 of 11MB worth of zeros.
|
||||||
|
// We just need something big enough to trigger the estimated size check.
|
||||||
|
// 14MB of base64 chars (decodes to ~10.5MB).
|
||||||
|
huge := strings.Repeat("A", 14*1024*1024)
|
||||||
|
_, err := decodeBase64Content(huge)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for oversized content")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "too large") {
|
||||||
|
t.Errorf("expected 'too large' error, got: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-10
@@ -178,7 +178,7 @@ func (c *Client) GetCommitStatuses(ctx context.Context, owner, repo, sha string)
|
|||||||
result = append(result, vcs.CommitStatus{
|
result = append(result, vcs.CommitStatus{
|
||||||
Context: cr.Name,
|
Context: cr.Name,
|
||||||
Status: mapCheckRunStatus(cr.Conclusion),
|
Status: mapCheckRunStatus(cr.Conclusion),
|
||||||
Description: derefString(cr.Conclusion), // raw conclusion value (e.g. "success", "failure", "skipped")
|
Description: "", // check runs have no human-readable description; conclusion is captured in Status
|
||||||
TargetURL: cr.HTMLURL,
|
TargetURL: cr.HTMLURL,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -199,7 +199,7 @@ func (c *Client) GetCommitStatuses(ctx context.Context, owner, repo, sha string)
|
|||||||
// - "success" → "success"
|
// - "success" → "success"
|
||||||
// - "failure", "action_required", "timed_out" → "failure"
|
// - "failure", "action_required", "timed_out" → "failure"
|
||||||
// - "cancelled", "skipped", "neutral" → "success" (non-blocking per GitHub check suite semantics)
|
// - "cancelled", "skipped", "neutral" → "success" (non-blocking per GitHub check suite semantics)
|
||||||
// - "stale", "waiting" → "pending"
|
// - "stale" → "pending" (check run became stale before completing)
|
||||||
// - unknown values → "pending" (conservative: treat unrecognized conclusions as incomplete)
|
// - unknown values → "pending" (conservative: treat unrecognized conclusions as incomplete)
|
||||||
func mapCheckRunStatus(conclusion *string) string {
|
func mapCheckRunStatus(conclusion *string) string {
|
||||||
if conclusion == nil {
|
if conclusion == nil {
|
||||||
@@ -213,17 +213,10 @@ func mapCheckRunStatus(conclusion *string) string {
|
|||||||
return "failure"
|
return "failure"
|
||||||
case "cancelled", "skipped", "neutral":
|
case "cancelled", "skipped", "neutral":
|
||||||
return "success" // non-blocking: these do not indicate a blocking failure per GitHub check suite semantics
|
return "success" // non-blocking: these do not indicate a blocking failure per GitHub check suite semantics
|
||||||
case "stale", "waiting":
|
case "stale":
|
||||||
return "pending"
|
return "pending"
|
||||||
default:
|
default:
|
||||||
return "pending"
|
return "pending"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// derefString safely dereferences a string pointer, returning empty string if nil.
|
|
||||||
func derefString(s *string) string {
|
|
||||||
if s == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return *s
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user