feat(api): send the organization ID as an HTTP header

Closes #8737 (closed)

What does this MR do and why?

Lets a user name a GitLab organization, after which every API request glab makes carries the X-Gitlab-Organization-Id header, so a GitLab Cells deployment's HTTP router can route the request.

One source: GITLAB_ORGANIZATION_ID. Unset, no header is sent and behaviour is unchanged.

The value must be the positive integer that identifies a GitLab organization. That is not arbitrary strictness: the Cells HTTP router parses the header with BigInt, and a value it cannot parse is dropped without a Topology Service round-trip and without anything being reported, so a typo would otherwise be invisible end to end. Rejecting it in glab is the only place it surfaces. Restricting the value to digits also keeps a header value from carrying a line break.

Deviation from the issue: no flag, no config key

The issue proposes a --organization_id flag, and earlier revisions of this MR shipped one plus a per-host organization_id config key. Both are gone.

@jay_mccure questioned the flag first: an organization belongs to an instance, so a global flag on every command looked like a lot of surface for something the config key and the environment variable already covered. @viktomas then took it further — ship only the environment variable and add config and flags once there is usage data, rather than guessing now at how people will configure a cell. Adding either later is a two-way door; taking one away is not.

Worth noting where that leaves jay_mccure's original point: he argued per-host config was the natural fit, and what shipped is the opposite, a single value for every host. See the behavioural note below.

The flag was not free, either. It cost two new methods on the cmdutils.Factory interface — so a field and two methods in each of its four implementations — plus a custom pflag.Value to dodge cobra's PersistentPreRunE shadowing (cmdutils.EnableRepoOverride assigns that hook on 80+ command subtrees and cobra runs only the first one it finds, so a hook-based flag is silently ignored by most of the CLI), plus an atomic.Pointer to dodge a self-deadlock against DefaultFactory.mu, plus two regression tests pinning both traps. That was a lot of load-bearing machinery for a value a user sets once per shell and never varies per invocation, and it widened an interface every command depends on.

What is left is 4 files: the header, its validation, its test, and one line of documentation. internal/cmdutils, internal/commands, internal/config/schema.go, cmd/gen-docs and internal/testing/cmdtest are untouched.

One behavioural note: because the variable is not scoped per host, the header goes to every host glab talks to while it is set. That is harmless — a non-Cells GitLab ignores an unknown header — but it is a difference from the per-host config key that was here before.

What the router does with it today

Verified against gitlab-org/cells/http-router (see the verification section below), not just inferred:

  • Only /api/graphql is routed by this header, added in http-router!1297 and sitting above the /api/* glob so it is not swallowed. The GraphQL endpoint is a single path with no routing key in the URL, which is why it needs the header.
  • Every other path falls through to path-based routing or the session/token JSON rule engine, and ignores the header. Confirmed incidentally during the verification below: glab's own /api/v4/usage_data/track_event call matched /api/* and carried no organization claim.
  • When the header is absent, unparseable, or the claim cannot be resolved, the handler falls back to the JSON rule engine, so sending it is purely additive.

Sending the header on every request is therefore forward-compatible and harmless, but today it only changes routing for GraphQL traffic.

Implementation notes

The header is injected in api.NewClientFromConfig, next to the existing X-Gitlab-Duo-Workflow-Id block, and delivered through the existing customHeadersTransport — the outermost RoundTripper wrapper. No new transport was needed, and every outbound path is covered: REST via client-go, GraphQL (only the base URL differs), glab api's raw NewHTTPRequest, CI trace and artifacts, glab stack, the glab cluster graph WebSocket, and the OAuth refresh request. That one construction point is why this is four files rather than forty.

The variable is read with os.Getenv and declared in config.nonSchemaEnvVars, alongside GITLAB_REPO and GITLAB_GROUP, which are env-only for the same reason: with no config-file equivalent there is nothing for KeySchema to resolve, and nonSchemaEnvVars is what gets it into the generated environment variable reference. This is the documented exception to the "no os.Getenv for settings" convention, not a dodge around it.

Deliberate omissions

These are known gaps, not oversights. Each is a candidate follow-up.

  • glab orbit and glab duo cli inherit the variable but may not act on it. Both hand off to a managed binary, which inherits GITLAB_ORGANIZATION_ID from the environment for free, so nothing is needed on glab's side. Whether the Orbit (gitlab-org/orbit/knowledge-graph) and Duo CLI (gitlab-org/editor-extensions/gitlab-lsp) binaries send the header on their own GitLab requests is up to them; both already consume GITLAB_-prefixed input from glab (GITLAB_ORBIT_DISTRIBUTION, GITLAB_DUO_DISTRIBUTION), so the variable name needs no new convention. glab duo ask and glab autoflow go through the API client and are already covered. glab df <pm> forwards to public package registries rather than GitLab, so there is nothing to route.
  • check_update.go's CreateUnauthenticatedClient bypasses NewClientFromConfig to fetch release notes from gitlab.com. Out of scope on purpose.
  • The variable clobbers the same header set another way. glab api -H 'X-GitLab-Organization-ID: 7' and an X-Gitlab-Organization-Id entry in the per-host custom_headers list are both overridden, because customHeadersTransport uses Header.Set. This mirrors the Duo header's documented precedence and is covered by a test. It also means custom_headers remains available as an escape hatch for anyone who needs a per-host organization before a config key exists.

Header name casing

The constant is spelled X-Gitlab-Organization-Id, not X-GitLab-Organization-ID as GitLab's documentation and the router's route table write it. http.Header.Set runs names through textproto.CanonicalMIMEHeaderKey, so this is what actually goes on the wire, and HTTP/2 lowercases everything regardless. Spelling the constant the way it is sent matches the existing X-Gitlab-Duo-Workflow-Id and avoids implying the casing is preserved. A test pins the wire key.

This is safe rather than merely conventional: the router reads the header through Hono's c.req.header(name), which is case-insensitive, and the measurement below confirms all three spellings produce the same claim.

How to set up and validate locally

make lint
make test-changed

Verified against the Cells HTTP router

Run the router from the GDK checkout against the GDK Topology Service, following the recipe in http-router!1297:

cd <gdk>/gitlab-http-router
npx wrangler dev -e dev \
  --var "GITLAB_RULES_CONFIG:session_prefix" \
  --var "GITLAB_PROXY_HOST:gdk.test:3000" \
  --var "GITLAB_TOPOLOGY_SERVICE_URL:http://gdk.test:9096" \
  --var "GITLAB_PATH_BASED_ROUTING_MODE:full" \
  --port 8799

Then point glab at it (a host entry with api_protocol: http) and watch the router's decision log. Results from this branch:

Request Router behaviour
X-GitLab-Organization-ID: 123, X-Gitlab-Organization-Id: 123, x-gitlab-organization-id: 123 All three produced a Classify call with the identical body hash, so all three parsed to the same organization_id claim — the canonicalized casing glab sends is accepted
GITLAB_ORGANIZATION_ID=4242 glab api graphql -f query='{__typename}' Matched the /api/graphql route and produced its own Classify call, carrying the claim from glab's header
X-Gitlab-Organization-Id: my-org No Classify call at all — the claim is dropped locally and silently. This is what motivated the integer validation
No header No Classify call; straight to the session/token rule engine, behaviour unchanged

Classification returns 404 because the organization IDs used do not exist in a local GDK, and the proxy then 502s because Rails is not reachable at gdk.test:3000 from workerd. Neither affects what is being verified: that the header is read and turned into the right claim.

End to end, with GLAB_DEBUG_HTTP=1 showing the header as actually sent (debugTransport sits inside customHeadersTransport):

GITLAB_ORGANIZATION_ID=42 GLAB_DEBUG_HTTP=1 glab api /version 2>&1 | grep -i organization
# => X-Gitlab-Organization-Id: 42

GLAB_DEBUG_HTTP=1 glab api /version 2>&1 | grep -ci organization
# => 0, unset sends nothing

GITLAB_ORGANIZATION_ID=my-org glab api /version
# => invalid GITLAB_ORGANIZATION_ID "my-org": it must be the positive integer
#    that identifies a GitLab organization

🤖 Generated with Claude Code

Edited by Rutger Wessels

Merge request reports

Loading
Loading