Skip to content

feat(providers): add GitLab provider supporting self-hosted instances - #307

Merged
jeff-r2026 merged 2 commits into
Tencent:mainfrom
ityoung:feat/gitlab-provider
Aug 24, 2026
Merged

jeff-r2026 merged 2 commits into
Tencent:mainfrom
ityoung:feat/gitlab-provider

Conversation

@ityoung

@ityoung ityoung commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a GitLab provider to teamai-cli, enabling the CLI to work with GitLab — including self-hosted / enterprise GitLab instances (the dominant self-hosted git platform).

Today the provider layer only supports github | tgit | cnb. Teams hosting their harness repo on a self-hosted GitLab (e.g. an internal GitLab instance) have no way to use teamai push / teamai init — they must fake provider: github and PR/MR creation fails. This PR fills that gap.

What's included

  • New provider src/providers/gitlab/ implementing the GitProvider interface:
    • repo-url.ts — parse owner/repo, group/subgroup/repo, HTTPS/SSH URLs on any host
    • gitlab-api.ts — REST API v4 client (no external CLI needed): auth, whoami, clone (token embedded), create repo, create MR (incl. reviewer resolution)
    • mr-fetch.ts — fetchMergeRequest (title / description / commits / diff)
    • org.ts — listOrgRepos via the groups endpoint (paginated)
    • index.ts — GitLabProvider
  • Registration in src/providers/registry.ts: gitlab.com → gitlab in HOST_MAP, gitlab in KNOWN_PROVIDERS / PROVIDERS, plus self-hosted host detection via GITLAB_URL / TEAMAI_GITLAB_HOST
  • Config schema src/types.ts: provider enum now includes cnb (was already implemented but missing from the schema) and gitlab
  • Docs docs/providers.md: GitLab provider section incl. self-hosted setup
  • Tests src/__tests__/gitlab-provider.test.ts (32 tests); updated github-provider.test.ts / provider-fallback.test.ts which previously used gitlab.com as a stand-in for an "unknown host"

Auth (env vars)

Standard GitLab environment variables:

export GITLAB_URL=https://git.example.com   # self-hosted instance base URL; default https://gitlab.com
export GITLAB_TOKEN=glpat-xxx               # PAT with `api` scope
# GITLAB_PRIVATE_TOKEN / GITLAB_PAT accepted as aliases

Verification

  • npm run typecheck — clean
  • npm test — 157 files / 2096 tests pass
  • npm run build — clean

@ityoung
ityoung force-pushed the feat/gitlab-provider branch 2 times, most recently from 8709faf to 3aaf413 Compare August 23, 2026 12:07
Comment thread src/providers/gitlab/gitlab-api.ts Outdated

if (!login || login.toLowerCase() !== owner.toLowerCase()) {
const namespaceId = await resolveNamespaceId(owner, token);
if (namespaceId !== null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

namespace_id is silently dropped when group resolution misses → repo created in the wrong (personal) namespace, reported as success

When owner is a group and resolveNamespaceId returns null (no exact full_path match — happens for subgroups, paginated results, or a non-200 /namespaces response), namespace_id is omitted here. GitLab then defaults to the current user's namespace, and createRepo still resolves as success.

Verified end-to-end against a mock GitLab API using this PR's source. createRepo('mygroup', 'repo') with whoami=alice and no exact namespace match emits:

GET  /api/v4/user                          → alice
GET  /api/v4/namespaces?search=mygroup     → no exact full_path match → null
POST /api/v4/projects  BODY={"name":"repo","path":"repo","visibility":"private"}
                                             ↑ namespace_id dropped → created under alice/

Scope is narrow — only the first-time create path (init.ts create-repo step, reached only when the clone 404s). But when it hits, init prints Repo mygroup/repo created, then the retry clone of mygroup/repo 404s and aborts — the repo actually landed under alice/repo.

Suggest failing loudly instead of falling back: when owner isn't the current user and resolveNamespaceId returns null, throw (group not found / insufficient token scope) rather than omitting namespace_id.

ityoung and others added 2 commits August 24, 2026 13:04
Review fixes on top of the GitLab provider, rebased onto the generic `git`
provider from Tencent#301. Detection order is now known host -> self-hosted GitLab
-> `git` transport fallback, so a self-hosted instance keeps the platform
features (create repo/MR, fetch MR, list group repos) that the generic
provider does not implement.

Host handling:
- Clone URLs derive from the instance base URL instead of being reassembled
  from GITLAB_HOST, so scheme (http:// internal deployments), port and
  relative-URL-root prefixes survive.
- fetchGitLabMR queries the host named by the MR URL rather than the
  configured instance, which previously sent a self-hosted PAT to gitlab.com
  and read whichever project shared that path.
- GITLAB_URL is validated; a scheme-less value used to leave GITLAB_HOST on
  gitlab.com while every API call threw "Failed to parse URL" from undici.
  Base URL resolution is lazy so an invalid value fails the GitLab operation
  instead of crashing every module that imports this one.
- Self-hosted host matching tolerates a configured port, since the ssh:// and
  scp-style URL forms never carry one.

Wiring that was implemented but unreachable:
- import --from-mr now routes /-/merge_requests/ URLs to the GitLab fetcher
  (previously "Unsupported MR URL"), and infers the repo URL for the
  incremental update.
- import --from-org resolves the provider through detectProvider instead of
  a hardcoded `woa.com ? tgit : github`, which sent every GitLab org to the
  GitHub API.
- shallowClone injects GITLAB_TOKEN via http.extraHeader instead of falling
  through to an anonymous clone, so private repos work; the token stays out
  of the URL.
- teamai doctor checks the GitLab token when provider is gitlab.

Correctness:
- parseGitLabRepoInput strips GitLab's /-/ route separator, so a URL copied
  from the browser resolves to the project instead of yielding
  owner="org/repo/-/tree", repo="main".
- createRepo resolves the group by exact path and fails when it cannot,
  rather than silently creating the project in the personal namespace and
  reporting success at the wrong location.
- listOrgRepos passes include_subgroups=true; GitLab defaults it to false,
  silently dropping every project nested under a subgroup.
- Blank/whitespace tokens read as absent, so isAuthenticated no longer
  disagrees with the rest of the provider, and a trailing newline from
  $(cat token) cannot produce an invalid header value.
- API error message is English, per the repo output-language rule.

Tests: regression coverage for each fix above, plus the first coverage for
org.ts and mr-fetch.ts.

Co-Authored-By: Shin Yang <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
@jeff-r2026
jeff-r2026 force-pushed the feat/gitlab-provider branch from 3aaf413 to c75580d Compare August 24, 2026 05:21
@jeff-r2026

Copy link
Copy Markdown
Collaborator

Thanks for this — the provider itself was well structured, and the REST-only shape (no external CLI) is the right call. I've rebased the branch onto current main and pushed review fixes on top, so a heads-up on what changed.

Rebase onto #301. main now has a generic git transport provider, which changed detectProvider: unknown hosts fall back to 'git' instead of the distribution default, and there are new ssh:// and relaxed scp-style branches. That collided with this PR (both touched the same lines, including the two tests that used gitlab.com as an "unknown host" stand-in). Resolved so detection is known host → self-hosted GitLab → git fallback, applied across all three URL forms. The two providers are complementary rather than overlapping: the generic one throws on createRepo/createPullRequest, so self-hosted GitLab users needed exactly this provider to get those.

Host handling. cloneUrl rebuilt the URL from GITLAB_HOST, which dropped the scheme, port and any relative-URL-root prefix — an http:// internal instance got an https:// clone URL. fetchGitLabMR parsed the host out of the MR URL and then discarded it, querying the configured instance instead, which would send a self-hosted PAT to gitlab.com. GITLAB_URL is now validated (a scheme-less value used to leave GITLAB_HOST on gitlab.com while every fetch threw Failed to parse URL from inside undici), and base-URL resolution is lazy so a bad value fails the GitLab operation rather than crashing every module that imports it.

Wiring. fetchMergeRequest and listOrgRepos were implemented but unreachable — import-mr.ts only branched on github.com/git.woa.com, and import-org.ts hardcoded woa.com ? tgit : github. Both now route to GitLab. shallowClone had no gitlab branch, so teamai import cloned private GitLab repos anonymously; it now injects the token via http.extraHeader (kept out of the URL). teamai doctor checks the token when provider is gitlab.

Correctness. parseGitLabRepoInput now strips GitLab's /-/ route separator — pasting a URL from the browser previously yielded owner: "org/repo/-/tree", repo: "main" with no error. createRepo resolves the group by exact path and fails when it can't, instead of omitting namespace_id and silently creating the project in the personal namespace while reporting success at the group path. listOrgRepos passes include_subgroups=true (GitLab defaults it to false, which dropped every subgroup project — notable given this PR's subgroup support). Blank tokens now read as absent, and the API error message is English per the repo's output-language rule.

Verification. 2138 tests pass on the locked vitest, typecheck and build clean. Beyond unit tests I ran the built CLI against a local mock GitLab instance and confirmed on the wire: MR fetch hits the host from the URL with group%2Fsub%2Frepo encoding, org listing sends include_subgroups=true, and git clone carries Authorization: Basic oauth2:<token>. Added regression tests for each fix, plus the first coverage for org.ts and mr-fetch.ts.

Two cleanups I deliberately left out of scope, worth separate PRs: org.ts duplicates tgit/gf-org.ts almost verbatim (the byte-capped streaming read block now exists in four places), and the self-hosted host override could be table-driven — which would also fix TEAMAI_CNB_HOST, currently unhonored by the registry.

@jeff-r2026
jeff-r2026 merged commit 51a4372 into Tencent:main Aug 24, 2026
7 checks passed
jeff-r2026 added a commit that referenced this pull request Aug 24, 2026
…host, keep clone token out of the URL (#314)

Three security issues in the GitLab provider (#307):

1. [HIGH] SSRF / credential exfiltration in mr-fetch.ts — fetchGitLabMR derived
   the API base (and sent the PAT) from the host in the user-supplied MR URL,
   with no check against the configured instance. A hand-crafted MR URL on an
   attacker-controlled host would receive the token. Now the URL host must match
   GITLAB_HOST (GITLAB_URL / TEAMAI_GITLAB_HOST, default gitlab.com) or the fetch
   is rejected before any network call. We still derive scheme/port from the URL
   so self-hosted instances keep working — but only for the trusted host.

2. [MEDIUM] Credential persistence in gitlab-api.ts — gitlabRepoClone embedded
   the token in the clone URL (oauth2:<token>@...), which git writes into the
   cloned repo's .git/config for every later fetch/push. Inject it via
   `-c http.extraHeader=Authorization: Basic <base64(oauth2:token)>` instead, so
   the token never enters the URL or .git/config. Mirrors clone.ts.

3. [MEDIUM] Inconsistent redaction in gitlab-api.ts — the clone-error path used
   an inline `oauth2:[^@]+@` regex. Use the shared sanitizeGitUrl from
   utils/redact.ts so redaction coverage stays consistent with clone.ts.

Tests: updated gitlab-provider.test.ts to assert the header-based auth, the
clean clone URL, and the SSRF rejection; added gitlab-clone-realspawn.test.ts
which runs a REAL git spawn against a fake `git` on PATH and confirms the token
never appears in the argv/URL (only base64 in the extraHeader) and that the
surfaced error is sanitized. docs/providers.md updated to match.

Co-authored-by: Claude Fable 5 <[email protected]>
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…Tencent#307)

Adds a GitLab provider (REST API v4, no external CLI) supporting gitlab.com
and self-hosted / enterprise instances: clone, create repo, create MR with
reviewer resolution, fetch MR data, and list group repos.

Detection order is known host -> self-hosted GitLab (GITLAB_URL /
TEAMAI_GITLAB_HOST) -> the generic `git` transport provider, across HTTPS,
ssh:// and scp-style URLs. This complements the generic provider from Tencent#301,
which is transport-only and cannot create repos or merge requests.

Includes review fixes: clone and MR URLs honour the instance scheme, port and
path prefix; GITLAB_URL is validated and resolved lazily; the MR fetcher
queries the host named by the URL; `/-/` route paths are stripped when parsing
repo input; group namespaces resolve by exact path and fail rather than
falling back to the personal namespace; group listing includes subgroups;
blank tokens read as absent. Wires GitLab into the MR-import dispatcher, the
org-import provider resolution, shallowClone token injection, and doctor.

Co-Authored-By: Shin Yang <[email protected]>
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…host, keep clone token out of the URL (Tencent#314)

Three security issues in the GitLab provider (Tencent#307):

1. [HIGH] SSRF / credential exfiltration in mr-fetch.ts — fetchGitLabMR derived
   the API base (and sent the PAT) from the host in the user-supplied MR URL,
   with no check against the configured instance. A hand-crafted MR URL on an
   attacker-controlled host would receive the token. Now the URL host must match
   GITLAB_HOST (GITLAB_URL / TEAMAI_GITLAB_HOST, default gitlab.com) or the fetch
   is rejected before any network call. We still derive scheme/port from the URL
   so self-hosted instances keep working — but only for the trusted host.

2. [MEDIUM] Credential persistence in gitlab-api.ts — gitlabRepoClone embedded
   the token in the clone URL (oauth2:<token>@...), which git writes into the
   cloned repo's .git/config for every later fetch/push. Inject it via
   `-c http.extraHeader=Authorization: Basic <base64(oauth2:token)>` instead, so
   the token never enters the URL or .git/config. Mirrors clone.ts.

3. [MEDIUM] Inconsistent redaction in gitlab-api.ts — the clone-error path used
   an inline `oauth2:[^@]+@` regex. Use the shared sanitizeGitUrl from
   utils/redact.ts so redaction coverage stays consistent with clone.ts.

Tests: updated gitlab-provider.test.ts to assert the header-based auth, the
clean clone URL, and the SSRF rejection; added gitlab-clone-realspawn.test.ts
which runs a REAL git spawn against a fake `git` on PATH and confirms the token
never appears in the argv/URL (only base64 in the extraHeader) and that the
surfaced error is sanitized. docs/providers.md updated to match.

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants