From 0b7e3a86b352703907a0e015be877a6573aae9fc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 14 Sep 2026 10:36:29 +0000 Subject: [PATCH] fix(webui): publish per-identity forges so multi-identity task rows keep their links Task rows in a deployment configuring [[identities]] rendered no forge links. ConfigView carried the default identity's forge alone, so resolveForge (api_tasks.go) withheld the links entirely rather than pointing every row at the wrong forge -- production behaviour since the UI process cutover (archie-core-8cda.5.4), where the dashboard runs in a process with no config.Holder. archie-core-ml30 then removed webui.forgeConfigForTask and its test, which resolved a task's forge from config.Config and had no reachable caller once the holder was gone. Fix at the producer, not the renderer. ConfigView gains `identities`: each configured identity's forge type and host, plus the repositories it owns. That is the whole answer to "which forge owns this task", and it is a projection the daemon already rebuilds and republishes on boot and on every reload, so nothing new is needed on the publish side. Only coordinates and repository names cross -- an identity's token is a secret reference and stays out, which the new test asserts alongside the existing leak guard. resolveForge ports the matching rules recovered from c65f9fb's forgeConfigForTask onto that projection: an exact identity name first, then repository ownership, and an ambiguous repository -- two identities claiming the same owner/name -- falling back to the default forge rather than inventing a link. Two deliberate departures from the recovered shape: it indexes the identity list once per request instead of rescanning config per task, since the projection supplies repo slices it can key on directly; and a document that reports multi-identity but carries no per-identity forges still withholds, because that is what an older daemon published and guessing there is the original bug. The recovered code's first-wins scan for a duplicated identity name is preserved. Tests: the projection's per-identity forges and their secret-freedom; the three matching rules and both fallbacks through resolveForge; every row of a multi-identity GET /api/tasks carrying the right forge's link; and the real archie-ui binary driven over HTTP against a multi-identity projection, which fails on the pre-fix resolver with three unlinked rows. --- cmd/archie-ui/main_test.go | 111 ++++++++++++ docs/prds/ui-service-boundary.md | 10 ++ internal/app/archied/config_snapshot_test.go | 54 ++++++ internal/webui/api_config.go | 60 ++++++- internal/webui/api_config_test.go | 73 ++++++++ internal/webui/api_tasks.go | 75 +++++++- internal/webui/api_tasks_test.go | 180 ++++++++++++++++++- 7 files changed, 551 insertions(+), 12 deletions(-) diff --git a/cmd/archie-ui/main_test.go b/cmd/archie-ui/main_test.go index c14e80714..317eb10a0 100644 --- a/cmd/archie-ui/main_test.go +++ b/cmd/archie-ui/main_test.go @@ -451,6 +451,117 @@ func seedStore(t *testing.T, dir string) *store.Store { return st } +// TestUIProcessLinksMultiIdentityTaskRowsToTheirOwningForge drives the real +// binary against a State Store holding a multi-identity deployment's +// projection. Task rows in such a deployment used to render no link at all: +// the projection carried the default identity's forge alone, so the renderer +// withheld rather than pointing every row at the wrong forge +// (archie-core-pv6t). With per-identity forges published, each row is +// attributed to the identity that owns it, by identity name first and repo +// ownership second. +// +// Its own store and process: it publishes a different projection than the +// single-identity smoke test, and republishing over a shared one would rewire +// that test's page underneath it. +func TestUIProcessLinksMultiIdentityTaskRowsToTheirOwningForge(t *testing.T) { + dir := t.TempDir() + st, err := store.Open(t.Context(), filepath.Join(dir, "tasks.sqlite")) + if err != nil { + t.Fatalf("open store: %v", err) + } + t.Cleanup(func() { _ = st.Close() }) + + // One task carrying its identity (name resolves it), one without an + // identity but on a repo only the Gitea identity owns (ownership + // resolves it), and one on a repo both identities claim (ambiguous, so + // it falls back to the default forge). + for _, seed := range []struct { + owner, repo, identity string + number int + }{ + {owner: "acme", repo: "widget", identity: "gitea-bot", number: 7}, + {owner: "beta", repo: "svc", number: 8}, + {owner: "acme", repo: "shared", number: 9}, + } { + if _, err := st.EnqueueIssue(t.Context(), seed.owner, seed.repo, seed.number, "seeded", "body", "", seed.identity); err != nil { + t.Fatalf("seed %s/%s: %v", seed.owner, seed.repo, err) + } + } + + published, err := json.Marshal(webui.ConfigView{ + Identity: webui.IdentityView{BotUser: "archie-bot", ForgeType: "github", ForgeHost: "https://github.example.com"}, + MultiIdentity: true, + Identities: []webui.ForgeIdentityView{ + { + Name: "gitea-bot", ForgeType: "gitea", ForgeHost: "https://gitea.example.com", + Repos: []webui.ForgeRepoView{{Owner: "acme", Name: "widget"}, {Owner: "acme", Name: "shared"}}, + }, + { + Name: "github-bot", ForgeType: "github", ForgeHost: "https://github.example.com", + Repos: []webui.ForgeRepoView{{Owner: "beta", Name: "svc"}, {Owner: "acme", Name: "shared"}}, + }, + }, + }) + if err != nil { + t.Fatal(err) + } + if err := st.PutConfigSnapshot(t.Context(), store.ConfigSnapshot{ + Schema: webui.ConfigViewSchema, Document: published, + }); err != nil { + t.Fatalf("publish config snapshot: %v", err) + } + + stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { + staterpc.RegisterServer(r, staterpc.Deps{ + Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Log: slog.New(slog.DiscardHandler), + }) + }) + defer stopState() + gatewayTarget, stopGateway := serveGRPC(t, func(r grpc.ServiceRegistrar) { + gatewayrpc.RegisterServer(r, &fakeGateway{}) + }) + defer stopGateway() + + ui := startUIProcess(t, buildUIBinary(t, dir), writeUIConfig(t, dir, stateTarget, gatewayTarget)) + d := dashboard{t: t, base: "http://" + ui.addr} + + got := d.get("/api/tasks") + if got.status != http.StatusOK { + t.Fatalf("GET /api/tasks = %d (%s), want 200", got.status, got.body) + } + var rows []struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + RepoURL string `json:"repo_url"` + IssueURL string `json:"issue_url"` + } + if err := json.Unmarshal(got.body, &rows); err != nil { + t.Fatalf("decode task rows: %v (%s)", err, got.body) + } + if len(rows) != 3 { + t.Fatalf("task rows = %d, want the 3 seeded behind the State Store (%s)", len(rows), got.body) + } + + want := map[string]string{ + "acme/widget#7": "https://gitea.example.com/acme/widget/issues/7", + "beta/svc#8": "https://github.example.com/beta/svc/issues/8", + "acme/shared#9": "https://github.example.com/acme/shared/issues/9", + } + for _, row := range rows { + key := fmt.Sprintf("%s/%s#%d", row.Owner, row.Repo, row.IssueNumber) + expected, ok := want[key] + if !ok { + t.Errorf("unexpected row %q (%s)", key, got.body) + continue + } + if row.RepoURL == "" || row.IssueURL != expected { + t.Errorf("row %s links = %q, %q; want %q", key, row.RepoURL, row.IssueURL, expected) + } + } +} + func TestUIProcessServesTheDashboardAgainstLiveDependencies(t *testing.T) { dir := t.TempDir() st := seedStore(t, dir) diff --git a/docs/prds/ui-service-boundary.md b/docs/prds/ui-service-boundary.md index 9895d681c..069b417ea 100644 --- a/docs/prds/ui-service-boundary.md +++ b/docs/prds/ui-service-boundary.md @@ -297,6 +297,16 @@ configured, and both surfaces now read the projection rather than a live holder. The end-to-end suite asserts the checklist renders from the published snapshot. +A third value degraded for the same reason and is closed by +`archie-core-pv6t`: in a deployment configuring `[[identities]]` the projection +carried the default identity's forge alone, so task rows withheld their links +rather than pointing every row at the wrong forge. `ConfigView` now also +publishes each identity's forge coordinates and the repositories it owns +(`identities`), which is what resolving a task to its owning forge needs — +coordinates and repository names only, never a token. The end-to-end suite +drives the real binary against a multi-identity projection and asserts each +row's issue link is built from the forge that owns it. + ## Non-goals and open work This ratification does not define a new domain model, move the dashboard's diff --git a/internal/app/archied/config_snapshot_test.go b/internal/app/archied/config_snapshot_test.go index 1c2fdf39f..a1631b511 100644 --- a/internal/app/archied/config_snapshot_test.go +++ b/internal/app/archied/config_snapshot_test.go @@ -137,6 +137,60 @@ func TestPublishedSnapshotCarriesOverlayOverrides(t *testing.T) { } } +// TestPublishedSnapshotCarriesPerIdentityForges: in a multi-identity +// deployment the task board attributes each task to the forge that owns it, +// and the only process that holds that configuration is the daemon. So the +// published projection has to name every configured identity's forge and the +// repositories it owns (archie-core-pv6t); with the default identity alone, +// every row in such a deployment renders unlinked. +func TestPublishedSnapshotCarriesPerIdentityForges(t *testing.T) { + st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + + b := &boot{ + log: slog.New(slog.DiscardHandler), + stateStore: st, + cfgHolder: config.NewHolder(config.Config{ + BotUser: "archie-bot", + Forge: config.Forge{Type: "github", Host: "https://github.example"}, + Repos: []config.Repo{{Owner: "acme", Name: "widget", Base: "main"}}, + Identities: []config.IdentityConfig{ + { + Name: "gitea-bot", BotUser: "archie-gitea", + Forge: config.Forge{Type: "gitea", Host: "https://gitea.example"}, + Repos: []config.Repo{{Owner: "beta", Name: "svc", Base: "main"}}, + }, + }, + }), + } + b.publishConfigSnapshot(t.Context()) + + snapshot, found, err := st.ConfigSnapshot(context.Background()) + if err != nil || !found { + t.Fatalf("ConfigSnapshot = (found %v, %v), want the published document", found, err) + } + var view webui.ConfigView + if err := json.Unmarshal(snapshot.Document, &view); err != nil { + t.Fatalf("decode published document: %v", err) + } + if !view.MultiIdentity { + t.Error("MultiIdentity = false with a configured identity") + } + if len(view.Identities) != 1 { + t.Fatalf("Identities = %+v, want the configured identity", view.Identities) + } + got := view.Identities[0] + if got.Name != "gitea-bot" || got.ForgeType != "gitea" || got.ForgeHost != "https://gitea.example" { + t.Errorf("Identities[0] = %+v, want the gitea-bot forge coordinates", got) + } + if len(got.Repos) != 1 || got.Repos[0].Owner != "beta" || got.Repos[0].Name != "svc" { + t.Errorf("Identities[0].Repos = %+v, want the repositories it owns", got.Repos) + } +} + // TestPublishConfigSnapshotWithoutConfiguration: called before the daemon has // a configuration Holder, publishing is a no-op rather than a panic. func TestPublishConfigSnapshotWithoutConfiguration(t *testing.T) { diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index d266c5278..f9156e960 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -155,11 +155,18 @@ type ConfigView struct { // is shadowed until reset) and offer a per-row reset. Overridden []string `json:"overridden,omitempty"` // MultiIdentity reports that the deployment configures [[identities]], - // which this projection does not carry: Identity and Repositories - // describe the default identity alone. A consumer that would otherwise - // attribute every task to the published forge uses this to withhold - // rather than guess. + // so Identity and Repositories describe the default identity alone. + // Identities below carries the rest; a consumer attributing a task to + // its forge reads that, and a document that sets this flag without + // carrying them (one published by an older daemon) must withhold the + // links rather than guess. MultiIdentity bool `json:"multi_identity,omitempty"` + // Identities publishes each configured identity's forge and the + // repositories it owns, which is everything a process rendering task + // rows needs to answer "which forge owns this task" -- see + // Server.resolveForge (api_tasks.go). Empty for a single-identity + // deployment, whose forge is Identity above. + Identities []ForgeIdentityView `json:"identities,omitempty"` // Editable reports whether this process can apply configuration // changes. False makes the page render values without edit controls, // which is what a process that only displays a published snapshot can @@ -186,6 +193,26 @@ type IdentityView struct { DiffCapLines int `json:"diff_cap_lines"` } +// ForgeRepoView names one repository an identity owns. Owner and name are +// all a reader needs to attribute a task to the identity that polls it, so +// that is all this carries. +type ForgeRepoView struct { + Owner string `json:"owner"` + Name string `json:"name"` +} + +// ForgeIdentityView is one configured identity's forge coordinates plus the +// repositories it owns. It is deliberately narrower than IdentityView and +// RepoView: the task board needs to locate a repository, not to render the +// configuration page, and an identity's token -- or any of its other +// settings -- must not travel to the browser for either purpose. +type ForgeIdentityView struct { + Name string `json:"name"` + ForgeType string `json:"forge_type"` + ForgeHost string `json:"forge_host"` + Repos []ForgeRepoView `json:"repos,omitempty"` +} + // RepoView is one managed repository and the quality gate it must pass. // Gate and Preflight are shell command argv lists -- test runners and // linters, not secrets -- so they are safe to show verbatim. @@ -351,6 +378,7 @@ func BuildConfigView(in ConfigViewInput) ConfigView { }, Repositories: reposView(cfg.Repos), MultiIdentity: len(cfg.Identities) > 0, + Identities: identityForgesView(cfg.Identities), Models: cfg.Models, Providers: providersView(cfg.Providers), Budgets: BudgetsView{ @@ -516,6 +544,30 @@ func reposView(repos []config.Repo) []RepoView { return out } +// identityForgesView renders each configured identity's forge coordinates and +// the repositories it owns. This is the half of a multi-identity deployment's +// configuration the task board needs: a process that holds no configuration +// answers "which forge owns this task" from here (api_tasks.go's +// resolveForge). Only the coordinates and the repository names cross -- an +// identity's token is a secret reference and must not, and nothing else on +// IdentityConfig is needed to locate a repository. +func identityForgesView(identities []config.IdentityConfig) []ForgeIdentityView { + out := make([]ForgeIdentityView, 0, len(identities)) + for _, id := range identities { + repos := make([]ForgeRepoView, 0, len(id.Repos)) + for _, r := range id.Repos { + repos = append(repos, ForgeRepoView{Owner: r.Owner, Name: r.Name}) + } + out = append(out, ForgeIdentityView{ + Name: id.Name, + ForgeType: id.Forge.Type, + ForgeHost: id.Forge.Host, + Repos: repos, + }) + } + return out +} + func providersView(providers map[string]config.Provider) map[string]ProviderView { out := make(map[string]ProviderView, len(providers)) for name, p := range providers { diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 36759a0a7..576b2efb8 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -93,6 +93,79 @@ func localConfig(srv *Server, cfg *config.Holder) { localView(srv, ConfigViewInput{Config: cfg.Get()}) } +// TestBuildConfigViewPublishesPerIdentityForges: in a multi-identity +// deployment Identity and Repositories describe the default identity alone, +// which is not enough to attribute a task to the forge that owns it. The +// projection publishes each identity's forge coordinates and its repository +// list so a process rendering task rows can resolve per task +// (archie-core-pv6t) -- and, like every other field here, without a token. +func TestBuildConfigViewPublishesPerIdentityForges(t *testing.T) { + cfg := config.Config{ + Forge: config.Forge{Type: "github", Host: "https://github.example"}, + Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, + Identities: []config.IdentityConfig{ + { + Name: "gitea-bot", + Forge: config.Forge{Type: "gitea", Host: "https://gitea.example", Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}}, + Repos: []config.Repo{{Owner: "acme", Name: "gadget"}, {Owner: "beta", Name: "svc"}}, + }, + { + Name: "github-bot", + Forge: config.Forge{Type: "github", Host: "https://github.example", TokenEnv: fakeForgeToken}, + Repos: []config.Repo{{Owner: "beta", Name: "app"}}, + }, + }, + } + + view := BuildConfigView(ConfigViewInput{Config: cfg}) + + if !view.MultiIdentity { + t.Error("MultiIdentity = false with two configured identities; a reader would attribute every task to the default forge") + } + if len(view.Identities) != 2 { + t.Fatalf("Identities = %+v, want both configured identities", view.Identities) + } + gitea := view.Identities[0] + if gitea.Name != "gitea-bot" || gitea.ForgeType != "gitea" || gitea.ForgeHost != "https://gitea.example" { + t.Errorf("Identities[0] = %+v, want the gitea-bot forge coordinates", gitea) + } + if len(gitea.Repos) != 2 || gitea.Repos[0].Owner != "acme" || gitea.Repos[0].Name != "gadget" || gitea.Repos[1].Name != "svc" { + t.Errorf("Identities[0].Repos = %+v, want the repositories it owns (owner and name are what attributing a task needs)", gitea.Repos) + } + if view.Identities[1].Name != "github-bot" || view.Identities[1].ForgeHost != "https://github.example" { + t.Errorf("Identities[1] = %+v, want the github-bot forge coordinates", view.Identities[1]) + } + + // The projection is the browser's copy, so the per-identity forges are a + // new surface for a token to escape through. + body, err := json.Marshal(view) + if err != nil { + t.Fatalf("marshal view: %v", err) + } + for _, leak := range leakCandidates() { + if strings.Contains(string(body), leak) { + t.Errorf("published projection leaked %q; per-identity forges must publish coordinates only, never credentials", leak) + } + } +} + +// TestConfigViewWithoutIdentitiesCarriesNone: a single-identity deployment +// publishes no identity list, and the default identity's forge in Identity +// stays the whole answer. This is the shape every deployment produces today. +func TestConfigViewWithoutIdentitiesCarriesNone(t *testing.T) { + view := BuildConfigView(ConfigViewInput{Config: configWithFakeSecrets().Get()}) + + if view.MultiIdentity { + t.Error("MultiIdentity = true without [[identities]]; the projection would claim a per-identity layout it does not have") + } + if len(view.Identities) != 0 { + t.Errorf("Identities = %+v, want none for a single-identity deployment", view.Identities) + } + if view.Identity.ForgeHost != "gitea.example.com" { + t.Errorf("Identity.ForgeHost = %q, want the deployment's own forge", view.Identity.ForgeHost) + } +} + func TestHandleConfigNeverLeaksSecrets(t *testing.T) { cases := []struct { name string diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index a24d3e9a3..11b8c011e 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -80,18 +80,79 @@ type forgeCoordinates struct { // resolveForge reads the forge layout once for a request and returns each // task's coordinates from it. // -// The projection carries the default identity alone, so where that is not -// the whole picture the links are withheld rather than pointed at the wrong -// forge. Publishing per-identity forges is what a multi-identity dashboard -// needs, and it is a projection change, not a rendering one. +// The projection publishes per-identity forges (ConfigView.Identities), so a +// multi-identity deployment links each task to the forge that owns it. The +// matching rules are the ones recovered from the pre-cutover resolver +// (forgeConfigForTask, 57d9be5): an exact identity name first, then repository +// ownership, and an ambiguous repository -- two identities claiming the same +// owner/name -- falling back to the default forge rather than pointing at +// either. Without this, every row in such a deployment renders unlinked. func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates { unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} } view, ok, err := s.configSource()(ctx) - if err != nil || !ok || view.MultiIdentity { + if err != nil || !ok { return unlinked } - published := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType} - return func(task.Task) forgeCoordinates { return published } + if len(view.Identities) == 0 { + // Nothing per-identity was published. A single-identity deployment's + // one forge is the whole answer. A document that reports identities + // but carries none is one an older daemon published, and there is + // nothing to attribute a task to -- so the links are withheld rather + // than pointed at the wrong forge. + if view.MultiIdentity { + return unlinked + } + published := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType} + return func(task.Task) forgeCoordinates { return published } + } + return forgeLocator(view) +} + +// ownedRepo identifies a repository within an identity's repo list. +type ownedRepo struct{ owner, name string } + +// forgeLocator indexes a published projection's per-identity forges once per +// request and resolves each task against them: exact identity name, then repo +// ownership, with an ambiguous repo falling back to the default forge. +func forgeLocator(view ConfigView) func(task.Task) forgeCoordinates { + fallback := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType} + byName := make(map[string]forgeCoordinates, len(view.Identities)) + byRepo := make(map[ownedRepo]forgeCoordinates) + // ambiguous records a repo two identities both claim, which ownership + // cannot decide -- it is answered by the default forge instead. + ambiguous := make(map[ownedRepo]bool) + for _, identity := range view.Identities { + coords := forgeCoordinates{host: identity.ForgeHost, forgeType: identity.ForgeType} + // First definition of a name wins, as the recovered resolver's + // forward scan did (and as daemon.identityFor still does), so the two + // agree even if a config ever names one identity twice. + if _, seen := byName[identity.Name]; !seen { + byName[identity.Name] = coords + } + for _, repo := range identity.Repos { + key := ownedRepo{owner: repo.Owner, name: repo.Name} + if _, seen := byRepo[key]; seen { + ambiguous[key] = true + continue + } + byRepo[key] = coords + } + } + return func(t task.Task) forgeCoordinates { + if t.Identity != "" { + if coords, ok := byName[t.Identity]; ok { + return coords + } + } + key := ownedRepo{owner: t.Owner, name: t.Repo} + if ambiguous[key] { + return fallback + } + if coords, ok := byRepo[key]; ok { + return coords + } + return fallback + } } func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL string) { diff --git a/internal/webui/api_tasks_test.go b/internal/webui/api_tasks_test.go index 9a88fac14..cb7e949a7 100644 --- a/internal/webui/api_tasks_test.go +++ b/internal/webui/api_tasks_test.go @@ -42,7 +42,10 @@ func TestTaskURLsFallBackToThePublishedProjection(t *testing.T) { wantPR: "https://github.example/acme/widget/pull/34", }, { - name: "multi-identity publishes only the default forge, so links are withheld", + // A document published before the deployment carried per-identity + // forges says so and carries none, so there is nothing to + // attribute this task to. Withholding beats guessing. + name: "a multi-identity document with no per-identity forges is withheld", view: ConfigView{ Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}, MultiIdentity: true, @@ -72,6 +75,181 @@ func TestTaskURLsFallBackToThePublishedProjection(t *testing.T) { } } +// multiIdentityView is a two-forge deployment as the daemon publishes it: the +// default identity on GitHub, and a Gitea identity owning one repository. +func multiIdentityView() ConfigView { + return ConfigView{ + Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}, + MultiIdentity: true, + Identities: []ForgeIdentityView{ + { + Name: "gitea-bot", ForgeType: "gitea", ForgeHost: "https://gitea.example", + Repos: []ForgeRepoView{{Owner: "acme", Name: "widget"}, {Owner: "acme", Name: "shared"}}, + }, + { + Name: "github-bot", ForgeType: "github", ForgeHost: "https://github.example", + Repos: []ForgeRepoView{{Owner: "beta", Name: "svc"}, {Owner: "acme", Name: "shared"}}, + }, + }, + } +} + +// TestResolveForgeMatchesEachTaskToItsOwningIdentity ports the matching rules +// recovered from 57d9be5's forgeConfigForTask onto the published projection: +// exact identity name first, then repository ownership, with an ambiguous +// match falling back to the default forge. Without them every row in a +// multi-identity deployment renders no link at all. +func TestResolveForgeMatchesEachTaskToItsOwningIdentity(t *testing.T) { + srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) { + return multiIdentityView(), true, nil + }} + forge := srv.resolveForge(t.Context()) + + tests := []struct { + name string + task workflow.Task + wantHost string + wantPRPath string + }{ + { + // The name is authoritative even though the identity that owns + // this repo would otherwise claim the task. + name: "exact identity name wins over repo ownership", + task: workflow.Task{Identity: "gitea-bot", Owner: "acme", Repo: "shared", PRNumber: 34}, + wantHost: "https://gitea.example", + wantPRPath: "/pulls/34", + }, + { + name: "repo ownership resolves a task with no identity recorded", + task: workflow.Task{Owner: "beta", Repo: "svc", PRNumber: 7}, + wantHost: "https://github.example", + wantPRPath: "/pull/7", + }, + { + name: "an identity the projection does not carry falls back to repo ownership", + task: workflow.Task{Identity: "retired", Owner: "acme", Repo: "widget", PRNumber: 12}, + wantHost: "https://gitea.example", + wantPRPath: "/pulls/12", + }, + { + // Two identities list acme/shared, so ownership cannot decide. + // Pointing at either would be a wrong link; the default forge is + // the same answer the pre-cutover resolver gave. + name: "an ambiguous repo belongs to the default forge", + task: workflow.Task{Owner: "acme", Repo: "shared", PRNumber: 3}, + wantHost: "https://github.example", + wantPRPath: "/pull/3", + }, + { + name: "no identity owns the repo", + task: workflow.Task{Owner: "other", Repo: "repo", PRNumber: 9}, + wantHost: "https://github.example", + wantPRPath: "/pull/9", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + coords := forge(tc.task) + if coords.host != tc.wantHost { + t.Fatalf("host = %q, want %q", coords.host, tc.wantHost) + } + repoURL, issueURL, prURL := taskURLs(tc.task, coords) + wantRepo := tc.wantHost + "/" + tc.task.Owner + "/" + tc.task.Repo + if repoURL != wantRepo { + t.Errorf("repo URL = %q, want %q", repoURL, wantRepo) + } + if tc.task.IssueNumber > 0 && issueURL == "" { + t.Errorf("issue URL is empty for forge-backed task with issue number %d", tc.task.IssueNumber) + } + if prURL != wantRepo+tc.wantPRPath { + t.Errorf("PR URL = %q, want %q", prURL, wantRepo+tc.wantPRPath) + } + }) + } +} + +// TestResolveForgeWithoutIdentitiesUsesTheDefault: a single-identity +// deployment publishes no identity list, so every task belongs to the one +// forge the projection carries -- exactly what this resolver did before +// per-identity forges were published. +func TestResolveForgeWithoutIdentitiesUsesTheDefault(t *testing.T) { + srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) { + return ConfigView{Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}}, true, nil + }} + forge := srv.resolveForge(t.Context()) + + for _, task := range []workflow.Task{ + {Owner: "acme", Repo: "widget"}, + {Identity: "whatever", Owner: "acme", Repo: "widget"}, + } { + if coords := forge(task); coords.host != "https://github.example" { + t.Errorf("task %+v resolved to forge %q, want the deployment's only forge", task, coords.host) + } + } +} + +// TestHandleTasksLinksEachRowToItsOwningForge proves the fix at the route the +// dashboard actually reads: a multi-identity deployment's task list carries a +// forge link on every row, built from the forge that owns that row. +func TestHandleTasksLinksEachRowToItsOwningForge(t *testing.T) { + base := newTestServer(t) + ctx := t.Context() + if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 12, "gitea work", "", "", "gitea-bot"); err != nil { + t.Fatal(err) + } + if _, err := base.Store.EnqueueIssue(ctx, "beta", "svc", 7, "github work", "", "", "github-bot"); err != nil { + t.Fatal(err) + } + tasks, err := base.Store.Tasks(ctx, 10) + if err != nil || len(tasks) != 2 { + t.Fatalf("seeded tasks = %d (%v), want 2", len(tasks), err) + } + for i := range tasks { + tasks[i].PRNumber = tasks[i].IssueNumber + if err := base.Store.Update(ctx, &tasks[i]); err != nil { + t.Fatal(err) + } + } + + srv := &Server{ + Store: base.Store, + Log: base.Log, + ConfigSource: func(context.Context) (ConfigView, bool, error) { + return multiIdentityView(), true, nil + }, + } + req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("GET /api/tasks = %d (%s), want 200", w.Code, w.Body) + } + var rows []taskView + if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil { + t.Fatalf("decode rows: %v (%s)", err, w.Body) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (%s)", len(rows), w.Body) + } + + want := map[string]struct{ repo, issue, pr string }{ + "acme/widget": {"https://gitea.example/acme/widget", "https://gitea.example/acme/widget/issues/12", "https://gitea.example/acme/widget/pulls/12"}, + "beta/svc": {"https://github.example/beta/svc", "https://github.example/beta/svc/issues/7", "https://github.example/beta/svc/pull/7"}, + } + for _, row := range rows { + key := row.Owner + "/" + row.Repo + expected, ok := want[key] + if !ok { + t.Errorf("unexpected row %q", key) + continue + } + if row.RepoURL != expected.repo || row.IssueURL != expected.issue || row.PRURL != expected.pr { + t.Errorf("%s links = %q, %q, %q; want %q, %q, %q", key, + row.RepoURL, row.IssueURL, row.PRURL, expected.repo, expected.issue, expected.pr) + } + } +} + // Approve requeues from the task's own recorded state rather than anything // the caller supplies, so a stale dashboard cannot approve a task twice. func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {