BerriAI/litellm · error · Exception

Authentication failed. Check your GitLab token and…

Error message

Authentication failed. Check your GitLab token and auth_method.

What it means

GitLab answered 401 Unauthorized for the raw file endpoint: the token is missing, expired, revoked, or sent under the wrong scheme. GitLabClient sends the token as a Private-Token header by default and as Authorization: Bearer only when config['auth_method'] == 'oauth', so an OAuth token left on the default auth_method is mis-sent and rejected.

Solutions

  1. Regenerate/verify the token and update the config or env var everywhere
  2. Set auth_method='oauth' when the credential is an OAuth/bearer token
  3. Confirm base_url matches the GitLab instance the token belongs to
  4. Call client.test_connection() at startup to fail fast

Example fix

# before: OAuth token sent via the default Private-Token header -> 401
gitlab_config = {"project": "mygroup/myrepo", "access_token": oauth_token}

# after
gitlab_config = {
    "project": "mygroup/myrepo",
    "access_token": oauth_token,
    "auth_method": "oauth",
}
Defensive patterns

Strategy: validation

Validate before calling

# Preflight credentials before any prompt fetch
if not client.test_connection():
    raise RuntimeError(
        "GitLab authentication failed - check access_token, "
        "auth_method (token vs oauth), and base_url"
    )

Type guard

from typing import Any


def looks_like_oauth_token(token: Any) -> bool:
    """Heuristic: OAuth/job tokens usually carry a dot; PATs do not."""
    t = str(token or "")
    return "." in t and not t.startswith("glpat-")

Try / catch

try:
    content = client.get_file_content("prompts/greet.prompt")
except Exception as e:
    if "Authentication failed" in str(e):
        raise RuntimeError(
            "GitLab token rejected - rotate it and verify auth_method"
        ) from e
    raise

Prevention

When it happens

Trigger: Expired or revoked PAT; token copied with whitespace or a typo; OAuth token used while auth_method stays 'token'; CI job token used against a different instance; token issued for a different base_url (self-hosted vs gitlab.com).

Common situations: Rotated tokens not propagated to every service; stale env vars in CI runners; migrating from PAT to OAuth without flipping auth_method; mixing tokens between a self-hosted instance and gitlab.com.

Understand the failure class

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/c8adce079f382b92. Report an issue: GitHub.

Appendix: source

Thrown at litellm/integrations/gitlab/gitlab_client.py:149

            ctype: Final = (resp.headers.get("content-type") or "").lower()
            if ctype.startswith("text/") or "charset=" in ctype or ctype.startswith("application/json"):
                return resp.text
            try:
                return resp.content.decode("utf-8")
            except Exception:
                return resp.content.decode("utf-8", errors="replace")

        except Exception as e:
            status: Final = getattr(getattr(e, "response", None), "status_code", None)
            if status == 404:
                return None
            if status == 403:
                raise Exception(
                    f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'."
                )
            if status == 401:
                raise Exception("Authentication failed. Check your GitLab token and auth_method.")
            raise Exception(f"Failed to fetch file '{file_path}': {e}")

    def _get_file_content_via_json(self, file_path: str, *, ref: str | None = None) -> str | None:
        """
        Fallback for get_file_content(): use the JSON file API which returns base64 content.
        """
        json_url: Final = self._file_json_url(file_path, ref=ref)
        try:
            resp: Final = self.http_handler.get(json_url, headers=self.headers)
            if resp.status_code == 404:
                return None
            resp.raise_for_status()
            data: Final = resp.json()
            content: Final = data.get("content")
            encoding: Final = data.get("encoding", "")
            if content and encoding == "base64":
                try:
                    return base64.b64decode(content).decode("utf-8")

View on GitHub (pinned to 77b7c6c40c)