Files
archie/internal/app/archied/repository_access.go
T
sam 0e889977c0
deploy / plan (push) Successful in 6s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
deploy / gate (push) Canceled after 2m50s
fix(archied): resolve merge, close and issue tools through the repository's connection (#1847)
2026-11-10 19:25:15 +11:00

242 lines
10 KiB
Go

package archied
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"path/filepath"
"strings"
"syscall"
"github.com/go-git/go-git/v6"
"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/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"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.")
}
// repositoryForge is the forge client of owner/repo's own connection, for
// operator and chat actions, in the org ctx carries. The instance's default
// forge may be a different host entirely.
func (b *boot) repositoryForge(ctx context.Context, owner, repo string) (forge.Forge, error) {
repository, err := b.repositoryBinding(ctx, owner, repo)
if err != nil {
return nil, err
}
if repository.Connection == "" {
return nil, &forge.AccessError{Code: "connection_required", Message: "Choose a connection for this repository."}
}
connections, err := b.repositoryConnections(ctx)
if err != nil {
return nil, err
}
for _, connection := range connections {
if connection.ID != repository.Connection {
continue
}
token, code, message := b.connectionToken(ctx, connection)
if code != "" {
return nil, &forge.AccessError{Code: code, Connection: connection.ID, Message: message}
}
client := b.connectionForge(ctx, connection, org.OrgFromContext(ctx), token)
if _, disabled := client.(*forge.NoopForge); disabled {
return nil, &forge.AccessError{Code: "forge_unavailable", Connection: connection.ID, Message: "Enable the forge extension for this connection."}
}
return client, nil
}
return nil, &forge.AccessError{Code: "connection_missing", Connection: repository.Connection, Message: "The selected connection no longer exists. Choose another connection."}
}
func (b *boot) repositoryBinding(ctx context.Context, owner, name string) (config.Repo, error) {
var repos []config.Repo
_, found, err := b.controlPlane.Query(ctx, controlplanestore.RepositoryPoliciesKind, func(value []byte) error { return json.Unmarshal(value, &repos) })
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, controlplanestore.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, code, message := b.connectionToken(ctx, connection)
if code != "" {
return failure(code, message)
}
host := strings.TrimRight(connection.Host, "/")
if !strings.Contains(host, "://") {
host = "https://" + host
}
out.Forge = b.connectionForge(ctx, connection, principal.Org, token)
cfg := b.cfgHolder.Get()
username := connection.Account
gitToken := token
var (
minted forge.GitCredential
err error
)
if issuer, ok := out.Forge.(forge.GitCredentialIssuer); ok {
minted, err = issuer.GitCredential(ctx, repository.Owner, repository.Name)
switch {
case errors.Is(err, errors.ErrUnsupported):
case err != nil:
b.log.WarnContext(ctx, "git credential unavailable", "connection", connection.ID, "error", err)
return failure("credential_unavailable", fmt.Sprintf("%s could not issue a credential for %s/%s. Check the app is installed on it.", connection.Name, repository.Owner, repository.Name))
default:
username, gitToken = minted.Username, minted.Token
}
}
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.")
}
}
botUser, botEmail := commitIdentity(cfg, connection, minted, username)
signer, code, message := b.connectionSigner(connection)
if code != "" {
return failure(code, message)
}
out.Trees = &worktree.Manager{WorkDir: worktree.OrgWorkDir(cfg.WorkDir, string(principal.Org)), Token: gitToken, AuthUser: username, BaseURL: host, BotUser: botUser, BotEmail: botEmail, Signer: signer, Log: b.log}
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
}
// connectionToken resolves the connection's credential, or returns a failure
// code and message. A full volume is reported as such, not as a bad reference.
func (b *boot) connectionToken(ctx context.Context, connection config.ForgeConnection) (string, string, string) {
token, err := b.secrets.Resolve(connection.Token)
if volume, full := exhaustedVolume(err); full {
b.log.ErrorContext(ctx, "secret resolution failed: host resource exhausted", "connection", connection.ID, "volume", volume, "error", err)
return "", "environment_exhausted", fmt.Sprintf("The host has run out of space on %s, so the credential for %s cannot be read. Free space there.", volume, connection.Name)
}
if err != nil || token == "" {
return "", "credential_unavailable", fmt.Sprintf("The credential for %s is unavailable. Check its secret reference.", connection.Name)
}
return token, "", ""
}
// exhaustedVolume reports whether err is a full volume or quota and names the
// volume, so the failure reads as an environment problem rather than a
// misconfigured secret.
func exhaustedVolume(err error) (string, bool) {
if !errors.Is(err, syscall.ENOSPC) && !errors.Is(err, syscall.EDQUOT) {
return "", false
}
if pathErr, ok := errors.AsType[*fs.PathError](err); ok {
return filepath.Dir(pathErr.Path), true
}
return "the host volume", true
}
// commitIdentity is the author of commits made through a connection: its
// configured commit identity, else the identity the forge minted with the
// credential, else the root bot fields, else its account.
func commitIdentity(cfg config.Config, connection config.ForgeConnection, minted forge.GitCredential, account string) (string, string) {
if connection.CommitName != "" {
return connection.CommitName, configuration.DefaultBotEmail(connection.Type, connection.CommitName, connection.CommitEmail)
}
if minted.CommitName != "" {
return minted.CommitName, minted.CommitEmail
}
if cfg.BotUser != "" {
return cfg.BotUser, cfg.BotEmail
}
user := account
if user == "" {
user = "archie"
}
return user, configuration.DefaultBotEmail(connection.Type, user, connection.CommitEmail)
}
// connectionSigner resolves the connection's SSH signing key. It returns nil
// when none is configured, or a failure code and message.
func (b *boot) connectionSigner(connection config.ForgeConnection) (git.Signer, string, string) {
if connection.SigningKey.Key == "" {
return nil, "", ""
}
key, err := b.secrets.Resolve(connection.SigningKey)
if err != nil || key == "" {
return nil, "signing_key_unavailable", fmt.Sprintf("The signing key for %s is unavailable. Check its secret reference.", connection.Name)
}
signer, err := worktree.NewSSHSigner([]byte(key))
if err != nil {
return nil, "signing_key_invalid", fmt.Sprintf("The signing key for %s is not an OpenSSH private key.", connection.Name)
}
return signer, "", ""
}