← Back to Pull requests

korg: add userinfo command for org and OWNERS lookup #6398

Open
palnabarun opened this pull request with 1360 lines diff across 5 files
View on GitHub
palnabarun palnabarun commented on May 24, 2026 11:33 UTC
Author

Adds korg userinfo <user>... to answer the recurring question this repo
exists for: which Kubernetes orgs is a user in, with what role, and where
do they appear in OWNERS files.

Sources:

  • GitHub user API for company / profile

  • config/<org>/org.yaml (Members / Admins) for k8s org membership

  • cs.k8s.io (hound) for OWNERS / OWNERS_ALIASES references
  • Behavior:

  • Honors GITHUB_TOKEN / GH_TOKEN to avoid the 60/hr unauth limit. GitHub

  • and hound use separate http.Client instances, so the token is never
    sent to cs.k8s.io
  • Per-request context with a 30s timeout; SIGINT cancels in flight

  • Multi-user batches run concurrently (errgroup, bounded to 4) with

  • output preserved in input order
  • One bad username does not kill the batch; per-user errors render in

  • both text and JSON output, and the process exits non-zero
  • Hound failures degrade to a warning instead of dropping org info

  • --output json for scripting
  • OWNERS matching:

  • Anchors the hound query on "- <user>" and keeps a hit only when the

  • YAML list item equals the username exactly, so prose mentions,
    commented-out entries and substring near-misses ("- alice-bot" for
    "alice") are all dropped. Surrounding quotes and trailing inline
    comments are stripped first, so - "alice" and "- alice # area expert"
    still match
  • Each surviving hit is confirmed against the file's real content via

  • gh api to exclude emeritus-only entries, toggled by --verify-owners.
    A hit that cannot be fetched is kept with a warning rather than dropped
  • Results render as an aligned REPO / PATH / URL table; the URL uses

  • /blob/HEAD/ so the link resolves to the default branch

    Tests:

  • Table-driven coverage of the OWNERS match filter (quoted values, inline

  • comments, commented-out entries, substring near-misses), emeritus
    exclusion, and the fail-open path when a hit cannot be verified
  • Batch coverage for both output modes: input ordering, mixed

  • success/failure runs, and the text renderer's company / orgs fallbacks
  • Asserts hound requests carry no Authorization header while GitHub

  • requests stay authenticated

    Dependencies:

  • adds github.com/google/go-github/v88 for the user API

  • promotes golang.org/x/sync from indirect v0.2.0 to direct v0.8.0 for

  • errgroup
  • go directive 1.22.4 -> 1.25.0
  • (This PR has gotten assistance from AI tools)

    Diff: 1360 lines (+1352 / -8) across 5 files Reviewer: Priyankasaggu11929 Review duration: 250136m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.56) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 1360 lines diff across 5 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    41 items
    k8s-ci-robot k8s-ci-robot commented on May 24, 2026 11:33 UTC
    Contributor

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes/org/pull/6398#" title="Author self-approved">palnabarun</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [palnabarun]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    palnabarun palnabarun commented on May 24, 2026 11:33 UTC
    Author

    /assign @kubernetes/owners

    Priyankasaggu11929 Priyankasaggu11929 commented on code on Jun 08, 2026 06:17 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    Priyankasaggu11929 Priyankasaggu11929 commented on code on Jun 08, 2026 06:17 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)

    should we do a search for "- " + username instead of just username?

    since OWNERS entries are always YAML list items

    Priyankasaggu11929 Priyankasaggu11929 commented on code on Jun 08, 2026 06:17 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")

    let's include OWNERS_ALIASES as well

    since that defines named groups (e.g. sig-foo-approvers) which are referenced in OWNERS files

    Priyankasaggu11929 Priyankasaggu11929 commented on code on Jun 08, 2026 06:18 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})

    can we add a check here to skip lines starting with # in the result before appending them to out?

    because commented out usernames also will show up as valid hit right now

    Also -

    (since we already have the repo + file path from hound)
    could we fetch the actual OWNERS file from GitHub and parse which section the username falls under? because someone in emeritus_approvers/emeritus_reviewers isn't valid

    it will add 1-2 extra API calls maybe but since its supposed to be used locally on a handful of users at a time, it think that should be ok

    Priyankasaggu11929 Priyankasaggu11929 commented on code on Jun 08, 2026 06:18 UTC
    Code Review
    cmd/korg/userinfo_test.go:1
    @@ -0,0 +1,286 @@
    +/*
    +Copyright 2026 The Kubernetes Authors.
    Priyankasaggu11929 Priyankasaggu11929 requested changes on Jun 08, 2026 06:18 UTC
    Changes Requested Reviewer

    Thank you, @palnabarun!

    left a few inline comments.

    cblecker cblecker commented on code on Jun 08, 2026 18:01 UTC
    Code Review
    go.mod:1
    @@ -1,89 +1,97 @@
     module k8s.io/org
     
    -go 1.22.4
    +go 1.25.8
     
     require (
     	github.com/bmatcuk/doublestar v1.3.4
    -	github.com/go-git/go-git/v5 v5.6.1
    -	github.com/hound-search/hound v0.7.1
    +	github.com/go-git/go-git/v5 v5.19.0
    +	github.com/google/go-github/v88 v88.0.0
    +	github.com/hound-search/hound v0.6.0
     	github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5
    -	github.com/sirupsen/logrus v1.9.0
    -	github.com/spf13/cobra v1.7.0
    -	k8s.io/apimachinery v0.27.4
    -	sigs.k8s.io/prow v0.0.0-20240418142548-4c9d8ca1213d
    -	sigs.k8s.io/yaml v1.5.0
    +	github.com/sirupsen/logrus v1.9.3
    +	github.com/spf13/cobra v1.10.2
    +	golang.org/x/sync v0.20.0
    +	k8s.io/apimachinery v0.33.11
    +	k8s.io/test-infra v0.0.0-20191222193732-de81526abe72

    I'm not sure what happened here, but you're pulling in a whole bunch of new/different stuff that seems unrelated, for example, the test-infra repo?

    cblecker cblecker commented on code on Jun 08, 2026 18:01 UTC
    Code Review
    go.mod:1
    @@ -1,89 +1,97 @@
     module k8s.io/org
     
    -go 1.22.4
    +go 1.25.8
     
     require (
     	github.com/bmatcuk/doublestar v1.3.4
    -	github.com/go-git/go-git/v5 v5.6.1
    -	github.com/hound-search/hound v0.7.1
    +	github.com/go-git/go-git/v5 v5.19.0
    +	github.com/google/go-github/v88 v88.0.0
    +	github.com/hound-search/hound v0.6.0
     	github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5
    -	github.com/sirupsen/logrus v1.9.0
    -	github.com/spf13/cobra v1.7.0
    -	k8s.io/apimachinery v0.27.4
    -	sigs.k8s.io/prow v0.0.0-20240418142548-4c9d8ca1213d
    -	sigs.k8s.io/yaml v1.5.0
    +	github.com/sirupsen/logrus v1.9.3
    +	github.com/spf13/cobra v1.10.2
    +	golang.org/x/sync v0.20.0
    +	k8s.io/apimachinery v0.33.11
    +	k8s.io/test-infra v0.0.0-20191222193732-de81526abe72
    +	sigs.k8s.io/prow v0.0.0-20260519230345-32fe11af9437
    +	sigs.k8s.io/yaml v1.6.0
     )
     
    -// Pin all k8s.io staging repositories to kubernetes v1.27.4
    +require (
    +	github.com/Microsoft/go-winio v0.6.2 // indirect
    +	github.com/ProtonMail/go-crypto v1.1.6 // indirect
    +	github.com/beorn7/perks v1.0.1 // indirect
    +	github.com/emirpasic/gods v1.18.1 // indirect
    +	github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
    +	github.com/go-git/go-billy/v5 v5.9.0 // indirect
    +	github.com/gomodule/redigo v1.8.5 // indirect
    +	github.com/google/btree v1.1.3 // indirect
    +	github.com/google/go-querystring v1.2.0 // indirect
    +	github.com/gregjones/httpcache v0.0.0-20190212212710-3befbb6ad0cc // indirect
    +	github.com/inconshreveable/mousetrap v1.1.0 // indirect
    +	github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
    +	github.com/kevinburke/ssh_config v1.2.0 // indirect
    +	github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
    +	github.com/prometheus/client_golang v1.22.0 // indirect
    +	github.com/prometheus/client_model v0.6.2 // indirect
    +	github.com/prometheus/common v0.62.0 // indirect
    +	github.com/prometheus/procfs v0.15.1 // indirect
    +	github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
    +	github.com/shurcooL/githubv4 v0.0.0-20210725200734-83ba7b4c9228 // indirect
    +	github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f // indirect
    +	github.com/spf13/pflag v1.0.9 // indirect
    +	github.com/xanzy/ssh-agent v0.3.3 // indirect
    +	golang.org/x/crypto v0.50.0 // indirect
    +	golang.org/x/net v0.53.0 // indirect
    +	golang.org/x/oauth2 v0.34.0 // indirect
    +	golang.org/x/sys v0.43.0 // indirect
    +	gopkg.in/warnings.v0 v0.1.2 // indirect
    +)
    +
    +// Pin all k8s.io staging repositories to kubernetes-1.15.3.

    This isn't accurate?

    cblecker cblecker commented on code on Jun 08, 2026 18:38 UTC
    Code Review
    cmd/korg/korg.go:1
    @@ -222,7 +235,29 @@ func main() {
     	rootCmd.AddCommand(removeCmd)
     	rootCmd.AddCommand(auditCmd)
     
    -	if err := rootCmd.Execute(); err != nil {
    +	var outputFormat string
    +	userInfoCmd := &cobra.Command{
    +		Use:   "userinfo",
    +		Short: "Get information about user(s)",
    +		Long:  userinfoHelpText,
    +		Args:  cobra.MinimumNArgs(1),
    +		RunE: func(cmd *cobra.Command, args []string) error {
    +			switch outputFormat {
    +			case "text", "json":
    +			default:
    +				return fmt.Errorf("invalid --output %q (want: text, json)", outputFormat)
    +			}
    +			return runUserinfo(cmd.Context(), o.RepoRoot, args, outputFormat == "json", cmd.OutOrStdout())
    +		},
    +	}
    +	userInfoCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "output format: text|json")
    +	rootCmd.AddCommand(userInfoCmd)
    +
    +	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    +	defer stop()
    +
    +	if err := rootCmd.ExecuteContext(ctx); err != nil {
    +		fmt.Fprintln(os.Stderr, "error:", err)

    Cobra already prints command errors to stderr by default, so this line will double-print every error. Either drop it to preserve the previous behavior, or set rootCmd.SilenceErrors = true before ExecuteContext if you want to own the formatting yourself.

    cblecker cblecker commented on code on Jun 08, 2026 18:38 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")

    ctx isn't used anywhere in this function — it only reads env vars and constructs a client. Either drop it from the signature or use _ if you're planning to need it later.

    cblecker cblecker commented on code on Jun 08, 2026 18:38 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}
    +	gh, err := newGitHubClient(ctx, hc)
    +	if err != nil {
    +		return fmt.Errorf("building github client: %w", err)
    +	}
    +
    +	results := make([]*UserDetails, len(usernames))
    +	errs := make([]error, len(usernames))
    +
    +	g, gctx := errgroup.WithContext(ctx)
    +	g.SetLimit(userinfoConcurrency)
    +	for i, name := range usernames {
    +		i, name := i, name
    +		g.Go(func() error {

    This loop-variable capture was needed before Go 1.22, but since the module is already at 1.22+ (and this PR bumps it further), loop variables are per-iteration by default. This line can be removed.

    cblecker cblecker commented on code on Jun 08, 2026 18:38 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}
    +	gh, err := newGitHubClient(ctx, hc)
    +	if err != nil {
    +		return fmt.Errorf("building github client: %w", err)
    +	}
    +
    +	results := make([]*UserDetails, len(usernames))
    +	errs := make([]error, len(usernames))
    +
    +	g, gctx := errgroup.WithContext(ctx)
    +	g.SetLimit(userinfoConcurrency)
    +	for i, name := range usernames {
    +		i, name := i, name
    +		g.Go(func() error {
    +			info, err := findUserDetails(gctx, gh, hc, configs, name)
    +			if err != nil {
    +				errs[i] = err
    +				return nil
    +			}
    +			results[i] = info
    +			return nil
    +		})
    +	}
    +	_ = g.Wait()
    +

    Since the goroutines always return nil today, discarding the Wait() return is technically safe — but it's a maintenance trap. If someone later changes a goroutine to return a real error, it'll vanish silently. A small guard makes the invariant explicit:

    if err := g.Wait(); err != nil {
        return fmt.Errorf("unexpected errgroup error: %w", err)
    }
    

    cblecker cblecker commented on code on Jun 08, 2026 18:38 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}
    +	gh, err := newGitHubClient(ctx, hc)
    +	if err != nil {
    +		return fmt.Errorf("building github client: %w", err)
    +	}
    +
    +	results := make([]*UserDetails, len(usernames))
    +	errs := make([]error, len(usernames))
    +
    +	g, gctx := errgroup.WithContext(ctx)
    +	g.SetLimit(userinfoConcurrency)
    +	for i, name := range usernames {
    +		i, name := i, name
    +		g.Go(func() error {
    +			info, err := findUserDetails(gctx, gh, hc, configs, name)
    +			if err != nil {
    +				errs[i] = err
    +				return nil
    +			}
    +			results[i] = info
    +			return nil
    +		})
    +	}
    +	_ = g.Wait()
    +
    +	if outputJSON {
    +		clean := make([]*UserDetails, 0, len(results))

    When a user lookup fails in JSON mode, that user is silently dropped from the output array. A script parsing stdout will get fewer results than expected, with no structured way to tell which lookups failed or why. Text mode handles this well (it renders an ERROR: block inline), but JSON consumers have to correlate via exit code alone.

    Worth either including an error entry in the array (e.g. {"username":"ghost","error":"..."}) or at least documenting in the help text that JSON mode omits failures and callers should check the exit code.

    cblecker cblecker commented on Jun 08, 2026 18:43 UTC
    Reviewer

    Nice addition — this fills a genuine gap and the overall structure is solid. The errgroup concurrency pattern is correct, Hound failures degrade gracefully, and it's good to see tests land alongside the new code. A few things worth addressing before this merges, mostly around the JSON output dropping failed users and a double-print in main(). The go.mod changes are covered separately.

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Jul 03, 2026 08:57 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes/org/pull/6398#" title="Author self-approved">palnabarun</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [palnabarun]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    palnabarun palnabarun commented on code on Jul 03, 2026 09:23 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.

    I will fix this in a separate PR. There are more changes to do to support this.

    palnabarun palnabarun commented on code on Jul 03, 2026 09:23 UTC
    Code Review
    cmd/korg/userinfo_test.go:1
    @@ -0,0 +1,286 @@
    +/*
    +Copyright 2026 The Kubernetes Authors.

    I will fix this in a separate PR. There are more changes to do to support this.

    palnabarun palnabarun commented on Jul 03, 2026 09:24 UTC
    Author

    @Priyankasaggu11929 @cblecker PTAL again. Thank you. 🙏🏽

    palnabarun palnabarun commented on code on Jul 03, 2026 10:25 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    palnabarun palnabarun commented on code on Jul 03, 2026 10:25 UTC
    Code Review
    cmd/korg/userinfo_test.go:1
    @@ -0,0 +1,286 @@
    +/*
    +Copyright 2026 The Kubernetes Authors.
    cblecker cblecker commented on code on Jul 03, 2026 22:59 UTC
    Code Review
    cmd/korg/userinfo_test.go:1

    The batch path is the most complex control flow here but only gets tested with single-user inputs. A mixed-batch test (e.g. ["alice", "ghost", "bob"] where ghost 404s) would exercise both branches of the JSON assembly loop in a single call and catch ordering / nil-dereference regressions.

    cblecker cblecker commented on code on Jul 03, 2026 22:59 UTC
    Code Review
    cmd/korg/userinfo_test.go:1

    Text mode is the default output but has no test coverage -- all runUserinfo tests pass outputJSON=true. A TestRunUserinfoText that checks for the === username header, Company: line, Orgs: section, and tabwriter table would guard against formatting regressions in renderText.

    cblecker cblecker commented on code on Jul 03, 2026 23:00 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}
    +	gh, err := newGitHubClient(ctx, hc)
    +	if err != nil {
    +		return fmt.Errorf("building github client: %w", err)
    +	}
    +
    +	results := make([]*UserDetails, len(usernames))
    +	errs := make([]error, len(usernames))
    +
    +	g, gctx := errgroup.WithContext(ctx)
    +	g.SetLimit(userinfoConcurrency)
    +	for i, name := range usernames {
    +		i, name := i, name
    +		g.Go(func() error {
    +			info, err := findUserDetails(gctx, gh, hc, configs, name)
    +			if err != nil {
    +				errs[i] = err
    +				return nil
    +			}
    +			results[i] = info
    +			return nil
    +		})
    +	}
    +	_ = g.Wait()
    +
    +	if outputJSON {
    +		clean := make([]*UserDetails, 0, len(results))

    +1 on the error-entry design. One thing worth hardening: the else branch on line 409 calls errs[i].Error() without checking that errs[i] is non-nil. Today findUserDetails always returns either (non-nil, nil) or (nil, error), so the invariant holds -- but if it's ever refactored to return (nil, nil), this panics. A nil guard (else if errs[i] != nil { ... } else { ... "unknown error" }) would make this robust for free.

    cblecker cblecker commented on code on Jul 03, 2026 23:00 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)

    The "- " prefix was a good fix. One edge: since hound does substring matching, "- alice" also hits lines containing "- alicexyz" or "- alice-bot". With --verify-owners=true (the default) this is filtered out by the YAML parse, but with --verify-owners=false those false positives pass through. Could tighten hasUncommentedMatch to also check the trimmed line after "- " matches the username exactly -- or just document this as a known limitation of the unverified mode.

    palnabarun palnabarun commented on Jul 06, 2026 03:20 UTC
    Author

    @cblecker addressed all four: nil-guard on the JSON error entry, tightened the "- <user>" match to require an exact username (not just substring) after the dash, and added tests for the mixed-batch case and the default text-mode renderer. PTAL 🙏🏽

    cblecker cblecker commented on code on Jul 07, 2026 05:33 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,441 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"sort"
    +	"strings"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	houndindex "github.com/hound-search/hound/index"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +	"sigs.k8s.io/yaml"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +	Error      string          `json:"error,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +// When verifyOwners is true, each OWNERS hit is additionally confirmed against the file's actual
    +// content (via the gh CLI) to exclude emeritus-only entries; this costs one gh api call per hit.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string, verifyOwners bool) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	hits, err := searchOwnerFiles(ctx, hc, username)
    +	switch {
    +	case err != nil:
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	case !verifyOwners:
    +		info.OwnerFiles = hits
    +	default:
    +		info.OwnerFiles = make([]OwnerFile, 0, len(hits))
    +		for _, hit := range hits {
    +			content, err := fetchOwnerFileContent(ctx, hit.Repo, hit.Path)
    +			if err != nil {
    +				// Fail open: we can't confirm the hit, but hound already found it, so keep it.
    +				info.Warnings = append(info.Warnings, fmt.Sprintf("could not verify %s/%s: %v", hit.Repo, hit.Path, err))
    +				info.OwnerFiles = append(info.OwnerFiles, hit)
    +				continue
    +			}
    +			if isActiveOwner(content, hit.Path, username) {
    +				info.OwnerFiles = append(info.OwnerFiles, hit)
    +			}
    +		}
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	// OWNERS/OWNERS_ALIASES entries are always YAML list items, so anchor the
    +	// search on "- <username>" to skip files that merely mention the name in
    +	// prose or as a substring of another username.
    +	q.Set("q", "- "+username)
    +	q.Set("literal", "true")
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS(_ALIASES)?")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			if !hasRealMatch(fm.Matches, username) {
    +				continue
    +			}
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// hasRealMatch reports whether any hit line is an uncommented YAML list item whose
    +// value is exactly username, rather than a comment or a substring match like
    +// "- alice-bot" or "- alicexyz" (hound's search is substring-based, so those also
    +// match a query for "- alice").
    +func hasRealMatch(matches []*houndindex.Match, username string) bool {
    +	for _, m := range matches {
    +		line := strings.TrimSpace(m.Line)
    +		rest, ok := strings.CutPrefix(line, "-")
    +		if !ok {
    +			continue
    +		}
    +		rest = strings.Trim(strings.TrimSpace(rest), `"'`)
    +		if strings.EqualFold(rest, username) {
    +			return true
    +		}
    +	}
    +	return false
    +}
    +
    +// ownersFileContent models the fields of an OWNERS file relevant to deciding
    +// whether a username is a current (non-emeritus) approver or reviewer.
    +type ownersFileContent struct {
    +	Approvers         []string                    `json:"approvers,omitempty"`
    +	Reviewers         []string                    `json:"reviewers,omitempty"`
    +	EmeritusApprovers []string                    `json:"emeritus_approvers,omitempty"`
    +	EmeritusReviewers []string                    `json:"emeritus_reviewers,omitempty"`
    +	Filters           map[string]ownersFilterRule `json:"filters,omitempty"`
    +}
    +
    +type ownersFilterRule struct {
    +	Approvers []string `json:"approvers,omitempty"`
    +	Reviewers []string `json:"reviewers,omitempty"`
    +}
    +
    +// ownersAliasesContent models an OWNERS_ALIASES file.
    +type ownersAliasesContent struct {
    +	Aliases map[string][]string `json:"aliases,omitempty"`
    +}
    +
    +// runGHCLI invokes the gh CLI and returns its stdout. Overridden in tests.
    +var runGHCLI = func(ctx context.Context, args ...string) ([]byte, error) {
    +	cmd := exec.CommandContext(ctx, "gh", args...)
    +	var stdout, stderr bytes.Buffer
    +	cmd.Stdout = &stdout
    +	cmd.Stderr = &stderr
    +	if err := cmd.Run(); err != nil {
    +		return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String()))
    +	}
    +	return stdout.Bytes(), nil
    +}
    +
    +// fetchOwnerFileContent fetches the raw contents of an OWNERS or OWNERS_ALIASES file at repo HEAD
    +// via the gh CLI, so it reuses the caller's existing `gh auth login` session.
    +func fetchOwnerFileContent(ctx context.Context, repo, path string) ([]byte, error) {
    +	endpoint := fmt.Sprintf("repos/%s/contents/%s", repo, escapeGitHubPath(path))
    +	return runGHCLI(ctx, "api", endpoint, "-H", "Accept: application/vnd.github.raw")
    +}
    +
    +// escapeGitHubPath percent-encodes each path segment while preserving "/" separators.
    +func escapeGitHubPath(path string) string {
    +	parts := strings.Split(path, "/")
    +	for i, p := range parts {
    +		parts[i] = url.PathEscape(p)
    +	}
    +	return strings.Join(parts, "/")
    +}
    +
    +// isActiveOwner reports whether username is a current (non-emeritus) approver,
    +// reviewer, or alias member per the given OWNERS/OWNERS_ALIASES file content.
    +// It fails open (returns true) if content can't be parsed, since hound already
    +// found the hit and we'd rather over- than under-report.
    +func isActiveOwner(content []byte, path, username string) bool {
    +	if filepath.Base(path) == "OWNERS_ALIASES" {
    +		var a ownersAliasesContent
    +		if err := yaml.Unmarshal(content, &a); err != nil {
    +			return true
    +		}
    +		for _, members := range a.Aliases {
    +			if stringInSliceCaseAgnostic(members, username) {
    +				return true
    +			}
    +		}
    +		return false
    +	}
    +
    +	var o ownersFileContent
    +	if err := yaml.Unmarshal(content, &o); err != nil {
    +		return true
    +	}
    +	if stringInSliceCaseAgnostic(o.Approvers, username) || stringInSliceCaseAgnostic(o.Reviewers, username) {
    +		return true
    +	}
    +	for _, f := range o.Filters {
    +		if stringInSliceCaseAgnostic(f.Approvers, username) || stringInSliceCaseAgnostic(f.Reviewers, username) {
    +			return true
    +		}
    +	}
    +	return false
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON, verifyOwners bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}

    The hc client is shared between newGitHubClient and searchOwnerFiles. The go-github library mutates the provided http.Client's Transport in-place to inject Authorization: Bearer <token> headers. After newGitHubClient(hc) returns, every subsequent hc.Do(req) — including hound requests to cs.k8s.io — sends the GitHub token.

    Fix: use separate http.Client instances for GitHub API and hound requests.

    cblecker cblecker commented on code on Jul 07, 2026 05:33 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,441 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"sort"
    +	"strings"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	houndindex "github.com/hound-search/hound/index"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +	"sigs.k8s.io/yaml"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +	Error      string          `json:"error,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +// When verifyOwners is true, each OWNERS hit is additionally confirmed against the file's actual
    +// content (via the gh CLI) to exclude emeritus-only entries; this costs one gh api call per hit.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string, verifyOwners bool) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	hits, err := searchOwnerFiles(ctx, hc, username)
    +	switch {
    +	case err != nil:
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	case !verifyOwners:
    +		info.OwnerFiles = hits
    +	default:
    +		info.OwnerFiles = make([]OwnerFile, 0, len(hits))
    +		for _, hit := range hits {
    +			content, err := fetchOwnerFileContent(ctx, hit.Repo, hit.Path)

    The fail-open behavior here (keep the hit + add a warning when verification fails) is a deliberate design choice, but no test exercises it. If someone refactored this to drop unverifiable hits, no test would break.

    Consider adding a subtest where stubGHCLI returns an error for one of two hits, then assert both hits are preserved and a warning is emitted.

    cblecker cblecker requested changes on Jul 07, 2026 05:34 UTC
    Changes Requested Reviewer

    Requested changes.

    cblecker cblecker commented on code on Jul 07, 2026 05:34 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)

    Following up on the matching improvements — hasRealMatch strips quotes via strings.Trim(rest, "\"'"), but no test exercises quoted YAML values like - "alice" or - 'alice'. A dedicated TestHasRealMatch table-driven test would cover this and provide a clearer safety net for future changes to the filtering logic.

    cblecker cblecker commented on code on Jul 07, 2026 05:35 UTC
    Code Review
    cmd/korg/userinfo_test.go:1

    TestRunUserinfoText covers the happy path now. A few edge branches in text mode are still untested: the ERROR block (lines 433-435), the Company: Not Found fallback for empty company, and the (none) display for empty orgs. A mixed-batch text test (similar to TestRunUserinfoJSONMixedBatch but with outputJSON=false) would close the gap.

    cblecker cblecker commented on code on Jul 07, 2026 05:35 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)

    One more edge case: YAML inline comments like - alice # area expert would fail the EqualFold check because the comment text is included in the comparison. Stripping inline comments before the equality check would handle this: if idx := strings.Index(rest, "#"); idx >= 0 { rest = strings.TrimSpace(rest[:idx]) }. Unlikely in practice since OWNERS files rarely use inline comments, but it's a silent false negative if it does.

    cblecker cblecker commented on code on Jul 07, 2026 05:36 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2023 The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"sort"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	files, err := searchOwnerFiles(ctx, hc, username)
    +	if err != nil {
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	} else {
    +		info.OwnerFiles = files
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	q.Set("q", username)
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")
    +	q.Set("files", "OWNERS")
    +	q.Set("excludeFiles", "vendor/")
    +	q.Set("i", "true")
    +	q.Set("stats", "true")
    +
    +	req, err := http.NewRequestWithContext(ctx, http.MethodGet, houndURL()+"?"+q.Encode(), nil)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	resp, err := hc.Do(req)
    +	if err != nil {
    +		return nil, err
    +	}
    +	defer resp.Body.Close()
    +
    +	if resp.StatusCode/100 != 2 {
    +		snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
    +		return nil, fmt.Errorf("hound %s: %s", resp.Status, bytes.TrimSpace(snippet))
    +	}
    +
    +	body, err := io.ReadAll(resp.Body)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var r houndclient.Response
    +	if err := json.Unmarshal(body, &r); err != nil {
    +		return nil, fmt.Errorf("decoding hound response: %w", err)
    +	}
    +
    +	out := []OwnerFile{}
    +	for repo, matches := range r.Results {
    +		if matches == nil {
    +			continue
    +		}
    +		for _, fm := range matches.Matches {
    +			out = append(out, OwnerFile{
    +				Repo: repo,
    +				Path: fm.Filename,
    +				URL:  ownerFileURL(repo, fm.Filename),
    +			})
    +		}
    +	}
    +	sort.Slice(out, func(i, j int) bool {
    +		if out[i].Repo != out[j].Repo {
    +			return out[i].Repo < out[j].Repo
    +		}
    +		return out[i].Path < out[j].Path
    +	})
    +	return out, nil
    +}
    +
    +// renderText writes a human-readable form of UserDetails to w.
    +func (u *UserDetails) renderText(w io.Writer) {
    +	fmt.Fprintf(w, "\n=== %s\n", u.Username)
    +	if u.Company != "" {
    +		fmt.Fprintln(w, "Company:", u.Company)
    +	} else {
    +		fmt.Fprintln(w, "Company: **Not Found**")
    +	}
    +
    +	fmt.Fprintln(w, "Orgs:")
    +	if len(u.Orgs) == 0 {
    +		fmt.Fprintln(w, "  (none)")
    +	}
    +	for _, m := range u.Orgs {
    +		fmt.Fprintf(w, "  %s (%s)\n", m.Org, m.Role)
    +	}
    +
    +	if len(u.OwnerFiles) > 0 {
    +		fmt.Fprintln(w, "Owner Files:")
    +		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    +		fmt.Fprintln(tw, "  REPO\tPATH\tURL")
    +		for _, of := range u.OwnerFiles {
    +			fmt.Fprintf(tw, "  %s\t%s\t%s\n", of.Repo, of.Path, of.URL)
    +		}
    +		tw.Flush()
    +	}
    +
    +	for _, warn := range u.Warnings {
    +		fmt.Fprintln(w, "Warning:", warn)
    +	}
    +}
    +
    +// newGitHubClient returns a GitHub client authenticated via GITHUB_TOKEN or GH_TOKEN if set.
    +func newGitHubClient(ctx context.Context, httpClient *http.Client) (*github.Client, error) {
    +	token := os.Getenv("GITHUB_TOKEN")
    +	if token == "" {
    +		token = os.Getenv("GH_TOKEN")
    +	}
    +	opts := []github.ClientOptionsFunc{}
    +	if httpClient != nil {
    +		opts = append(opts, github.WithHTTPClient(httpClient))
    +	}
    +	if token != "" {
    +		opts = append(opts, github.WithAuthToken(token))
    +	}
    +	if ghBaseURLOverride != "" {
    +		opts = append(opts, github.WithEnterpriseURLs(ghBaseURLOverride, ghBaseURLOverride))
    +	}
    +	return github.NewClient(opts...)
    +}
    +
    +// runUserinfo fetches info for every username concurrently and writes ordered output to w.
    +// Returns a joined error of all per-user failures; users without errors still render.
    +func runUserinfo(ctx context.Context, repoRoot string, usernames []string, outputJSON bool, w io.Writer) error {
    +	configs, err := loadOrgConfigs(repoRoot, validOrgs)
    +	if err != nil {
    +		return err
    +	}
    +
    +	hc := &http.Client{Timeout: defaultHTTPTimeout}
    +	gh, err := newGitHubClient(ctx, hc)
    +	if err != nil {
    +		return fmt.Errorf("building github client: %w", err)
    +	}
    +
    +	results := make([]*UserDetails, len(usernames))
    +	errs := make([]error, len(usernames))
    +
    +	g, gctx := errgroup.WithContext(ctx)
    +	g.SetLimit(userinfoConcurrency)
    +	for i, name := range usernames {
    +		i, name := i, name
    +		g.Go(func() error {
    +			info, err := findUserDetails(gctx, gh, hc, configs, name)
    +			if err != nil {
    +				errs[i] = err
    +				return nil
    +			}
    +			results[i] = info
    +			return nil
    +		})
    +	}
    +	_ = g.Wait()
    +
    +	if outputJSON {
    +		clean := make([]*UserDetails, 0, len(results))

    The JSON mode now has a defensive default: "unknown error" handler for the (nil, nil) case. Text mode (lines 429-437) uses two independent if-checks with no fallback, so a user with both values nil would be silently omitted. Adding a parallel fallback in text mode would maintain parity.

    palnabarun palnabarun commented on Aug 04, 2026 09:12 UTC
    Author

    /test pull-org-verify-all

    cblecker cblecker commented on code on Aug 10, 2026 20:19 UTC
    Code Review
    cmd/korg/userinfo_test.go:1
    @@ -0,0 +1,824 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"fmt"
    +	"net/http"
    +	"net/http/httptest"
    +	"net/url"
    +	"os"
    +	"path/filepath"
    +	"reflect"
    +	"strings"
    +	"testing"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndindex "github.com/hound-search/hound/index"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +)
    +
    +// stubGHCLI overrides runGHCLI for the duration of t, restoring it on cleanup.
    +func stubGHCLI(t *testing.T, fn func(ctx context.Context, args ...string) ([]byte, error)) {
    +	t.Helper()
    +	orig := runGHCLI
    +	runGHCLI = fn
    +	t.Cleanup(func() { runGHCLI = orig })
    +}
    +
    +func TestFindOrgMembership(t *testing.T) {
    +	configs := map[string]*org.Config{
    +		"kubernetes": {
    +			Members: []string{"alice", "BOB"},
    +			Admins:  []string{"carol"},
    +		},
    +		"kubernetes-sigs": {
    +			Members: []string{"bob"},
    +			Admins:  []string{"alice"},
    +		},
    +		"kubernetes-csi": {},
    +	}
    +
    +	cases := map[string][]OrgMembership{
    +		"alice":  {{Org: "kubernetes", Role: "member"}, {Org: "kubernetes-sigs", Role: "admin"}},
    +		"bob":    {{Org: "kubernetes", Role: "member"}, {Org: "kubernetes-sigs", Role: "member"}},
    +		"BoB":    {{Org: "kubernetes", Role: "member"}, {Org: "kubernetes-sigs", Role: "member"}},
    +		"carol":  {{Org: "kubernetes", Role: "admin"}},
    +		"nobody": {},
    +	}
    +
    +	for user, want := range cases {
    +		got := findOrgMembership(configs, user)
    +		if !reflect.DeepEqual(got, want) {
    +			t.Errorf("user %q: got %+v, want %+v", user, got, want)
    +		}
    +	}
    +}
    +
    +func TestLoadOrgConfigs(t *testing.T) {
    +	root := t.TempDir()
    +	for _, name := range []string{"kubernetes", "kubernetes-sigs"} {
    +		dir := filepath.Join(root, "config", name)
    +		if err := os.MkdirAll(dir, 0o755); err != nil {
    +			t.Fatal(err)
    +		}
    +		yaml := fmt.Sprintf("members:\n- user-%s\nadmins:\n- admin-%s\n", name, name)
    +		if err := os.WriteFile(filepath.Join(dir, "org.yaml"), []byte(yaml), 0o644); err != nil {
    +			t.Fatal(err)
    +		}
    +	}
    +
    +	configs, err := loadOrgConfigs(root, []string{"kubernetes", "kubernetes-sigs"})
    +	if err != nil {
    +		t.Fatalf("loadOrgConfigs: %v", err)
    +	}
    +	if got := configs["kubernetes"].Members[0]; got != "user-kubernetes" {
    +		t.Errorf("kubernetes member: got %q", got)
    +	}
    +	if got := configs["kubernetes-sigs"].Admins[0]; got != "admin-kubernetes-sigs" {
    +		t.Errorf("kubernetes-sigs admin: got %q", got)
    +	}
    +
    +	if _, err := loadOrgConfigs(root, []string{"kubernetes-csi"}); err == nil {
    +		t.Error("expected error for missing org config")
    +	}
    +}
    +
    +func TestSearchOwnerFiles(t *testing.T) {
    +	const happyBody = `{
    +		"Results": {
    +			"kubernetes/kubernetes": {
    +				"Matches": [
    +					{"Filename": "OWNERS", "Matches": [{"Line": "  - alice", "LineNumber": 3}]},
    +					{"Filename": "pkg/foo/OWNERS", "Matches": [{"Line": "  - alice", "LineNumber": 5}]},
    +					{"Filename": "commented/OWNERS", "Matches": [{"Line": "  # - alice", "LineNumber": 2}]},
    +					{"Filename": "substring/OWNERS", "Matches": [{"Line": "  - alice-bot", "LineNumber": 7}]}
    +				]
    +			}
    +		}
    +	}`
    +
    +	tests := []struct {
    +		name     string
    +		status   int
    +		body     string
    +		wantErr  bool
    +		wantRepo string
    +		wantLen  int
    +	}{
    +		{name: "happy", status: 200, body: happyBody, wantRepo: "kubernetes/kubernetes", wantLen: 2},
    +		{name: "500", status: 500, body: "boom", wantErr: true},
    +		{name: "bad json", status: 200, body: "not json", wantErr: true},
    +	}
    +
    +	for _, tc := range tests {
    +		t.Run(tc.name, func(t *testing.T) {
    +			var seenURL string
    +			srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    +				seenURL = r.URL.String()
    +				w.WriteHeader(tc.status)
    +				_, _ = w.Write([]byte(tc.body))
    +			}))
    +			defer srv.Close()
    +
    +			origURL := houndSearchURLOverride
    +			houndSearchURLOverride = srv.URL
    +			defer func() { houndSearchURLOverride = origURL }()
    +
    +			out, err := searchOwnerFiles(context.Background(), srv.Client(), "alice")
    +			if tc.wantErr {
    +				if err == nil {
    +					t.Fatal("expected error")
    +				}
    +				return
    +			}
    +			if err != nil {
    +				t.Fatalf("unexpected error: %v", err)
    +			}
    +			parsed, perr := url.Parse(seenURL)
    +			if perr != nil {
    +				t.Fatalf("parsing seen URL: %v", perr)
    +			}
    +			if got := parsed.Query().Get("q"); got != "- alice" {
    +				t.Errorf("query: got %q, want %q", got, "- alice")
    +			}
    +			if got := len(out); got != tc.wantLen {
    +				t.Errorf("got %d entries, want %d", got, tc.wantLen)
    +			}
    +			for _, of := range out {
    +				if of.Repo != tc.wantRepo {
    +					t.Errorf("repo: got %q want %q", of.Repo, tc.wantRepo)
    +				}
    +				wantURL := "https://github.com/" + of.Repo + "/blob/HEAD/" + of.Path
    +				if of.URL != wantURL {
    +					t.Errorf("url: got %q want %q", of.URL, wantURL)
    +				}
    +			}
    +		})
    +	}
    +}
    +
    +func TestHasRealMatch(t *testing.T) {
    +	tests := []struct {
    +		name string
    +		line string
    +		want bool
    +	}{
    +		{name: "plain list item", line: "- alice", want: true},
    +		{name: "indented list item", line: "  - alice", want: true},
    +		{name: "no space after dash", line: "-alice", want: true},
    +		{name: "double quoted", line: `- "alice"`, want: true},
    +		{name: "single quoted", line: "- 'alice'", want: true},
    +		{name: "case insensitive", line: "- ALICE", want: true},
    +		{name: "inline comment", line: "- alice # area expert", want: true},
    +		{name: "quoted with inline comment", line: `- "alice" # area expert`, want: true},
    +		{name: "commented out entry", line: "# - alice", want: false},
    +		{name: "indented commented out entry", line: "  #- alice", want: false},
    +		{name: "substring with suffix", line: "- alice-bot", want: false},
    +		{name: "substring without separator", line: "- alicexyz", want: false},
    +		{name: "quoted substring", line: `- "alice-bot"`, want: false},
    +		{name: "prose mention", line: "alice is an approver", want: false},
    +		{name: "not a list item", line: "approvers: alice", want: false},
    +		{name: "different user", line: "- bob", want: false},
    +	}
    +
    +	for _, tc := range tests {
    +		t.Run(tc.name, func(t *testing.T) {
    +			got := hasRealMatch([]*houndindex.Match{{Line: tc.line}}, "alice")
    +			if got != tc.want {
    +				t.Errorf("hasRealMatch(%q) = %v, want %v", tc.line, got, tc.want)
    +			}
    +		})
    +	}
    +
    +	t.Run("one real match among noise", func(t *testing.T) {
    +		matches := []*houndindex.Match{
    +			{Line: "# - alice"},
    +			{Line: "- alice-bot"},
    +			{Line: "  - alice"},
    +		}
    +		if !hasRealMatch(matches, "alice") {
    +			t.Error("expected a real match to be found among commented and substring lines")
    +		}
    +	})
    +
    +	t.Run("no matches", func(t *testing.T) {
    +		if hasRealMatch(nil, "alice") {
    +			t.Error("expected no match for an empty match list")
    +		}
    +	})
    +}
    +
    +func TestFindUserDetails(t *testing.T) {
    +	stubGHCLI(t, func(ctx context.Context, args ...string) ([]byte, error) {
    +		if len(args) == 4 && args[0] == "api" && args[1] == "repos/k/k/contents/OWNERS" {
    +			return []byte("approvers:\n- alice\n"), nil
    +		}
    +		return nil, fmt.Errorf("unexpected gh invocation: %v", args)
    +	})
    +
    +	ghHits := 0

    nit: ghHits is incremented but never read or asserted on — it's dead code. Either remove it or add an assertion like if ghHits == 0 { t.Error("expected at least one GitHub API call") } to make the intent explicit.

    cblecker cblecker commented on code on Sep 28, 2026 21:34 UTC
    Code Review
    cmd/korg/korg.go:1
    @@ -222,7 +246,32 @@ func main() {
     	rootCmd.AddCommand(removeCmd)
     	rootCmd.AddCommand(auditCmd)
     
    -	if err := rootCmd.Execute(); err != nil {
    +	var (
    +		outputFormat string
    +		verifyOwners bool
    +	)
    +	userInfoCmd := &cobra.Command{
    +		Use:   "userinfo",
    +		Short: "Get information about user(s)",
    +		Long:  userinfoHelpText,
    +		Args:  cobra.MinimumNArgs(1),
    +		RunE: func(cmd *cobra.Command, args []string) error {
    +			switch outputFormat {
    +			case "text", "json":
    +			default:
    +				return fmt.Errorf("invalid --output %q (want: text, json)", outputFormat)
    +			}
    +			return runUserinfo(cmd.Context(), o.RepoRoot, args, outputFormat == "json", verifyOwners, cmd.OutOrStdout())
    +		},
    +	}
    +	userInfoCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "output format: text|json")
    +	userInfoCmd.Flags().BoolVar(&verifyOwners, "verify-owners", true, "confirm each OWNERS/OWNERS_ALIASES hit via the gh CLI and exclude emeritus-only entries; requires gh to be installed and authenticated")
    +	rootCmd.AddCommand(userInfoCmd)
    +
    +	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)

    This signal context is installed for every subcommand, but only userinfo reads cmd.Context(). For add/remove/audit, SIGINT/SIGTERM now cancel a context nothing watches, and since stop() only runs when main returns, repeated Ctrl-C gets swallowed too. audit --check-owners can only be killed with SIGKILL now, and Ctrl-C in the hack/add-members.sh loop no longer stops the loop.

    Can we scope this to userinfo instead? Something like:

    RunE: func(cmd *cobra.Command, args []string) error {
    	// ...
    	ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
    	defer stop()
    	return runUserinfo(ctx, o.RepoRoot, args, outputFormat == "json", verifyOwners, cmd.OutOrStdout())
    },
    

    and go back to plain rootCmd.Execute() here.

    cblecker cblecker commented on code on Sep 28, 2026 21:34 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,463 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"sort"
    +	"strings"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	houndindex "github.com/hound-search/hound/index"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +	"sigs.k8s.io/yaml"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +
    +	// unknownLookupError is reported when a lookup yields neither a result nor an
    +	// error. findUserDetails never returns that combination today; both output modes
    +	// carry the fallback so that if the invariant ever breaks, the user is still
    +	// reported instead of silently disappearing.
    +	unknownLookupError = "unknown error"
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`
    +	OwnerFiles []OwnerFile     `json:"owner_files,omitempty"`
    +	Warnings   []string        `json:"warnings,omitempty"`
    +	Error      string          `json:"error,omitempty"`
    +}
    +
    +// findUserDetails gathers GitHub profile, k8s org membership, and OWNERS file references for a username.
    +// GitHub or k/org config failures are fatal (returned as error). Hound failures are non-fatal warnings.
    +// When verifyOwners is true, each OWNERS hit is additionally confirmed against the file's actual
    +// content (via the gh CLI) to exclude emeritus-only entries; this costs one gh api call per hit.
    +func findUserDetails(ctx context.Context, gh *github.Client, hc *http.Client, configs map[string]*org.Config, username string, verifyOwners bool) (*UserDetails, error) {
    +	info := &UserDetails{Username: username}
    +
    +	u, _, err := gh.Users.Get(ctx, username)
    +	if err != nil {
    +		return nil, fmt.Errorf("github user %q: %w", username, err)
    +	}
    +	if u.Company != nil {
    +		info.Company = *u.Company
    +	}
    +
    +	info.Orgs = findOrgMembership(configs, username)
    +
    +	hits, err := searchOwnerFiles(ctx, hc, username)
    +	switch {
    +	case err != nil:
    +		info.Warnings = append(info.Warnings, fmt.Sprintf("OWNERS lookup failed: %v", err))
    +	case !verifyOwners:
    +		info.OwnerFiles = hits
    +	default:
    +		info.OwnerFiles = make([]OwnerFile, 0, len(hits))
    +		for _, hit := range hits {
    +			content, err := fetchOwnerFileContent(ctx, hit.Repo, hit.Path)
    +			if err != nil {
    +				// Fail open: we can't confirm the hit, but hound already found it, so keep it.
    +				info.Warnings = append(info.Warnings, fmt.Sprintf("could not verify %s/%s: %v", hit.Repo, hit.Path, err))
    +				info.OwnerFiles = append(info.OwnerFiles, hit)
    +				continue
    +			}
    +			if isActiveOwner(content, hit.Path, username) {
    +				info.OwnerFiles = append(info.OwnerFiles, hit)
    +			}
    +		}
    +	}
    +
    +	return info, nil
    +}
    +
    +func findOrgMembership(configs map[string]*org.Config, username string) []OrgMembership {
    +	out := []OrgMembership{}
    +	orgNames := make([]string, 0, len(configs))
    +	for name := range configs {
    +		orgNames = append(orgNames, name)
    +	}
    +	sort.Strings(orgNames)
    +
    +	for _, name := range orgNames {
    +		cfg := configs[name]
    +		switch {
    +		case stringInSliceCaseAgnostic(cfg.Admins, username):
    +			out = append(out, OrgMembership{Org: name, Role: "admin"})
    +		case stringInSliceCaseAgnostic(cfg.Members, username):
    +			out = append(out, OrgMembership{Org: name, Role: "member"})
    +		}
    +	}
    +	return out
    +}
    +
    +func loadOrgConfigs(repoRoot string, orgs []string) (map[string]*org.Config, error) {
    +	out := make(map[string]*org.Config, len(orgs))
    +	for _, name := range orgs {
    +		path := filepath.Join(repoRoot, fmt.Sprintf(orgConfigPathFormat, name))
    +		cfg, err := readConfig(path)
    +		if err != nil {
    +			return nil, fmt.Errorf("loading org config %s: %w", name, err)
    +		}
    +		out[name] = cfg
    +	}
    +	return out, nil
    +}
    +
    +func ownerFileURL(repo, path string) string {
    +	return fmt.Sprintf("https://github.com/%s/blob/HEAD/%s", repo, path)
    +}
    +
    +func searchOwnerFiles(ctx context.Context, hc *http.Client, username string) ([]OwnerFile, error) {
    +	q := url.Values{}
    +	// OWNERS/OWNERS_ALIASES entries are always YAML list items, so anchor the
    +	// search on "- <username>" to skip files that merely mention the name in
    +	// prose or as a substring of another username.
    +	q.Set("q", "- "+username)
    +	q.Set("literal", "true")
    +	q.Set("repos", "*")
    +	q.Set("rng", ":20")

    rng=:20 caps hound at 20 matching files per repo. Those slots are filled before hasRealMatch and emeritus filtering run, so commented-out entries and - alice-bot-style near-misses eat into them. Nothing compares FilesWithMatch against what actually came back, so for long-time approvers in k/k the list is silently incomplete, which is exactly the case this command most needs to get right.

    Either drop the cap or page through with rng offsets. At minimum, add a warning when matches.FilesWithMatch > len(matches.Matches) so the output doesn't look authoritative when it isn't. A test stub that reports more files than it returns would pin it.

    cblecker cblecker commented on code on Sep 28, 2026 21:34 UTC
    Code Review
    cmd/korg/userinfo.go:1
    @@ -0,0 +1,463 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package main
    +
    +import (
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net/http"
    +	"net/url"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"sort"
    +	"strings"
    +	"text/tabwriter"
    +	"time"
    +
    +	"github.com/google/go-github/v88/github"
    +	houndclient "github.com/hound-search/hound/client"
    +	houndindex "github.com/hound-search/hound/index"
    +	"golang.org/x/sync/errgroup"
    +	"sigs.k8s.io/prow/pkg/config/org"
    +	"sigs.k8s.io/yaml"
    +)
    +
    +const (
    +	houndSearchURL      = "https://cs.k8s.io/api/v1/search"
    +	defaultHTTPTimeout  = 30 * time.Second
    +	userinfoConcurrency = 4
    +
    +	// unknownLookupError is reported when a lookup yields neither a result nor an
    +	// error. findUserDetails never returns that combination today; both output modes
    +	// carry the fallback so that if the invariant ever breaks, the user is still
    +	// reported instead of silently disappearing.
    +	unknownLookupError = "unknown error"
    +)
    +
    +// Test-only overrides. Empty means use defaults / api.github.com.
    +var (
    +	houndSearchURLOverride string
    +	ghBaseURLOverride      string
    +)
    +
    +func houndURL() string {
    +	if houndSearchURLOverride != "" {
    +		return houndSearchURLOverride
    +	}
    +	return houndSearchURL
    +}
    +
    +type OrgMembership struct {
    +	Org  string `json:"org"`
    +	Role string `json:"role"` // "member" or "admin"
    +}
    +
    +type OwnerFile struct {
    +	Repo string `json:"repo"`
    +	Path string `json:"path"`
    +	URL  string `json:"url"`
    +}
    +
    +type UserDetails struct {
    +	Username   string          `json:"username"`
    +	Company    string          `json:"company,omitempty"`
    +	Orgs       []OrgMembership `json:"orgs"`

    Orgs has no omitempty, and the error paths leave it nil, so failed users serialize "orgs": null while successes emit []. The help text says error entries only carry username and error, and something like jq '.[].orgs[]' fails on a mixed batch.

    The simplest fix is probably to set Orgs: []OrgMembership{} in the error paths and adjust the help text to match. omitempty would also drop the key for successful users with no orgs. It's also worth pinning this with a raw-JSON assertion, because the current test decodes back into the struct and can't see the difference.

    cblecker cblecker requested changes on Sep 28, 2026 21:35 UTC
    Changes Requested Reviewer

    Thanks for turning around the earlier feedback. The batch/error handling and the token separation look good now.

    Two things I'd like addressed before merge, both inline: the root-level signal handling changes behaviour for the existing subcommands, and the 20-file hound cap silently truncates OWNERS results. The orgs: null one is a quick fix if you're in there anyway.

    The rest I'm happy to see as a follow-up rather than hold this PR for:

  • hound returns search errors as HTTP 200 with {"Error": ...}. houndclient.Response has no field for it, so a failed search looks like "no OWNERS files" instead of producing a warning.

  • after Ctrl-C, the verify loop turns each remaining gh failure into a "could not verify" warning, and the run can still exit 0. Cancellation should be treated as fatal.

  • the gh api subprocess has no deadline (the 30s timeout only covers the http.Clients), so a hung gh stalls the whole batch.

  • isActiveOwner returns true on YAML parse errors without a warning, unlike the fetch-failure path.
  • Nit: ghHits in TestFindUserDetails is still unused.

    Assignees
    palnabarun palnabarun
    Labels
    risk: low confidence: 88.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.9% (MEDIUM) · Higher = larger blast radius
    55.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.6% · Lower = rushed or shallow review
    88.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.4% · Safe to merge
    6.4%
    Repository