beads/internal/creds/command_test.go
ecuthiell 4e804885dd
test(credentials): make remaining credential-command fixtures native-Windows portable (#5748) (#5749)
* test(credentials): make command fixtures Windows-portable (#5748)

Replace POSIX-only credential test commands with a shared shell-portable protocol, exercise their intended failure and non-invocation semantics on native Windows, and add the focused required CI selector.

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* test(ci): require each Windows credential fixture to pass

Include the standalone credentialcmd protocol test in the existing Windows
step. One package/test map drives both selection and exact terminal checks,
so missing, skipped, failed, or duplicate tests cannot report success.
Resolve native Go once and reuse it for the test invocation.

Bead: saa-cgh.66
Agent-Signature: unknown-model/unknown-reasoning

* test(ci): select the first Go application on PATH

Hosted Windows images can expose more than one Go application. Preserve
setup-go's PATH precedence, select one absolute application and reuse it.

Bead: saa-cgh.66
Agent-Signature: unknown-model/unknown-reasoning

* chore(bazel): sync BUILD.bazel srcs for the new credentialcmd test helper

Base landed the Bazel PR gates (#6881/#6887) after this PR was authored, so
the PR's new internal/testutil/credentialcmd package and internal/creds
testmain_test.go were never enumerated in any BUILD.bazel. Two already
enumerated test srcs (internal/creds/command_test.go and
internal/storage/dolt/gateway_credential_test.go) import the new package, so
`bazel build //internal/creds:all` fails GoCompilePkg without this.

Generated by `make bazel-sync` (gazelle); a second sync is a no-op. The
internal/storage/dolt version_staging_completeness_test.go srcs row is
pre-existing base drift that gazelle corrects in the same pass, not PR content.

* test(credentialcmd): pin the Windows gate's assertions and stop claiming foreign helpers

Maintainer review fixes for PR #5749, adoption iteration 1. The synthesis is
`approve` with no required changes; all four findings are minor or nit. A
maintainer bazel commit already exists on this branch, so the push was owed
regardless and none of these cost anything extra. No production code changes.

F1 — the new required Windows gate pinned its own wiring but almost none of its
assertions. The guard checked three package paths and one test name, so it
stayed green if someone dropped six of the nine test names from $expected,
deleted the `Action -in 'fail', 'skip'` throw, or deleted the exactly-one-PASS
loop -- leaving a required gate whose only real guarantee was "go test exited
0", which a fully skipped suite also satisfies. The pinned slice now carries all
nine test names plus both load-bearing guard tokens, keeping the file's existing
substring idiom.

F2 — the property the fixture exists for was unassertable end to end. Emit is
written to produce byte-exact stdout across sh and the Windows .cmd trampoline,
but parseCredential runs bytes.TrimSpace before every comparison, so every
existing assertion is blind to a trailing newline: a trampoline changed to
`echo %OUT%` would keep the whole suite green. TestCommandSourceRealShell now
wraps the existing credRunner package seam to capture the helper's stdout as the
shell produced it, and asserts it byte-exact. The real shell stays in the loop,
so this remains end-to-end rather than becoming a second in-process test.

F3 — Dispatch claimed any process where BEADS_TEST_CREDENTIAL_COMMAND_HELPER=1,
on the env alone and before inspecting argv, exiting 97 when the sentinel was
absent. command() arms that variable in the *parent* process and BEADS_-prefixed
variables reach every re-exec'd child through the integration allowlist, so the
first composition with a package that re-execs its own test binary -- which
internal/storage/dolt already does -- would have died with a wrong-subsystem
"missing protocol sentinel". Both gates are now required, and an env-armed
process without the sentinel falls through to its own TestMain.

The second half of that finding's prescription is deliberately NOT applied.
Adding BEADS_TEST_CREDENTIAL_COMMAND_HELPER to helperSubprocessSentinels reds
TestHelperSubprocessSentinelsAreComplete: that guard has a reverse-direction
control, and its regex looks for a literal os.Getenv("BEADS_..._HELPER") in
internal/storage/dolt's own test sources. This sentinel is read in
internal/testutil/credentialcmd, so the entry registers as a stale one. Measured,
not assumed -- the failure is "helperSubprocessSentinels lists
BEADS_TEST_CREDENTIAL_COMMAND_HELPER, but no test source reads it". With the
Dispatch gate fixed the entry also buys nothing: a dolt helper child already
carries its own sentinel, so isHelperSubprocess is true for it either way.

F4 — the exported constructors documented themselves as "returns a unique shell
command" while replacing PATH for the rest of the calling test, setting env vars
via t.Setenv (which bans t.Parallel), and silently rejecting an empty payload.
The shared contract is now stated once above the three of them, and Emit fails
fast with an explanation instead of letting the shell drop the empty payload
word and the helper exit 97. No caller passes an empty payload today.

Each fix was checked by reverting it and confirming its own pin reddens: the
dropped test name reds the guard by name; the trailing-newline wrong
implementation reds the new raw-stdout assertion while the sibling end-to-end
test stays green, which is the blindness the finding described; and reverting
the Dispatch gate reproduces `(97, true)`. `make bazel-sync` is a no-op -- every
edit landed in a file already enumerated in srcs.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:30:25 -07:00

173 lines
6.2 KiB
Go

package creds
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/testutil/credentialcmd"
)
func TestParseCredential(t *testing.T) {
cases := []struct {
name string
in string
wantTok string
wantUser string
wantExp bool // expect a non-zero expiry
wantErr bool
}{
{"bare token (JWT-shaped)", "eyJhbGciOiJSUzI1NiJ9.eyJvIjoib18xIn0.sig\n", "eyJhbGciOiJSUzI1NiJ9.eyJvIjoib18xIn0.sig", "", false, false},
{"execcredential token+exp", `{"token":"abc","expirationTimestamp":"2099-01-02T15:04:05Z"}`, "abc", "", true, false},
{"OAuth access_token+expires_in", `{"access_token":"xyz","expires_in":90,"token_type":"Bearer"}`, "xyz", "", true, false},
{"vault dynamic user+pass pair", `{"username":"v-app-beads-xyz","password":"s3cr3t","expires_in":3600}`, "", "", true, true}, // token/access_token absent -> error
{"pair via access_token+username", `{"access_token":"pw","username":"dynuser","expires_in":900}`, "pw", "dynuser", true, false},
{"json without token", `{"foo":"bar"}`, "", "", false, true},
{"unparseable json", `{not json`, "", "", false, true},
{"empty output", " \n", "", "", false, true},
{"bare with whitespace (error message)", "access denied: nope", "", "", false, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
tok, user, exp, err := parseCredential([]byte(c.in))
if c.wantErr {
if err == nil {
t.Fatalf("expected error, got token=%q", tok)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tok != c.wantTok {
t.Fatalf("token = %q, want %q", tok, c.wantTok)
}
if user != c.wantUser {
t.Fatalf("username = %q, want %q", user, c.wantUser)
}
if c.wantExp && exp.IsZero() {
t.Fatal("expected a non-zero expiry")
}
if !c.wantExp && !exp.IsZero() {
t.Fatalf("expected zero expiry, got %v", exp)
}
})
}
}
// resetCache isolates the process-level command cache and runner for a test.
func resetCache(t *testing.T) {
t.Helper()
credCacheMu.Lock()
credCache = map[string]cachedCred{}
credCacheMu.Unlock()
orig := credRunner
t.Cleanup(func() { credRunner = orig })
}
// resolveCredentialToken caches by command until near expiry, then re-runs the helper.
func TestResolveCredentialTokenCachesUntilExpiry(t *testing.T) {
resetCache(t)
var calls int
credRunner = func(_ context.Context, _ string) ([]byte, error) {
calls++
// Long-lived expiry so the cache holds across the second call.
return []byte(fmt.Sprintf(`{"token":"tok-%d","expirationTimestamp":%q}`, calls,
time.Now().Add(time.Hour).Format(time.RFC3339))), nil
}
tok1, _, _, err := resolveCredentialToken(context.Background(), "helper --x")
if err != nil {
t.Fatalf("first resolve: %v", err)
}
tok2, _, _, err := resolveCredentialToken(context.Background(), "helper --x")
if err != nil {
t.Fatalf("second resolve: %v", err)
}
if tok1 != tok2 || calls != 1 {
t.Fatalf("expected one cached helper call, got calls=%d tok1=%q tok2=%q", calls, tok1, tok2)
}
// A different command is a different cache key -> a fresh run.
if _, _, _, err := resolveCredentialToken(context.Background(), "helper --y"); err != nil {
t.Fatalf("third resolve: %v", err)
}
if calls != 2 {
t.Fatalf("expected a fresh run for a new command, got calls=%d", calls)
}
}
func TestResolveCredentialTokenPropagatesHelperError(t *testing.T) {
resetCache(t)
credRunner = func(_ context.Context, _ string) ([]byte, error) {
return nil, fmt.Errorf("boom")
}
if _, _, _, err := resolveCredentialToken(context.Background(), "broken-helper"); err == nil {
t.Fatal("expected an error when the helper fails")
}
}
// A real shell command flows end-to-end through CommandSource (no stub), proving the
// platform shell runner and the bare-token path work together.
func TestCommandSourceRealShell(t *testing.T) {
resetCache(t)
// Capture the helper's stdout as the shell actually produced it. The whole
// reason Emit exists rather than an echo-style emitter is byte-exact stdout
// across sh and the Windows .cmd trampoline — but parseCredential runs
// bytes.TrimSpace before every comparison (command.go), so every assertion
// on cred.Value is blind to a trailing "\r\n". Without the capture below,
// a trampoline changed to `echo %OUT%` would keep this test green while
// silently breaking the property the fixture was built for. Wrapping the
// existing package seam keeps the real shell in the loop instead of
// replacing it, so this stays an end-to-end assertion.
var rawStdout []byte
origRunner := credRunner
t.Cleanup(func() { credRunner = origRunner })
credRunner = func(ctx context.Context, command string) ([]byte, error) {
out, err := origRunner(ctx, command)
rawStdout = append([]byte(nil), out...)
return out, err
}
src := CommandSource{Command: credentialcmd.Emit(t, "s3cr3t"), Kind: KindSecret, Label: "TEST_CMD"}
cred, ok, err := src.Resolve(context.Background())
if err != nil || !ok {
t.Fatalf("resolve: ok=%v err=%v", ok, err)
}
if string(rawStdout) != "s3cr3t" {
t.Fatalf("helper raw stdout = %q, want exactly %q: the fixture must emit the payload with no "+
"trailing newline on either shell, and parseCredential's TrimSpace hides any that appears", rawStdout, "s3cr3t")
}
if cred.Value != "s3cr3t" {
t.Fatalf("value = %q, want s3cr3t", cred.Value)
}
if cred.Kind != KindSecret {
t.Fatalf("kind = %v, want KindSecret", cred.Kind)
}
if cred.Source != "TEST_CMD" {
t.Fatalf("source = %q, want TEST_CMD", cred.Source)
}
}
func TestCredentialCommandFixtureProtocol(t *testing.T) {
resetCache(t)
marker := filepath.Join(t.TempDir(), "marker path with spaces")
src := CommandSource{Command: credentialcmd.Marker(t, marker), Kind: KindSecret, Label: "TEST_MARKER"}
_, ok, err := src.Resolve(context.Background())
if !ok || err == nil || !strings.Contains(err.Error(), "credential command produced no output") {
t.Fatalf("marker resolve: ok=%v err=%v, want configured empty-output error", ok, err)
}
got, err := os.ReadFile(marker)
if err != nil {
t.Fatalf("read credential command marker: %v", err)
}
if string(got) != "invoked" {
t.Fatalf("credential command marker = %q, want invoked", got)
}
}