302 lines
13 KiB
Go
302 lines
13 KiB
Go
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/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/infrastructure/controlplanestore"
|
|
"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 == controlplanestore.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: controlplanestore.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: controlplanestore.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)
|
|
}
|
|
})
|
|
}
|
|
}
|