Auth token is not sent when the configured host includes a port

Abierto
#326 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

  • #332 de @nanami7777777 — cerrado sin fusionar
  • #333 de @draarivpatel-ui — cerrado sin fusionar

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
58/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
github, go

Línea de trabajo

Start in pkg/api/http_client.go at headerRoundTripper.RoundTrip and the TestNewHTTPClient table. Compare how the request host is checked against a configured host with a port, then add coverage for a matching port and a different port. Done means the matching request carries Authorization while the request to another port does not; the issue reports an earlier PR was closed without explanation.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Bug

When ClientOptions.Host includes a port (for example GH_HOST=127.0.0.1:8443, or a GitHub Enterprise Server instance on a non-standard port), clients built with api.NewRESTClient / api.NewGraphQLClient never send the Authorization header. The token is found, because client construction doesn't fail with "authentication token not found", but the header round tripper drops it on every request. The server answers 401.

gh itself sends the token in the same environment. So gh api … works while every extension built on go-gh fails on the same endpoint. We hit it with github/gh-stack v0.3.0, which is built on go-gh v2.16.2. I checked the code in v2.16.2 and v2.17.0, and the comparison looks the same as far back as v2.4.0.

Cause

pkg/api/http_client.go, headerRoundTripper.RoundTrip:

requestHost := req.URL.Hostname()
if k == authorization {
    isAPIHost := hrt.apiHost != "" && strings.EqualFold(requestHost, hrt.apiHost)
    if !isSameDomain(requestHost, hrt.host) && !isAPIHost {
        continue
    }
}

req.URL.Hostname() strips the port, but hrt.host is the configured host with its port. For Host: "127.0.0.1:8443" the comparison is "127.0.0.1" == "127.0.0.1:8443", which is always false, so the header is skipped. APIHost can't work around it, because it must be a bare hostname without a port.

Steps to reproduce

This needs no network and no real token. A small server on a local socket file logs whether each request carried Authorization. The socket is only there to observe the requests without setting up TLS. go-gh sends plain HTTP over http_unix_socket even for https URLs. The bug is the same over TCP: we first saw it as a 401 from a TLS server at 127.0.0.1:8443.

Needs gh, python3, and any go-gh-based extension. This uses gh-stack: gh extension install github/gh-stack.

set -eu
work=$(mktemp -d) && cd "$work"
mkdir ghcfg repo && cd repo
git init -q && git commit -q --allow-empty -m init

cat > ../server.py <<'PY'
import json, os, socket, sys, threading
path = sys.argv[1]
if os.path.exists(path): os.unlink(path)
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); srv.bind(path); srv.listen(16)
def serve(c):
    data = b""
    while b"\r\n\r\n" not in data:
        chunk = c.recv(4096)
        if not chunk: break
        data += chunk
    head = data.split(b"\r\n\r\n", 1)[0].decode().split("\r\n")
    hdrs = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in head[1:])}
    print(json.dumps({"request": head[0], "host": hdrs.get("host"),
                      "authorization_sent": "authorization" in hdrs,
                      "user_agent": hdrs.get("user-agent")}), flush=True)
    body = b"[]" if "/stacks" in head[0] else b'{"full_name":"OWNER/REPO"}'
    c.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" % len(body) + body)
    c.close()
while True:
    c, _ = srv.accept(); threading.Thread(target=serve, args=(c,), daemon=True).start()
PY

python3 ../server.py p.sock & server=$!
sleep 0.5
printf 'http_unix_socket: p.sock\n' > ../ghcfg/config.yml

run() {
  env -i HOME="$HOME" PATH="$PATH" GH_CONFIG_DIR=../ghcfg GH_HOST="$1" \
    GH_ENTERPRISE_TOKEN=dummy GH_REPO=OWNER/REPO GH_PROMPT_DISABLED=1 "${@:2}" </dev/null || true
}

run 127.0.0.1:8443 gh api repos/OWNER/REPO --jq .full_name
run 127.0.0.1:8443 gh stack checkout 999999 --print-path
run example.localhost gh stack checkout 999999 --print-path

kill "$server"
Expected

Every request carries Authorization, because every request targets the configured host.

Actual

With gh 2.103.3 and gh-stack v0.3.0 (go-gh v2.16.2), on macOS. Output trimmed to one request per command:

{"request": "GET /api/v3/repos/OWNER/REPO HTTP/1.1", "host": "127.0.0.1:8443", "authorization_sent": true, "user_agent": "GitHub CLI 2.103.3"}
{"request": "GET /api/v3/repos/OWNER/REPO/stacks?pull_request=999999 HTTP/1.1", "host": "127.0.0.1:8443", "authorization_sent": false, "user_agent": "go-gh"}
{"request": "GET /api/v3/repos/OWNER/REPO/stacks?pull_request=999999 HTTP/1.1", "host": "example.localhost", "authorization_sent": true, "user_agent": "go-gh"}

The gh row confirms the token resolves for a host with a port. The go-gh row with a port gets no header. The same go-gh call against a host without a port gets one.

Suggested fix

When the configured host has a port, compare the request's full authority (host:port) instead of its hostname. That fixes the bug, and the token still isn't sent to a different port on the same machine, which stripping the port from both sides would allow:

requestHost := req.URL.Hostname()
if _, _, err := net.SplitHostPort(hrt.host); err == nil {
    requestHost = req.URL.Host
}

isSameDomain then works unchanged on the authority, subdomain suffix included. The APIHost comparison keeps the bare hostname, since APIHost can't carry a port.

Test cases in the shape of the TestNewHTTPClient table:

{
    name:        "adds authorization for a matching host with a port",
    host:        "test.com:8443",
    reqURL:      "https://test.com:8443/x",
    wantHeaders: defaultHeaders(),
},
{
    name:   "withholds authorization from the same host on another port",
    host:   "test.com:8443",
    reqURL: "https://test.com:9443/x",
    wantHeaders: func() http.Header {
        h := defaultHeaders()
        h.Del(authorization)
        return h
    }(),
},

I opened a PR https://github.com/cli/go-gh/pull/325 to fix this but it was closed without explanation.

Lenguaje dominante
Go
Estrellas
450
Forks
106
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de cli/go-gh

Todos los issues de cli/go-gh

Issues similares

Más issues de Go

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.