feat(daemon): execute and verify organisation repository connections
This commit is contained in:
1 parent
32642af4a9
commit
05987f04e2
45 files changed
+1600
-284
No files matched your search
@@ -92,9 +92,6 @@ type boot struct {
|
||||
forgeClient forge.Forge
|
||||
forgeExt *forgeExtensions
|
||||
token string
|
||||
// rootRPC is the root (identity-less) task RPC server pair, held so a
|
||||
// live connection change reaches the servers a task already asks.
|
||||
rootRPC *rootTaskRPC
|
||||
|
||||
// stateStore is the State Store contract adapter every daemon and gateway
|
||||
// store consumer depends on. It is ALWAYS the remote *staterpc.Client
|
||||
@@ -287,10 +284,6 @@ func (b *boot) reopenForge(ctx context.Context) {
|
||||
if b.d != nil {
|
||||
b.d.Forge = client
|
||||
}
|
||||
if b.rootRPC != nil {
|
||||
b.rootRPC.forge.Forge = client
|
||||
b.rootRPC.trees.Trees = b.trees
|
||||
}
|
||||
}
|
||||
|
||||
func (b *boot) openStateStoreAdapter(ctx context.Context) error {
|
||||
@@ -564,12 +557,16 @@ func (b *boot) registerNATSRPC() error {
|
||||
log.Error("nats connection unavailable for task RPC", "err", err)
|
||||
return err
|
||||
}
|
||||
unsubscribe, rootRPC, err := registerTaskRPCServers(coreConn, b.forgeClient, b.trees, b.identityRunners, b.stateStoreGrants.Client, installedAuthorities{b.stateStoreGrants.Client}, log)
|
||||
unsubscribe, err := registerTaskRPCServers(coreConn, func(ctx context.Context, t *workflow.Task, op string) (daemon.RepositoryAccess, error) {
|
||||
if b.d == nil {
|
||||
return daemon.RepositoryAccess{}, errors.New("repository connections starting")
|
||||
}
|
||||
return b.d.Repository(ctx, t, op)
|
||||
}, b.stateStoreGrants.Client, installedAuthorities{b.stateStoreGrants.Client}, log)
|
||||
if err != nil {
|
||||
log.Error("task RPC server registration failed", "err", err)
|
||||
return err
|
||||
}
|
||||
b.rootRPC = rootRPC
|
||||
b.addCleanup(unsubscribe)
|
||||
|
||||
stopLogs, err := logrpc.RegisterDaemon(coreConn, b.logFeed, log)
|
||||
@@ -603,6 +600,7 @@ func (b *boot) registerNATSRPC() error {
|
||||
func (b *boot) buildDaemon() {
|
||||
log := b.log
|
||||
b.d = &daemon.Daemon{
|
||||
ResolveRepository: b.repositoryAccess,
|
||||
Cfg: b.cfgHolder,
|
||||
ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken, Scoped: b.cfg.NATS.Mode != config.NATSModeExternal},
|
||||
ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.Get(config.ServiceNameState).Target), CA: b.stateStoreCA()},
|
||||
|
||||
@@ -17,10 +17,12 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
daemonpb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/harness/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/harnesssession"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
)
|
||||
|
||||
// setupSessionTTL bounds a setup container's life independently of the pool's
|
||||
@@ -177,13 +179,11 @@ func (h *harnessServer) pumpInput(stream pb.HarnessService_OpenServer, session *
|
||||
}
|
||||
}
|
||||
|
||||
// setupHarness serves the harness session contract on the configured listen
|
||||
// address. It is skipped, with the reason logged, when no service token is
|
||||
// configured: a session is a shell in a container that holds an org's
|
||||
// credential, so the token is required even on loopback.
|
||||
func (b *boot) setupHarness(ctx context.Context) {
|
||||
conn := b.cfg.Services.Get(config.ServiceNameHarness)
|
||||
listen, err := servicekit.ResolveListen(config.ServiceNameHarness, "", conn.Listen)
|
||||
// setupDaemonRPC serves repository checks and optional terminal sessions.
|
||||
// Without certificates it binds only loopback and does not serve terminals.
|
||||
func (b *boot) setupDaemonRPC(ctx context.Context) {
|
||||
conn := b.cfg.Services.Get(config.ServiceNameDaemon)
|
||||
listen, err := servicekit.ResolveListen(config.ServiceNameDaemon, "", conn.Listen)
|
||||
if err != nil {
|
||||
b.log.Warn("harness sessions disabled", "err", err)
|
||||
return
|
||||
@@ -193,10 +193,6 @@ func (b *boot) setupHarness(ctx context.Context) {
|
||||
b.log.Warn("harness sessions disabled", "err", err)
|
||||
return
|
||||
}
|
||||
if id == nil {
|
||||
b.log.Warn("harness sessions disabled: a session is a shell holding an org's credential, so it needs [tls] ca_file and cert_dir")
|
||||
return
|
||||
}
|
||||
creds, err := id.ServerOption(listen, false)
|
||||
if err != nil {
|
||||
b.log.Warn("harness sessions disabled", "err", err)
|
||||
@@ -207,14 +203,15 @@ func (b *boot) setupHarness(ctx context.Context) {
|
||||
b.log.Warn("harness sessions disabled: listen", "err", err)
|
||||
return
|
||||
}
|
||||
manager := &harnesssession.Manager{
|
||||
Launcher: b.kitLauncher,
|
||||
Client: b.containerPool.Client(),
|
||||
Profile: func(name string) (config.AgentProfile, error) { return b.cfgHolder.Get().Containers.Profile(name) },
|
||||
TTL: setupSessionTTL,
|
||||
callers := rpcidentity.Callers{Principals: b.d.Principals}
|
||||
srv := grpc.NewServer(append(servicekit.ServerLimits(), creds, grpc.ChainUnaryInterceptor(callers.Unary()))...)
|
||||
daemonpb.RegisterDaemonServiceServer(srv, &repositoryServer{boot: b})
|
||||
// Terminal sessions still require certificates and a container launcher.
|
||||
if id != nil && b.kitLauncher != nil && b.containerPool != nil {
|
||||
manager := &harnesssession.Manager{Launcher: b.kitLauncher, Client: b.containerPool.Client(), Profile: func(name string) (config.AgentProfile, error) { return b.cfgHolder.Get().Containers.Profile(name) }, TTL: setupSessionTTL}
|
||||
pb.RegisterHarnessServiceServer(srv, &harnessServer{sessions: manager, runs: b.runView(), log: b.log})
|
||||
}
|
||||
srv := grpc.NewServer(append(servicekit.ServerLimits(), creds)...)
|
||||
pb.RegisterHarnessServiceServer(srv, &harnessServer{sessions: manager, runs: b.runView(), log: b.log})
|
||||
|
||||
go func() {
|
||||
if err := srv.Serve(ln); err != nil && !errors.Is(err, grpc.ErrServerStopped) {
|
||||
b.log.Error("harness listener stopped", "err", err)
|
||||
|
||||
@@ -90,7 +90,6 @@ func (b *boot) setupKitLauncher(ctx context.Context) {
|
||||
Grants: b.sessionGrants,
|
||||
}
|
||||
b.kitLauncher = kitLauncher
|
||||
b.setupHarness(ctx)
|
||||
log.Info("kit harness runs enabled", "proxy", ln.Addr().String())
|
||||
}
|
||||
|
||||
|
||||
@@ -207,6 +207,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
|
||||
}
|
||||
|
||||
b.buildDaemon()
|
||||
b.setupDaemonRPC(ctx)
|
||||
b.playbooks.Keep(ctx, playbookRefreshInterval)
|
||||
b.workflowDefinitions.Keep(ctx, playbookRefreshInterval)
|
||||
b.controlPlane.KeepSchedules(ctx, playbookRefreshInterval)
|
||||
@@ -348,89 +349,39 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u
|
||||
}, nil
|
||||
}
|
||||
|
||||
// registerTaskRPCServers subscribes the forgerpc/worktreerpc handlers on nc so
|
||||
// an archie-agent container (which holds no forge token, or push credential)
|
||||
// can proxy those operations back to archied. The returned func unsubscribes
|
||||
// all of them. The agent's store calls are NOT proxied here: they go over gRPC
|
||||
// to the State Store, so the legacy NATS storerpc registration is deleted.
|
||||
//
|
||||
// Forge and worktree are identity-scoped: the root servers answer the root
|
||||
// (identity-less) subjects for single-identity deployments and root-owned
|
||||
// tasks, and one server pair per identity answers that identity's scoped
|
||||
// subjects so a container-mode task owned by a non-root identity has its RPC
|
||||
// calls served by its own forge client and worktree manager.
|
||||
func registerTaskRPCServers(nc *natsio.Conn, forgeClient forge.Forge, trees *worktree.Manager, identities []*daemon.IdentityRunner, runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (unsubscribe func(), root *rootTaskRPC, err error) {
|
||||
unsubs := make([]func(), 0, 2+2*len(identities))
|
||||
unsubAll := func() {
|
||||
for _, u := range unsubs {
|
||||
u()
|
||||
// registerTaskRPCServers routes each request through the current task binding.
|
||||
// Wildcard subjects serve identities created after daemon startup; credentials
|
||||
// and repository bounds are checked before the connection is resolved.
|
||||
func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *workflow.Task, string) (daemon.RepositoryAccess, error), runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (func(), error) {
|
||||
var unsubs []func()
|
||||
unsubscribe := func() {
|
||||
for _, stop := range unsubs {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
registerForge := func(fg forge.Forge, identity string) (*forgerpc.Server, error) {
|
||||
srv := &forgerpc.Server{Forge: fg, Runs: runs, Authorities: authorities, Log: log.With("rpc_identity", identity)}
|
||||
u, err := srv.RegisterFor(nc, identity)
|
||||
fg := &forgerpc.Server{Runs: runs, Authorities: authorities, Log: log, Resolve: func(ctx context.Context, t *workflow.Task) (forge.Forge, error) {
|
||||
resolved, err := resolve(ctx, t, config.OperationPR)
|
||||
return resolved.Forge, err
|
||||
}}
|
||||
trees := &worktreerpc.Server{Runs: runs, Log: log, Resolve: func(ctx context.Context, t *workflow.Task) (*worktree.Manager, error) {
|
||||
resolved, err := resolve(ctx, t, config.OperationPush)
|
||||
return resolved.Trees, err
|
||||
}}
|
||||
for _, identity := range []string{"", "*"} {
|
||||
stop, err := fg.RegisterFor(nc, identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register forgerpc%s: %w", identitySuffix(identity), err)
|
||||
unsubscribe()
|
||||
return nil, err
|
||||
}
|
||||
unsubs = append(unsubs, u)
|
||||
return srv, nil
|
||||
}
|
||||
registerTrees := func(mgr *worktree.Manager, identity string) (*worktreerpc.Server, error) {
|
||||
srv := &worktreerpc.Server{Trees: mgr, Runs: runs, Log: log.With("rpc_identity", identity)}
|
||||
u, err := srv.RegisterFor(nc, identity)
|
||||
unsubs = append(unsubs, stop)
|
||||
stop, err = trees.RegisterFor(nc, identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register worktreerpc%s: %w", identitySuffix(identity), err)
|
||||
unsubscribe()
|
||||
return nil, err
|
||||
}
|
||||
unsubs = append(unsubs, u)
|
||||
return srv, nil
|
||||
unsubs = append(unsubs, stop)
|
||||
}
|
||||
|
||||
// Root (identity-less) forge and worktree servers.
|
||||
rootForge, err := registerForge(forgeClient, "")
|
||||
if err != nil {
|
||||
unsubAll()
|
||||
return nil, nil, err
|
||||
}
|
||||
rootTrees, err := registerTrees(trees, "")
|
||||
if err != nil {
|
||||
unsubAll()
|
||||
return nil, nil, err
|
||||
}
|
||||
root = &rootTaskRPC{forge: rootForge, trees: rootTrees}
|
||||
|
||||
// One forge/worktree server pair per identity, on identity-scoped
|
||||
// subjects.
|
||||
for _, id := range identities {
|
||||
if _, err := registerForge(id.Forge, string(id.ID)); err != nil {
|
||||
unsubAll()
|
||||
return nil, nil, err
|
||||
}
|
||||
if _, err := registerTrees(id.Trees, string(id.ID)); err != nil {
|
||||
unsubAll()
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return unsubAll, root, nil
|
||||
}
|
||||
|
||||
// rootTaskRPC is the pair of root (identity-less) task RPC servers. It is
|
||||
// held so a live connection change replaces the forge the servers answer
|
||||
// with: a task already connected asks the new credential, rather than the
|
||||
// one the process booted with.
|
||||
type rootTaskRPC struct {
|
||||
forge *forgerpc.Server
|
||||
trees *worktreerpc.Server
|
||||
}
|
||||
|
||||
// identitySuffix renders a log suffix for an identity-scoped registration,
|
||||
// empty for the root set.
|
||||
func identitySuffix(identity string) string {
|
||||
if identity == "" {
|
||||
return ""
|
||||
}
|
||||
return " (" + identity + ")"
|
||||
return unsubscribe, nil
|
||||
}
|
||||
|
||||
// updateReportPath is where the update watchdog leaves the phase-2 outcome of
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// repositoryAccess re-reads the org's binding and connection at the operation
|
||||
// boundary. Neither a removed permit nor a rotated credential survives here.
|
||||
func (b *boot) repositoryAccess(ctx context.Context, task *workflow.Task, operation string) (daemon.RepositoryAccess, error) {
|
||||
var out daemon.RepositoryAccess
|
||||
failure := func(code, message string) (daemon.RepositoryAccess, error) {
|
||||
return daemon.RepositoryAccess{}, &forge.AccessError{Code: code, Connection: out.Repository.Connection, Operation: operation, Message: message}
|
||||
}
|
||||
if !config.ValidOperation(operation) {
|
||||
return failure("operation_invalid", "Unsupported repository operation.")
|
||||
}
|
||||
principal, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok || principal.Org == "" || principal.IdentityID == "" || string(principal.Org) != task.OrgOrDefault() {
|
||||
return failure("identity_unavailable", "The agent could not be identified.")
|
||||
}
|
||||
repository, err := b.repositoryBinding(ctx, task.Owner, task.Repo)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Repository = repository
|
||||
if out.Repository.Connection == "" {
|
||||
return failure("connection_required", "Choose a connection for this repository.")
|
||||
}
|
||||
connections, err := b.repositoryConnections(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for _, connection := range connections {
|
||||
if connection.ID != out.Repository.Connection {
|
||||
continue
|
||||
}
|
||||
return b.openRepositoryConnection(ctx, principal, out.Repository, connection, operation)
|
||||
}
|
||||
|
||||
return failure("connection_missing", "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, controlplane.RepositoryPoliciesKind, func(value []byte) error { return json.Unmarshal(value, &repos) })
|
||||
if err != nil || !found {
|
||||
return config.Repo{}, &forge.AccessError{Code: "configuration_unavailable", Message: "Repository settings could not be loaded. Try again."}
|
||||
}
|
||||
for _, repo := range repos {
|
||||
if strings.EqualFold(repo.Owner, owner) && strings.EqualFold(repo.Name, name) {
|
||||
return repo, nil
|
||||
}
|
||||
}
|
||||
return config.Repo{}, &forge.AccessError{Code: "repository_not_configured", Message: "Add this repository to the organisation before starting a task."}
|
||||
}
|
||||
|
||||
func (b *boot) repositoryConnections(ctx context.Context) ([]config.ForgeConnection, error) {
|
||||
var connections []config.ForgeConnection
|
||||
_, found, err := b.controlPlane.Query(ctx, controlplane.ForgeConnectionsKind, func(value []byte) error { return json.Unmarshal(value, &connections) })
|
||||
if err != nil || !found {
|
||||
return nil, &forge.AccessError{Code: "configuration_unavailable", Message: "Connection settings could not be loaded. Try again."}
|
||||
}
|
||||
return connections, nil
|
||||
}
|
||||
|
||||
func (b *boot) connectionForge(ctx context.Context, connection config.ForgeConnection, owner org.OrgID, token string) forge.Forge {
|
||||
if client, handled := b.forgeExt.open(access.WithoutPrincipal(ctx), connection.Type, string(owner)+"/"+connection.ID, connection.Host, token); handled {
|
||||
return client
|
||||
}
|
||||
return forge.NewNoop(b.log)
|
||||
}
|
||||
|
||||
func (b *boot) openRepositoryConnection(ctx context.Context, principal access.Principal, repository config.Repo, connection config.ForgeConnection, operation string) (daemon.RepositoryAccess, error) {
|
||||
out := daemon.RepositoryAccess{Repository: repository, Connection: connection}
|
||||
failure := func(code, message string) (daemon.RepositoryAccess, error) {
|
||||
return daemon.RepositoryAccess{}, &forge.AccessError{Code: code, Connection: connection.ID, Operation: operation, Message: message}
|
||||
}
|
||||
if !connection.Permitted(string(principal.IdentityID), operation) {
|
||||
return failure("operation_denied", fmt.Sprintf("Allow this agent to %s through %s before continuing.", operation, connection.Name))
|
||||
}
|
||||
token, err := b.secrets.Resolve(connection.Token)
|
||||
if err != nil || token == "" {
|
||||
return failure("credential_unavailable", fmt.Sprintf("The credential for %s is unavailable. Check its secret reference.", connection.Name))
|
||||
}
|
||||
host := strings.TrimRight(connection.Host, "/")
|
||||
if !strings.Contains(host, "://") {
|
||||
host = "https://" + host
|
||||
}
|
||||
username := connection.Account
|
||||
if username == "" && connection.Type == "gitea" {
|
||||
username, err = connectionAccount(ctx, connection.Type, host, token)
|
||||
if err != nil {
|
||||
return failure("account_unverified", "The forge account could not be verified. Check the credential and its permissions.")
|
||||
}
|
||||
}
|
||||
cfg := b.cfgHolder.Get()
|
||||
out.Trees = &worktree.Manager{WorkDir: worktree.OrgWorkDir(cfg.WorkDir, string(principal.Org)), Token: token, AuthUser: username, BaseURL: host, BotUser: cfg.BotUser, BotEmail: cfg.BotEmail, Log: b.log}
|
||||
out.Forge = b.connectionForge(ctx, connection, principal.Org, token)
|
||||
if operation == config.OperationPR {
|
||||
if _, disabled := out.Forge.(*forge.NoopForge); disabled {
|
||||
return failure("forge_unavailable", "Enable the forge extension for this connection.")
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/cgi"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
git "github.com/go-git/go-git/v6"
|
||||
gitconfig "github.com/go-git/go-git/v6/config"
|
||||
"github.com/go-git/go-git/v6/plumbing"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
daemonpb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
type repositoryDocuments struct {
|
||||
controlpb.ControlPlaneServiceClient
|
||||
repos map[org.OrgID][]config.Repo
|
||||
connections map[org.OrgID][]config.ForgeConnection
|
||||
}
|
||||
|
||||
func (d *repositoryDocuments) Query(ctx context.Context, r *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) {
|
||||
var doc any = d.repos[org.OrgFromContext(ctx)]
|
||||
if r.Kind == controlplane.ForgeConnectionsKind {
|
||||
doc = d.connections[org.OrgFromContext(ctx)]
|
||||
}
|
||||
value, err := json.Marshal(doc)
|
||||
return &controlpb.QueryResponse{Resource: &controlpb.Resource{ValueJson: value}}, err
|
||||
}
|
||||
|
||||
func TestRepositoryConnectionAccess(t *testing.T) {
|
||||
t.Setenv("ARCHIE_TEST_CONNECTION_TOKEN", "initial-token")
|
||||
docs := &repositoryDocuments{
|
||||
repos: map[org.OrgID][]config.Repo{"org-a": {{Owner: "acme", Name: "app", Connection: "github", Base: "main"}}},
|
||||
connections: map[org.OrgID][]config.ForgeConnection{"org-a": {{ID: "github", Name: "GitHub", Type: "github", Host: "github.com", Token: config.SecretRef{Engine: "env", Key: "ARCHIE_TEST_CONNECTION_TOKEN"}, Permits: map[string][]string{"bot-a": {"clone"}}}}},
|
||||
}
|
||||
b := &boot{controlPlane: controlplane.NewRPCClient(docs), cfgHolder: config.NewHolder(config.Config{WorkDir: t.TempDir(), BotUser: "author", BotEmail: "author@example.test"}), secrets: secret.NewRegistry(), log: slog.New(slog.DiscardHandler)}
|
||||
for _, tt := range []struct {
|
||||
name, actingOrg, agent, op string
|
||||
denied bool
|
||||
}{
|
||||
{"clone allowed", "org-a", "bot-a", "clone", false},
|
||||
{"ungranted push", "org-a", "bot-a", "push", true},
|
||||
{"ungranted PR", "org-a", "bot-a", "pr", true},
|
||||
{"other identity", "org-a", "bot-b", "clone", true},
|
||||
{"same binding ID in another org", "org-b", "bot-a", "clone", true},
|
||||
{"unknown operation", "org-a", "bot-a", "delete", true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p := access.Principal{IdentityID: identity.IdentityID(tt.agent), Org: org.OrgID(tt.actingOrg)}
|
||||
ctx := org.WithOrg(access.WithPrincipal(t.Context(), p), p.Org)
|
||||
got, err := b.repositoryAccess(ctx, &workflow.Task{Org: p.Org, Identity: tt.agent, Owner: "acme", Repo: "app"}, tt.op)
|
||||
if (err != nil) != tt.denied {
|
||||
t.Fatalf("error = %v, denied = %v", err, tt.denied)
|
||||
}
|
||||
if err == nil && (got.Trees.Token != "initial-token" || got.Trees.BaseURL != "https://github.com" || got.Repository.Connection != "github") {
|
||||
t.Fatalf("wrong connection selected: repo=%s host=%s", got.Repository.Connection, got.Trees.BaseURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
p := access.Principal{IdentityID: "bot-a", Org: "org-a"}
|
||||
ctx := org.WithOrg(access.WithPrincipal(t.Context(), p), p.Org)
|
||||
task := &workflow.Task{Org: p.Org, Identity: "bot-a", Owner: "acme", Repo: "app"}
|
||||
first, err := b.repositoryAccess(ctx, task, "clone")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("ARCHIE_TEST_CONNECTION_TOKEN", "rotated-token")
|
||||
next, err := b.repositoryAccess(ctx, task, "clone")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Trees.Token != "initial-token" || next.Trees.Token != "rotated-token" {
|
||||
t.Fatal("credential rotation did not reach the next operation independently")
|
||||
}
|
||||
docs.connections["org-a"][0].Permits = nil
|
||||
if _, err = b.repositoryAccess(ctx, task, "clone"); err == nil {
|
||||
t.Fatal("revoked permission still accepted")
|
||||
}
|
||||
docs.connections["org-a"][0].Permits = map[string][]string{"bot-a": {"clone"}}
|
||||
t.Setenv("ARCHIE_TEST_CONNECTION_TOKEN", "")
|
||||
if _, err = b.repositoryAccess(ctx, task, "clone"); err == nil || strings.Contains(err.Error(), "initial-token") {
|
||||
t.Fatal("missing credential accepted or credential leaked")
|
||||
}
|
||||
}
|
||||
|
||||
// The check and execution use one resolver against an authenticated Git
|
||||
// endpoint; the fixture rejects every request without the selected secret.
|
||||
func TestPrivateRepositoryConnection(t *testing.T) {
|
||||
t.Setenv("ARCHIE_TEST_CONNECTION_TOKEN", "private-token")
|
||||
root := t.TempDir()
|
||||
bare, err := git.PlainInit(filepath.Join(root, "acme", "app.git"), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := bare.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName("main"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := bare.Config()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Raw.Section("http").SetOption("receivepack", "true")
|
||||
if err := bare.SetConfig(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedDir := t.TempDir()
|
||||
seed, err := git.PlainInit(seedDir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedCfg, err := seed.Config()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedCfg.Raw.Section("commit").SetOption("gpgsign", "false")
|
||||
if err := seed.SetConfig(seedCfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := seed.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName("main"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(seedDir, "README"), []byte("private fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
author := &worktree.Manager{BotUser: "Commit author", BotEmail: "author@example.test"}
|
||||
if _, err := author.CommitAll(t.Context(), seedDir, "seed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := seed.CreateRemote(&gitconfig.RemoteConfig{Name: "origin", URLs: []string{filepath.Join(root, "acme", "app.git")}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := seed.PushContext(t.Context(), &git.PushOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend := &cgi.Handler{Path: mustGit(t), Args: []string{"http-backend"}, Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}}
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/user" {
|
||||
if r.Header.Get("Authorization") != "token private-token" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"login":"forge-account"}`))
|
||||
return
|
||||
}
|
||||
user, token, ok := r.BasicAuth()
|
||||
if !ok || user != "forge-account" || token != "private-token" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
backend.ServeHTTP(w, r)
|
||||
}))
|
||||
defer fixture.Close()
|
||||
docs := &repositoryDocuments{repos: map[org.OrgID][]config.Repo{"org-a": {{Owner: "acme", Name: "app", Connection: "private", Base: "main"}}}, connections: map[org.OrgID][]config.ForgeConnection{"org-a": {{ID: "private", Name: "Private forge", Type: "gitea", Host: fixture.URL, Account: "forge-account", Token: config.SecretRef{Engine: "env", Key: "ARCHIE_TEST_CONNECTION_TOKEN"}, Permits: map[string][]string{"bot-a": {"clone", "push"}}}}}}
|
||||
b := &boot{controlPlane: controlplane.NewRPCClient(docs), cfgHolder: config.NewHolder(config.Config{WorkDir: t.TempDir(), BotUser: "Commit author", BotEmail: "author@example.test"}), secrets: secret.NewRegistry(), log: slog.New(slog.DiscardHandler)}
|
||||
b.d = &daemon.Daemon{Access: infraaccess.New(access.ShippedOrgPolicies("org-a")), Principals: connectionPrincipals{"bot-a": "org-a", "bot-b": "org-b"}, IdentityRepository: connectionIdentities{}, AgentAssignments: connectionAssignments{}, ResolveRepository: b.repositoryAccess}
|
||||
checker := &repositoryServer{boot: b}
|
||||
request := &daemonpb.CheckRepositoryRequest{Owner: "acme", Repository: "app", IdentityId: "bot-a"}
|
||||
operator := access.Principal{IdentityID: "operator", Kind: identity.KindUser, Org: "org-a", Memberships: []org.Membership{{IdentityID: "operator", OrgID: "org-a", Role: org.RoleAdmin}}}
|
||||
operatorCtx := access.WithPrincipal(t.Context(), operator)
|
||||
if _, err := checker.CheckRepository(t.Context(), request); status.Code(err) != codes.Unauthenticated {
|
||||
t.Fatalf("unauthenticated check: %v", err)
|
||||
}
|
||||
deniedCtx := access.WithPrincipal(t.Context(), access.Principal{IdentityID: "outsider", Org: "org-a"})
|
||||
if _, err := checker.CheckRepository(deniedCtx, request); status.Code(err) != codes.PermissionDenied {
|
||||
t.Fatalf("unauthorised check: %v", err)
|
||||
}
|
||||
verified, err := checker.CheckRepository(operatorCtx, request)
|
||||
if err != nil || !verified.GetVerified() || verified.GetAccount() != "forge-account" {
|
||||
t.Fatalf("repository check = %+v, error = %v", verified, err)
|
||||
}
|
||||
request.IdentityId = "bot-b"
|
||||
refused, err := checker.CheckRepository(operatorCtx, request)
|
||||
if err != nil || refused.GetVerified() {
|
||||
t.Fatalf("another org agent verified: %+v, %v", refused, err)
|
||||
}
|
||||
request.IdentityId = "bot-a"
|
||||
docs.repos["org-a"][0].Base = "missing"
|
||||
missing, err := checker.CheckRepository(operatorCtx, request)
|
||||
if err != nil || missing.GetCode() != "base_branch_missing" {
|
||||
t.Fatalf("missing branch result = %+v, error = %v", missing, err)
|
||||
}
|
||||
docs.repos["org-a"][0].Base = "main"
|
||||
principal := access.Principal{IdentityID: "bot-a", Org: "org-a"}
|
||||
ctx := org.WithOrg(access.WithPrincipal(t.Context(), principal), principal.Org)
|
||||
task := &workflow.Task{Org: "org-a", Identity: "bot-a", Owner: "acme", Repo: "app", IssueNumber: 1}
|
||||
resolved, err := b.repositoryAccess(ctx, task, config.OperationClone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account, err := connectionAccount(ctx, resolved.Connection.Type, resolved.Trees.BaseURL, resolved.Trees.Token)
|
||||
if err != nil || account != "forge-account" {
|
||||
t.Fatalf("account = %q, error = %v", account, err)
|
||||
}
|
||||
if err := resolved.Trees.CheckAccess(ctx, "acme", "app", "main"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir, branch, err := resolved.Trees.Prepare(ctx, "acme", "app", "main", 1, "Private task", "", "", worktree.Fresh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
contents, err := os.ReadFile(filepath.Join(dir, "README"))
|
||||
if err != nil || string(contents) != "private fixture" {
|
||||
t.Fatalf("private clone failed: %v", err)
|
||||
}
|
||||
gitConfig, err := os.ReadFile(filepath.Join(dir, ".git", "config"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(gitConfig), "private-token") {
|
||||
t.Fatal("daemon secret written to worktree")
|
||||
}
|
||||
task.Branch = branch
|
||||
push, err := b.repositoryAccess(ctx, task, config.OperationPush)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := push.Trees.PushRepository(ctx, "acme", "app", 1, branch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := bare.Reference(plumbing.NewBranchReferenceName(branch), true); err != nil {
|
||||
t.Fatalf("private push failed: %v", err)
|
||||
}
|
||||
docs.connections["org-a"][0].Permits["bot-a"] = []string{"clone"}
|
||||
if _, err := b.repositoryAccess(ctx, task, config.OperationPush); err == nil {
|
||||
t.Fatal("push accepted after permission removal")
|
||||
}
|
||||
}
|
||||
|
||||
func mustGit(t *testing.T) string {
|
||||
t.Helper()
|
||||
path, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
type connectionPrincipals map[identity.IdentityID]org.OrgID
|
||||
|
||||
func (p connectionPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||
owner, ok := p[id]
|
||||
if !ok {
|
||||
return access.Principal{}, identity.ErrNotFound
|
||||
}
|
||||
return access.Principal{IdentityID: id, Kind: identity.KindBot, Org: owner}, nil
|
||||
}
|
||||
|
||||
type connectionIdentities struct{ identity.Repository }
|
||||
|
||||
func (connectionIdentities) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
|
||||
return identity.Identity{ID: id, Kind: identity.KindBot, Lifecycle: identity.LifecycleActive}, nil
|
||||
}
|
||||
|
||||
type connectionAssignments struct{}
|
||||
|
||||
func (connectionAssignments) ListOrgAgents(_ context.Context, owner org.OrgID) ([]org.AgentAssignment, error) {
|
||||
return []org.AgentAssignment{{OrgID: owner, IdentityID: "bot-a"}}, nil
|
||||
}
|
||||
|
||||
func TestConnectionAccountRefusesRedirects(t *testing.T) {
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("account credential followed a redirect")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer target.Close()
|
||||
for _, code := range []int{http.StatusMovedPermanently, http.StatusTemporaryRedirect, http.StatusUnauthorized, http.StatusForbidden} {
|
||||
t.Run(http.StatusText(code), func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", target.URL)
|
||||
w.WriteHeader(code)
|
||||
}))
|
||||
defer server.Close()
|
||||
if _, err := connectionAccount(t.Context(), "gitea", server.URL, "private-token"); err == nil || strings.Contains(err.Error(), "private-token") {
|
||||
t.Fatalf("unsafe account result: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v6/plumbing/transport"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
type repositoryServer struct {
|
||||
pb.UnimplementedDaemonServiceServer
|
||||
boot *boot
|
||||
}
|
||||
|
||||
func (s *repositoryServer) CheckRepository(ctx context.Context, r *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error) {
|
||||
b := s.boot
|
||||
caller, ok := access.PrincipalFromContext(ctx)
|
||||
if !ok || caller.IdentityID == "" {
|
||||
return nil, status.Error(codes.Unauthenticated, "Sign in before checking repository access.")
|
||||
}
|
||||
if b.d == nil || b.d.Access == nil || b.d.Principals == nil {
|
||||
return nil, status.Error(codes.Unavailable, "Repository checks are temporarily unavailable.")
|
||||
}
|
||||
decision := b.d.Access.Authorize(caller, access.ActionUpdate, access.Resource{Kind: access.KindPolicy, ID: "repository-policies", Org: caller.Org}, access.Context{})
|
||||
if !decision.Allowed {
|
||||
return nil, status.Error(codes.PermissionDenied, "You do not have permission to check repository access.")
|
||||
}
|
||||
if r.Owner == "" || r.Repository == "" || r.IdentityId == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "Choose a repository and agent.")
|
||||
}
|
||||
task := &workflow.Task{Org: caller.Org, Owner: r.Owner, Repo: r.Repository, Identity: r.IdentityId}
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
resolved, err := b.d.Repository(ctx, task, config.OperationClone)
|
||||
response := &pb.CheckRepositoryResponse{Operation: config.OperationClone}
|
||||
if err != nil {
|
||||
response.Code = "configuration_unavailable"
|
||||
response.Message = "Repository access could not be checked. Try again."
|
||||
if failure, ok := errors.AsType[*forge.AccessError](err); ok {
|
||||
response.Code = failure.Code
|
||||
response.Message = failure.Message
|
||||
response.Connection = failure.Connection
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
return checkRepositoryAccess(ctx, resolved), nil
|
||||
}
|
||||
|
||||
func checkRepositoryAccess(ctx context.Context, resolved daemon.RepositoryAccess) *pb.CheckRepositoryResponse {
|
||||
response := &pb.CheckRepositoryResponse{Connection: resolved.Repository.Connection, BaseBranch: resolved.Repository.BaseBranch(), Operation: config.OperationClone}
|
||||
response.Connection = resolved.Repository.Connection
|
||||
response.BaseBranch = resolved.Repository.BaseBranch()
|
||||
account, err := connectionAccount(ctx, resolved.Connection.Type, resolved.Trees.BaseURL, resolved.Trees.Token)
|
||||
if err != nil {
|
||||
response.Code = "account_unverified"
|
||||
response.Message = "The forge account could not be verified. Check the host, credential and token permissions."
|
||||
return response
|
||||
}
|
||||
response.Account = account
|
||||
resolved.Trees.AuthUser = account
|
||||
if resolved.Connection.Account != "" && !strings.EqualFold(resolved.Connection.Account, account) {
|
||||
response.Code = "account_mismatch"
|
||||
response.Message = "This credential belongs to a different account than the connection specifies."
|
||||
return response
|
||||
}
|
||||
if err := resolved.Trees.CheckAccess(ctx, resolved.Repository.Owner, resolved.Repository.Name, response.BaseBranch); err != nil {
|
||||
response.Code = "repository_unavailable"
|
||||
response.Message = "The repository could not be read. Check its name and the credential's repository access."
|
||||
switch {
|
||||
case errors.Is(err, worktree.ErrBaseBranchNotFound):
|
||||
response.Code = "base_branch_missing"
|
||||
response.Message = "The base branch was not found. Check the repository's base branch."
|
||||
case errors.Is(err, transport.ErrAuthenticationRequired), errors.Is(err, transport.ErrAuthorizationFailed):
|
||||
response.Code = "repository_access_denied"
|
||||
response.Message = "Repository access was refused. Check the credential's repository permissions."
|
||||
}
|
||||
return response
|
||||
}
|
||||
response.Verified = true
|
||||
response.Message = "Account, repository and base branch verified. No changes were made."
|
||||
return response
|
||||
}
|
||||
|
||||
// Account discovery is read-only and never follows redirects with credentials.
|
||||
func connectionAccount(ctx context.Context, typ, host, token string) (string, error) {
|
||||
endpoint, err := url.Parse(host)
|
||||
if err != nil || endpoint.Host == "" || endpoint.User != nil {
|
||||
return "", errors.New("invalid forge host")
|
||||
}
|
||||
authorization := "Bearer " + token
|
||||
switch typ {
|
||||
case "github":
|
||||
if endpoint.Hostname() == "github.com" {
|
||||
endpoint.Host = "api.github.com"
|
||||
endpoint.Path = "/user"
|
||||
} else {
|
||||
endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/api/v3/user"
|
||||
}
|
||||
case "gitea":
|
||||
authorization = "token " + token
|
||||
endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/api/v1/user"
|
||||
default:
|
||||
return "", errors.New("account checks are unavailable for this forge")
|
||||
}
|
||||
endpoint.RawQuery = ""
|
||||
endpoint.Fragment = ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
request.Header.Set("Authorization", authorization)
|
||||
request.Header.Set("Accept", "application/json")
|
||||
client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", errors.New("forge account unavailable")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.New("forge account refused")
|
||||
}
|
||||
var account struct {
|
||||
Login string `json:"login"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(&account); err != nil || account.Login == "" {
|
||||
return "", errors.New("forge account unavailable")
|
||||
}
|
||||
return account.Login, nil
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
)
|
||||
@@ -76,7 +77,7 @@ func (b *boot) removeTaskWorktree(task *taskactions.Task) error {
|
||||
if b.d == nil {
|
||||
return nil
|
||||
}
|
||||
return b.d.RemoveWorktree(task.Owner, task.Repo, task.Identity, task.IssueNumber)
|
||||
return b.d.RemoveWorktree(&workflow.Task{Owner: task.Owner, Repo: task.Repo, Identity: task.Identity, IssueNumber: task.IssueNumber, Org: task.Org})
|
||||
}
|
||||
|
||||
func (b *boot) publishEvent(e events.Event) {
|
||||
|
||||
@@ -63,6 +63,7 @@ type projection struct {
|
||||
state ServiceTarget
|
||||
messaging ServiceTarget
|
||||
harness ServiceTarget
|
||||
daemon ServiceTarget
|
||||
tls config.TLS
|
||||
capture CaptureOptions
|
||||
}
|
||||
@@ -75,6 +76,7 @@ func project(cfg config.Config) projection {
|
||||
messaging: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameMessaging).Target},
|
||||
state: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameState).Target},
|
||||
harness: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameHarness).Target},
|
||||
daemon: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameDaemon).Target},
|
||||
tls: cfg.TLS,
|
||||
capture: CaptureOptions{
|
||||
Retention: cfg.Capture.Retention.Std(),
|
||||
@@ -99,6 +101,7 @@ func merge(o Options, p projection) Options {
|
||||
o.Messaging = mergeTarget(o.Messaging, p.messaging)
|
||||
o.State = mergeTarget(o.State, p.state)
|
||||
o.Harness = mergeTarget(o.Harness, p.harness)
|
||||
o.Daemon = mergeTarget(o.Daemon, p.daemon)
|
||||
if o.Capture.Retention <= 0 {
|
||||
o.Capture.Retention = p.capture.Retention
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ type Options struct {
|
||||
Gateway ServiceTarget
|
||||
State ServiceTarget
|
||||
Messaging ServiceTarget
|
||||
Daemon ServiceTarget
|
||||
// Harness is the daemon's session contract. Optional: empty leaves the
|
||||
// setup terminal unwired, and /api/harness reports terminal:false rather
|
||||
// than offering a control that would fail.
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/harnessrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
@@ -102,7 +103,7 @@ func Run(ctx context.Context, options Options) error {
|
||||
return err
|
||||
}
|
||||
cleanups = append(cleanups, stopLogs)
|
||||
if err := wireHarness(opts, srv, &cleanups); err != nil {
|
||||
if err := wireDaemon(opts, srv, &cleanups); err != nil {
|
||||
return err
|
||||
}
|
||||
// Priming event history must not delay the listener.
|
||||
@@ -139,12 +140,23 @@ func warnPlainHTTP(log *slog.Logger, opts Options) {
|
||||
"listen", opts.Listen)
|
||||
}
|
||||
|
||||
func wireDaemon(opts Options, srv *webui.Server, cleanups *[]func()) error {
|
||||
checks, closeChecks, err := daemonrpc.Dial(opts.Daemon.Target, opts.identity)
|
||||
if err != nil {
|
||||
return fmt.Errorf("repository checks: %w", err)
|
||||
}
|
||||
srv.RepositoryChecks = checks
|
||||
*cleanups = append(*cleanups, closeChecks)
|
||||
return wireHarness(opts, srv, cleanups)
|
||||
}
|
||||
|
||||
// wireHarness attaches the setup terminal and the run-scoped sandbox view to the daemon's session contract
|
||||
// when the operator configured one, and registers its cleanup.
|
||||
func wireHarness(opts Options, srv *webui.Server, cleanups *[]func()) error {
|
||||
if opts.Harness.Target == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
harness, closeHarness, err := harnessrpc.Dial(opts.Harness.Target, opts.identity)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -226,7 +226,7 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W
|
||||
// configuration or a not-found the dashboard cannot tell from a failure.
|
||||
var orgSeededKinds = map[string]bool{
|
||||
WorkflowDefinitionsKind: true, WorkflowEnablementKind: true,
|
||||
ForgeConnectionsKind: true,
|
||||
ForgeConnectionsKind: true, RepositoryPoliciesKind: true,
|
||||
}
|
||||
|
||||
// resource seeds an org's workflow documents on first use, including orgs
|
||||
|
||||
@@ -154,11 +154,8 @@ func (s *Server) readResource(ctx context.Context, orgID, kind string, into any)
|
||||
|
||||
// instanceOnlyKinds are the kinds the runtime layers from the system org's
|
||||
// copy alone. Another org's write would be stored and never applied.
|
||||
// Repository policies stay here until the daemon resolves a task's bindings
|
||||
// in the task's own organisation: while only the system org's document is
|
||||
// read, another org's write would be stored and never applied.
|
||||
var instanceOnlyKinds = map[string]bool{
|
||||
RepositoryPoliciesKind: true, ChannelSettingsKind: true, SchedulingPolicyKind: true,
|
||||
ChannelSettingsKind: true, SchedulingPolicyKind: true,
|
||||
ReviewSettingsKind: true, TaskPolicyKind: true, ToolSettingsKind: true,
|
||||
PluginSettingsKind: true, ContainerRuntimePoliciesKind: true, AgentProfileKind: true,
|
||||
ExtensionSettingsKind: true, UpdateSettingsKind: true, WorkflowExecutionSettingsKind: true,
|
||||
|
||||
@@ -44,6 +44,7 @@ const (
|
||||
ServiceNameState = "state"
|
||||
ServiceNameMessaging = "messaging"
|
||||
ServiceNameHarness = "harness"
|
||||
ServiceNameDaemon = "daemon"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -115,5 +116,6 @@ func init() {
|
||||
// dashboard dials it, and its target is the operator's to supply, so a
|
||||
// deployment with no [services.harness].target leaves the setup terminal
|
||||
// unwired rather than dialling a default nothing owns.
|
||||
RegisterService(ServiceBoth, ServiceNameHarness, "", "127.0.0.1:8587")
|
||||
RegisterService(ServiceBoth, ServiceNameDaemon, "127.0.0.1:8587", "127.0.0.1:8587")
|
||||
RegisterService(ServiceClient, ServiceNameHarness, "", "")
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.11
|
||||
// protoc (unknown)
|
||||
// source: daemon/v1/daemon.proto
|
||||
|
||||
package daemonv1
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type CheckRepositoryRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"`
|
||||
Repository string `protobuf:"bytes,2,opt,name=repository,proto3" json:"repository,omitempty"`
|
||||
IdentityId string `protobuf:"bytes,3,opt,name=identity_id,json=identityId,proto3" json:"identity_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryRequest) Reset() {
|
||||
*x = CheckRepositoryRequest{}
|
||||
mi := &file_daemon_v1_daemon_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*CheckRepositoryRequest) ProtoMessage() {}
|
||||
|
||||
func (x *CheckRepositoryRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_v1_daemon_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use CheckRepositoryRequest.ProtoReflect.Descriptor instead.
|
||||
func (*CheckRepositoryRequest) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_v1_daemon_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryRequest) GetOwner() string {
|
||||
if x != nil {
|
||||
return x.Owner
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryRequest) GetRepository() string {
|
||||
if x != nil {
|
||||
return x.Repository
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryRequest) GetIdentityId() string {
|
||||
if x != nil {
|
||||
return x.IdentityId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type CheckRepositoryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Verified bool `protobuf:"varint,1,opt,name=verified,proto3" json:"verified,omitempty"`
|
||||
Connection string `protobuf:"bytes,2,opt,name=connection,proto3" json:"connection,omitempty"`
|
||||
Operation string `protobuf:"bytes,3,opt,name=operation,proto3" json:"operation,omitempty"`
|
||||
Account string `protobuf:"bytes,4,opt,name=account,proto3" json:"account,omitempty"`
|
||||
BaseBranch string `protobuf:"bytes,5,opt,name=base_branch,json=baseBranch,proto3" json:"base_branch,omitempty"`
|
||||
Code string `protobuf:"bytes,6,opt,name=code,proto3" json:"code,omitempty"`
|
||||
Message string `protobuf:"bytes,7,opt,name=message,proto3" json:"message,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) Reset() {
|
||||
*x = CheckRepositoryResponse{}
|
||||
mi := &file_daemon_v1_daemon_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*CheckRepositoryResponse) ProtoMessage() {}
|
||||
|
||||
func (x *CheckRepositoryResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_v1_daemon_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use CheckRepositoryResponse.ProtoReflect.Descriptor instead.
|
||||
func (*CheckRepositoryResponse) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_v1_daemon_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetVerified() bool {
|
||||
if x != nil {
|
||||
return x.Verified
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetConnection() string {
|
||||
if x != nil {
|
||||
return x.Connection
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetOperation() string {
|
||||
if x != nil {
|
||||
return x.Operation
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetAccount() string {
|
||||
if x != nil {
|
||||
return x.Account
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetBaseBranch() string {
|
||||
if x != nil {
|
||||
return x.BaseBranch
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetCode() string {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CheckRepositoryResponse) GetMessage() string {
|
||||
if x != nil {
|
||||
return x.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_daemon_v1_daemon_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_daemon_v1_daemon_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x16daemon/v1/daemon.proto\x12\tdaemon.v1\"o\n" +
|
||||
"\x16CheckRepositoryRequest\x12\x14\n" +
|
||||
"\x05owner\x18\x01 \x01(\tR\x05owner\x12\x1e\n" +
|
||||
"\n" +
|
||||
"repository\x18\x02 \x01(\tR\n" +
|
||||
"repository\x12\x1f\n" +
|
||||
"\videntity_id\x18\x03 \x01(\tR\n" +
|
||||
"identityId\"\xdc\x01\n" +
|
||||
"\x17CheckRepositoryResponse\x12\x1a\n" +
|
||||
"\bverified\x18\x01 \x01(\bR\bverified\x12\x1e\n" +
|
||||
"\n" +
|
||||
"connection\x18\x02 \x01(\tR\n" +
|
||||
"connection\x12\x1c\n" +
|
||||
"\toperation\x18\x03 \x01(\tR\toperation\x12\x18\n" +
|
||||
"\aaccount\x18\x04 \x01(\tR\aaccount\x12\x1f\n" +
|
||||
"\vbase_branch\x18\x05 \x01(\tR\n" +
|
||||
"baseBranch\x12\x12\n" +
|
||||
"\x04code\x18\x06 \x01(\tR\x04code\x12\x18\n" +
|
||||
"\amessage\x18\a \x01(\tR\amessage2i\n" +
|
||||
"\rDaemonService\x12X\n" +
|
||||
"\x0fCheckRepository\x12!.daemon.v1.CheckRepositoryRequest\x1a\".daemon.v1.CheckRepositoryResponseB\xac\x01\n" +
|
||||
"\rcom.daemon.v1B\vDaemonProtoP\x01ZIgithub.com/samcharles93/archie-core/internal/contracts/daemon/v1;daemonv1\xa2\x02\x03DXX\xaa\x02\tDaemon.V1\xca\x02\tDaemon\\V1\xe2\x02\x15Daemon\\V1\\GPBMetadata\xea\x02\n" +
|
||||
"Daemon::V1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_daemon_v1_daemon_proto_rawDescOnce sync.Once
|
||||
file_daemon_v1_daemon_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_daemon_v1_daemon_proto_rawDescGZIP() []byte {
|
||||
file_daemon_v1_daemon_proto_rawDescOnce.Do(func() {
|
||||
file_daemon_v1_daemon_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_daemon_v1_daemon_proto_rawDesc), len(file_daemon_v1_daemon_proto_rawDesc)))
|
||||
})
|
||||
return file_daemon_v1_daemon_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_daemon_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_daemon_v1_daemon_proto_goTypes = []any{
|
||||
(*CheckRepositoryRequest)(nil), // 0: daemon.v1.CheckRepositoryRequest
|
||||
(*CheckRepositoryResponse)(nil), // 1: daemon.v1.CheckRepositoryResponse
|
||||
}
|
||||
var file_daemon_v1_daemon_proto_depIdxs = []int32{
|
||||
0, // 0: daemon.v1.DaemonService.CheckRepository:input_type -> daemon.v1.CheckRepositoryRequest
|
||||
1, // 1: daemon.v1.DaemonService.CheckRepository:output_type -> daemon.v1.CheckRepositoryResponse
|
||||
1, // [1:2] is the sub-list for method output_type
|
||||
0, // [0:1] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_daemon_v1_daemon_proto_init() }
|
||||
func file_daemon_v1_daemon_proto_init() {
|
||||
if File_daemon_v1_daemon_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_v1_daemon_proto_rawDesc), len(file_daemon_v1_daemon_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_daemon_v1_daemon_proto_goTypes,
|
||||
DependencyIndexes: file_daemon_v1_daemon_proto_depIdxs,
|
||||
MessageInfos: file_daemon_v1_daemon_proto_msgTypes,
|
||||
}.Build()
|
||||
File_daemon_v1_daemon_proto = out.File
|
||||
file_daemon_v1_daemon_proto_goTypes = nil
|
||||
file_daemon_v1_daemon_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc (unknown)
|
||||
// source: daemon/v1/daemon.proto
|
||||
|
||||
package daemonv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
DaemonService_CheckRepository_FullMethodName = "/daemon.v1.DaemonService/CheckRepository"
|
||||
)
|
||||
|
||||
// DaemonServiceClient is the client API for DaemonService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// DaemonService exposes checks that must use the daemon's actual credentials.
|
||||
type DaemonServiceClient interface {
|
||||
// CheckRepository checks a saved binding for an execution identity. It does
|
||||
// not create a branch, commit or pull request.
|
||||
CheckRepository(ctx context.Context, in *CheckRepositoryRequest, opts ...grpc.CallOption) (*CheckRepositoryResponse, error)
|
||||
}
|
||||
|
||||
type daemonServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewDaemonServiceClient(cc grpc.ClientConnInterface) DaemonServiceClient {
|
||||
return &daemonServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *daemonServiceClient) CheckRepository(ctx context.Context, in *CheckRepositoryRequest, opts ...grpc.CallOption) (*CheckRepositoryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CheckRepositoryResponse)
|
||||
err := c.cc.Invoke(ctx, DaemonService_CheckRepository_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DaemonServiceServer is the server API for DaemonService service.
|
||||
// All implementations must embed UnimplementedDaemonServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// DaemonService exposes checks that must use the daemon's actual credentials.
|
||||
type DaemonServiceServer interface {
|
||||
// CheckRepository checks a saved binding for an execution identity. It does
|
||||
// not create a branch, commit or pull request.
|
||||
CheckRepository(context.Context, *CheckRepositoryRequest) (*CheckRepositoryResponse, error)
|
||||
mustEmbedUnimplementedDaemonServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedDaemonServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedDaemonServiceServer struct{}
|
||||
|
||||
func (UnimplementedDaemonServiceServer) CheckRepository(context.Context, *CheckRepositoryRequest) (*CheckRepositoryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method CheckRepository not implemented")
|
||||
}
|
||||
func (UnimplementedDaemonServiceServer) mustEmbedUnimplementedDaemonServiceServer() {}
|
||||
func (UnimplementedDaemonServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeDaemonServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to DaemonServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeDaemonServiceServer interface {
|
||||
mustEmbedUnimplementedDaemonServiceServer()
|
||||
}
|
||||
|
||||
func RegisterDaemonServiceServer(s grpc.ServiceRegistrar, srv DaemonServiceServer) {
|
||||
// If the following call panics, it indicates UnimplementedDaemonServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&DaemonService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _DaemonService_CheckRepository_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CheckRepositoryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(DaemonServiceServer).CheckRepository(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: DaemonService_CheckRepository_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(DaemonServiceServer).CheckRepository(ctx, req.(*CheckRepositoryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// DaemonService_ServiceDesc is the grpc.ServiceDesc for DaemonService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var DaemonService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "daemon.v1.DaemonService",
|
||||
HandlerType: (*DaemonServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "CheckRepository",
|
||||
Handler: _DaemonService_CheckRepository_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "daemon/v1/daemon.proto",
|
||||
}
|
||||
+46
-10
@@ -86,6 +86,7 @@ type StateStoreEndpoint struct {
|
||||
}
|
||||
|
||||
type Daemon struct {
|
||||
ResolveRepository func(context.Context, *workflow.Task, string) (RepositoryAccess, error)
|
||||
// Cfg publishes the running configuration. Read through Cfg() so a
|
||||
// reload swaps the published snapshot atomically. See config.Holder.
|
||||
Cfg *config.Holder
|
||||
@@ -1529,6 +1530,14 @@ func (d *Daemon) closeResolvedIssue(ctx context.Context, fg forge.Forge, task *w
|
||||
if !task.IsForgeBacked() {
|
||||
return
|
||||
}
|
||||
if d.ResolveRepository != nil {
|
||||
resolved, err := d.Repository(ctx, task, config.OperationPR)
|
||||
if err != nil {
|
||||
d.Log.Warn("issue closure not permitted", "task", task.ID)
|
||||
return
|
||||
}
|
||||
fg = resolved.Forge
|
||||
}
|
||||
if err := fg.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
|
||||
d.Log.Warn("closing resolved issue failed; it stays open and will be re-polled",
|
||||
"repo", task.Owner+"/"+task.Repo, "issue", task.IssueNumber, "err", err)
|
||||
@@ -1544,7 +1553,10 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
for _, t := range tasks {
|
||||
fg := d.forgeFor(&t)
|
||||
fg := d.forgeFor(ctx, &t)
|
||||
if _, unavailable := fg.(*forge.NoopForge); unavailable {
|
||||
continue
|
||||
}
|
||||
trees := d.treesFor(&t)
|
||||
// PRState/PR reconciliation is valid regardless of Source -- a
|
||||
// chat-sourced task can still open a real PR against a real
|
||||
@@ -1601,12 +1613,12 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task, hold *taskHol
|
||||
return
|
||||
}
|
||||
|
||||
trees := d.treesFor(task)
|
||||
repo, ok := d.repoFor(task)
|
||||
if !ok && task.HasRepository() {
|
||||
d.parkRunningTask(ctx, task, "repo no longer in config", taskstate.ParkTerminal)
|
||||
trees, repo, err := d.taskWorkspace(ctx, task)
|
||||
if err != nil {
|
||||
d.parkRunningTask(ctx, task, err.Error(), pinParkClass(err))
|
||||
return
|
||||
}
|
||||
|
||||
if d.ContainerPool == nil || d.Tasks == nil {
|
||||
d.parkCapabilityUnavailable(ctx, task)
|
||||
return
|
||||
@@ -1673,6 +1685,19 @@ func (d *Daemon) teardownStorage(ctx context.Context, task *workflow.Task, repo
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Daemon) taskWorkspace(ctx context.Context, task *workflow.Task) (*worktree.Manager, config.Repo, error) {
|
||||
if task.HasRepository() && d.ResolveRepository != nil {
|
||||
resolved, err := d.Repository(ctx, task, config.OperationClone)
|
||||
return resolved.Trees, resolved.Repository, err
|
||||
}
|
||||
trees := d.treesFor(task)
|
||||
repo, ok := d.repoFor(task)
|
||||
if !ok && task.HasRepository() {
|
||||
return nil, repo, pinFailure{taskstate.ParkTerminal, errors.New("repository is no longer configured")}
|
||||
}
|
||||
return trees, repo, nil
|
||||
}
|
||||
|
||||
// prepareWorkspace makes the directory the container binds as its
|
||||
// workspace, which must exist before Acquire: a fresh clone of the task's
|
||||
// repository, or an empty scratch directory for a task with none. It parks
|
||||
@@ -1822,7 +1847,7 @@ func (d *Daemon) acquireTaskContainer(
|
||||
// Fetch the pull request with the daemon's forge credential into workDir,
|
||||
// so the container reads it without credentials.
|
||||
if task.Workflow == "pr-review" {
|
||||
if err := prefetchPRReview(ctx, d.forgeFor(task), task.Owner, task.Repo, task.PRNumber, workDir); err != nil {
|
||||
if err := prefetchPRReview(ctx, d.forgeFor(ctx, task), task.Owner, task.Repo, task.PRNumber, workDir); err != nil {
|
||||
park("pr-review prefetch failed", err)
|
||||
return nil, "", nil, false
|
||||
}
|
||||
@@ -2434,7 +2459,14 @@ func (d *Daemon) identityActive(ctx context.Context, id identity.IdentityID) boo
|
||||
// client when task.Identity names a configured identity, else the root
|
||||
// d.Forge for the root alone. This is the safety boundary that keeps one identity's forge
|
||||
// token from being used against another identity's repos.
|
||||
func (d *Daemon) forgeFor(task *workflow.Task) forge.Forge {
|
||||
func (d *Daemon) forgeFor(ctx context.Context, task *workflow.Task) forge.Forge {
|
||||
if d.ResolveRepository != nil && task.HasRepository() {
|
||||
resolved, err := d.Repository(ctx, task, config.OperationClone)
|
||||
if err != nil {
|
||||
return forge.NewNoop(d.Log)
|
||||
}
|
||||
return resolved.Forge
|
||||
}
|
||||
if id := d.identityFor(task); id != nil {
|
||||
return id.Forge
|
||||
}
|
||||
@@ -2446,6 +2478,10 @@ func (d *Daemon) forgeFor(task *workflow.Task) forge.Forge {
|
||||
|
||||
// treesFor returns the worktree manager that owns task, mirroring forgeFor.
|
||||
func (d *Daemon) treesFor(task *workflow.Task) *worktree.Manager {
|
||||
if d.ResolveRepository != nil && task.HasRepository() {
|
||||
// Cleanup needs only the org's path, not a still-valid external credential.
|
||||
return &worktree.Manager{WorkDir: worktree.OrgWorkDir(d.Cfg.Get().WorkDir, task.OrgOrDefault())}
|
||||
}
|
||||
if id := d.identityFor(task); id != nil {
|
||||
return id.Trees
|
||||
}
|
||||
@@ -2543,14 +2579,14 @@ func withTaskTimeLimit(ctx context.Context, limit time.Duration) (context.Contex
|
||||
// RemoveWorktree deletes a task's clone from the trees of the identity that
|
||||
// owns it. Archiving calls it: terminal cleanup keeps a worktree that may hold
|
||||
// uncaptured work, and the operator's archive is the decision to discard it.
|
||||
func (d *Daemon) RemoveWorktree(owner, repo, identity string, issue int) error {
|
||||
trees := d.treesFor(&workflow.Task{Owner: owner, Repo: repo, Identity: identity})
|
||||
func (d *Daemon) RemoveWorktree(task *workflow.Task) error {
|
||||
trees := d.treesFor(task)
|
||||
if trees == nil {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
return d.cleanupWorktree(ctx, trees, owner, repo, issue)
|
||||
return d.cleanupWorktree(ctx, trees, task.Owner, task.Repo, task.IssueNumber)
|
||||
}
|
||||
|
||||
// cleanupWorktree removes a task's clone, first handing back any root-owned
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// RepositoryAccess holds host-side clients for one authorised operation.
|
||||
// It is never included in the container handoff.
|
||||
type RepositoryAccess struct {
|
||||
Repository config.Repo
|
||||
Connection config.ForgeConnection
|
||||
Trees *worktree.Manager
|
||||
Forge forge.Forge
|
||||
}
|
||||
|
||||
// Repository resolves current credentials and permissions for the run's
|
||||
// execution identity, never the identity that originally requested the task.
|
||||
func (d *Daemon) Repository(ctx context.Context, task *workflow.Task, operation string) (RepositoryAccess, error) {
|
||||
if d.ResolveRepository == nil {
|
||||
return RepositoryAccess{}, fmt.Errorf("repository connections unavailable")
|
||||
}
|
||||
run := *task
|
||||
if run.WorkflowDefinitionYAML != "" {
|
||||
iface, err := workflowtask.ParseWorkflowInterface(run.WorkflowDefinitionYAML)
|
||||
if err != nil || iface.Identity == "" {
|
||||
return RepositoryAccess{}, fmt.Errorf("workflow execution identity unavailable")
|
||||
}
|
||||
_, name, err := d.declaredIdentity(ctx, &run, iface.Identity)
|
||||
if err != nil {
|
||||
return RepositoryAccess{}, err
|
||||
}
|
||||
run.Identity = name
|
||||
}
|
||||
ctx, err := d.workflowContext(ctx, &run)
|
||||
if err != nil {
|
||||
return RepositoryAccess{}, err
|
||||
}
|
||||
if _, err := d.databaseExecutionIdentity(ctx, &run, d.publisherIdentity(run.Identity)); err != nil {
|
||||
return RepositoryAccess{}, err
|
||||
}
|
||||
return d.ResolveRepository(ctx, &run, operation)
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func (d *Daemon) scanPRReviews(ctx context.Context) {
|
||||
}
|
||||
for i := range tasks {
|
||||
t := &tasks[i]
|
||||
reader, ok := d.forgeFor(t).(forge.PullRequestReviewReader)
|
||||
reader, ok := d.forgeFor(ctx, t).(forge.PullRequestReviewReader)
|
||||
if !ok {
|
||||
continue // the noop forge and any forge without the capability
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -23,6 +24,7 @@ var (
|
||||
|
||||
// Task is the state needed to authorize and apply an operator action.
|
||||
type Task struct {
|
||||
Org org.OrgID
|
||||
ID int64
|
||||
Owner, Repo, Identity, Status, ParkReason string
|
||||
IssueNumber, RetryCount int
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package forge
|
||||
|
||||
// AccessError identifies an actionable connection failure without returning a
|
||||
// credential or a transport's raw response to the dashboard.
|
||||
type AccessError struct {
|
||||
Code string `json:"code"`
|
||||
Connection string `json:"connection,omitempty"`
|
||||
Operation string `json:"operation"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *AccessError) Error() string { return e.Message }
|
||||
@@ -146,7 +146,7 @@ type Authorities interface {
|
||||
|
||||
// Server proxies forgerpc requests to a real forge.Forge implementation.
|
||||
type Server struct {
|
||||
Forge forge.Forge
|
||||
Resolve func(context.Context, *workflow.Task) (forge.Forge, error)
|
||||
Runs Runs
|
||||
Authorities Authorities
|
||||
Log *slog.Logger
|
||||
@@ -162,15 +162,23 @@ func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
|
||||
// RegisterFor registers all handlers under the subjects scoped to identity.
|
||||
func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) {
|
||||
as := func(h func(string, *nats.Msg)) nats.MsgHandler { return func(msg *nats.Msg) { h(identity, msg) } }
|
||||
as := func(h func(string, *nats.Msg)) nats.MsgHandler {
|
||||
return func(msg *nats.Msg) {
|
||||
scoped := identity
|
||||
if identity == "*" {
|
||||
scoped = strings.Split(msg.Subject, ".")[2]
|
||||
}
|
||||
h(scoped, msg)
|
||||
}
|
||||
}
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectFor(identity, SubjectComment), Handler: as(s.handleComment)},
|
||||
{Subject: SubjectFor(identity, SubjectCloseIssue), Handler: as(s.handleCloseIssue)},
|
||||
{Subject: SubjectFor(identity, SubjectCreatePR), Handler: as(s.handleCreatePR)},
|
||||
{Subject: SubjectFor(identity, SubjectLinkBranch), Handler: as(s.handleLinkBranch)},
|
||||
{Subject: SubjectFor(identity, SubjectSetStateLabel), Handler: as(s.handleSetStateLabel)},
|
||||
{Subject: SubjectFor(identity, SubjectCreateReviewComment), Handler: as(s.handleCreateReviewComments)},
|
||||
{Subject: SubjectFor(identity, SubjectReplyToReview), Handler: as(s.handleReplyToReview)},
|
||||
{Subject: serverSubject(identity, SubjectComment), Handler: as(s.handleComment)},
|
||||
{Subject: serverSubject(identity, SubjectCloseIssue), Handler: as(s.handleCloseIssue)},
|
||||
{Subject: serverSubject(identity, SubjectCreatePR), Handler: as(s.handleCreatePR)},
|
||||
{Subject: serverSubject(identity, SubjectLinkBranch), Handler: as(s.handleLinkBranch)},
|
||||
{Subject: serverSubject(identity, SubjectSetStateLabel), Handler: as(s.handleSetStateLabel)},
|
||||
{Subject: serverSubject(identity, SubjectCreateReviewComment), Handler: as(s.handleCreateReviewComments)},
|
||||
{Subject: serverSubject(identity, SubjectReplyToReview), Handler: as(s.handleReplyToReview)},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -186,7 +194,7 @@ func (s *Server) authorize(identity string, target Target, permission string) er
|
||||
if err != nil {
|
||||
return fmt.Errorf("forge request credential is invalid: %w", err)
|
||||
}
|
||||
if task.Identity != identity || task.Owner == "" ||
|
||||
if (task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity)) || task.Owner == "" ||
|
||||
!strings.EqualFold(task.Owner, target.Owner) || !strings.EqualFold(task.Repo, target.Repo) {
|
||||
return errors.New("forge request is outside its run's repository")
|
||||
}
|
||||
@@ -210,17 +218,39 @@ func (s *Server) authorize(identity string, target Target, permission string) er
|
||||
return nil
|
||||
}
|
||||
|
||||
func serverSubject(identity, base string) string {
|
||||
if identity == "*" {
|
||||
return "archie.forge.*." + strings.TrimPrefix(base, "archie.forge.")
|
||||
}
|
||||
return SubjectFor(identity, base)
|
||||
}
|
||||
|
||||
func (s *Server) authorizedForge(identity string, target Target, permission string) (forge.Forge, error) {
|
||||
if err := s.authorize(identity, target, permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.Resolve == nil {
|
||||
return nil, errors.New("forge connection unavailable")
|
||||
}
|
||||
task, err := s.Runs.TaskForCredential(context.Background(), target.Credential)
|
||||
if err != nil {
|
||||
return nil, errors.New("forge request credential is invalid")
|
||||
}
|
||||
return s.Resolve(context.Background(), task)
|
||||
}
|
||||
|
||||
func (s *Server) handleComment(identity string, msg *nats.Msg) {
|
||||
var req CommentRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CommentResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode comment request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "comment"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "comment")
|
||||
if err != nil {
|
||||
s.respond(msg, CommentResponse{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
id, err := s.Forge.Comment(context.Background(), req.Owner, req.Repo, req.Number, req.Body)
|
||||
id, err := client.Comment(context.Background(), req.Owner, req.Repo, req.Number, req.Body)
|
||||
s.respond(msg, CommentResponse{ID: id, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -230,11 +260,12 @@ func (s *Server) handleCloseIssue(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode close_issue request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "comment"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "comment")
|
||||
if err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
err := s.Forge.CloseIssue(context.Background(), req.Owner, req.Repo, req.Number, req.Comment)
|
||||
err = client.CloseIssue(context.Background(), req.Owner, req.Repo, req.Number, req.Comment)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -244,11 +275,12 @@ func (s *Server) handleCreatePR(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, CreatePRResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_pr request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "open_pr"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "open_pr")
|
||||
if err != nil {
|
||||
s.respond(msg, CreatePRResponse{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
num, err := s.Forge.CreatePR(context.Background(), req.Owner, req.Repo, req.Title, req.Head, req.Base, req.Body)
|
||||
num, err := client.CreatePR(context.Background(), req.Owner, req.Repo, req.Title, req.Head, req.Base, req.Body)
|
||||
s.respond(msg, CreatePRResponse{Number: num, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -258,11 +290,12 @@ func (s *Server) handleLinkBranch(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode link_branch request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "open_pr"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "open_pr")
|
||||
if err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
err := s.Forge.LinkBranch(context.Background(), req.Owner, req.Repo, req.IssueNumber, req.Branch)
|
||||
err = client.LinkBranch(context.Background(), req.Owner, req.Repo, req.IssueNumber, req.Branch)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -272,11 +305,12 @@ func (s *Server) handleCreateReviewComments(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_review_comments request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "review"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "review")
|
||||
if err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
writer, ok := s.Forge.(forge.ReviewCommentWriter)
|
||||
writer, ok := client.(forge.ReviewCommentWriter)
|
||||
if !ok {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(errors.New("this forge cannot post review comments"))})
|
||||
return
|
||||
@@ -285,7 +319,7 @@ func (s *Server) handleCreateReviewComments(identity string, msg *nats.Msg) {
|
||||
for _, cm := range req.Comments {
|
||||
comments = append(comments, forge.InlineReviewComment{Path: cm.Path, Line: cm.Line, Body: cm.Body})
|
||||
}
|
||||
err := writer.CreateReviewComments(context.Background(), req.Owner, req.Repo, req.Number, req.ReviewedHeadSHA, comments)
|
||||
err = writer.CreateReviewComments(context.Background(), req.Owner, req.Repo, req.Number, req.ReviewedHeadSHA, comments)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -295,16 +329,17 @@ func (s *Server) handleReplyToReview(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode reply_to_review request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "review"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "review")
|
||||
if err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
reader, ok := s.Forge.(forge.PullRequestReviewReader)
|
||||
reader, ok := client.(forge.PullRequestReviewReader)
|
||||
if !ok {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(errors.New("this forge cannot reply to reviews"))})
|
||||
return
|
||||
}
|
||||
err := reader.ReplyToReview(context.Background(), req.Owner, req.Repo, req.Number, req.CommentID, req.Body)
|
||||
err = reader.ReplyToReview(context.Background(), req.Owner, req.Repo, req.Number, req.CommentID, req.Body)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
@@ -314,11 +349,12 @@ func (s *Server) handleSetStateLabel(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode set_state_label request: %w", err))})
|
||||
return
|
||||
}
|
||||
if err := s.authorize(identity, req.Target, "comment"); err != nil {
|
||||
client, err := s.authorizedForge(identity, req.Target, "comment")
|
||||
if err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
s.Forge.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
client.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ var dashboardPages = []DashboardPage{
|
||||
{Path: "/settings/appearance", Label: "Appearance", Description: "Theme, density, motion."},
|
||||
{Path: "/settings/task-execution", Label: "Task execution", Description: "Statuses, operator actions, budgets."},
|
||||
{Path: "/settings/models", Label: "Models", Description: "Instance model aliases and providers."},
|
||||
{Path: "/settings/repositories", Label: "Repositories", Description: "Watched repositories and gate overrides."},
|
||||
{Path: "/org/repositories", Label: "Repositories", Description: "Watched repositories and gate overrides."},
|
||||
{Path: "/settings/scheduling-policy", Label: "Scheduling policy", Description: "Work discovery and forge labels."},
|
||||
{Path: "/settings/review", Label: "Review", Description: "Pull request review: precision filter and approval."},
|
||||
{Path: "/settings/tools", Label: "Tools & MCP", Description: "Agent tools and MCP servers."},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Package daemonrpc calls the daemon's credential-backed repository checks.
|
||||
package daemonrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
|
||||
)
|
||||
|
||||
type Client struct{ rpc pb.DaemonServiceClient }
|
||||
|
||||
func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
|
||||
creds, err := id.DialOption(target, presence.Daemon)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
conn, err := grpc.NewClient(target, creds)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &Client{rpc: pb.NewDaemonServiceClient(conn)}, func() { _ = conn.Close() }, nil
|
||||
}
|
||||
|
||||
func (c *Client) CheckRepository(ctx context.Context, r *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error) {
|
||||
return c.rpc.CheckRepository(rpcidentity.Outgoing(ctx, presence.UI), r)
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error
|
||||
}
|
||||
// A pinned definition that no longer parses offers no resume points.
|
||||
stages, _ := workflow.StageNames(t.WorkflowDefinitionYAML)
|
||||
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, PRNumber: t.PRNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds, Stages: stages}, nil
|
||||
return &taskactions.Task{ID: t.ID, Org: t.Org, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, PRNumber: t.PRNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds, Stages: stages}, nil
|
||||
}
|
||||
|
||||
// CancelExecution delegates to the store.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
|
||||
)
|
||||
|
||||
type RepositoryChecker interface {
|
||||
CheckRepository(context.Context, *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error)
|
||||
}
|
||||
|
||||
func (s *Server) handleRepositoryCheck(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.RepositoryChecks == nil {
|
||||
http.Error(w, "Repository checks are unavailable. See Instance → Status for service availability.", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
|
||||
var request pb.CheckRepositoryRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
http.Error(w, "Choose a repository and agent.", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
response, err := s.RepositoryChecks.CheckRepository(r.Context(), &request)
|
||||
if err != nil {
|
||||
code, message := http.StatusServiceUnavailable, "Repository access could not be checked. See Instance → Status, then try again."
|
||||
switch status.Code(err) {
|
||||
case codes.PermissionDenied:
|
||||
code, message = http.StatusForbidden, "You do not have permission to check repository access."
|
||||
case codes.Unauthenticated:
|
||||
code, message = http.StatusUnauthorized, "Sign in before checking repository access."
|
||||
case codes.InvalidArgument:
|
||||
code, message = http.StatusBadRequest, "Choose a repository and agent."
|
||||
}
|
||||
http.Error(w, message, code)
|
||||
return
|
||||
}
|
||||
writeJSON(w, response)
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
@@ -195,32 +196,55 @@ func (s *Server) workRequestRepository(ctx context.Context, mode task.Repository
|
||||
if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") {
|
||||
return "", "", http.StatusBadRequest, errors.New("repository must be owner/name")
|
||||
}
|
||||
view, found, err := s.configSource()(ctx)
|
||||
if err != nil || !found {
|
||||
return "", "", http.StatusServiceUnavailable, errors.New("configured repositories unavailable")
|
||||
repos, err := s.configuredRepositories(ctx)
|
||||
if err != nil {
|
||||
return "", "", http.StatusServiceUnavailable, err
|
||||
}
|
||||
if !viewHasRepo(view, owner, repo) {
|
||||
found := false
|
||||
for _, r := range repos {
|
||||
if strings.EqualFold(r.Owner, owner) && strings.EqualFold(r.Name, repo) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return "", "", http.StatusBadRequest, fmt.Errorf("repository %s/%s is not configured", owner, repo)
|
||||
}
|
||||
return owner, repo, 0, nil
|
||||
}
|
||||
|
||||
// viewHasRepo reports whether the default identity or any named identity
|
||||
// manages owner/repo.
|
||||
func viewHasRepo(view ConfigView, owner, repo string) bool {
|
||||
for _, r := range view.Repositories {
|
||||
if strings.EqualFold(r.Owner, owner) && strings.EqualFold(r.Name, repo) {
|
||||
return true
|
||||
}
|
||||
// handleRepositories lists configured names without requiring permission to
|
||||
// read or edit the organisation's full settings document.
|
||||
func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) {
|
||||
repos, err := s.configuredRepositories(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "Configured repositories are unavailable.", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
for _, identity := range view.Identities {
|
||||
for _, r := range identity.Repos {
|
||||
if strings.EqualFold(r.Owner, owner) && strings.EqualFold(r.Name, repo) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
type repositoryName struct {
|
||||
Owner string `json:"owner"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
return false
|
||||
names := make([]repositoryName, 0, len(repos))
|
||||
for _, repo := range repos {
|
||||
names = append(names, repositoryName{Owner: repo.Owner, Name: repo.Name})
|
||||
}
|
||||
writeJSON(w, names)
|
||||
}
|
||||
|
||||
func (s *Server) configuredRepositories(ctx context.Context) ([]config.Repo, error) {
|
||||
if s.ControlPlane == nil {
|
||||
return nil, errors.New("configured repositories unavailable")
|
||||
}
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: "repository-policies"})
|
||||
if err != nil || response.Resource == nil {
|
||||
return nil, errors.New("configured repositories unavailable")
|
||||
}
|
||||
var repos []config.Repo
|
||||
if err := json.Unmarshal(response.Resource.ValueJson, &repos); err != nil {
|
||||
return nil, errors.New("configured repositories unavailable")
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
// enabledWorkflowInterface returns a workflow's declared interface and whether
|
||||
|
||||
@@ -61,6 +61,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
|
||||
{"GET", "/api/harness/terminal"},
|
||||
{"GET", "/api/identities"},
|
||||
{"GET", "/api/logs"},
|
||||
{"GET", "/api/repositories"},
|
||||
{"GET", "/api/mappings"},
|
||||
{"GET", "/api/mappings/7"},
|
||||
{"GET", "/api/orgs"},
|
||||
@@ -125,6 +126,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
|
||||
{"POST", "/api/tasks/7/action"},
|
||||
{"POST", "/api/tokens"},
|
||||
{"POST", "/api/work-requests"},
|
||||
{"POST", "/api/control-plane/resources/repository-policies/check"},
|
||||
{"PUT", "/api/access/policies"},
|
||||
{"PUT", "/api/authentication"},
|
||||
{"PUT", "/api/event-types/7"},
|
||||
|
||||
@@ -378,7 +378,7 @@ func kindOf(path string) access.ResourceKind {
|
||||
return access.KindBinding
|
||||
case matchPrefix(path, "/api/sources"):
|
||||
return access.KindSource
|
||||
case matchPrefix(path, "/api/work-requests"):
|
||||
case matchPrefix(path, "/api/work-requests"), matchPrefix(path, "/api/repositories"):
|
||||
return access.KindTask
|
||||
}
|
||||
return access.KindDashboard
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
RepositoryChecks RepositoryChecker
|
||||
Accounts identity.Accounts
|
||||
accountRateLimit *ratelimit.Limiter
|
||||
|
||||
@@ -261,6 +262,8 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
|
||||
mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled)
|
||||
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
|
||||
mux.HandleFunc("GET /api/repositories", s.handleRepositories)
|
||||
mux.HandleFunc("POST /api/control-plane/resources/repository-policies/check", s.handleRepositoryCheck)
|
||||
mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills))
|
||||
mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators))
|
||||
mux.HandleFunc("GET /api/captures", s.handleCaptures)
|
||||
|
||||
@@ -143,6 +143,30 @@ func TestForgeHTTPAuthentication(t *testing.T) {
|
||||
if _, _, err := m.Prepare(t.Context(), "org", "repo", "main", issue, "test", "", "", Target(branch)); err != nil {
|
||||
t.Fatalf("authenticated fetch: %v", err)
|
||||
}
|
||||
if err := m.CheckAccess(t.Context(), "org", "repo", "main"); err != nil {
|
||||
t.Fatalf("read-only access check: %v", err)
|
||||
}
|
||||
if err := m.CheckAccess(t.Context(), "org", "repo", "missing"); err == nil {
|
||||
t.Fatal("missing base branch verified")
|
||||
}
|
||||
cloned, err := git.PlainOpen(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed, err := cloned.Config()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed.Remotes["origin"].URLs = []string{target.URL + "/org/repo.git"}
|
||||
if err := cloned.SetConfig(changed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.PushRepository(t.Context(), "org", "repo", issue, branch); err != nil {
|
||||
t.Fatalf("push to authorised connection: %v", err)
|
||||
}
|
||||
if _, _, err := m.Prepare(t.Context(), "org", "repo", "main", issue, "test", "", "", Fresh); err == nil {
|
||||
t.Fatal("prepared worktree from another origin was reused")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
fdiff "github.com/go-git/go-git/v6/plumbing/format/diff"
|
||||
"github.com/go-git/go-git/v6/plumbing/object"
|
||||
githttp "github.com/go-git/go-git/v6/plumbing/transport/http"
|
||||
"github.com/go-git/go-git/v6/storage/memory"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
@@ -40,6 +41,7 @@ type Manager struct {
|
||||
// and passed to go-git directly, never written to .git/config, an
|
||||
// askpass helper, or a child process environment.
|
||||
Token string
|
||||
AuthUser string
|
||||
BotUser string
|
||||
BotEmail string
|
||||
// BaseURL overrides the forge host. Set from config [forge].host.
|
||||
@@ -57,6 +59,12 @@ func (m *Manager) logger() *slog.Logger {
|
||||
return slog.Default()
|
||||
}
|
||||
|
||||
// OrgWorkDir confines an organisation's worktrees beneath root, including
|
||||
// legacy organisation IDs that contain filesystem separators.
|
||||
func OrgWorkDir(root, org string) string {
|
||||
return filepath.Join(root, "org-"+base64.RawURLEncoding.EncodeToString([]byte(org)))
|
||||
}
|
||||
|
||||
// Dir is the worktree path for a task.
|
||||
func (m *Manager) Dir(owner, repo string, issue int) string {
|
||||
ownerKey := base64.RawURLEncoding.EncodeToString([]byte(owner))
|
||||
@@ -77,7 +85,7 @@ func (m *Manager) auth() []gitclient.Option {
|
||||
if m.Token == "" {
|
||||
return nil
|
||||
}
|
||||
username := m.BotUser
|
||||
username := m.AuthUser
|
||||
if username == "" {
|
||||
// Any non-empty username is accepted alongside a token; this one
|
||||
// makes the origin obvious in a forge's audit log.
|
||||
@@ -130,6 +138,9 @@ func (m *Manager) Prepare(
|
||||
prepared = migrated
|
||||
}
|
||||
|
||||
if prepared && !repositoryUsesURL(dir, m.cloneURL(owner, repo)) {
|
||||
return "", "", fmt.Errorf("the worktree belongs to a different repository connection; archive it before starting again")
|
||||
}
|
||||
if !prepared {
|
||||
if err := m.createClone(ctx, owner, repo, base, dir); err != nil {
|
||||
return "", "", err
|
||||
@@ -466,18 +477,29 @@ func (m *Manager) CommitAll(ctx context.Context, dir, message string) (bool, err
|
||||
|
||||
// Push publishes the branch and sets it to track origin.
|
||||
func (m *Manager) Push(ctx context.Context, dir, branch string) error {
|
||||
return m.push(ctx, dir, branch, "")
|
||||
}
|
||||
|
||||
// PushRepository pins the destination to the authorised connection rather
|
||||
// than trusting origin in a container-writable Git configuration.
|
||||
func (m *Manager) PushRepository(ctx context.Context, owner, repo string, issue int, branch string) error {
|
||||
return m.push(ctx, m.Dir(owner, repo, issue), branch, m.cloneURL(owner, repo))
|
||||
}
|
||||
|
||||
func (m *Manager) push(ctx context.Context, dir, branch, remoteURL string) error {
|
||||
r, err := git.PlainOpen(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open worktree: %w", err)
|
||||
}
|
||||
if m.Token == "" && remoteUsesHTTP(r) {
|
||||
return fmt.Errorf("push %s: no forge credential configured; "+
|
||||
"set [forge].token (or the identity's forge.token) so archied can authenticate", branch)
|
||||
"check the repository connection's credential", branch)
|
||||
}
|
||||
ref := plumbing.NewBranchReferenceName(branch)
|
||||
spec := gitconfig.RefSpec(fmt.Sprintf("%s:%s", ref, ref))
|
||||
if err := r.PushContext(ctx, &git.PushOptions{
|
||||
RemoteName: git.DefaultRemoteName,
|
||||
RemoteURL: remoteURL,
|
||||
RefSpecs: []gitconfig.RefSpec{spec},
|
||||
ClientOptions: m.auth(),
|
||||
}); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
|
||||
@@ -990,3 +1012,21 @@ func (m *Manager) cloneURL(owner, repo string) string {
|
||||
}
|
||||
return fmt.Sprintf("https://github.com/%s/%s.git", owner, repo)
|
||||
}
|
||||
|
||||
var ErrBaseBranchNotFound = errors.New("base branch not found")
|
||||
|
||||
// CheckAccess checks the same authenticated Git endpoint as Prepare, without
|
||||
// creating a clone, branch, or commit.
|
||||
func (m *Manager) CheckAccess(ctx context.Context, owner, repo, base string) error {
|
||||
remote := git.NewRemote(memory.NewStorage(), &gitconfig.RemoteConfig{Name: "origin", URLs: []string{m.cloneURL(owner, repo)}})
|
||||
refs, err := remote.ListContext(ctx, &git.ListOptions{ClientOptions: m.auth()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if ref.Name() == plumbing.NewBranchReferenceName(base) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w: %s", ErrBaseBranchNotFound, base)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func publishable(ctx context.Context, runs Runs, token, identity string) (*workf
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("worktree publication grant is invalid: %w", err)
|
||||
}
|
||||
if task.Identity != identity || task.Branch == "" ||
|
||||
if (task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity)) || task.Branch == "" ||
|
||||
!worktree.ValidCoordinates(task.Owner, task.Repo, task.IssueNumber) {
|
||||
return nil, errors.New("worktree publication grant is invalid")
|
||||
}
|
||||
@@ -74,9 +74,9 @@ const defaultHandlerTimeout = 15 * time.Minute
|
||||
// Server proxies push requests to a real worktree.Manager holding the
|
||||
// forge push token.
|
||||
type Server struct {
|
||||
Trees *worktree.Manager
|
||||
Runs Runs
|
||||
Log *slog.Logger
|
||||
Resolve func(context.Context, *workflow.Task) (*worktree.Manager, error)
|
||||
Runs Runs
|
||||
Log *slog.Logger
|
||||
// Timeout bounds a single publication. Zero uses
|
||||
// defaultHandlerTimeout.
|
||||
Timeout time.Duration
|
||||
@@ -99,8 +99,18 @@ func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
|
||||
// RegisterFor registers publication under the subject scoped to identity.
|
||||
func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) {
|
||||
subject := SubjectFor(identity, SubjectPush)
|
||||
if identity == "*" {
|
||||
subject = "archie.worktree.*.push"
|
||||
}
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectFor(identity, SubjectPush), Handler: func(msg *nats.Msg) { s.handlePush(identity, msg) }},
|
||||
{Subject: subject, Handler: func(msg *nats.Msg) {
|
||||
scoped := identity
|
||||
if identity == "*" {
|
||||
scoped = strings.Split(msg.Subject, ".")[2]
|
||||
}
|
||||
s.handlePush(scoped, msg)
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -117,8 +127,16 @@ func (s *Server) handlePush(identity string, msg *nats.Msg) {
|
||||
s.respond(msg, err)
|
||||
return
|
||||
}
|
||||
dir := s.Trees.Dir(task.Owner, task.Repo, task.IssueNumber)
|
||||
s.respond(msg, s.Trees.Push(ctx, dir, task.Branch))
|
||||
if s.Resolve == nil {
|
||||
s.respond(msg, errors.New("repository connection unavailable"))
|
||||
return
|
||||
}
|
||||
trees, err := s.Resolve(ctx, task)
|
||||
if err != nil {
|
||||
s.respond(msg, err)
|
||||
return
|
||||
}
|
||||
s.respond(msg, trees.PushRepository(ctx, task.Owner, task.Repo, task.IssueNumber, task.Branch))
|
||||
}
|
||||
|
||||
func (s *Server) respond(msg *nats.Msg, err error) {
|
||||
|
||||
Reference in new issue
Block a user