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, r.IdentityId), nil } func checkRepositoryAccess(ctx context.Context, resolved daemon.RepositoryAccess, identityID string) *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.Operations = []string{config.OperationClone} canWrite, err := repositoryWritable(ctx, resolved.Connection.Type, resolved.Trees.BaseURL, resolved.Trees.Token, resolved.Repository.Owner, resolved.Repository.Name) if err != nil { response.Code = "write_unverified" response.Message = "Write access could not be checked." return response } for _, op := range []string{config.OperationPush, config.OperationPR} { if canWrite && resolved.Connection.Permitted(identityID, op) { response.Operations = append(response.Operations, op) } } return response } // Account discovery is read-only and never follows redirects with credentials. func connectionAccount(ctx context.Context, typ, host, token string) (string, error) { var account struct { Login string `json:"login"` } if err := forgeGet(ctx, typ, host, token, "user", &account); err != nil || account.Login == "" { return "", errors.New("forge account unavailable") } return account.Login, nil } // repositoryWritable reports whether the credential can push to the repository. func repositoryWritable(ctx context.Context, typ, host, token, owner, repo string) (bool, error) { var repository struct { Permissions struct { Push bool `json:"push"` } `json:"permissions"` } if err := forgeGet(ctx, typ, host, token, "repos/"+url.PathEscape(owner)+"/"+url.PathEscape(repo), &repository); err != nil { return false, err } return repository.Permissions.Push, nil } func forgeGet(ctx context.Context, typ, host, token, path string, out any) 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 = "/" + path } else { endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/api/v3/" + path } case "gitea": authorization = "token " + token endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/api/v1/" + path default: return errors.New("access 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 unavailable") } defer response.Body.Close() if response.StatusCode != http.StatusOK { return errors.New("forge refused") } return json.NewDecoder(io.LimitReader(response.Body, 256<<10)).Decode(out) }