diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 43ad82a85..9b27cfb88 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -581,7 +581,7 @@ func (b *boot) registerNATSRPC() error { } b.addCleanup(unsubscribeTaskActions) - unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Allowed: b.managedRepository, Log: log}).Register(coreConn) + unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Log: log}).Register(coreConn) if err != nil { log.Error("issue RPC register failed", "err", err) return err @@ -590,18 +590,9 @@ func (b *boot) registerNATSRPC() error { return nil } -// issueForge is the instance forge, or nil while none is configured. -func (b *boot) issueForge() forge.IssueForge { - if b.forgeClient == nil { - return nil - } - return b.forgeClient -} - -// managedRepository refuses a repository the organisation has not added. -func (b *boot) managedRepository(ctx context.Context, owner, repo string) error { - _, err := b.repositoryBinding(ctx, owner, repo) - return err +// issueForge is the forge of owner/repo's own connection. +func (b *boot) issueForge(ctx context.Context, owner, repo string) (forge.IssueForge, error) { + return b.repositoryForge(ctx, owner, repo) } func (b *boot) buildDaemon() { diff --git a/internal/app/archied/repository_access.go b/internal/app/archied/repository_access.go index 43f891022..52ead3a91 100644 --- a/internal/app/archied/repository_access.go +++ b/internal/app/archied/repository_access.go @@ -59,6 +59,38 @@ func (b *boot) repositoryAccess(ctx context.Context, task *workflow.Task, operat return failure("connection_missing", "The selected connection no longer exists. Choose another connection.") } +// repositoryForge is the forge client of owner/repo's own connection, for +// operator and chat actions, in the org ctx carries. The instance's default +// forge may be a different host entirely. +func (b *boot) repositoryForge(ctx context.Context, owner, repo string) (forge.Forge, error) { + repository, err := b.repositoryBinding(ctx, owner, repo) + if err != nil { + return nil, err + } + if repository.Connection == "" { + return nil, &forge.AccessError{Code: "connection_required", Message: "Choose a connection for this repository."} + } + connections, err := b.repositoryConnections(ctx) + if err != nil { + return nil, err + } + for _, connection := range connections { + if connection.ID != repository.Connection { + continue + } + token, code, message := b.connectionToken(ctx, connection) + if code != "" { + return nil, &forge.AccessError{Code: code, Connection: connection.ID, Message: message} + } + client := b.connectionForge(ctx, connection, org.OrgFromContext(ctx), token) + if _, disabled := client.(*forge.NoopForge); disabled { + return nil, &forge.AccessError{Code: "forge_unavailable", Connection: connection.ID, Message: "Enable the forge extension for this connection."} + } + return client, nil + } + return nil, &forge.AccessError{Code: "connection_missing", Connection: repository.Connection, Message: "The selected connection no longer exists. Choose another connection."} +} + func (b *boot) repositoryBinding(ctx context.Context, owner, name string) (config.Repo, error) { var repos []config.Repo _, found, err := b.controlPlane.Query(ctx, controlplanestore.RepositoryPoliciesKind, func(value []byte) error { return json.Unmarshal(value, &repos) }) diff --git a/internal/app/archied/repository_access_test.go b/internal/app/archied/repository_access_test.go index c62de654e..107223e11 100644 --- a/internal/app/archied/repository_access_test.go +++ b/internal/app/archied/repository_access_test.go @@ -3,6 +3,7 @@ package archied import ( "context" "encoding/json" + "errors" "log/slog" "net/http" "net/http/cgi" @@ -28,6 +29,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/forge" infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore" "github.com/samcharles93/archie-core/internal/secret" @@ -299,3 +301,40 @@ func TestConnectionAccountRefusesRedirects(t *testing.T) { }) } } + +type recordingForge struct { + forge.Forge + merged bool +} + +func (f *recordingForge) MergePR(context.Context, string, string, int) error { + f.merged = true + return nil +} + +// An operator merge goes through the repository's own connection: the +// instance's default forge may be another host that does not have the repo. +func TestMergeUsesRepositoryConnection(t *testing.T) { + t.Setenv("ARCHIE_TEST_CONNECTION_TOKEN", "token") + docs := &repositoryDocuments{ + repos: map[org.OrgID][]config.Repo{"org-a": {{Owner: "acme", Name: "app", Connection: "gitea"}}}, + connections: map[org.OrgID][]config.ForgeConnection{"org-a": {{ID: "gitea", Name: "Gitea", Type: "gitea", Host: "git.example.test", Token: config.SecretRef{Engine: "env", Key: "ARCHIE_TEST_CONNECTION_TOKEN"}}}}, + } + instance := &recordingForge{} + b := &boot{controlPlane: controlplanestore.NewRPCClient(docs), forgeClient: instance, cfgHolder: config.NewHolder(config.Config{}), secrets: secret.NewRegistry(), log: slog.New(slog.DiscardHandler)} + for _, tt := range []struct{ name, owner, repo, code string }{ + {"bound repository", "acme", "app", "forge_unavailable"}, + {"unmanaged repository", "acme", "other", "repository_not_configured"}, + } { + t.Run(tt.name, func(t *testing.T) { + err := b.mergePR(org.WithOrg(t.Context(), "org-a"), tt.owner, tt.repo, 1) + accessErr, ok := errors.AsType[*forge.AccessError](err) + if !ok || accessErr.Code != tt.code { + t.Fatalf("error = %v, want code %s", err, tt.code) + } + if instance.merged { + t.Fatal("merged through the instance forge") + } + }) + } +} diff --git a/internal/app/archied/task_actions.go b/internal/app/archied/task_actions.go index 1e06c3d09..e83f61193 100644 --- a/internal/app/archied/task_actions.go +++ b/internal/app/archied/task_actions.go @@ -2,7 +2,6 @@ package archied import ( "context" - "fmt" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -37,24 +36,27 @@ func (b *boot) cancelTask(id int64) bool { } func (b *boot) closeIssue(ctx context.Context, owner, repo string, number int, comment string) error { - if b.forgeClient == nil { - return fmt.Errorf("forge is not configured") + f, err := b.repositoryForge(ctx, owner, repo) + if err != nil { + return err } - return b.forgeClient.CloseIssue(ctx, owner, repo, number, comment) + return f.CloseIssue(ctx, owner, repo, number, comment) } func (b *boot) closePR(ctx context.Context, owner, repo string, number int, comment string) error { - if b.forgeClient == nil { - return fmt.Errorf("forge is not configured") + f, err := b.repositoryForge(ctx, owner, repo) + if err != nil { + return err } - return b.forgeClient.ClosePR(ctx, owner, repo, number, comment) + return f.ClosePR(ctx, owner, repo, number, comment) } func (b *boot) mergePR(ctx context.Context, owner, repo string, number int) error { - if b.forgeClient == nil { - return fmt.Errorf("forge is not configured") + f, err := b.repositoryForge(ctx, owner, repo) + if err != nil { + return err } - return b.forgeClient.MergePR(ctx, owner, repo, number) + return f.MergePR(ctx, owner, repo, number) } func (b *boot) removeTaskLogs(id int64) error { diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index 8dff837fc..4d7fb932e 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -587,7 +587,7 @@ func (s Service) applyMerge(ctx context.Context, task *Task, actor Actor, o outc if task.PRNumber <= 0 { return o, fmt.Errorf("%w: task has no pull request", ErrConflict) } - if err := s.MergePR(ctx, task.Owner, task.Repo, task.PRNumber); err != nil { + if err := s.MergePR(org.WithOrg(ctx, task.Org), task.Owner, task.Repo, task.PRNumber); err != nil { return o, fmt.Errorf("%w: merge pull request #%d: %w", ErrConflict, task.PRNumber, err) } o.event.Kind, o.event.Detail = events.KindPRMergeRequested, actor.describe(fmt.Sprintf("merged pull request #%d", task.PRNumber)) @@ -624,7 +624,7 @@ func (s Service) closeRejectedPR(ctx context.Context, task *Task, actor Actor, v return } comment := fmt.Sprintf("Closing: this task was %s in archie (%s).", verb, actor.describe("actioned")) - if err := s.ClosePR(ctx, task.Owner, task.Repo, task.PRNumber, comment); err != nil { + if err := s.ClosePR(org.WithOrg(ctx, task.Org), task.Owner, task.Repo, task.PRNumber, comment); err != nil { s.warn("closing rejected task's pull request failed; it stays open", "task", task.ID, "pr", task.PRNumber, "err", err) return } @@ -641,7 +641,7 @@ func (s Service) closeRejectedIssue(ctx context.Context, task *Task, actor Actor return } comment := fmt.Sprintf("Closing: this task was %s in archie (%s). Reopen the issue to have archie pick it up again.", verb, actor.describe("actioned")) - if err := s.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil { + if err := s.CloseIssue(org.WithOrg(ctx, task.Org), task.Owner, task.Repo, task.IssueNumber, comment); err != nil { s.warn("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "err", err) } } diff --git a/internal/infrastructure/issuerpc/issuerpc.go b/internal/infrastructure/issuerpc/issuerpc.go index 9183164d3..453cd99c7 100644 --- a/internal/infrastructure/issuerpc/issuerpc.go +++ b/internal/infrastructure/issuerpc/issuerpc.go @@ -39,23 +39,11 @@ type createResponse struct { Number int `json:"number,omitempty"` } -// Server is the daemon side. Forge returns the instance forge, or nil while -// none is configured; Allowed refuses a repository the instance does not manage. +// Server is the daemon side. Forge returns the forge of the repository's +// connection, refusing a repository the instance does not manage. type Server struct { - Forge func() forge.IssueForge - Allowed func(ctx context.Context, owner, repo string) error - Log *slog.Logger -} - -func (s *Server) forge(ctx context.Context, req request) (forge.IssueForge, error) { - if err := s.Allowed(ctx, req.Owner, req.Repo); err != nil { - return nil, err - } - f := s.Forge() - if f == nil { - return nil, errors.New("forge is not configured") - } - return f, nil + Forge func(ctx context.Context, owner, repo string) (forge.IssueForge, error) + Log *slog.Logger } // Register serves the issue subjects on nc. @@ -67,7 +55,7 @@ func (s *Server) Register(nc *nats.Conn) (func(), error) { natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err)}) return } - f, err := s.forge(ctx, req) + f, err := s.Forge(ctx, req.Owner, req.Repo) var issues []forge.Issue if err == nil { issues, err = f.IssuesWithLabel(ctx, req.Owner, req.Repo, "") @@ -83,7 +71,7 @@ func (s *Server) Register(nc *nats.Conn) (func(), error) { natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err)}) return } - f, err := s.forge(ctx, req) + f, err := s.Forge(ctx, req.Owner, req.Repo) var number int if err == nil { number, err = f.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels)