korg: add userinfo command for org and OWNERS lookup #6398
[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:
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":[]} -->
/assign @kubernetes/owners
Copyright The Kubernetes Authors.
per https://github.com/kubernetes/kubernetes/commit/c247514f47f4331b82b9b6ca374b9a7a85690b57
should we do a search for "- " + username instead of just username?
since OWNERS entries are always YAML list items
let's include OWNERS_ALIASES as well
since that defines named groups (e.g. sig-foo-approvers) which are referenced in OWNERS files
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
Copyright The Kubernetes Authors.
per https://github.com/kubernetes/kubernetes/commit/c247514f47f4331b82b9b6ca374b9a7a85690b57
Thank you, @palnabarun!
left a few inline comments.
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?
This isn't accurate?
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.
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.
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.
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)
}
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.
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.
[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:
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":[]} -->
I will fix this in a separate PR. There are more changes to do to support this.
I will fix this in a separate PR. There are more changes to do to support this.
@Priyankasaggu11929 @cblecker PTAL again. Thank you. 🙏🏽
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.
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.
+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.
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.
@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 🙏🏽
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.
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.
Requested changes.
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.
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.
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.
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.
/test pull-org-verify-all
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.
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.
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.
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.
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:
{"Error": ...}. houndclient.Response has no field for it, so a failed search looks like "no OWNERS files" instead of producing a warning.gh failure into a "could not verify" warning, and the run can still exit 0. Cancellation should be treated as fatal.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.
Priyankasaggu11929
palnabarun
Adds
korg userinfo <user>...to answer the recurring question this repoexists for: which Kubernetes orgs is a user in, with what role, and where
do they appear in OWNERS files.
Sources:
Behavior:
and hound use separate http.Client instances, so the token is never
sent to cs.k8s.io
output preserved in input order
both text and JSON output, and the process exits non-zero
--output jsonfor scriptingOWNERS matching:
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
gh apito exclude emeritus-only entries, toggled by --verify-owners.A hit that cannot be fetched is kept with a warning rather than dropped
/blob/HEAD/ so the link resolves to the default branch
Tests:
comments, commented-out entries, substring near-misses), emeritus
exclusion, and the fail-open path when a hit cannot be verified
success/failure runs, and the text renderer's company / orgs fallbacks
requests stay authenticated
Dependencies:
errgroup
(This PR has gotten assistance from AI tools)