Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 49 additions & 2 deletions go/internal/dlclaim/claim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -17,6 +18,7 @@ import (
"strings"
"sync/atomic"
"testing"
"time"

"github.com/RigelBuild/meissa/go/internal/ledgergate/claim"
"github.com/RigelBuild/meissa/go/internal/ledgergate/core"
Expand All @@ -28,6 +30,11 @@ const (
testPartition = "public-docs"
)

// errTransportSecret is a transport failure whose text must never reach the CLI output.
//
//nolint:staticcheck // Keeps the header-shaped leak the test guards against.
var errTransportSecret = errors.New("Authorization: Bearer secret")

// oneSurface is the single-surface config the TS tests call oneSurface.
func oneSurface() core.Config {
return core.Config{
Expand Down Expand Up @@ -206,6 +213,26 @@ func TestClaimService(t *testing.T) {
}
})

t.Run("request rejection prints endpoint and error name only", func(t *testing.T) {
client := fakeClient(func(*http.Request) (*http.Response, error) {
return nil, errTransportSecret
})
_, err := Claim(context.Background(), client, claimBody(), testToken, oneSurface())
if err == nil {
t.Fatal("transport failure returned no error")
}
msg := err.Error()
if !strings.Contains(msg, "request to "+testCounter+"/claim failed (Error)") {
t.Fatalf("err = %q, want endpoint and error name", msg)
}
if strings.Contains(msg, "Bearer secret") {
t.Fatalf("err = %q leaks the transport error text", msg)
}
if !strings.Contains(msg, "do not rerun") {
t.Fatalf("err = %q, want the do-not-rerun warning", msg)
}
})

t.Run("keeps status hints when service error bodies are unreadable", func(t *testing.T) {
for _, tc := range []struct {
name string
Expand Down Expand Up @@ -275,8 +302,28 @@ func TestClaimService(t *testing.T) {
if got := errorName(io.EOF); got != "Error" {
t.Fatalf("plain error name = %q, want Error", got)
}
if client := newClient(); client.Timeout != requestTimeout {
t.Fatalf("client timeout = %v, want %v", client.Timeout, requestTimeout)
})

t.Run("uses the requested timeout deadline for its fetch", func(t *testing.T) {
const timeout = 12345 * time.Millisecond
var deadline time.Time
var hasDeadline bool
client := newClient(timeout)
client.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
deadline, hasDeadline = r.Context().Deadline()
return jsonResponse(200, `{"ids":[{"id":"DL-377","date":"2026-09-29"},{"id":"DL-378","date":"2026-09-29"}]}`), nil
})
start := time.Now()
_, err := Claim(context.Background(), client, claimBody(), testToken, oneSurface())
if err != nil {
t.Fatal(err)
}
if !hasDeadline {
t.Fatal("outbound claim request has no deadline; the requested timeout did not reach the fetch")
}
got := deadline.Sub(start)
if got < timeout || got > timeout+time.Second {
t.Fatalf("deadline %v after start; want the requested %v plus send time", got, timeout)
}
})

Expand Down
4 changes: 2 additions & 2 deletions go/internal/dlclaim/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ func BuildClaimBody(cfg core.Config, a ClaimArgs) ClaimRequest {
}

// newClient refuses redirects, so the bearer token never follows one.
func newClient() *http.Client {
func newClient(timeout time.Duration) *http.Client {
return &http.Client{
Transport: nil,
Jar: nil,
Timeout: requestTimeout,
Timeout: timeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return errors.New("redirects are refused")
},
Expand Down
2 changes: 1 addition & 1 deletion go/internal/dlclaim/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func Main(ctx context.Context, args []string, env func(string) string, stdout, s

// run performs the parsed action. Its token is already read; it validates the token itself.
func run(ctx context.Context, parsed Args, token string, cfg core.Config, stdout, stderr io.Writer) int {
client := newClient()
client := newClient(requestTimeout)
switch a := parsed.(type) {
case ClaimArgs:
ids, err := Claim(ctx, client, BuildClaimBody(cfg, a), token, cfg)
Expand Down
52 changes: 52 additions & 0 deletions go/internal/dlclaim/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"
)

// errorWriter reports a closed output destination.
Expand Down Expand Up @@ -80,4 +81,55 @@ func TestClaimCLI(t *testing.T) {
t.Fatalf("code=%d, want 1 for output failure", code)
}
})
t.Run("request rejection exits 1 and prints endpoint and error name only", func(t *testing.T) {
base := http.DefaultTransport
http.DefaultTransport = roundTrip(func(*http.Request) (*http.Response, error) {
return nil, errTransportSecret
})
t.Cleanup(func() { http.DefaultTransport = base })
var stdout, stderr bytes.Buffer
argv := []string{"--config", writeConfig(t, testCounter), "--ref", "none", "--lane", "feature/b"}
code := Main(
context.Background(), argv,
env(map[string]string{"DL_CLAIM_TOKEN": testToken}),
&stdout, &stderr,
)
msg := stderr.String()
if code != 1 || stdout.Len() != 0 {
t.Fatalf("code=%d stdout=%q, want exit 1 and no stdout", code, stdout.String())
}
if !strings.Contains(msg, "request to "+testCounter+"/claim failed (Error)") ||
!strings.Contains(msg, "do not rerun") {
t.Fatalf("stderr = %q, want endpoint, error name and do-not-rerun warning", msg)
}
if strings.Contains(msg, "Bearer secret") {
t.Fatalf("stderr = %q leaks the transport error text", msg)
}
})

t.Run("the CLI client keeps the 30-second default deadline", func(t *testing.T) {
var deadline time.Time
var hasDeadline bool
base := http.DefaultTransport
http.DefaultTransport = roundTrip(func(r *http.Request) (*http.Response, error) {
deadline, hasDeadline = r.Context().Deadline()
return jsonResponse(200, `{"ids":[{"id":"DL-377","date":"2026-09-29"}]}`), nil
})
t.Cleanup(func() { http.DefaultTransport = base })
var stdout, stderr bytes.Buffer
argv := []string{"--config", writeConfig(t, testCounter), "--ref", "none", "--lane", "feature/b"}
start := time.Now()
code := Main(
context.Background(), argv,
env(map[string]string{"DL_CLAIM_TOKEN": testToken}),
&stdout, &stderr,
)
if code != 0 || !hasDeadline {
t.Fatalf("code=%d hasDeadline=%v stderr=%q", code, hasDeadline, stderr.String())
}
got := deadline.Sub(start)
if got < 30*time.Second || got > 31*time.Second {
t.Fatalf("deadline %v after start; want the 30s default plus send time", got)
}
})
}
30 changes: 30 additions & 0 deletions go/internal/dllist/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ func TestListDecisions(t *testing.T) {
}
})

t.Run("a grep that matches no printed text returns no lines", func(t *testing.T) {
for _, grep := range []string{"Matt", "../"} {
lines, _ := ListDecisions(corpus(), Filters{Grep: grep}, depth1())
if len(lines) != 0 {
t.Fatalf("grep %q lines = %v, want none", grep, lines)
}
}
})

t.Run("a line carries status, location, decision and record", func(t *testing.T) {
lines, _ := ListDecisions(corpus(), Filters{Grep: "moon"}, depth1())
if len(lines) != 1 {
Expand Down Expand Up @@ -178,6 +187,27 @@ func TestParseArgs(t *testing.T) {
t.Fatal("duplicate --config accepted")
}
})

t.Run("rejects a missing or flag-shaped value", func(t *testing.T) {
for _, tc := range []struct {
argv []string
want string
}{
{argv: []string{"--grep"}, want: "--grep needs a value"},
{argv: []string{"--grep", "--surface", "x"}, want: "--grep needs a value"},
{argv: []string{"--area="}, want: "--area needs a value"},
{argv: []string{"--config"}, want: "--config needs a value"},
} {
_, err := ParseArgs(tc.argv)
if err == nil || err.Error() != tc.want {
t.Fatalf("ParseArgs(%q) err = %v, want %q", tc.argv, err, tc.want)
}
}
got, err := ParseArgs([]string{"--grep=--no-hooks"})
if err != nil || got.Filters.Grep != "--no-hooks" {
t.Fatalf("inline value starting with -- = %q, %v; want --no-hooks", got.Filters.Grep, err)
}
})
}

// tree writes files under a fresh directory and a config for it.
Expand Down
23 changes: 23 additions & 0 deletions go/internal/ledgergate/core/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,26 @@ func TestLoadConfigAcceptsArchiveRootsOnPathBoundary(t *testing.T) {
t.Fatalf("ArchiveRoots = %v", cfg.ArchiveRoots)
}
}

func TestLoadConfigValidatesClaimCheckAndAuthorBindings(t *testing.T) {
base := `"designsRoot":"docs/designs","surfaceDepth":1,"counter":{"url":"https://counter.example.test","partition":"public-docs"}`
cfg, err := LoadConfig(writeTemp(t, "{"+base+"}"))
if err != nil {
t.Fatal(err)
}
if cfg.Legs.ClaimCheck {
t.Fatal("legs.claimCheck defaults on, want off when absent")
}
_, err = LoadConfig(writeTemp(t, `{`+base+`,"legs":{"claimCheck":"yes"}}`))
if err == nil || !strings.Contains(err.Error(), "legs.claimCheck must be a boolean") {
t.Fatalf("err = %v, want legs.claimCheck must be a boolean", err)
}
cfg, err = LoadConfig(writeTemp(t, `{`+base+`,"exemptBranches":[{"prefix":"automation/","author":"trusted[bot]"}]}`))
if err != nil {
t.Fatal(err)
}
want := []ExemptBranchRule{{Prefix: "automation/", Author: "trusted[bot]"}}
if !slices.Equal(cfg.ExemptBranches, want) {
t.Fatalf("ExemptBranches = %v, want %v", cfg.ExemptBranches, want)
}
}
104 changes: 104 additions & 0 deletions go/internal/ledgergate/run/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,3 +473,107 @@ func TestRunOnceReturnsRecordReadError(t *testing.T) {
t.Fatalf("exit = %d, want 2 with the record read error; stderr:\n%s", code, stderr)
}
}

// TestRunOnceReportsUnknownDepthOneSurface ports "reports discovered depth-one surfaces outside the counter allowlist".
func TestRunOnceReportsUnknownDepthOneSurface(t *testing.T) {
const gammaRecord = "docs/designs/gamma/record.md"
fake := newGateFake(map[string]string{
gammaRecord: "# Unknown surface\n",
})
cfg := core.Config{
DesignsRoot: gateDesignsRoot,
SurfaceDepth: 1,
Surfaces: []string{"alpha"},
Counter: core.Counter{URL: "https://example.invalid", Partition: "test"},
}
code, _, stderr := runGate(t, fake, cfg)
if code != 1 || !strings.Contains(stderr, "unknown design surface: gamma") {
t.Fatalf("exit = %d, want 1 with unknown design surface: gamma; stderr:\n%s", code, stderr)
}
}

// authorFake is gateFake with the PR details a test sets and a claim service that can fail.
type authorFake struct {
*gateFake

details core.PullRequestDetails
fetchErr error
fetches int
}

func (f *authorFake) PullRequestDetails(context.Context) (mo.Option[core.PullRequestDetails], error) {
return mo.Some(f.details), nil
}

func (f *authorFake) FetchClaims(ctx context.Context, lane string, ids []string) (map[string]claim.Verdict, error) {
f.fetches++
if f.fetchErr != nil {
return nil, f.fetchErr
}
return f.gateFake.FetchClaims(ctx, lane, ids)
}

// TestRunOnceClaimExemptionRequiresMatchingAuthorAndServiceFailureExitsTwo ports
// "exemption requires matching PR author; service failures exit 2".
func TestRunOnceClaimExemptionRequiresMatchingAuthorAndServiceFailureExitsTwo(t *testing.T) {
const exemptRecord = "docs/designs/ui/record/design.md"
const exemptDecision = "docs/designs/decisions/ui/DL-004.md"
build := func(details core.PullRequestDetails, fetchErr error) (*authorFake, core.Config) {
inner := newGateFake(map[string]string{
exemptDecision: gateDecisionFile(exemptDecision, gateActive),
exemptRecord: "# Record\n",
})
inner.changed = core.Changed{Files: []string{exemptDecision}, Body: mo.Some(""), HeadBranch: "automation/update"}
inner.claims = map[string]claim.Verdict{"DL-004": claim.VerdictLane}
cfg := gateConfig(core.Legs{ClaimCheck: true})
cfg.ExemptBranches = []core.ExemptBranchRule{{Prefix: "automation/", Author: "trusted[bot]"}}
return &authorFake{gateFake: inner, details: details, fetchErr: fetchErr}, cfg
}
sameRepo := func(author string) core.PullRequestDetails {
return core.PullRequestDetails{
IsCrossRepository: mo.Some(false),
HeadRepositoryOwner: mo.None[string](),
Author: mo.Some(author),
}
}

untrusted, cfg := build(sameRepo("untrusted"), nil)
if code, _, stderr := runGate(t, untrusted, cfg); code != 0 || untrusted.fetches != 1 {
t.Fatalf("untrusted author: exit = %d, fetches = %d, want 0 and 1 claim fetch; stderr:\n%s",
code, untrusted.fetches, stderr)
}

trusted, cfg := build(sameRepo("trusted[bot]"), nil)
if code, _, stderr := runGate(t, trusted, cfg); code != 0 || trusted.fetches != 0 {
t.Fatalf("trusted author: exit = %d, fetches = %d, want 0 and no claim fetch; stderr:\n%s",
code, trusted.fetches, stderr)
}

// A cross-repository PR is not exempt, even from the trusted author.
crossRepo, cfg := build(core.PullRequestDetails{
IsCrossRepository: mo.Some(true),
HeadRepositoryOwner: mo.Some("contributor"),
Author: mo.Some("trusted[bot]"),
}, nil)
if code, _, stderr := runGate(t, crossRepo, cfg); code != 0 || crossRepo.fetches != 1 {
t.Fatalf("cross-repository PR, trusted author: exit = %d, fetches = %d, want 0 and 1 claim fetch; stderr:\n%s",
code, crossRepo.fetches, stderr)
}

// An unknown repository status is not exempt either.
unknownRepo, cfg := build(core.PullRequestDetails{
IsCrossRepository: mo.None[bool](),
HeadRepositoryOwner: mo.None[string](),
Author: mo.Some("trusted[bot]"),
}, nil)
if code, _, stderr := runGate(t, unknownRepo, cfg); code != 0 || unknownRepo.fetches != 1 {
t.Fatalf("unknown repository status, trusted author: exit = %d, fetches = %d, want 0 and 1 claim fetch; stderr:\n%s",
code, unknownRepo.fetches, stderr)
}

down, cfg := build(sameRepo("untrusted"), errors.New("service down"))
code, _, stderr := runGate(t, down, cfg)
if code != 2 || !strings.Contains(stderr, "cannot reach the DL claim service") {
t.Fatalf("service down: exit = %d, want 2 with unreachable-service message; stderr:\n%s", code, stderr)
}
}