chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,382 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxJSONResponseBytes bounds project, user, commit and paginated tree JSON.
|
||||
// Those listings are small; a larger body means a broken or hostile server.
|
||||
maxJSONResponseBytes int64 = 16 << 20
|
||||
// maxCompareResponseBytes bounds GET /repository/compare. That body carries
|
||||
// the full commit list and patch text. A straight compare across a long
|
||||
// unsynced range or a force-push routinely exceeds the metadata cap, and
|
||||
// failing it aborts the project sync before the cursor advances. Sync only
|
||||
// keeps paths and compare_timeout, but the response still has to be buffered.
|
||||
maxCompareResponseBytes int64 = 128 << 20
|
||||
// maxRawFileBytes bounds a single repository blob. GitLab's tree and
|
||||
// compare endpoints do not report blob sizes, so the download itself is the
|
||||
// only place a limit can be enforced. 512 MiB matches the Feishu connector,
|
||||
// the other connector that pulls arbitrary binary files.
|
||||
maxRawFileBytes int64 = 512 << 20
|
||||
)
|
||||
|
||||
// base64FileBytes is the JSON cap for the file-detail fallback, whose body
|
||||
// carries the raw blob base64-encoded (4/3 of its size) plus an envelope.
|
||||
func base64FileBytes(rawLimit int64) int64 {
|
||||
return rawLimit/3*4 + (1 << 20)
|
||||
}
|
||||
|
||||
// maxPaginationHops bounds a single paginated walk. GitLab reports the next
|
||||
// page through the X-Next-Page header, so a broken instance or reverse proxy
|
||||
// could keep advertising pages indefinitely.
|
||||
const maxPaginationHops = 10000
|
||||
|
||||
type client struct {
|
||||
baseURL, token string
|
||||
http *http.Client
|
||||
// jsonLimit, compareLimit and rawLimit are fields rather than direct uses of
|
||||
// the constants above so tests can lower them without materialising hundreds
|
||||
// of megabytes. newClient always sets the production values.
|
||||
jsonLimit int64
|
||||
compareLimit int64
|
||||
rawLimit int64
|
||||
}
|
||||
|
||||
// readCapped reads a response body, refusing anything larger than limit instead
|
||||
// of buffering it. Oversized payloads are reported as an error: a truncated
|
||||
// body would be indexed as if it were the whole document.
|
||||
func readCapped(body io.Reader, limit int64) ([]byte, error) {
|
||||
data, err := io.ReadAll(io.LimitReader(body, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("response exceeds maximum size (%d bytes)", limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
endpoint string
|
||||
status int
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string {
|
||||
return fmt.Sprintf("gitlab API %s: status %d", e.endpoint, e.status)
|
||||
}
|
||||
|
||||
type project struct {
|
||||
ID int64 `json:"id"`
|
||||
PathWithNamespace string `json:"path_with_namespace"`
|
||||
Name string `json:"name"`
|
||||
WebURL string `json:"web_url"`
|
||||
DefaultBranch string `json:"default_branch"`
|
||||
Namespace struct {
|
||||
ID int64 `json:"id"`
|
||||
} `json:"namespace"`
|
||||
}
|
||||
type treeEntry struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type comparison struct {
|
||||
Diffs []struct {
|
||||
OldPath string `json:"old_path"`
|
||||
NewPath string `json:"new_path"`
|
||||
NewFile bool `json:"new_file"`
|
||||
DeletedFile bool `json:"deleted_file"`
|
||||
RenamedFile bool `json:"renamed_file"`
|
||||
} `json:"diffs"`
|
||||
CompareTimeout bool `json:"compare_timeout"`
|
||||
CompareSameRef bool `json:"compare_same_ref"`
|
||||
}
|
||||
|
||||
func newClient(baseURL, token string) (*client, error) {
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if baseURL == "" || strings.TrimSpace(token) == "" {
|
||||
return nil, fmt.Errorf("GitLab platform configuration is missing")
|
||||
}
|
||||
if err := datasource.ValidateConnectorBaseURL(baseURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !strings.Contains(baseURL, "://") {
|
||||
baseURL = "https://" + baseURL
|
||||
}
|
||||
if !strings.HasSuffix(baseURL, "/api/v4") {
|
||||
baseURL += "/api/v4"
|
||||
}
|
||||
return &client{
|
||||
baseURL: baseURL,
|
||||
token: token,
|
||||
http: datasource.NewConnectorHTTPClient(30 * time.Second),
|
||||
jsonLimit: maxJSONResponseBytes,
|
||||
compareLimit: maxCompareResponseBytes,
|
||||
rawLimit: maxRawFileBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *client) get(ctx context.Context, endpoint string, out interface{}) error {
|
||||
return c.getCapped(ctx, endpoint, out, c.jsonLimit)
|
||||
}
|
||||
|
||||
// getCapped is get with an explicit response cap. Compare and the base64 file
|
||||
// fallback pass their own limits because those bodies are larger than metadata.
|
||||
func (c *client) getCapped(ctx context.Context, endpoint string, out interface{}, limit int64) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("PRIVATE-TOKEN", c.token)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return &apiError{endpoint: endpoint, status: resp.StatusCode}
|
||||
}
|
||||
body, err := readCapped(resp.Body, limit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gitlab API %s: %w", endpoint, err)
|
||||
}
|
||||
return json.Unmarshal(body, out)
|
||||
}
|
||||
|
||||
func (c *client) getRaw(ctx context.Context, endpoint string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("PRIVATE-TOKEN", c.token)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, &apiError{endpoint: endpoint, status: resp.StatusCode}
|
||||
}
|
||||
body, err := readCapped(resp.Body, c.rawLimit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gitlab raw file %s: %w", endpoint, err)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// projectPath encodes a GitLab project identifier for URL path segments.
|
||||
// Numeric IDs are used verbatim. Namespace paths accept either "group/project"
|
||||
// or a once-encoded "group%2Fproject" without double-encoding percent signs.
|
||||
func projectPath(id string) string {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return ""
|
||||
}
|
||||
if _, err := strconv.ParseInt(id, 10, 64); err == nil {
|
||||
return id
|
||||
}
|
||||
decoded := id
|
||||
if strings.Contains(id, "%") {
|
||||
if unescaped, err := url.PathUnescape(id); err == nil {
|
||||
decoded = unescaped
|
||||
}
|
||||
}
|
||||
if strings.Contains(decoded, "/") {
|
||||
parts := strings.Split(decoded, "/")
|
||||
for i, part := range parts {
|
||||
parts[i] = url.PathEscape(part)
|
||||
}
|
||||
return strings.Join(parts, "%2F")
|
||||
}
|
||||
return url.PathEscape(decoded)
|
||||
}
|
||||
|
||||
func (c *client) project(ctx context.Context, id string) (*project, error) {
|
||||
var p project
|
||||
err := c.get(ctx, "/projects/"+projectPath(id), &p)
|
||||
return &p, err
|
||||
}
|
||||
|
||||
// trackPage records the page a paginated walk is about to request. A page that
|
||||
// was already requested means X-Next-Page is not advancing, so the walk stops
|
||||
// with an error instead of re-reading the same page; the hop cap bounds a
|
||||
// server that keeps advertising fresh page numbers.
|
||||
func trackPage(ctx context.Context, scope string, seen map[string]struct{}, page string) error {
|
||||
if _, dup := seen[page]; dup {
|
||||
return fmt.Errorf("gitlab %s pagination repeated page %q", scope, page)
|
||||
}
|
||||
if len(seen) >= maxPaginationHops {
|
||||
logger.Warnf(ctx, "[GitLab] %s pagination exceeded %d pages; aborting", scope, maxPaginationHops)
|
||||
return fmt.Errorf("gitlab %s pagination exceeded %d pages", scope, maxPaginationHops)
|
||||
}
|
||||
seen[page] = struct{}{}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) projects(ctx context.Context) ([]project, error) {
|
||||
q := url.Values{
|
||||
"membership": {"true"}, "per_page": {"100"}, "page": {"1"},
|
||||
"order_by": {"path_with_namespace"}, "sort": {"asc"},
|
||||
}
|
||||
var all []project
|
||||
seen := make(map[string]struct{})
|
||||
for {
|
||||
if err := trackPage(ctx, "project", seen, q.Get("page")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var page []project
|
||||
nextPage, err := c.getPage(ctx, "/projects", q, &page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, page...)
|
||||
if nextPage == "" {
|
||||
return all, nil
|
||||
}
|
||||
q.Set("page", nextPage)
|
||||
}
|
||||
}
|
||||
|
||||
// ping verifies that the supplied private token is accepted by this GitLab
|
||||
// instance. It avoids project-list ordering parameters that older GitLab
|
||||
// deployments may reject even when the token is valid.
|
||||
func (c *client) ping(ctx context.Context) error {
|
||||
var user struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
return c.get(ctx, "/user", &user)
|
||||
}
|
||||
|
||||
func (c *client) commitSHA(ctx context.Context, id, ref string) (string, error) {
|
||||
var v struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
err := c.get(ctx, "/projects/"+projectPath(id)+"/repository/commits/"+url.PathEscape(ref), &v)
|
||||
return v.ID, err
|
||||
}
|
||||
|
||||
func (c *client) tree(ctx context.Context, id, ref, dir string) ([]treeEntry, error) {
|
||||
q := url.Values{"ref": {ref}, "per_page": {"100"}, "page": {"1"}}
|
||||
if dir != "" {
|
||||
q.Set("path", dir)
|
||||
}
|
||||
endpoint := "/projects/" + projectPath(id) + "/repository/tree"
|
||||
var all []treeEntry
|
||||
seen := make(map[string]struct{})
|
||||
for {
|
||||
if err := trackPage(ctx, "tree", seen, q.Get("page")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var page []treeEntry
|
||||
nextPage, err := c.getPage(ctx, endpoint, q, &page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, page...)
|
||||
if nextPage == "" {
|
||||
return all, nil
|
||||
}
|
||||
q.Set("page", nextPage)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client) getPage(ctx context.Context, endpoint string, query url.Values, out interface{}) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint+"?"+query.Encode(), nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("PRIVATE-TOKEN", c.token)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", &apiError{endpoint: endpoint, status: resp.StatusCode}
|
||||
}
|
||||
body, err := readCapped(resp.Body, c.jsonLimit)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("gitlab API %s: %w", endpoint, err)
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resp.Header.Get("X-Next-Page"), nil
|
||||
}
|
||||
|
||||
func (c *client) raw(ctx context.Context, id, ref, file string) ([]byte, error) {
|
||||
q := url.Values{"ref": {ref}}
|
||||
encodedFile := gitlabFilePathEscape(file)
|
||||
rawEndpoint := "/projects/" + projectPath(id) + "/repository/files/" + encodedFile + "/raw?" + q.Encode()
|
||||
content, err := c.getRaw(ctx, rawEndpoint)
|
||||
if err == nil {
|
||||
return content, nil
|
||||
}
|
||||
var apiErr *apiError
|
||||
if !errors.As(err, &apiErr) || apiErr.status != http.StatusNotFound {
|
||||
return nil, fmt.Errorf("gitlab file %s: %w", file, err)
|
||||
}
|
||||
|
||||
// Some GitLab deployments expose the file detail endpoint but return 404
|
||||
// for the otherwise standard /raw route. The detail response contains the
|
||||
// same content as base64 and provides a compatible fallback.
|
||||
var detail struct {
|
||||
Encoding string `json:"encoding"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
detailEndpoint := "/projects/" + projectPath(id) + "/repository/files/" + encodedFile + "?" + q.Encode()
|
||||
if err := c.getCapped(ctx, detailEndpoint, &detail, base64FileBytes(c.rawLimit)); err != nil {
|
||||
return nil, fmt.Errorf("gitlab file %s: %w", file, err)
|
||||
}
|
||||
if detail.Encoding != "base64" {
|
||||
return nil, fmt.Errorf("gitlab file %s: unsupported encoding %q", file, detail.Encoding)
|
||||
}
|
||||
content, err = base64.StdEncoding.DecodeString(detail.Content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gitlab file %s: decode base64: %w", file, err)
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// gitlabFilePathEscape mirrors the company GitLab raw-file route: only ASCII
|
||||
// letters, digits, hyphen and underscore remain literal. In particular dots,
|
||||
// path separators and UTF-8 bytes must be percent-encoded.
|
||||
func gitlabFilePathEscape(file string) string {
|
||||
const hex = "0123456789ABCDEF"
|
||||
var b strings.Builder
|
||||
b.Grow(len(file) * 3)
|
||||
for _, c := range []byte(file) {
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
|
||||
b.WriteByte(c)
|
||||
continue
|
||||
}
|
||||
b.WriteByte('%')
|
||||
b.WriteByte(hex[c>>4])
|
||||
b.WriteByte(hex[c&0x0f])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (c *client) compare(ctx context.Context, id, from, to string) (*comparison, error) {
|
||||
// Sync compares snapshots, not changes since their merge base. The default
|
||||
// comparison misses reverted files when a branch is reset or force-pushed.
|
||||
q := url.Values{"from": {from}, "to": {to}, "straight": {"true"}}
|
||||
var v comparison
|
||||
err := c.getCapped(ctx, "/projects/"+projectPath(id)+"/repository/compare?"+q.Encode(), &v, c.compareLimit)
|
||||
return &v, err
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
func allowLocalGitLabServer(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
}
|
||||
|
||||
func TestConnectorValidateUsesDataSourceCredentials(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v4/user" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if got := r.Header.Get("PRIVATE-TOKEN"); got != "per-source-token" {
|
||||
t.Fatalf("PRIVATE-TOKEN = %q", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id": 42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ds := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"base_url": server.URL,
|
||||
"access_token": "per-source-token",
|
||||
},
|
||||
}
|
||||
|
||||
if err := NewConnector().Validate(context.Background(), ds); err != nil {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidateReturnsGitLabAPIError(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v4/user" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "invalid token", http.StatusUnauthorized)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"base_url": server.URL,
|
||||
"access_token": "invalid-token",
|
||||
},
|
||||
})
|
||||
var apiErr *apiError
|
||||
if !errors.As(err, &apiErr) {
|
||||
t.Fatalf("Validate() error = %v, want GitLab API error", err)
|
||||
}
|
||||
if apiErr.endpoint != "/user" || apiErr.status != http.StatusUnauthorized {
|
||||
t.Fatalf("apiError = %#v", apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidateRejectsMissingCredentials(t *testing.T) {
|
||||
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": "https://gitlab.example.com"},
|
||||
})
|
||||
if err == nil || err.Error() != "GitLab platform configuration is missing" {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidateRejectsMissingProjectsOnSave(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v4/user" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id": 42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"base_url": server.URL,
|
||||
"access_token": "token",
|
||||
},
|
||||
Settings: map[string]interface{}{
|
||||
"projects": []interface{}{},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected missing projects validation error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorConfiguredDoesNotReuseRegistryClient(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
var requestedTokens []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v4/user" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
requestedTokens = append(requestedTokens, r.Header.Get("PRIVATE-TOKEN"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id": 42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
connector := NewConnector()
|
||||
first := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-a"},
|
||||
}
|
||||
second := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-b"},
|
||||
}
|
||||
if err := connector.Validate(context.Background(), first); err != nil {
|
||||
t.Fatalf("first validate: %v", err)
|
||||
}
|
||||
if err := connector.Validate(context.Background(), second); err != nil {
|
||||
t.Fatalf("second validate: %v", err)
|
||||
}
|
||||
if len(requestedTokens) != 2 || requestedTokens[0] != "token-a" || requestedTokens[1] != "token-b" {
|
||||
t.Fatalf("requested tokens = %#v", requestedTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientNormalizesAPIBaseURL(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
|
||||
c, err := newClient(server.URL+"/", "token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := c.baseURL, server.URL+"/api/v4"; got != want {
|
||||
t.Fatalf("baseURL = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchIncrementalSyncsMultipleProjects(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{"id":1,"name":"project-one","path_with_namespace":"group/project-one","web_url":"https://gitlab.test/group/project-one","default_branch":"master"}`))
|
||||
case "/api/v4/projects/2":
|
||||
_, _ = w.Write([]byte(`{"id":2,"name":"project-two","path_with_namespace":"group/project-two","web_url":"https://gitlab.test/group/project-two","default_branch":"master"}`))
|
||||
case "/api/v4/projects/1/repository/commits/master":
|
||||
_, _ = w.Write([]byte(`{"id":"commit-1"}`))
|
||||
case "/api/v4/projects/2/repository/commits/master":
|
||||
_, _ = w.Write([]byte(`{"id":"commit-2"}`))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
|
||||
case "/api/v4/projects/2/repository/tree":
|
||||
_, _ = w.Write([]byte(`[{"name":"two.md","type":"blob","path":"two.md"}]`))
|
||||
default:
|
||||
if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/1/repository/files/one%2Emd/raw") {
|
||||
_, _ = w.Write([]byte("one"))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/2/repository/files/two%2Emd/raw") {
|
||||
_, _ = w.Write([]byte("two"))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
connector := NewConnector()
|
||||
config := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"base_url": server.URL,
|
||||
"access_token": "token",
|
||||
},
|
||||
Settings: map[string]interface{}{
|
||||
"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "ref": "master", "paths": []interface{}{}},
|
||||
map[string]interface{}{"project_id": "2", "ref": "master", "paths": []interface{}{}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
items, cursor, err := connector.FetchIncremental(context.Background(), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("first sync items = %d, want 2", len(items))
|
||||
}
|
||||
if cursor == nil || fmt.Sprint(cursor.ConnectorCursor["projects"]) == "" {
|
||||
t.Fatal("first sync did not return per-project cursor state")
|
||||
}
|
||||
|
||||
items, _, err = connector.FetchIncremental(context.Background(), config, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
if len(items) != 0 {
|
||||
t.Fatalf("second sync items = %d, want 0", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
type gitLabStreamRecorder struct {
|
||||
items []types.FetchedItem
|
||||
checkpoints []*types.SyncCursor
|
||||
}
|
||||
|
||||
func (h *gitLabStreamRecorder) Emit(_ context.Context, item types.FetchedItem) error {
|
||||
h.items = append(h.items, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *gitLabStreamRecorder) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
|
||||
h.checkpoints = append(h.checkpoints, cursor)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestFetchStreamFiltersUnsupportedFilesAndCheckpointsProjects(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
|
||||
var rawRequests []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{"id":1,"name":"docs","path_with_namespace":"group/docs","web_url":"https://gitlab.test/group/docs","default_branch":"main"}`))
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = w.Write([]byte(`{"id":"commit-1"}`))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
_, _ = w.Write([]byte(`[
|
||||
{"name":"README.md","type":"blob","path":"README.md"},
|
||||
{"name":"server.go","type":"blob","path":"server.go"},
|
||||
{"name":"payload.exe","type":"blob","path":"payload.exe"}
|
||||
]`))
|
||||
default:
|
||||
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
|
||||
rawRequests = append(rawRequests, r.URL.EscapedPath())
|
||||
_, _ = w.Write([]byte("# readme"))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
connector := NewConnector()
|
||||
config := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"base_url": server.URL,
|
||||
"access_token": "token",
|
||||
},
|
||||
Settings: map[string]interface{}{
|
||||
"projects": []interface{}{map[string]interface{}{"project_id": "1", "paths": []interface{}{}}},
|
||||
},
|
||||
}
|
||||
handler := &gitLabStreamRecorder{}
|
||||
next, err := connector.FetchStream(context.Background(), config, nil, handler)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchStream() error = %v", err)
|
||||
}
|
||||
if len(handler.items) != 1 || handler.items[0].FileName != "docs-main/README.md" {
|
||||
t.Fatalf("emitted items = %#v", handler.items)
|
||||
}
|
||||
if len(rawRequests) != 1 || !strings.Contains(rawRequests[0], "README%2Emd") {
|
||||
t.Fatalf("raw requests = %v, want only README.md", rawRequests)
|
||||
}
|
||||
if len(handler.checkpoints) != 1 || next == nil {
|
||||
t.Fatalf("checkpoints = %d, next = %#v", len(handler.checkpoints), next)
|
||||
}
|
||||
projects, _ := next.ConnectorCursor["projects"].(map[string]string)
|
||||
if projects["1"] != "commit-1" {
|
||||
t.Fatalf("cursor projects = %#v", next.ConnectorCursor["projects"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsSupportedFile(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
file string
|
||||
want bool
|
||||
}{
|
||||
{file: "docs/guide.MD", want: true},
|
||||
{file: "docs/guide.mdx", want: true},
|
||||
{file: "report.pdf", want: true},
|
||||
{file: "src/main.go", want: false},
|
||||
{file: "archive.tar.gz", want: false},
|
||||
{file: "LICENSE", want: false},
|
||||
} {
|
||||
if got := isSupportedFile(tc.file); got != tc.want {
|
||||
t.Errorf("isSupportedFile(%q) = %v, want %v", tc.file, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTreeFollowsGitLabPagination(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
var requestedPages []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v4/projects/1/repository/tree" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
requestedPages = append(requestedPages, r.URL.Query().Get("page"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Query().Get("page") {
|
||||
case "1":
|
||||
w.Header().Set("X-Next-Page", "2")
|
||||
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
|
||||
case "2":
|
||||
_, _ = w.Write([]byte(`[{"name":"two.md","type":"blob","path":"two.md"}]`))
|
||||
default:
|
||||
http.Error(w, "unexpected page", http.StatusBadRequest)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c, err := newClient(server.URL, "token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := c.tree(context.Background(), "1", "main", "")
|
||||
if err != nil {
|
||||
t.Fatalf("tree() error = %v", err)
|
||||
}
|
||||
if len(entries) != 2 || entries[1].Path != "two.md" {
|
||||
t.Fatalf("entries = %#v", entries)
|
||||
}
|
||||
if got, want := strings.Join(requestedPages, ","), "1,2"; got != want {
|
||||
t.Fatalf("requested pages = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectPathEncodesNamespaceWithoutDoubleEscaping(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
in, want string
|
||||
}{
|
||||
{in: "12345", want: "12345"},
|
||||
{in: "group/project", want: "group%2Fproject"},
|
||||
{in: "group%2Fproject", want: "group%2Fproject"},
|
||||
{in: "my group/my project", want: "my%20group%2Fmy%20project"},
|
||||
} {
|
||||
if got := projectPath(tc.in); got != tc.want {
|
||||
t.Errorf("projectPath(%q) = %q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawFallsBackToBase64FileDetail(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.EscapedPath() {
|
||||
case "/api/v4/projects/18724/repository/files/docs%2Finternal%2Freadme%2Emd/raw":
|
||||
http.NotFound(w, r)
|
||||
case "/api/v4/projects/18724/repository/files/docs%2Finternal%2Freadme%2Emd":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"encoding":"base64","content":"SGVsbG8sIEdpdExhYiE="}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c, err := newClient(server.URL, "token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content, err := c.raw(context.Background(), "18724", "master", "docs/internal/readme.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(content) != "Hello, GitLab!" {
|
||||
t.Fatalf("content = %q", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitlabFilePathEscape(t *testing.T) {
|
||||
got := gitlabFilePathEscape("docs/internal/中文-file.md")
|
||||
want := "docs%2Finternal%2F%E4%B8%AD%E6%96%87-file%2Emd"
|
||||
if got != want {
|
||||
t.Fatalf("gitlabFilePathEscape() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// newCappedTestClient builds a client whose JSON and raw-file caps are small
|
||||
// enough to exercise them without materialising the production limits.
|
||||
// compareLimit stays at the production value unless the test assigns it.
|
||||
func newCappedTestClient(t *testing.T, serverURL string, jsonLimit, rawLimit int64) *client {
|
||||
t.Helper()
|
||||
c, err := newClient(serverURL, "token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.jsonLimit = jsonLimit
|
||||
c.rawLimit = rawLimit
|
||||
return c
|
||||
}
|
||||
|
||||
func TestGetRawRejectsBlobLargerThanCap(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const rawLimit = 1 << 20
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
|
||||
content, err := c.getRaw(context.Background(), "/projects/1/repository/files/big.bin/raw")
|
||||
if err == nil {
|
||||
t.Fatalf("getRaw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
|
||||
}
|
||||
if content != nil {
|
||||
t.Fatalf("getRaw() returned %d bytes alongside the error, want no partial body", len(content))
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), fmt.Sprint(rawLimit)) {
|
||||
t.Fatalf("error = %v, want it to name the %d-byte limit", err, rawLimit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRawAcceptsBlobAtCap(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const rawLimit = 1 << 20
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
|
||||
content, err := c.getRaw(context.Background(), "/projects/1/repository/files/fit.bin/raw")
|
||||
if err != nil {
|
||||
t.Fatalf("getRaw() rejected a blob exactly at the cap: %v", err)
|
||||
}
|
||||
if len(content) != rawLimit {
|
||||
t.Fatalf("content = %d bytes, want the full %d", len(content), rawLimit)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRawSurfacesOversizedBlobInsteadOfFallingBack checks that hitting the size
|
||||
// cap fails the fetch rather than being mistaken for a missing /raw route and
|
||||
// retried through the base64 detail endpoint.
|
||||
func TestRawSurfacesOversizedBlobInsteadOfFallingBack(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const rawLimit = 1 << 20
|
||||
detailHits := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
|
||||
return
|
||||
}
|
||||
detailHits++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"encoding":"base64","content":"SGk="}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
|
||||
const file = "docs/guide.mp3"
|
||||
content, err := c.raw(context.Background(), "1", "main", file)
|
||||
if err == nil {
|
||||
t.Fatalf("raw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), file) {
|
||||
t.Fatalf("error = %v, want the repository path %s", err, file)
|
||||
}
|
||||
if detailHits != 0 {
|
||||
t.Fatalf("base64 detail endpoint hit %d times, want 0", detailHits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBase64FallbackRejectsOversizedDetail(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const rawLimit = 3 << 20
|
||||
limit := base64FileBytes(rawLimit)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), int(limit)+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
|
||||
const file = "docs/guide.mp3"
|
||||
if _, err := c.raw(context.Background(), "1", "main", file); err == nil {
|
||||
t.Fatal("raw() accepted an oversized base64 detail response")
|
||||
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
} else if !strings.Contains(err.Error(), file) {
|
||||
t.Fatalf("error = %v, want the repository path %s", err, file)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRejectsOversizedJSONResponse(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const jsonLimit = 512 << 10
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
|
||||
var out struct{}
|
||||
err := c.get(context.Background(), "/projects/1", &out)
|
||||
if err == nil {
|
||||
t.Fatal("get() accepted an oversized JSON response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPageRejectsOversizedJSONResponse(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const jsonLimit = 512 << 10
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
|
||||
if _, err := c.tree(context.Background(), "1", "main", ""); err == nil {
|
||||
t.Fatal("tree() accepted an oversized JSON response")
|
||||
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOversizedErrorBodyKeepsStatusError pins that an oversized body on a
|
||||
// non-2xx response is still reported as the HTTP status, so a large error page
|
||||
// cannot mask the real failure.
|
||||
func TestOversizedErrorBodyKeepsStatusError(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const jsonLimit = 512 << 10
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
for name, call := range map[string]func(*client) error{
|
||||
"get": func(c *client) error {
|
||||
var out struct{}
|
||||
return c.get(context.Background(), "/projects/1", &out)
|
||||
},
|
||||
"getPage": func(c *client) error {
|
||||
_, err := c.tree(context.Background(), "1", "main", "")
|
||||
return err
|
||||
},
|
||||
} {
|
||||
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
|
||||
err := call(c)
|
||||
var apiErr *apiError
|
||||
if !errors.As(err, &apiErr) {
|
||||
t.Fatalf("%s: error = %v, want an *apiError", name, err)
|
||||
}
|
||||
if apiErr.status != http.StatusInternalServerError {
|
||||
t.Fatalf("%s: status = %d, want %d", name, apiErr.status, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientSetsResponseCaps(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer server.Close()
|
||||
|
||||
c, err := newClient(server.URL, "token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.jsonLimit != maxJSONResponseBytes ||
|
||||
c.compareLimit != maxCompareResponseBytes ||
|
||||
c.rawLimit != maxRawFileBytes {
|
||||
t.Fatalf("caps = json %d compare %d raw %d", c.jsonLimit, c.compareLimit, c.rawLimit)
|
||||
}
|
||||
if c.compareLimit <= c.jsonLimit {
|
||||
t.Fatalf("compare cap %d must sit above the metadata cap %d", c.compareLimit, c.jsonLimit)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompareAllowsPayloadAboveMetadataCap pins that a straight compare larger
|
||||
// than the metadata JSON cap still succeeds. That body carries commits and
|
||||
// patches the sync does not store; rejecting it would stall the project cursor.
|
||||
func TestCompareAllowsPayloadAboveMetadataCap(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const (
|
||||
jsonLimit = 512
|
||||
compareLimit = 8 << 10
|
||||
)
|
||||
padding := strings.Repeat("p", jsonLimit)
|
||||
payload := `{"diffs":[{"old_path":"docs/old.md","new_path":"docs/new.md","renamed_file":true}],` +
|
||||
`"compare_timeout":false,"padding":"` + padding + `"}`
|
||||
body := []byte(payload)
|
||||
if int64(len(body)) <= jsonLimit || int64(len(body)) > compareLimit {
|
||||
t.Fatalf("fixture is %d bytes, want it between %d and %d", len(body), jsonLimit, compareLimit)
|
||||
}
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(body)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
|
||||
c.compareLimit = compareLimit
|
||||
|
||||
var project struct{}
|
||||
if err := c.get(context.Background(), "/projects/1", &project); err == nil {
|
||||
t.Fatal("get() accepted a body above the metadata cap")
|
||||
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("get() error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
|
||||
diff, err := c.compare(context.Background(), "1", "abc", "def")
|
||||
if err != nil {
|
||||
t.Fatalf("compare() rejected a body above the metadata cap and under the compare cap: %v", err)
|
||||
}
|
||||
if diff.CompareTimeout {
|
||||
t.Fatal("compare_timeout = true, want false")
|
||||
}
|
||||
if len(diff.Diffs) != 1 ||
|
||||
diff.Diffs[0].OldPath != "docs/old.md" ||
|
||||
diff.Diffs[0].NewPath != "docs/new.md" ||
|
||||
!diff.Diffs[0].RenamedFile {
|
||||
t.Fatalf("diffs = %+v", diff.Diffs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareRejectsPayloadAboveCompareCap(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
const compareLimit = 1024
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), compareLimit+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, maxRawFileBytes)
|
||||
c.compareLimit = compareLimit
|
||||
_, err := c.compare(context.Background(), "1", "abc", "def")
|
||||
if err == nil {
|
||||
t.Fatal("compare() accepted a body above the compare cap")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") ||
|
||||
!strings.Contains(err.Error(), fmt.Sprint(compareLimit)) {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error naming %d", err, compareLimit)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConnectorRollbackEmitsSnapshotChanges(t *testing.T) {
|
||||
for _, mode := range []string{"incremental", "stream"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
server := rollbackGitLabServer(t)
|
||||
cfg := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "ref": "main"},
|
||||
}},
|
||||
}
|
||||
old := gitLabCursor(cursor{Projects: map[string]string{"1": "descendant"}})
|
||||
connector := NewConnector()
|
||||
var items []types.FetchedItem
|
||||
var next *types.SyncCursor
|
||||
var err error
|
||||
if mode == "incremental" {
|
||||
items, next, err = connector.FetchIncremental(context.Background(), cfg, old)
|
||||
} else {
|
||||
handler := &gitLabStreamRecorder{}
|
||||
next, err = connector.FetchStream(context.Background(), cfg, old, handler)
|
||||
items = handler.items
|
||||
require.Len(t, handler.checkpoints, 1)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 2, "rollback must restore changed files and delete files absent from the target")
|
||||
require.Equal(t, []byte("# original README"), items[0].Content)
|
||||
require.Equal(t, "README.md", items[0].Metadata["gitlab_path"])
|
||||
require.True(t, items[1].IsDeleted)
|
||||
require.Equal(t, "added.md", items[1].Metadata["gitlab_path"])
|
||||
require.Equal(t, server.URL+"/api/v4:1:main:added.md", strings.TrimPrefix(items[1].ExternalID, "gitlab:"))
|
||||
require.Equal(t, "ancestor", next.ConnectorCursor["projects"].(map[string]string)["1"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func rollbackGitLabServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = fmt.Fprint(w, `{"id":1,"name":"docs","default_branch":"main"}`)
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = fmt.Fprint(w, `{"id":"ancestor"}`)
|
||||
case "/api/v4/projects/1/repository/compare":
|
||||
assert.Equal(t, "descendant", r.URL.Query().Get("from"))
|
||||
assert.Equal(t, "ancestor", r.URL.Query().Get("to"))
|
||||
// GitLab's default merge-base comparison returns no diffs when to
|
||||
// is an ancestor of from. Direct comparison returns the rollback.
|
||||
if r.URL.Query().Get("straight") != "true" {
|
||||
_, _ = fmt.Fprint(w, `{"diffs":[]}`)
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprint(w, `{"diffs":[
|
||||
{"old_path":"README.md","new_path":"README.md"},
|
||||
{"old_path":"added.md","new_path":"added.md","deleted_file":true}
|
||||
]}`)
|
||||
case "/api/v4/projects/1/repository/files/README.md/raw":
|
||||
assert.Equal(t, "main", r.URL.Query().Get("ref"))
|
||||
_, _ = fmt.Fprint(w, "# original README")
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
var _ datasource.StreamingConnector = (*Connector)(nil)
|
||||
|
||||
type Connector struct {
|
||||
client *client
|
||||
canonicalBase string
|
||||
}
|
||||
|
||||
// NewConnector creates a stateless connector. Each data source provides its
|
||||
// own GitLab URL and access token in its encrypted credentials.
|
||||
func NewConnector() *Connector { return &Connector{} }
|
||||
func (c *Connector) Type() string { return types.ConnectorTypeGitLab }
|
||||
|
||||
func (c *Connector) configured(ds *types.DataSourceConfig) (*Connector, error) {
|
||||
if ds == nil {
|
||||
return nil, datasource.ErrInvalidConfig
|
||||
}
|
||||
baseURL, _ := ds.Credentials["base_url"].(string)
|
||||
token, _ := ds.Credentials["access_token"].(string)
|
||||
client, err := newClient(baseURL, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Connector{client: client, canonicalBase: client.baseURL}, nil
|
||||
}
|
||||
|
||||
func (c *Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error {
|
||||
configured, err := c.configured(ds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := configured.client.ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if ds != nil {
|
||||
if _, ok := ds.Settings["projects"]; ok {
|
||||
if _, err := parseConfig(ds); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Connector) ListResources(ctx context.Context, ds *types.DataSourceConfig, parent string) ([]types.Resource, error) {
|
||||
var err error
|
||||
if c, err = c.configured(ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := parseConfig(ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent == "" {
|
||||
ps, err := c.client.projects(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]types.Resource, 0, len(ps))
|
||||
for _, p := range ps {
|
||||
out = append(out, types.Resource{ExternalID: fmt.Sprint(p.ID), Name: p.PathWithNamespace, Type: "project", URL: p.WebURL, HasChildren: true})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
id, dir := splitResourceID(parent)
|
||||
p, err := c.client.project(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ref := p.DefaultBranch
|
||||
entries, err := c.client.tree(ctx, id, ref, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]types.Resource, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if e.Type == "tree" {
|
||||
out = append(out, types.Resource{ExternalID: id + ":" + e.Path, Name: e.Name, Type: "directory", ParentID: parent, HasChildren: true})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (c *Connector) ResolveResourceAncestors(context.Context, *types.DataSourceConfig, []string) ([]string, error) {
|
||||
return []string{}, nil
|
||||
}
|
||||
func (c *Connector) FetchAll(ctx context.Context, ds *types.DataSourceConfig, _ []string) ([]types.FetchedItem, error) {
|
||||
var err error
|
||||
if c, err = c.configured(ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []types.FetchedItem
|
||||
for _, s := range cfg.Projects {
|
||||
p, err := c.client.project(ctx, s.ProjectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ref := s.Ref
|
||||
if ref == "" {
|
||||
ref = p.DefaultBranch
|
||||
}
|
||||
files, err := c.files(ctx, s.ProjectID, ref, s.Paths)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
item, err := c.item(ctx, p, ref, file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type cursor struct {
|
||||
Projects map[string]string `json:"projects"`
|
||||
}
|
||||
|
||||
func (c *Connector) FetchIncremental(ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) {
|
||||
var err error
|
||||
if c, err = c.configured(ds); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
prev := cursor{Projects: map[string]string{}}
|
||||
if old != nil {
|
||||
b, _ := json.Marshal(old.ConnectorCursor)
|
||||
_ = json.Unmarshal(b, &prev)
|
||||
if prev.Projects == nil {
|
||||
prev.Projects = map[string]string{}
|
||||
}
|
||||
}
|
||||
var out []types.FetchedItem
|
||||
next := cursor{Projects: map[string]string{}}
|
||||
for _, s := range cfg.Projects {
|
||||
p, err := c.client.project(ctx, s.ProjectID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ref := s.Ref
|
||||
if ref == "" {
|
||||
ref = p.DefaultBranch
|
||||
}
|
||||
head, err := c.client.commitSHA(ctx, s.ProjectID, ref)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
previous := prev.Projects[s.ProjectID]
|
||||
if previous == "" {
|
||||
files, err := c.files(ctx, s.ProjectID, ref, s.Paths)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, f := range files {
|
||||
item, err := c.item(ctx, p, ref, f)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
} else if previous != head {
|
||||
diff, err := c.compareChanges(ctx, s.ProjectID, previous, head)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, d := range diff.Diffs {
|
||||
if d.DeletedFile {
|
||||
if c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {
|
||||
out = append(out, c.deleted(p, ref, d.OldPath))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if d.RenamedFile && c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {
|
||||
out = append(out, c.deleted(p, ref, d.OldPath))
|
||||
}
|
||||
if c.inScope(d.NewPath, s.Paths) && isSupportedFile(d.NewPath) {
|
||||
item, err := c.item(ctx, p, ref, d.NewPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
next.Projects[s.ProjectID] = head
|
||||
}
|
||||
raw, _ := json.Marshal(next)
|
||||
return out, &types.SyncCursor{LastSyncTime: time.Now().UTC(), ConnectorCursor: map[string]interface{}{"projects": next.Projects, "raw": string(raw)}}, nil
|
||||
}
|
||||
|
||||
// FetchStream is the production sync path. It emits each supported repository
|
||||
// file as soon as it is read, so large GitLab projects do not accumulate their
|
||||
// contents in memory. The service prefers this method for StreamingConnector
|
||||
// implementations; FetchAll and FetchIncremental remain compatibility methods
|
||||
// required by the base Connector interface.
|
||||
func (c *Connector) FetchStream(
|
||||
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
|
||||
) (*types.SyncCursor, error) {
|
||||
var err error
|
||||
if c, err = c.configured(ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prev := cursor{Projects: map[string]string{}}
|
||||
if old != nil {
|
||||
b, _ := json.Marshal(old.ConnectorCursor)
|
||||
_ = json.Unmarshal(b, &prev)
|
||||
if prev.Projects == nil {
|
||||
prev.Projects = map[string]string{}
|
||||
}
|
||||
}
|
||||
next := cursor{Projects: make(map[string]string, len(cfg.Projects))}
|
||||
for projectID, commit := range prev.Projects {
|
||||
next.Projects[projectID] = commit
|
||||
}
|
||||
|
||||
for _, selection := range cfg.Projects {
|
||||
project, err := c.client.project(ctx, selection.ProjectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ref := selection.Ref
|
||||
if ref == "" {
|
||||
ref = project.DefaultBranch
|
||||
}
|
||||
head, err := c.client.commitSHA(ctx, selection.ProjectID, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
previous := prev.Projects[selection.ProjectID]
|
||||
switch {
|
||||
case previous == "":
|
||||
err = c.streamFiles(ctx, project, ref, selection.Paths, h)
|
||||
case previous != head:
|
||||
err = c.streamChanges(ctx, project, ref, previous, head, selection.Paths, h)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
next.Projects[selection.ProjectID] = head
|
||||
checkpoint := gitLabCursor(next)
|
||||
if err := h.Checkpoint(ctx, checkpoint); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return gitLabCursor(next), nil
|
||||
}
|
||||
|
||||
func gitLabCursor(value cursor) *types.SyncCursor {
|
||||
raw, _ := json.Marshal(value)
|
||||
return &types.SyncCursor{
|
||||
LastSyncTime: time.Now().UTC(),
|
||||
ConnectorCursor: map[string]interface{}{"projects": value.Projects, "raw": string(raw)},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Connector) streamChanges(
|
||||
ctx context.Context, project *project, ref, from, to string, roots []string, h datasource.StreamHandler,
|
||||
) error {
|
||||
diff, err := c.compareChanges(ctx, fmt.Sprint(project.ID), from, to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, change := range diff.Diffs {
|
||||
if change.DeletedFile {
|
||||
if c.inScope(change.OldPath, roots) && isSupportedFile(change.OldPath) {
|
||||
if err := h.Emit(ctx, c.deleted(project, ref, change.OldPath)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if change.RenamedFile && c.inScope(change.OldPath, roots) && isSupportedFile(change.OldPath) {
|
||||
if err := h.Emit(ctx, c.deleted(project, ref, change.OldPath)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if c.inScope(change.NewPath, roots) && isSupportedFile(change.NewPath) {
|
||||
item, err := c.item(ctx, project, ref, change.NewPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.Emit(ctx, item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Connector) compareChanges(ctx context.Context, projectID, from, to string) (*comparison, error) {
|
||||
diff, err := c.client.compare(ctx, projectID, from, to)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gitlab compare project %s: %w", projectID, err)
|
||||
}
|
||||
if diff.CompareTimeout {
|
||||
return nil, fmt.Errorf("gitlab compare project %s timed out", projectID)
|
||||
}
|
||||
return diff, nil
|
||||
}
|
||||
|
||||
func (c *Connector) streamFiles(
|
||||
ctx context.Context, project *project, ref string, roots []string, h datasource.StreamHandler,
|
||||
) error {
|
||||
return c.walkFiles(ctx, fmt.Sprint(project.ID), ref, roots, func(file string) error {
|
||||
item, err := c.item(ctx, project, ref, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return h.Emit(ctx, item)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connector) files(ctx context.Context, id, ref string, roots []string) ([]string, error) {
|
||||
var out []string
|
||||
err := c.walkFiles(ctx, id, ref, roots, func(file string) error {
|
||||
out = append(out, file)
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// walkFiles visits supported blobs while traversing the selected directories.
|
||||
// It deliberately does not collect paths, keeping streaming sync memory bounded
|
||||
// by the traversal depth plus the current file body.
|
||||
func (c *Connector) walkFiles(ctx context.Context, id, ref string, roots []string, visit func(string) error) error {
|
||||
if len(roots) == 0 {
|
||||
roots = []string{""}
|
||||
}
|
||||
var walk func(string) error
|
||||
walk = func(dir string) error {
|
||||
entries, err := c.client.tree(ctx, id, ref, dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Type == "tree" {
|
||||
if err := walk(e.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if e.Type == "blob" && isSupportedFile(e.Path) {
|
||||
if err := visit(e.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, r := range roots {
|
||||
if err := walk(r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isSupportedFile(file string) bool {
|
||||
_, ok := gitLabSupportedFileExtensions[strings.ToLower(path.Ext(file))]
|
||||
return ok
|
||||
}
|
||||
|
||||
// gitLabSupportedFileExtensions limits repository sync to formats the current
|
||||
// knowledge import pipeline can process. This is intentionally connector-local:
|
||||
// GitLab exposes arbitrary repository blobs, unlike document-centric sources.
|
||||
var gitLabSupportedFileExtensions = map[string]struct{}{
|
||||
".pdf": {}, ".txt": {}, ".docx": {}, ".doc": {}, ".epub": {},
|
||||
".html": {}, ".htm": {}, ".mhtml": {}, ".md": {}, ".markdown": {}, ".mdx": {},
|
||||
".png": {}, ".jpg": {}, ".jpeg": {}, ".gif": {},
|
||||
".csv": {}, ".xlsx": {}, ".xls": {}, ".pptx": {}, ".ppt": {}, ".json": {},
|
||||
".mp3": {}, ".wav": {}, ".m4a": {}, ".flac": {}, ".ogg": {},
|
||||
}
|
||||
|
||||
func (c *Connector) item(ctx context.Context, p *project, ref, file string) (types.FetchedItem, error) {
|
||||
body, err := c.client.raw(ctx, fmt.Sprint(p.ID), ref, file)
|
||||
if err != nil {
|
||||
return types.FetchedItem{}, err
|
||||
}
|
||||
id := fmt.Sprintf("gitlab:%s:%d:%s:%s", c.canonicalBase, p.ID, ref, file)
|
||||
title := p.PathWithNamespace + "/" + file
|
||||
// A file emptied by a commit still exists at this path, and ingestion reads
|
||||
// an item with no content and no URL as "nothing to sync" (see
|
||||
// datasource_service applyFetchedItem): the sync is acknowledged as
|
||||
// successful while the body indexed from an earlier commit stays fully
|
||||
// searchable. Nothing revisits it afterwards either — a full sync sees the
|
||||
// file present in the tree, and an incremental sync only walks the diffs of
|
||||
// commits newer than the recorded head, which the emptying commit already
|
||||
// moved past.
|
||||
//
|
||||
// Emitting the file's path as its content replaces the stale body instead,
|
||||
// which is what the Notion (b9be7d0d), Confluence and IMA (b71b31c8)
|
||||
// connectors already do for the same case. The check is on length alone, not
|
||||
// on TrimSpace: a blob that holds only whitespace still carries content the
|
||||
// repository has, and only a zero-byte blob has none.
|
||||
if len(body) == 0 {
|
||||
logger.Infof(ctx, "[GitLab] %s is empty, syncing its path only", title)
|
||||
body = []byte("# " + title + "\n")
|
||||
}
|
||||
// UpdatedAt is intentionally left unset: the file's last commit time is not
|
||||
// fetched here, and a fetch timestamp would be a fabricated source time.
|
||||
return types.FetchedItem{
|
||||
ExternalID: id,
|
||||
Title: title,
|
||||
FileName: knowledgeRelativePath(p.Name, ref, file),
|
||||
Content: body,
|
||||
ContentType: "text/plain",
|
||||
SourceResourceID: fmt.Sprint(p.ID),
|
||||
Metadata: map[string]string{
|
||||
"channel": types.ConnectorTypeGitLab,
|
||||
"source_type": "gitlab",
|
||||
"gitlab_project_id": fmt.Sprint(p.ID),
|
||||
"gitlab_ref": ref,
|
||||
"gitlab_path": file,
|
||||
"gitlab_url": p.WebURL + "/-/blob/" + ref + "/" + file,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// knowledgeRelativePath maps a repository file to the KB folder convention:
|
||||
// <GitLab project name>-<branch>/<repository-relative file path>.
|
||||
func knowledgeRelativePath(projectName, ref, file string) string {
|
||||
root := strings.TrimSpace(projectName) + "-" + strings.ReplaceAll(strings.TrimSpace(ref), "/", "-")
|
||||
return path.Join(root, file)
|
||||
}
|
||||
func (c *Connector) deleted(p *project, ref, file string) types.FetchedItem {
|
||||
return types.FetchedItem{ExternalID: fmt.Sprintf("gitlab:%s:%d:%s:%s", c.canonicalBase, p.ID, ref, file), IsDeleted: true, Metadata: map[string]string{"channel": types.ConnectorTypeGitLab, "gitlab_path": file}}
|
||||
}
|
||||
func (c *Connector) inScope(file string, roots []string) bool {
|
||||
if len(roots) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, r := range roots {
|
||||
if file == r || strings.HasPrefix(file, r+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func splitResourceID(value string) (string, string) {
|
||||
parts := strings.SplitN(value, ":", 2)
|
||||
if len(parts) == 1 {
|
||||
return value, ""
|
||||
}
|
||||
return parts[0], parts[1]
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Exercise the real tree and raw-file APIs, including a subdirectory returned
|
||||
// on the second page. Browsing remains shallow; fetching must visit every level.
|
||||
func TestConnectorFetchesNestedDirectories(t *testing.T) {
|
||||
for _, mode := range []string{
|
||||
"all", "incremental", "stream",
|
||||
} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
dirs := []string{"docs", "docs/a", "docs/a/b", "docs/a/b/c", "docs/a/b/c/d"}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":1,"name":"docs","path_with_namespace":"group/docs","default_branch":"main"
|
||||
}`))
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = w.Write([]byte(`{"id":"head"}`))
|
||||
case "/api/v4/projects/1/repository/compare":
|
||||
_, _ = w.Write([]byte(`{"compare_timeout":true}`))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
dir := r.URL.Query().Get("path")
|
||||
index := slices.Index(dirs, dir)
|
||||
if index < 0 || r.URL.Query().Get("ref") != "main" {
|
||||
http.Error(w, "unexpected tree scope", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var entries []treeEntry
|
||||
switch r.URL.Query().Get("page") {
|
||||
case "1":
|
||||
entries = append(entries, treeEntry{Name: "README.md", Path: dir + "/README.md", Type: "blob"})
|
||||
if index < len(dirs)-1 {
|
||||
w.Header().Set("X-Next-Page", "2")
|
||||
}
|
||||
case "2":
|
||||
if index < len(dirs)-1 {
|
||||
child := dirs[index+1]
|
||||
entries = append(entries, treeEntry{Name: path.Base(child), Path: child, Type: "tree"})
|
||||
}
|
||||
default:
|
||||
http.Error(w, "unexpected page", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(entries)
|
||||
default:
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v4/projects/1/repository/files/docs/") &&
|
||||
strings.HasSuffix(r.URL.Path, "/raw") {
|
||||
_, _ = fmt.Fprint(w, "# same content")
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
cfg := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "paths": []interface{}{"docs", "docs/a"}},
|
||||
}},
|
||||
}
|
||||
connector := NewConnector()
|
||||
var old *types.SyncCursor
|
||||
if strings.Contains(mode, "fallback") {
|
||||
old = gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
|
||||
}
|
||||
var items []types.FetchedItem
|
||||
var err error
|
||||
switch {
|
||||
case mode == "all":
|
||||
items, err = connector.FetchAll(context.Background(), cfg, nil)
|
||||
case strings.HasPrefix(mode, "incremental"):
|
||||
items, _, err = connector.FetchIncremental(context.Background(), cfg, old)
|
||||
default:
|
||||
handler := &gitLabStreamRecorder{}
|
||||
_, err = connector.FetchStream(context.Background(), cfg, old, handler)
|
||||
items = handler.items
|
||||
require.Len(t, handler.checkpoints, 1)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, len(dirs), "overlapping selected roots must not duplicate files")
|
||||
for i, dir := range dirs {
|
||||
require.Equal(t, "docs-main/"+dir+"/README.md", items[i].FileName)
|
||||
require.Equal(t, dir+"/README.md", items[i].Metadata["gitlab_path"])
|
||||
}
|
||||
|
||||
resources, err := connector.ListResources(context.Background(), cfg, "1:docs")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resources, 1)
|
||||
require.Equal(t, "1:docs/a", resources[0].ExternalID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorCompareFailuresDoNotFallBackToFullSync(t *testing.T) {
|
||||
for _, failure := range []struct {
|
||||
name string
|
||||
statusCode int
|
||||
body string
|
||||
}{
|
||||
{name: "timeout response", statusCode: http.StatusOK, body: `{"compare_timeout":true}`},
|
||||
{name: "API error", statusCode: http.StatusInternalServerError, body: `{"message":"compare failed"}`},
|
||||
} {
|
||||
for _, mode := range []string{"incremental", "stream"} {
|
||||
t.Run(failure.name+" "+mode, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
downstreamRequests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":1,"name":"docs","path_with_namespace":"group/docs","default_branch":"main"
|
||||
}`))
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = w.Write([]byte(`{"id":"head"}`))
|
||||
case "/api/v4/projects/1/repository/compare":
|
||||
w.WriteHeader(failure.statusCode)
|
||||
_, _ = w.Write([]byte(failure.body))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
downstreamRequests++
|
||||
_, _ = w.Write([]byte(`[{"name":"README.md","path":"README.md","type":"blob"}]`))
|
||||
default:
|
||||
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
|
||||
downstreamRequests++
|
||||
_, _ = w.Write([]byte("# unchanged"))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
|
||||
}},
|
||||
}
|
||||
old := gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
|
||||
connector := NewConnector()
|
||||
|
||||
switch mode {
|
||||
case "incremental":
|
||||
items, next, err := connector.FetchIncremental(context.Background(), cfg, old)
|
||||
require.ErrorContains(t, err, "gitlab compare project 1")
|
||||
require.Empty(t, items)
|
||||
require.Nil(t, next)
|
||||
case "stream":
|
||||
handler := &gitLabStreamRecorder{}
|
||||
next, err := connector.FetchStream(context.Background(), cfg, old, handler)
|
||||
require.ErrorContains(t, err, "gitlab compare project 1")
|
||||
require.Nil(t, next)
|
||||
require.Empty(t, handler.items)
|
||||
require.Empty(t, handler.checkpoints)
|
||||
}
|
||||
require.Zero(t, downstreamRequests, "compare failures must not trigger a full repository walk")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorSuccessfulCompareStillEmitsOnlyChangedFiles(t *testing.T) {
|
||||
for _, mode := range []string{"incremental", "stream"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
var compareQuery string
|
||||
treeRequests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":1,"name":"docs","path_with_namespace":"group/docs",
|
||||
"web_url":"https://gitlab.test/group/docs","default_branch":"main"
|
||||
}`))
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = w.Write([]byte(`{"id":"head"}`))
|
||||
case "/api/v4/projects/1/repository/compare":
|
||||
compareQuery = r.URL.RawQuery
|
||||
_, _ = w.Write([]byte(`{"diffs":[
|
||||
{"old_path":"removed.md","new_path":"removed.md","deleted_file":true},
|
||||
{"old_path":"old.md","new_path":"renamed.md","renamed_file":true},
|
||||
{"old_path":"guide.md","new_path":"guide.md"},
|
||||
{"old_path":"server.go","new_path":"server.go"}
|
||||
]}`))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
treeRequests++
|
||||
http.Error(w, "unexpected full repository walk", http.StatusInternalServerError)
|
||||
default:
|
||||
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
|
||||
_, _ = w.Write([]byte("# changed"))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
|
||||
}},
|
||||
}
|
||||
old := gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
|
||||
connector := NewConnector()
|
||||
var items []types.FetchedItem
|
||||
var next *types.SyncCursor
|
||||
|
||||
switch mode {
|
||||
case "incremental":
|
||||
var err error
|
||||
items, next, err = connector.FetchIncremental(context.Background(), cfg, old)
|
||||
require.NoError(t, err)
|
||||
case "stream":
|
||||
handler := &gitLabStreamRecorder{}
|
||||
var err error
|
||||
next, err = connector.FetchStream(context.Background(), cfg, old, handler)
|
||||
require.NoError(t, err)
|
||||
items = handler.items
|
||||
require.Len(t, handler.checkpoints, 1)
|
||||
}
|
||||
|
||||
require.Equal(t, "from=previous&straight=true&to=head", compareQuery)
|
||||
require.Zero(t, treeRequests)
|
||||
require.Len(t, items, 4)
|
||||
require.True(t, items[0].IsDeleted)
|
||||
require.Equal(t, "removed.md", items[0].Metadata["gitlab_path"])
|
||||
require.True(t, items[1].IsDeleted)
|
||||
require.Equal(t, "old.md", items[1].Metadata["gitlab_path"])
|
||||
require.False(t, items[2].IsDeleted)
|
||||
require.Equal(t, "renamed.md", items[2].Metadata["gitlab_path"])
|
||||
require.False(t, items[3].IsDeleted)
|
||||
require.Equal(t, "guide.md", items[3].Metadata["gitlab_path"])
|
||||
require.Equal(t, "head", next.ConnectorCursor["projects"].(map[string]string)["1"])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// An emptied file is still a file. Ingestion treats an item with neither content
|
||||
// nor URL as nothing to ingest and acknowledges the sync, so emitting the
|
||||
// emptied blob verbatim leaves the body indexed from an earlier commit
|
||||
// searchable forever — and no later sync revisits it, because a full sync still
|
||||
// sees the path in the tree and an incremental sync has already moved its head
|
||||
// past the commit that emptied it.
|
||||
//
|
||||
// The Notion (b9be7d0d), Confluence and IMA (b71b31c8) connectors emit the
|
||||
// document's title in this case so ingestion replaces the stale body. GitLab
|
||||
// does the same with the file's path, on both sync paths that can observe the
|
||||
// change.
|
||||
//
|
||||
// Only a zero-byte blob is rewritten. A blob holding whitespace carries content
|
||||
// the repository still has, so its bytes must reach ingestion untouched.
|
||||
func TestConnectorEmitsPathWhenAFileIsEmptied(t *testing.T) {
|
||||
for _, mode := range []string{"full", "incremental", "stream"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/v4/projects/1":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":1,"name":"docs","path_with_namespace":"group/docs",
|
||||
"web_url":"https://gitlab.test/group/docs","default_branch":"main"
|
||||
}`))
|
||||
case "/api/v4/projects/1/repository/commits/main":
|
||||
_, _ = w.Write([]byte(`{"id":"head"}`))
|
||||
case "/api/v4/projects/1/repository/compare":
|
||||
_, _ = w.Write([]byte(`{"diffs":[
|
||||
{"old_path":"runbook.md","new_path":"runbook.md"},
|
||||
{"old_path":"indented.md","new_path":"indented.md"},
|
||||
{"old_path":"kept.md","new_path":"kept.md"}
|
||||
]}`))
|
||||
case "/api/v4/projects/1/repository/tree":
|
||||
_, _ = w.Write([]byte(`[
|
||||
{"name":"runbook.md","path":"runbook.md","type":"blob"},
|
||||
{"name":"indented.md","path":"indented.md","type":"blob"},
|
||||
{"name":"kept.md","path":"kept.md","type":"blob"}
|
||||
]`))
|
||||
default:
|
||||
if strings.Contains(r.URL.Path, "/repository/files/") {
|
||||
switch {
|
||||
case strings.Contains(r.URL.Path, "runbook.md"):
|
||||
// 200 with no bytes at all: the emptied commit.
|
||||
case strings.Contains(r.URL.Path, "indented.md"):
|
||||
_, _ = w.Write([]byte(" \n\t\n"))
|
||||
default:
|
||||
_, _ = w.Write([]byte("# still here"))
|
||||
}
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
|
||||
}},
|
||||
}
|
||||
connector := NewConnector()
|
||||
var items []types.FetchedItem
|
||||
var err error
|
||||
|
||||
switch mode {
|
||||
case "full":
|
||||
items, err = connector.FetchAll(context.Background(), cfg, nil)
|
||||
case "incremental":
|
||||
items, _, err = connector.FetchIncremental(
|
||||
context.Background(), cfg, gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}}))
|
||||
default:
|
||||
handler := &gitLabStreamRecorder{}
|
||||
_, err = connector.FetchStream(
|
||||
context.Background(), cfg,
|
||||
gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}}), handler)
|
||||
items = handler.items
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 3)
|
||||
|
||||
byPath := make(map[string]types.FetchedItem, len(items))
|
||||
for _, item := range items {
|
||||
byPath[item.Metadata["gitlab_path"]] = item
|
||||
}
|
||||
|
||||
emptied := byPath["runbook.md"]
|
||||
require.False(t, emptied.IsDeleted)
|
||||
require.Equal(t,
|
||||
"# group/docs/runbook.md\n",
|
||||
string(emptied.Content),
|
||||
"an emptied file must still reach ingestion, or its stale body stays searchable")
|
||||
require.Equal(t, "group/docs/runbook.md", emptied.Title)
|
||||
|
||||
// Whitespace is content: it must not be mistaken for an emptied file.
|
||||
require.Equal(t, " \n\t\n", string(byPath["indented.md"].Content))
|
||||
|
||||
require.Equal(t, "# still here", string(byPath["kept.md"].Content))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// guardTestTimeout bounds every walk here so that a missing guard fails the
|
||||
// test instead of hanging it.
|
||||
const guardTestTimeout = 5 * time.Second
|
||||
|
||||
// repeatedPageServer always advertises the same X-Next-Page value and refuses
|
||||
// to serve more than three requests: a walk without a repeated-page guard then
|
||||
// fails quickly with an unexpected error instead of spinning until the context
|
||||
// deadline.
|
||||
func repeatedPageServer(t *testing.T) (*httptest.Server, *int64) {
|
||||
t.Helper()
|
||||
allowLocalGitLabServer(t)
|
||||
var requests int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if atomic.AddInt64(&requests, 1) > 3 {
|
||||
http.Error(w, "pagination guard missing: too many requests", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Next-Page", "2")
|
||||
if strings.HasSuffix(r.URL.Path, "/repository/tree") {
|
||||
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`[{"id":1,"path_with_namespace":"group/project-001"}]`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server, &requests
|
||||
}
|
||||
|
||||
func TestProjectsStopsOnRepeatedNextPage(t *testing.T) {
|
||||
server, requests := repeatedPageServer(t)
|
||||
c, err := newClient(server.URL, "test-token")
|
||||
require.NoError(t, err)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), guardTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
projects, err := c.projects(ctx)
|
||||
|
||||
require.Error(t, err, "a repeated X-Next-Page must not be treated as the end of the list")
|
||||
require.Nil(t, projects)
|
||||
require.Contains(t, err.Error(), `gitlab project pagination repeated page "2"`)
|
||||
require.LessOrEqual(t, atomic.LoadInt64(requests), int64(3), "must stop before re-reading the repeated page")
|
||||
}
|
||||
|
||||
func TestTreeStopsOnRepeatedNextPage(t *testing.T) {
|
||||
server, requests := repeatedPageServer(t)
|
||||
c, err := newClient(server.URL, "test-token")
|
||||
require.NoError(t, err)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), guardTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
entries, err := c.tree(ctx, "1", "main", "")
|
||||
|
||||
require.Error(t, err, "a repeated X-Next-Page must not be treated as the end of the list")
|
||||
require.Nil(t, entries)
|
||||
require.Contains(t, err.Error(), `gitlab tree pagination repeated page "2"`)
|
||||
require.LessOrEqual(t, atomic.LoadInt64(requests), int64(3), "must stop before re-reading the repeated page")
|
||||
}
|
||||
|
||||
// TestPaginationHopCapStopsWalk drives each walk with a server that always
|
||||
// advertises a fresh page number, so only the hop cap can end it.
|
||||
func TestPaginationHopCapStopsWalk(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
want string
|
||||
walk func(context.Context, *client) error
|
||||
}{
|
||||
{
|
||||
name: "projects",
|
||||
want: "gitlab project pagination exceeded 10000 pages",
|
||||
walk: func(ctx context.Context, c *client) error {
|
||||
_, err := c.projects(ctx)
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tree",
|
||||
want: "gitlab tree pagination exceeded 10000 pages",
|
||||
walk: func(ctx context.Context, c *client) error {
|
||||
_, err := c.tree(ctx, "1", "main", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
allowLocalGitLabServer(t)
|
||||
var requests int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt64(&requests, 1)
|
||||
if n > maxPaginationHops+10 {
|
||||
http.Error(w, "hop cap missing: too many requests", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
page, convErr := strconv.Atoi(r.URL.Query().Get("page"))
|
||||
if convErr != nil {
|
||||
http.Error(w, "unexpected page", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Next-Page", strconv.Itoa(page+1))
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
c, err := newClient(server.URL, "test-token")
|
||||
require.NoError(t, err)
|
||||
|
||||
var logs bytes.Buffer
|
||||
logger.SetOutput(&logs)
|
||||
t.Cleanup(logger.ConfigureFromEnv)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
err = tc.walk(ctx, c)
|
||||
|
||||
require.EqualError(t, err, tc.want)
|
||||
require.Equal(t, int64(maxPaginationHops), atomic.LoadInt64(&requests))
|
||||
require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
|
||||
"hitting the cap must leave a warning in the log")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrackPageAllowsForwardPages(t *testing.T) {
|
||||
seen := make(map[string]struct{})
|
||||
for _, page := range []string{"1", "2", "3"} {
|
||||
require.NoError(t, trackPage(context.Background(), "project", seen, page))
|
||||
}
|
||||
require.Error(t, trackPage(context.Background(), "project", seen, "2"))
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestListResourcesIncludesProjectsAfterFirstPage(t *testing.T) {
|
||||
const pageSize = 100
|
||||
const projectCount = 2*pageSize + 1
|
||||
server, requests := projectListServer(t, map[string]projectListPage{
|
||||
"1": {body: projectListJSON(t, 1, pageSize), next: "2"},
|
||||
"2": {body: projectListJSON(t, pageSize+1, pageSize), next: "3"},
|
||||
"3": {body: projectListJSON(t, projectCount, 1)},
|
||||
})
|
||||
ds := &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "test-token"},
|
||||
Settings: map[string]interface{}{"projects": []interface{}{
|
||||
map[string]interface{}{"project_id": "1"},
|
||||
}},
|
||||
}
|
||||
|
||||
resources, err := NewConnector().ListResources(context.Background(), ds, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, projectCount, len(resources), "every GitLab project must be available for selection")
|
||||
for i, resource := range resources {
|
||||
require.Equal(t, fmt.Sprint(i+1), resource.ExternalID)
|
||||
require.Equal(t, fmt.Sprintf("group/project-%03d", i+1), resource.Name)
|
||||
require.Equal(t, fmt.Sprintf("https://gitlab.example.com/group/project-%03d", i+1), resource.URL)
|
||||
require.Equal(t, "project", resource.Type)
|
||||
require.True(t, resource.HasChildren)
|
||||
}
|
||||
require.Equal(t, []string{"1", "2", "3"}, recordedProjectPages(requests))
|
||||
}
|
||||
|
||||
func TestProjectsStopsAtFinalPage(t *testing.T) {
|
||||
const pageSize = 100
|
||||
for _, count := range []int{0, pageSize} {
|
||||
t.Run(fmt.Sprintf("%d projects", count), func(t *testing.T) {
|
||||
server, requests := projectListServer(t, map[string]projectListPage{
|
||||
"1": {body: projectListJSON(t, 1, count)},
|
||||
})
|
||||
c, err := newClient(server.URL, "test-token")
|
||||
require.NoError(t, err)
|
||||
projects, err := c.projects(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, projects, count)
|
||||
require.Equal(t, []string{"1"}, recordedProjectPages(requests))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectsRejectsIncompleteList(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
page projectListPage
|
||||
}{
|
||||
{name: "HTTP error", page: projectListPage{status: http.StatusServiceUnavailable}},
|
||||
{name: "malformed JSON", page: projectListPage{body: "not JSON"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server, requests := projectListServer(t, map[string]projectListPage{
|
||||
"1": {body: projectListJSON(t, 1, 1), next: "2"},
|
||||
"2": tc.page,
|
||||
})
|
||||
c, err := newClient(server.URL, "test-token")
|
||||
require.NoError(t, err)
|
||||
projects, err := c.projects(context.Background())
|
||||
require.Error(t, err)
|
||||
require.Nil(t, projects, "do not return a partial list as a successful result")
|
||||
require.Equal(t, []string{"1", "2"}, recordedProjectPages(requests))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type projectListPage struct {
|
||||
body string
|
||||
next string
|
||||
status int
|
||||
}
|
||||
|
||||
func projectListServer(t *testing.T, pages map[string]projectListPage) (*httptest.Server, <-chan string) {
|
||||
t.Helper()
|
||||
allowLocalGitLabServer(t)
|
||||
requests := make(chan string, len(pages)+1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query()
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/v4/projects" ||
|
||||
r.Header.Get("PRIVATE-TOKEN") != "test-token" || query.Get("membership") != "true" ||
|
||||
query.Get("per_page") != "100" || query.Get("order_by") != "path_with_namespace" ||
|
||||
query.Get("sort") != "asc" {
|
||||
http.Error(w, "unexpected project-list request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
page := query.Get("page")
|
||||
if page == "" {
|
||||
page = "1" // GitLab defaults to its first page when the parameter is omitted.
|
||||
}
|
||||
response, ok := pages[page]
|
||||
if !ok {
|
||||
http.Error(w, "unexpected page", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case requests <- page:
|
||||
default:
|
||||
http.Error(w, "too many page requests", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Next-Page", response.next)
|
||||
if response.status != 0 {
|
||||
w.WriteHeader(response.status)
|
||||
}
|
||||
_, _ = fmt.Fprint(w, response.body)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server, requests
|
||||
}
|
||||
|
||||
func projectListJSON(t *testing.T, start, count int) string {
|
||||
t.Helper()
|
||||
projects := make([]project, 0, count)
|
||||
for id := start; id < start+count; id++ {
|
||||
projects = append(projects, project{
|
||||
ID: int64(id), PathWithNamespace: fmt.Sprintf("group/project-%03d", id),
|
||||
WebURL: fmt.Sprintf("https://gitlab.example.com/group/project-%03d", id),
|
||||
})
|
||||
}
|
||||
data, err := json.Marshal(projects)
|
||||
require.NoError(t, err)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func recordedProjectPages(requests <-chan string) []string {
|
||||
var pages []string
|
||||
for len(requests) > 0 {
|
||||
pages = append(pages, <-requests)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type projectSelection struct {
|
||||
ProjectID string `json:"project_id"`
|
||||
Ref string `json:"ref"`
|
||||
Paths []string `json:"paths"`
|
||||
}
|
||||
|
||||
type config struct {
|
||||
Projects []projectSelection `json:"projects"`
|
||||
}
|
||||
|
||||
func parseConfig(ds *types.DataSourceConfig) (*config, error) {
|
||||
if ds == nil {
|
||||
return nil, datasource.ErrInvalidConfig
|
||||
}
|
||||
raw, ok := ds.Settings["projects"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: settings.projects is required", datasource.ErrInvalidConfig)
|
||||
}
|
||||
items, ok := raw.([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: settings.projects must be an array", datasource.ErrInvalidConfig)
|
||||
}
|
||||
out := &config{Projects: make([]projectSelection, 0, len(items))}
|
||||
seen := map[string]bool{}
|
||||
for _, rawProject := range items {
|
||||
m, ok := rawProject.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: invalid project selection", datasource.ErrInvalidConfig)
|
||||
}
|
||||
id, _ := m["project_id"].(string)
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || seen[id] {
|
||||
return nil, fmt.Errorf("%w: project_id must be unique and non-empty", datasource.ErrInvalidConfig)
|
||||
}
|
||||
seen[id] = true
|
||||
ref, _ := m["ref"].(string)
|
||||
p := projectSelection{ProjectID: id, Ref: strings.TrimSpace(ref)}
|
||||
if rawPaths, exists := m["paths"]; exists {
|
||||
values, ok := rawPaths.([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: paths must be an array", datasource.ErrInvalidConfig)
|
||||
}
|
||||
for _, value := range values {
|
||||
s, ok := value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: path must be a string", datasource.ErrInvalidConfig)
|
||||
}
|
||||
normalized, err := normalizePath(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Paths = append(p.Paths, normalized)
|
||||
}
|
||||
}
|
||||
p.Paths = collapsePaths(p.Paths)
|
||||
out.Projects = append(out.Projects, p)
|
||||
}
|
||||
if len(out.Projects) == 0 {
|
||||
return nil, fmt.Errorf("%w: at least one project is required", datasource.ErrInvalidConfig)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func normalizePath(value string) (string, error) {
|
||||
v := strings.Trim(strings.TrimSpace(value), "/")
|
||||
if v == "" {
|
||||
return "", nil
|
||||
}
|
||||
if strings.Contains(v, "\\") {
|
||||
return "", fmt.Errorf("%w: path must use forward slashes", datasource.ErrInvalidConfig)
|
||||
}
|
||||
if path.Clean(v) != v || v == "." || strings.HasPrefix(v, "../") || strings.Contains(v, "/../") {
|
||||
return "", fmt.Errorf("%w: invalid repository path", datasource.ErrInvalidConfig)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func collapsePaths(paths []string) []string {
|
||||
if len(paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.Strings(paths)
|
||||
for _, p := range paths {
|
||||
if p == "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(paths))
|
||||
for _, p := range paths {
|
||||
if len(out) > 0 && (p == out[len(out)-1] || strings.HasPrefix(p, out[len(out)-1]+"/")) {
|
||||
continue
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestParseConfigCollapsesDirectories(t *testing.T) {
|
||||
cfg, err := parseConfig(&types.DataSourceConfig{Settings: map[string]interface{}{
|
||||
"projects": []interface{}{map[string]interface{}{
|
||||
"project_id": "team/docs", "ref": "main",
|
||||
"paths": []interface{}{"docs/guide", "docs", "docs"},
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Projects) != 1 || len(cfg.Projects[0].Paths) != 1 || cfg.Projects[0].Paths[0] != "docs" {
|
||||
t.Fatalf("unexpected config: %#v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigRootMeansWholeProject(t *testing.T) {
|
||||
cfg, err := parseConfig(&types.DataSourceConfig{Settings: map[string]interface{}{
|
||||
"projects": []interface{}{map[string]interface{}{"project_id": "42", "paths": []interface{}{"/"}}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Projects[0].Paths) != 0 {
|
||||
t.Fatalf("root path must collapse to whole project: %#v", cfg.Projects[0].Paths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePathRejectsTraversal(t *testing.T) {
|
||||
if _, err := normalizePath("docs/../secrets"); err == nil {
|
||||
t.Fatal("expected traversal rejection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeRelativePathPreservesRepositoryTreeBelowProjectAndBranch(t *testing.T) {
|
||||
got := knowledgeRelativePath("knowledge", "feature/login", "docs/guide/install.md")
|
||||
if got != "knowledge-feature-login/docs/guide/install.md" {
|
||||
t.Fatalf("knowledge relative path = %q", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user