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

オープン
#326 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

  • #332 @nanami7777777 による — マージされずにクローズ
  • #333 @draarivpatel-ui による — マージされずにクローズ

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
58/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
github, go

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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.

主要言語
Go
スター
450
フォーク
106
PR マージ指標
30日以内にマージされた PR はありません

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

cli/go-gh のほかの issue

cli/go-gh の issue をすべて見る

似ている issue

Go の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。