code cleaning, address pr comments

gitness-public-repo-testing
atefeh 2024-05-07 00:06:26 -07:00
parent 1f410581af
commit 0ff77052f7
84 changed files with 536 additions and 637 deletions

View File

@ -58,18 +58,7 @@ func CheckRepoIsPublic(
publicAccess publicaccess.PublicAccess, publicAccess publicaccess.PublicAccess,
repo *types.Repository, repo *types.Repository,
) (bool, error) { ) (bool, error) {
parentSpace, name, err := paths.DisectLeaf(repo.Path) return publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path)
if err != nil {
return false, fmt.Errorf("failed to disect path '%s': %w", repo.Path, err)
}
scope := &types.Scope{SpacePath: parentSpace}
resource := &types.Resource{
Type: enum.ResourceTypeRepo,
Identifier: name,
}
return publicAccess.Get(ctx, scope, resource)
} }
func IsRepoOwner( func IsRepoOwner(

View File

@ -75,16 +75,5 @@ func CheckSpaceIsPublic(
publicAccess publicaccess.PublicAccess, publicAccess publicaccess.PublicAccess,
space *types.Space, space *types.Space,
) (bool, error) { ) (bool, error) {
parentSpace, name, err := paths.DisectLeaf(space.Path) return publicAccess.Get(ctx, enum.PublicResourceTypeSpace, space.Path)
if err != nil {
return false, fmt.Errorf("failed to disect path '%s': %w", space.Path, err)
}
scope := &types.Scope{SpacePath: parentSpace}
resource := &types.Resource{
Type: enum.ResourceTypeSpace,
Identifier: name,
}
return publicAccess.Get(ctx, scope, resource)
} }

View File

@ -43,7 +43,7 @@ func (c *Controller) ReviewerAdd(
prNum int64, prNum int64,
in *ReviewerAddInput, in *ReviewerAddInput,
) (*types.PullReqReviewer, error) { ) (*types.PullReqReviewer, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err) return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
} }

View File

@ -25,7 +25,7 @@ import (
// ReviewerDelete deletes reviewer from the reviewerlist for the given PR. // ReviewerDelete deletes reviewer from the reviewerlist for the given PR.
func (c *Controller) ReviewerDelete(ctx context.Context, session *auth.Session, func (c *Controller) ReviewerDelete(ctx context.Context, session *auth.Session,
repoRef string, prNum, reviewerID int64) error { repoRef string, prNum, reviewerID int64) error {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoReview)
if err != nil { if err != nil {
return fmt.Errorf("failed to acquire access to repo: %w", err) return fmt.Errorf("failed to acquire access to repo: %w", err)
} }

View File

@ -37,7 +37,7 @@ func (c *Controller) Archive(
} }
return c.git.Archive(ctx, git.ArchiveParams{ return c.git.Archive(ctx, git.ArchiveParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
ArchiveParams: params, ArchiveParams: params,
}, w) }, w)
} }

View File

@ -45,12 +45,12 @@ func (c *Controller) Blame(ctx context.Context,
} }
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
reader := git.NewStreamReader( reader := git.NewStreamReader(
c.git.Blame(ctx, &git.BlameParams{ c.git.Blame(ctx, &git.BlameParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
GitRef: gitRef, GitRef: gitRef,
Path: path, Path: path,
LineFrom: lineFrom, LineFrom: lineFrom,

View File

@ -34,10 +34,10 @@ func (c *Controller) CodeOwnersValidate(
} }
if ref == "" { if ref == "" {
ref = repo.Repository.DefaultBranch ref = repo.DefaultBranch
} }
violations, err := c.codeOwners.Validate(ctx, &repo.Repository, ref) violations, err := c.codeOwners.Validate(ctx, repo, ref)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -67,7 +67,7 @@ func (c *Controller) CommitFiles(ctx context.Context,
return types.CommitFilesResponse{}, nil, err return types.CommitFilesResponse{}, nil, err
} }
rules, isRepoOwner, err := c.fetchRules(ctx, session, &repo.Repository) rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil { if err != nil {
return types.CommitFilesResponse{}, nil, err return types.CommitFilesResponse{}, nil, err
} }
@ -86,7 +86,7 @@ func (c *Controller) CommitFiles(ctx context.Context,
Actor: &session.Principal, Actor: &session.Principal,
AllowBypass: in.BypassRules, AllowBypass: in.BypassRules,
IsRepoOwner: isRepoOwner, IsRepoOwner: isRepoOwner,
Repo: &repo.Repository, Repo: repo,
RefAction: refAction, RefAction: refAction,
RefType: protection.RefTypeBranch, RefType: protection.RefTypeBranch,
RefNames: []string{branchName}, RefNames: []string{branchName},
@ -131,7 +131,7 @@ func (c *Controller) CommitFiles(ctx context.Context,
} }
// Create internal write params. Note: This will skip the pre-commit protection rules check. // Create internal write params. Note: This will skip the pre-commit protection rules check.
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }

View File

@ -108,11 +108,11 @@ func (c *Controller) GetContent(ctx context.Context,
// set gitRef to default branch in case an empty reference was provided // set gitRef to default branch in case an empty reference was provided
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
// create read params once // create read params once
readParams := git.CreateReadParams(repo.Repository) readParams := git.CreateReadParams(repo)
treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
ReadParams: readParams, ReadParams: readParams,

View File

@ -56,11 +56,11 @@ func (c *Controller) PathsDetails(ctx context.Context,
// set gitRef to default branch in case an empty reference was provided // set gitRef to default branch in case an empty reference was provided
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
result, err := c.git.PathsDetails(ctx, git.PathsDetailsParams{ result, err := c.git.PathsDetails(ctx, git.PathsDetailsParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
GitREF: gitRef, GitREF: gitRef,
Paths: input.Paths, Paths: input.Paths,
}) })

View File

@ -53,18 +53,6 @@ type Repository struct {
IsPublic bool `json:"is_public" yaml:"is_public"` IsPublic bool `json:"is_public" yaml:"is_public"`
} }
// Clone makes deep copy of repository object.
func (r Repository) Clone() Repository {
var deleted *int64
if r.Repository.Deleted != nil {
id := *r.Repository.Deleted
deleted = &id
}
r.Repository.Deleted = deleted
return r
}
type Controller struct { type Controller struct {
defaultBranch string defaultBranch string
publicResourceCreationEnabled bool publicResourceCreationEnabled bool
@ -153,10 +141,9 @@ func NewController(
func (c *Controller) getRepo( func (c *Controller) getRepo(
ctx context.Context, ctx context.Context,
repoRef string, repoRef string,
) (*Repository, error) { ) (*types.Repository, error) {
return GetRepo( return GetRepo(
ctx, ctx,
c.publicAccess,
c.repoStore, c.repoStore,
repoRef, repoRef,
) )
@ -169,12 +156,11 @@ func (c *Controller) getRepoCheckAccess(
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
) (*Repository, error) { ) (*types.Repository, error) {
return GetRepoCheckAccess( return GetRepoCheckAccess(
ctx, ctx,
c.repoStore, c.repoStore,
c.authorizer, c.authorizer,
c.publicAccess,
session, session,
repoRef, repoRef,
reqPermission, reqPermission,

View File

@ -109,28 +109,21 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
IsEmpty: isEmpty, IsEmpty: isEmpty,
} }
err = c.repoStore.Create(ctx, repo) return c.repoStore.Create(ctx, repo)
}, sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil { if err != nil {
// best effort cleanup
if dErr := c.DeleteGitRepository(ctx, session, repo); dErr != nil { if dErr := c.DeleteGitRepository(ctx, session, repo); dErr != nil {
log.Ctx(ctx).Warn().Err(dErr).Msg("failed to delete repo for cleanup") log.Ctx(ctx).Warn().Err(dErr).Msg("failed to delete repo for cleanup")
} }
return fmt.Errorf("failed to create repository in storage: %w", err)
}
return nil
}, sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
return nil, err return nil, err
} }
if in.IsPublic && c.publicResourceCreationEnabled { if err = c.SetRepoPublicAccess(ctx, repo, in.IsPublic); err != nil {
err = c.SetPublicRepo(ctx, repo)
if err != nil {
if dErr := c.PurgeNoAuth(ctx, session, repo); dErr != nil { if dErr := c.PurgeNoAuth(ctx, session, repo); dErr != nil {
log.Ctx(ctx).Warn().Err(dErr).Msg("failed to purge repo for cleanup") log.Ctx(ctx).Warn().Err(dErr).Msg("failed to purge repo for cleanup")
} }
return nil, fmt.Errorf("failed to set a public resource: %w", err) return nil, fmt.Errorf("failed to set repo public access: %w", err)
}
} }
// backfil GitURL // backfil GitURL
@ -287,19 +280,16 @@ func (c *Controller) createGitRepository(ctx context.Context, session *auth.Sess
return resp, len(files) == 0, nil return resp, len(files) == 0, nil
} }
func (c *Controller) SetPublicRepo(ctx context.Context, repo *types.Repository) error { func (c *Controller) SetRepoPublicAccess(
parentSpace, name, err := paths.DisectLeaf(repo.Path) ctx context.Context,
if err != nil { repo *types.Repository,
return fmt.Errorf("failed to disect path '%s': %w", repo.Path, err) isPublic bool,
) error {
if isPublic && !c.publicResourceCreationEnabled {
return errPublicRepoCreationDisabled
} }
scope := &types.Scope{SpacePath: parentSpace} return c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic)
resource := &types.Resource{
Type: enum.ResourceTypeRepo,
Identifier: name,
}
return c.publicAccess.Set(ctx, scope, resource, true)
} }
func createReadme(name, description string) []byte { func createReadme(name, description string) []byte {

View File

@ -50,10 +50,10 @@ func (c *Controller) CreateBranch(ctx context.Context,
// set target to default branch in case no target was provided // set target to default branch in case no target was provided
if in.Target == "" { if in.Target == "" {
in.Target = repo.Repository.DefaultBranch in.Target = repo.DefaultBranch
} }
rules, isRepoOwner, err := c.fetchRules(ctx, session, &repo.Repository) rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -62,7 +62,7 @@ func (c *Controller) CreateBranch(ctx context.Context,
Actor: &session.Principal, Actor: &session.Principal,
AllowBypass: in.BypassRules, AllowBypass: in.BypassRules,
IsRepoOwner: isRepoOwner, IsRepoOwner: isRepoOwner,
Repo: &repo.Repository, Repo: repo,
RefAction: protection.RefActionCreate, RefAction: protection.RefActionCreate,
RefType: protection.RefTypeBranch, RefType: protection.RefTypeBranch,
RefNames: []string{in.Name}, RefNames: []string{in.Name},
@ -74,7 +74,7 @@ func (c *Controller) CreateBranch(ctx context.Context,
return nil, violations, nil return nil, violations, nil
} }
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }

View File

@ -54,10 +54,10 @@ func (c *Controller) CreateCommitTag(ctx context.Context,
// set target to default branch in case no branch or commit was provided // set target to default branch in case no branch or commit was provided
if in.Target == "" { if in.Target == "" {
in.Target = repo.Repository.DefaultBranch in.Target = repo.DefaultBranch
} }
rules, isRepoOwner, err := c.fetchRules(ctx, session, &repo.Repository) rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -66,7 +66,7 @@ func (c *Controller) CreateCommitTag(ctx context.Context,
Actor: &session.Principal, Actor: &session.Principal,
AllowBypass: in.BypassRules, AllowBypass: in.BypassRules,
IsRepoOwner: isRepoOwner, IsRepoOwner: isRepoOwner,
Repo: &repo.Repository, Repo: repo,
RefAction: protection.RefActionCreate, RefAction: protection.RefActionCreate,
RefType: protection.RefTypeTag, RefType: protection.RefTypeTag,
RefNames: []string{in.Name}, RefNames: []string{in.Name},
@ -78,7 +78,7 @@ func (c *Controller) CreateCommitTag(ctx context.Context,
return nil, violations, nil return nil, violations, nil
} }
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }

View File

@ -57,7 +57,7 @@ func (c *Controller) UpdateDefaultBranch(
// requests will wait for previous ones to compelete before proceed // requests will wait for previous ones to compelete before proceed
unlock, err := c.locker.LockDefaultBranch( unlock, err := c.locker.LockDefaultBranch(
ctx, ctx,
repo.Repository.ID, repo.ID,
in.Name, // branch name only used for logging (lock is on repo) in.Name, // branch name only used for logging (lock is on repo)
timeout+30*time.Second, // add 30s to the lock to give enough time for updating default branch timeout+30*time.Second, // add 30s to the lock to give enough time for updating default branch
) )
@ -66,7 +66,7 @@ func (c *Controller) UpdateDefaultBranch(
} }
defer unlock() defer unlock()
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create RPC write params: %w", err) return nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }
@ -87,8 +87,8 @@ func (c *Controller) UpdateDefaultBranch(
return nil, fmt.Errorf("failed to update the repo default branch: %w", err) return nil, fmt.Errorf("failed to update the repo default branch: %w", err)
} }
oldName := repo.Repository.DefaultBranch oldName := repo.DefaultBranch
repoBase, err := c.repoStore.UpdateOptLock(ctx, &repo.Repository, func(r *types.Repository) error { repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error {
r.DefaultBranch = in.Name r.DefaultBranch = in.Name
return nil return nil
}) })
@ -96,16 +96,11 @@ func (c *Controller) UpdateDefaultBranch(
return nil, fmt.Errorf("failed to update the repo default branch on db:%w", err) return nil, fmt.Errorf("failed to update the repo default branch on db:%w", err)
} }
repo = &Repository{
Repository: *repoBase,
IsPublic: repo.IsPublic,
}
err = c.auditService.Log(ctx, err = c.auditService.Log(ctx,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeRepository, repo.Repository.Identifier), audit.NewResource(audit.ResourceTypeRepository, repo.Identifier),
audit.ActionUpdated, audit.ActionUpdated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(repoClone), audit.WithOldObject(repoClone),
audit.WithNewObject(repo), audit.WithNewObject(repo),
) )
@ -114,11 +109,11 @@ func (c *Controller) UpdateDefaultBranch(
} }
c.eventReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{ c.eventReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{
RepoID: repoBase.ID, RepoID: repo.ID,
PrincipalID: bootstrap.NewSystemServiceSession().Principal.ID, PrincipalID: bootstrap.NewSystemServiceSession().Principal.ID,
OldName: oldName, OldName: oldName,
NewName: repoBase.DefaultBranch, NewName: repo.DefaultBranch,
}) })
return repo, nil return GetRepoOutput(ctx, c.publicAccess, repo)
} }

View File

@ -43,11 +43,11 @@ func (c *Controller) DeleteBranch(ctx context.Context,
// ASSUMPTION: lower layer calls explicit branch api // ASSUMPTION: lower layer calls explicit branch api
// and 'refs/heads/branch1' would fail if 'branch1' exists. // and 'refs/heads/branch1' would fail if 'branch1' exists.
// TODO: Add functional test to ensure the scenario is covered! // TODO: Add functional test to ensure the scenario is covered!
if branchName == repo.Repository.DefaultBranch { if branchName == repo.DefaultBranch {
return nil, usererror.ErrDefaultBranchCantBeDeleted return nil, usererror.ErrDefaultBranchCantBeDeleted
} }
rules, isRepoOwner, err := c.fetchRules(ctx, session, &repo.Repository) rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -56,7 +56,7 @@ func (c *Controller) DeleteBranch(ctx context.Context,
Actor: &session.Principal, Actor: &session.Principal,
AllowBypass: bypassRules, AllowBypass: bypassRules,
IsRepoOwner: isRepoOwner, IsRepoOwner: isRepoOwner,
Repo: &repo.Repository, Repo: repo,
RefAction: protection.RefActionDelete, RefAction: protection.RefActionDelete,
RefType: protection.RefTypeBranch, RefType: protection.RefTypeBranch,
RefNames: []string{branchName}, RefNames: []string{branchName},
@ -68,7 +68,7 @@ func (c *Controller) DeleteBranch(ctx context.Context,
return violations, nil return violations, nil
} }
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create RPC write params: %w", err) return nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }

View File

@ -38,7 +38,7 @@ func (c *Controller) DeleteTag(ctx context.Context,
return nil, err return nil, err
} }
rules, isRepoOwner, err := c.fetchRules(ctx, session, &repo.Repository) rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -47,7 +47,7 @@ func (c *Controller) DeleteTag(ctx context.Context,
Actor: &session.Principal, Actor: &session.Principal,
AllowBypass: bypassRules, AllowBypass: bypassRules,
IsRepoOwner: isRepoOwner, IsRepoOwner: isRepoOwner,
Repo: &repo.Repository, Repo: repo,
RefAction: protection.RefActionDelete, RefAction: protection.RefActionDelete,
RefType: protection.RefTypeTag, RefType: protection.RefTypeTag,
RefNames: []string{tagName}, RefNames: []string{tagName},
@ -59,7 +59,7 @@ func (c *Controller) DeleteTag(ctx context.Context,
return violations, nil return violations, nil
} }
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create RPC write params: %w", err) return nil, fmt.Errorf("failed to create RPC write params: %w", err)
} }

View File

@ -47,7 +47,7 @@ func (c *Controller) RawDiff(
} }
return c.git.RawDiff(ctx, w, &git.DiffParams{ return c.git.RawDiff(ctx, w, &git.DiffParams{
ReadParams: git.CreateReadParams(&repo.Repository), ReadParams: git.CreateReadParams(repo),
BaseRef: info.BaseRef, BaseRef: info.BaseRef,
HeadRef: info.HeadRef, HeadRef: info.HeadRef,
MergeBase: info.MergeBase, MergeBase: info.MergeBase,
@ -67,7 +67,7 @@ func (c *Controller) CommitDiff(
} }
return c.git.CommitDiff(ctx, &git.GetCommitParams{ return c.git.CommitDiff(ctx, &git.GetCommitParams{
ReadParams: git.CreateReadParams(&repo.Repository), ReadParams: git.CreateReadParams(repo),
Revision: rev, Revision: rev,
}, w) }, w)
} }

View File

@ -35,7 +35,7 @@ func (c *Controller) GetBranch(ctx context.Context,
} }
rpcOut, err := c.git.GetBranch(ctx, &git.GetBranchParams{ rpcOut, err := c.git.GetBranch(ctx, &git.GetBranchParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
BranchName: branchName, BranchName: branchName,
}) })
if err != nil { if err != nil {

View File

@ -37,7 +37,7 @@ func (c *Controller) GetCommit(ctx context.Context,
} }
rpcOut, err := c.git.GetCommit(ctx, &git.GetCommitParams{ rpcOut, err := c.git.GetCommit(ctx, &git.GetCommitParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
Revision: sha, Revision: sha,
}) })
if err != nil { if err != nil {

View File

@ -71,7 +71,7 @@ func (c *Controller) GetCommitDivergences(ctx context.Context,
// map to rpc params // map to rpc params
options := &git.GetCommitDivergencesParams{ options := &git.GetCommitDivergencesParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
MaxCount: in.MaxCount, MaxCount: in.MaxCount,
Requests: make([]git.CommitDivergenceRequest, len(in.Requests)), Requests: make([]git.CommitDivergenceRequest, len(in.Requests)),
} }
@ -80,7 +80,7 @@ func (c *Controller) GetCommitDivergences(ctx context.Context,
options.Requests[i].To = in.Requests[i].To options.Requests[i].To = in.Requests[i].To
// backfil default branch if no 'to' was provided // backfil default branch if no 'to' was provided
if len(options.Requests[i].To) == 0 { if len(options.Requests[i].To) == 0 {
options.Requests[i].To = repo.Repository.DefaultBranch options.Requests[i].To = repo.DefaultBranch
} }
} }

View File

@ -39,7 +39,7 @@ func (c *Controller) GitInfoRefs(
} }
if err = c.git.GetInfoRefs(ctx, w, &git.InfoRefsParams{ if err = c.git.GetInfoRefs(ctx, w, &git.InfoRefsParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
// TODO: git shouldn't take a random string here, but instead have accepted enum values. // TODO: git shouldn't take a random string here, but instead have accepted enum values.
Service: string(service), Service: string(service),
Options: nil, Options: nil,

View File

@ -59,13 +59,13 @@ func (c *Controller) GitServicePack(
// setup read/writeparams depending on whether it's a write operation // setup read/writeparams depending on whether it's a write operation
if isWriteOperation { if isWriteOperation {
var writeParams git.WriteParams var writeParams git.WriteParams
writeParams, err = controller.CreateRPCExternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err = controller.CreateRPCExternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return fmt.Errorf("failed to create RPC write params: %w", err) return fmt.Errorf("failed to create RPC write params: %w", err)
} }
params.WriteParams = &writeParams params.WriteParams = &writeParams
} else { } else {
readParams := git.CreateReadParams(repo.Repository) readParams := git.CreateReadParams(repo)
params.ReadParams = &readParams params.ReadParams = &readParams
} }

View File

@ -24,16 +24,16 @@ import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
// GetRepo fetches an active repo (not one that is currently being imported). // GetRepo fetches an active repo (not one that is currently being imported).
func GetRepo( func GetRepo(
ctx context.Context, ctx context.Context,
publicAccess publicaccess.PublicAccess,
repoStore store.RepoStore, repoStore store.RepoStore,
repoRef string, repoRef string,
) (*Repository, error) { ) (*types.Repository, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
@ -47,6 +47,36 @@ func GetRepo(
return nil, usererror.BadRequest("Repository import is in progress.") return nil, usererror.BadRequest("Repository import is in progress.")
} }
return repo, nil
}
// GetRepoCheckAccess fetches an active repo (not one that is currently being imported)
// and checks if the current user has permission to access it.
func GetRepoCheckAccess(
ctx context.Context,
repoStore store.RepoStore,
authorizer authz.Authorizer,
session *auth.Session,
repoRef string,
reqPermission enum.Permission,
) (*types.Repository, error) {
repo, err := GetRepo(ctx, repoStore, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err)
}
if err = apiauth.CheckRepo(ctx, authorizer, session, repo, reqPermission); err != nil {
return nil, fmt.Errorf("access check failed: %w", err)
}
return repo, nil
}
func GetRepoOutput(
ctx context.Context,
publicAccess publicaccess.PublicAccess,
repo *types.Repository,
) (*Repository, error) {
isPublic, err := apiauth.CheckRepoIsPublic(ctx, publicAccess, repo) isPublic, err := apiauth.CheckRepoIsPublic(ctx, publicAccess, repo)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to check if repo is public: %w", err) return nil, fmt.Errorf("failed to check if repo is public: %w", err)
@ -57,26 +87,3 @@ func GetRepo(
IsPublic: isPublic, IsPublic: isPublic,
}, nil }, nil
} }
// GetRepoCheckAccess fetches an active repo (not one that is currently being imported)
// and checks if the current user has permission to access it.
func GetRepoCheckAccess(
ctx context.Context,
repoStore store.RepoStore,
authorizer authz.Authorizer,
publicAccess publicaccess.PublicAccess,
session *auth.Session,
repoRef string,
reqPermission enum.Permission,
) (*Repository, error) {
repo, err := GetRepo(ctx, publicAccess, repoStore, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err)
}
if err = apiauth.CheckRepo(ctx, authorizer, session, &repo.Repository, reqPermission); err != nil {
return nil, fmt.Errorf("access check failed: %w", err)
}
return repo, nil
}

View File

@ -82,11 +82,8 @@ func (c *Controller) Import(ctx context.Context, session *auth.Session, in *Impo
return fmt.Errorf("failed to create repository in storage: %w", err) return fmt.Errorf("failed to create repository in storage: %w", err)
} }
// update public resources if err = c.SetRepoPublicAccess(ctx, repo, isPublic); err != nil {
if isPublic && c.publicResourceCreationEnabled { return fmt.Errorf("failed to set repo public access: %w", err)
if err = c.SetPublicRepo(ctx, repo); err != nil {
return fmt.Errorf("failed to set a public repo: %w", err)
}
} }
err = c.importer.Run(ctx, err = c.importer.Run(ctx,

View File

@ -44,7 +44,7 @@ func (c *Controller) ListBranches(ctx context.Context,
} }
rpcOut, err := c.git.ListBranches(ctx, &git.ListBranchesParams{ rpcOut, err := c.git.ListBranches(ctx, &git.ListBranchesParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
IncludeCommit: includeCommit, IncludeCommit: includeCommit,
Query: filter.Query, Query: filter.Query,
Sort: mapToRPCBranchSortOption(filter.Sort), Sort: mapToRPCBranchSortOption(filter.Sort),

View File

@ -48,7 +48,7 @@ func (c *Controller) ListCommitTags(ctx context.Context,
} }
rpcOut, err := c.git.ListCommitTags(ctx, &git.ListCommitTagsParams{ rpcOut, err := c.git.ListCommitTags(ctx, &git.ListCommitTagsParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
IncludeCommit: includeCommit, IncludeCommit: includeCommit,
Query: filter.Query, Query: filter.Query,
Sort: mapToRPCTagSortOption(filter.Sort), Sort: mapToRPCTagSortOption(filter.Sort),

View File

@ -39,11 +39,11 @@ func (c *Controller) ListCommits(ctx context.Context,
// set gitRef to default branch in case an empty reference was provided // set gitRef to default branch in case an empty reference was provided
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
rpcOut, err := c.git.ListCommits(ctx, &git.ListCommitsParams{ rpcOut, err := c.git.ListCommits(ctx, &git.ListCommitsParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
GitREF: gitRef, GitREF: gitRef,
After: filter.After, After: filter.After,
Page: int32(filter.Page), Page: int32(filter.Page),

View File

@ -42,11 +42,11 @@ func (c *Controller) ListPaths(ctx context.Context,
// set gitRef to default branch in case an empty reference was provided // set gitRef to default branch in case an empty reference was provided
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
rpcOut, err := c.git.ListPaths(ctx, &git.ListPathsParams{ rpcOut, err := c.git.ListPaths(ctx, &git.ListPathsParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
GitREF: gitRef, GitREF: gitRef,
IncludeDirectories: includeDirectories, IncludeDirectories: includeDirectories,
}) })

View File

@ -37,7 +37,7 @@ func (c *Controller) ListPipelines(
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to find repo: %w", err) return nil, 0, fmt.Errorf("failed to find repo: %w", err)
} }
if err := apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Repository.Path, "", enum.PermissionPipelineView); err != nil { if err := apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path, "", enum.PermissionPipelineView); err != nil {
return nil, 0, fmt.Errorf("access check failed: %w", err) return nil, 0, fmt.Errorf("access check failed: %w", err)
} }
@ -45,18 +45,18 @@ func (c *Controller) ListPipelines(
var pipelines []*types.Pipeline var pipelines []*types.Pipeline
err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) {
count, err = c.pipelineStore.Count(ctx, repo.Repository.ID, filter) count, err = c.pipelineStore.Count(ctx, repo.ID, filter)
if err != nil { if err != nil {
return fmt.Errorf("failed to count child executions: %w", err) return fmt.Errorf("failed to count child executions: %w", err)
} }
if !latest { if !latest {
pipelines, err = c.pipelineStore.List(ctx, repo.Repository.ID, filter) pipelines, err = c.pipelineStore.List(ctx, repo.ID, filter)
if err != nil { if err != nil {
return fmt.Errorf("failed to list pipelines: %w", err) return fmt.Errorf("failed to list pipelines: %w", err)
} }
} else { } else {
pipelines, err = c.pipelineStore.ListLatest(ctx, repo.Repository.ID, filter) pipelines, err = c.pipelineStore.ListLatest(ctx, repo.ID, filter)
if err != nil { if err != nil {
return fmt.Errorf("failed to list latest pipelines: %w", err) return fmt.Errorf("failed to list latest pipelines: %w", err)
} }

View File

@ -42,12 +42,12 @@ func (c *Controller) ListServiceAccounts(
c.spaceStore, c.spaceStore,
c.repoStore, c.repoStore,
enum.ParentResourceTypeRepo, enum.ParentResourceTypeRepo,
repo.Repository.ID, repo.ID,
"", "",
enum.PermissionServiceAccountView, enum.PermissionServiceAccountView,
); err != nil { ); err != nil {
return nil, fmt.Errorf("access check failed: %w", err) return nil, fmt.Errorf("access check failed: %w", err)
} }
return c.principalStore.ListServiceAccounts(ctx, enum.ParentResourceTypeRepo, repo.Repository.ID) return c.principalStore.ListServiceAccounts(ctx, enum.ParentResourceTypeRepo, repo.ID)
} }

View File

@ -45,7 +45,7 @@ func (c *Controller) MergeCheck(
return MergeCheck{}, err return MergeCheck{}, err
} }
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, &repo.Repository) writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil { if err != nil {
return MergeCheck{}, fmt.Errorf("failed to create rpc write params: %w", err) return MergeCheck{}, fmt.Errorf("failed to create rpc write params: %w", err)
} }

View File

@ -35,7 +35,7 @@ func (c *Controller) PipelineGenerate(
} }
result, err := c.git.GeneratePipeline(ctx, &git.GeneratePipelineParams{ result, err := c.git.GeneratePipeline(ctx, &git.GeneratePipelineParams{
ReadParams: git.CreateReadParams(repo.Repository), ReadParams: git.CreateReadParams(repo),
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to generate pipeline: %w", err) return nil, fmt.Errorf("failed to generate pipeline: %w", err)

View File

@ -18,10 +18,10 @@ import (
"context" "context"
"fmt" "fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit" "github.com/harness/gitness/audit"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -31,49 +31,48 @@ type PublicAccessUpdateInput struct {
EnablePublic bool `json:"enable_public"` EnablePublic bool `json:"enable_public"`
} }
type PublicAccessUpdateOutput struct {
IsPublic bool `json:"is_public"`
}
func (c *Controller) PublicAccessUpdate(ctx context.Context, func (c *Controller) PublicAccessUpdate(ctx context.Context,
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
in *PublicAccessUpdateInput, in *PublicAccessUpdateInput,
) (*PublicAccessUpdateOutput, error) { ) (*Repository, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
repoClone := repo.Clone()
if err = c.sanitizeVisibilityInput(in); err != nil { if err = c.sanitizeVisibilityInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
parentSpace, name, err := paths.DisectLeaf(repo.Repository.Path) repoClone := repo.Clone()
// get current public access vale for audit
isPublic, err := apiauth.CheckRepoIsPublic(ctx, c.publicAccess, repo)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to disect path '%s': %w", repo.Repository.Path, err) return nil, fmt.Errorf("failed to check current public access status: %w", err)
} }
scope := &types.Scope{SpacePath: parentSpace} // no op
resource := &types.Resource{ if isPublic == in.EnablePublic {
Type: enum.ResourceTypeRepo, return GetRepoOutput(ctx, c.publicAccess, repo)
Identifier: name,
} }
if err = c.publicAccess.Set(ctx, scope, resource, in.EnablePublic); err != nil { if err = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, in.EnablePublic); err != nil {
return nil, fmt.Errorf("failed to update repo public access: %w", err) return nil, fmt.Errorf("failed to update repo public access: %w", err)
} }
err = c.auditService.Log(ctx, err = c.auditService.Log(ctx,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeRepository, repo.Repository.Identifier), audit.NewResource(audit.ResourceTypeRepository, repo.Identifier),
audit.ActionUpdated, audit.ActionUpdated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(repoClone), audit.WithOldObject(&Repository{
Repository: repoClone,
IsPublic: isPublic,
}),
audit.WithNewObject(&Repository{ audit.WithNewObject(&Repository{
Repository: repo.Repository, Repository: *repo,
IsPublic: in.EnablePublic, IsPublic: in.EnablePublic,
}), }),
) )
@ -81,9 +80,7 @@ func (c *Controller) PublicAccessUpdate(ctx context.Context,
log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository operation: %s", err) log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository operation: %s", err)
} }
return &PublicAccessUpdateOutput{ return GetRepoOutput(ctx, c.publicAccess, repo)
in.EnablePublic,
}, nil
} }

View File

@ -23,7 +23,6 @@ import (
"github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
repoevents "github.com/harness/gitness/app/events/repo" repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/errors" "github.com/harness/gitness/errors"
"github.com/harness/gitness/git" "github.com/harness/gitness/git"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
@ -79,7 +78,7 @@ func (c *Controller) PurgeNoAuth(
} }
if isPublic { if isPublic {
if err := c.disablePublicRepo(ctx, repo); err != nil { if err := c.SetRepoPublicAccess(ctx, repo, false); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to disable repo public access") log.Ctx(ctx).Err(err).Msg("failed to disable repo public access")
} }
} }
@ -124,18 +123,3 @@ func (c *Controller) DeleteGitRepository(
} }
return nil return nil
} }
func (c *Controller) disablePublicRepo(ctx context.Context, repo *types.Repository) error {
parentSpace, name, err := paths.DisectLeaf(repo.Path)
if err != nil {
return fmt.Errorf("failed to disect path '%s': %w", repo.Path, err)
}
scope := &types.Scope{SpacePath: parentSpace}
resource := &types.Resource{
Type: enum.ResourceTypeRepo,
Identifier: name,
}
return c.publicAccess.Set(ctx, scope, resource, false)
}

View File

@ -40,11 +40,11 @@ func (c *Controller) Raw(ctx context.Context,
// set gitRef to default branch in case an empty reference was provided // set gitRef to default branch in case an empty reference was provided
if gitRef == "" { if gitRef == "" {
gitRef = repo.Repository.DefaultBranch gitRef = repo.DefaultBranch
} }
// create read params once // create read params once
readParams := git.CreateReadParams(repo.Repository) readParams := git.CreateReadParams(repo)
treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
ReadParams: readParams, ReadParams: readParams,
GitREF: gitRef, GitREF: gitRef,

View File

@ -100,7 +100,7 @@ func (c *Controller) RuleCreate(ctx context.Context,
CreatedBy: session.Principal.ID, CreatedBy: session.Principal.ID,
Created: now, Created: now,
Updated: now, Updated: now,
RepoID: &repo.Repository.ID, RepoID: &repo.ID,
SpaceID: nil, SpaceID: nil,
Type: in.Type, Type: in.Type,
State: in.State, State: in.State,
@ -120,7 +120,7 @@ func (c *Controller) RuleCreate(ctx context.Context,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier), audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier),
audit.ActionCreated, audit.ActionCreated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithNewObject(r), audit.WithNewObject(r),
) )
if err != nil { if err != nil {

View File

@ -37,7 +37,7 @@ func (c *Controller) RuleDelete(ctx context.Context,
return err return err
} }
r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.Repository.ID, identifier) r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.ID, identifier)
if err != nil { if err != nil {
return fmt.Errorf("failed to find repository-level protection rule by identifier: %w", err) return fmt.Errorf("failed to find repository-level protection rule by identifier: %w", err)
} }
@ -51,7 +51,7 @@ func (c *Controller) RuleDelete(ctx context.Context,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier), audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier),
audit.ActionDeleted, audit.ActionDeleted,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(r), audit.WithOldObject(r),
) )
if err != nil { if err != nil {

View File

@ -34,7 +34,7 @@ func (c *Controller) RuleFind(ctx context.Context,
return nil, err return nil, err
} }
r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.Repository.ID, identifier) r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.ID, identifier)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repository-level protection rule by identifier: %w", err) return nil, fmt.Errorf("failed to find repository-level protection rule by identifier: %w", err)
} }

View File

@ -39,7 +39,7 @@ func (c *Controller) RuleList(ctx context.Context,
var count int64 var count int64
err = c.tx.WithTx(ctx, func(ctx context.Context) error { err = c.tx.WithTx(ctx, func(ctx context.Context) error {
list, err = c.ruleStore.List(ctx, nil, &repo.Repository.ID, filter) list, err = c.ruleStore.List(ctx, nil, &repo.ID, filter)
if err != nil { if err != nil {
return fmt.Errorf("failed to list repository-level protection rules: %w", err) return fmt.Errorf("failed to list repository-level protection rules: %w", err)
} }
@ -49,7 +49,7 @@ func (c *Controller) RuleList(ctx context.Context,
return nil return nil
} }
count, err = c.ruleStore.Count(ctx, nil, &repo.Repository.ID, filter) count, err = c.ruleStore.Count(ctx, nil, &repo.ID, filter)
if err != nil { if err != nil {
return fmt.Errorf("failed to count repository-level protection rules: %w", err) return fmt.Errorf("failed to count repository-level protection rules: %w", err)
} }

View File

@ -96,7 +96,7 @@ func (c *Controller) RuleUpdate(ctx context.Context,
return nil, err return nil, err
} }
r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.Repository.ID, identifier) r, err := c.ruleStore.FindByIdentifier(ctx, nil, &repo.ID, identifier)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get a repository rule by its identifier: %w", err) return nil, fmt.Errorf("failed to get a repository rule by its identifier: %w", err)
} }
@ -142,7 +142,7 @@ func (c *Controller) RuleUpdate(ctx context.Context,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier), audit.NewResource(audit.ResourceTypeBranchRule, r.Identifier),
audit.ActionUpdated, audit.ActionUpdated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(oldRule), audit.WithOldObject(oldRule),
audit.WithNewObject(r), audit.WithNewObject(r),
) )

View File

@ -19,7 +19,6 @@ import (
"fmt" "fmt"
"strings" "strings"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit" "github.com/harness/gitness/audit"
@ -52,15 +51,15 @@ func (c *Controller) Update(ctx context.Context,
repoClone := repo.Clone() repoClone := repo.Clone()
if !in.hasChanges(&repo.Repository) { if !in.hasChanges(repo) {
return repo, nil return GetRepoOutput(ctx, c.publicAccess, repo)
} }
if err = c.sanitizeUpdateInput(in); err != nil { if err = c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
repoBase, err := c.repoStore.UpdateOptLock(ctx, &repo.Repository, func(repo *types.Repository) error { repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(repo *types.Repository) error {
// update values only if provided // update values only if provided
if in.Description != nil { if in.Description != nil {
repo.Description = *in.Description repo.Description = *in.Description
@ -72,21 +71,11 @@ func (c *Controller) Update(ctx context.Context,
return nil, err return nil, err
} }
isPublic, err := apiauth.CheckRepoIsPublic(ctx, c.publicAccess, repoBase)
if err != nil {
return nil, fmt.Errorf("failed to get resource public access mode: %w", err)
}
repo = &Repository{
Repository: *repoBase,
IsPublic: isPublic,
}
err = c.auditService.Log(ctx, err = c.auditService.Log(ctx,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeRepository, repo.Repository.Identifier), audit.NewResource(audit.ResourceTypeRepository, repo.Identifier),
audit.ActionUpdated, audit.ActionUpdated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(repoClone), audit.WithOldObject(repoClone),
audit.WithNewObject(repo), audit.WithNewObject(repo),
) )
@ -95,9 +84,9 @@ func (c *Controller) Update(ctx context.Context,
} }
// backfill repo url // backfill repo url
repo.Repository.GitURL = c.urlProvider.GenerateGITCloneURL(repo.Repository.Path) repo.GitURL = c.urlProvider.GenerateGITCloneURL(repo.Path)
return repo, nil return GetRepoOutput(ctx, c.publicAccess, repo)
} }
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error { func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {

View File

@ -20,10 +20,10 @@ import (
"github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/audit" "github.com/harness/gitness/audit"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
@ -31,7 +31,6 @@ type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
repoStore store.RepoStore repoStore store.RepoStore
settings *settings.Service settings *settings.Service
publicAccess publicaccess.PublicAccess
auditService audit.Service auditService audit.Service
} }
@ -39,14 +38,12 @@ func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
repoStore store.RepoStore, repoStore store.RepoStore,
settings *settings.Service, settings *settings.Service,
publicAccess publicaccess.PublicAccess,
auditService audit.Service, auditService audit.Service,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
authorizer: authorizer, authorizer: authorizer,
repoStore: repoStore, repoStore: repoStore,
settings: settings, settings: settings,
publicAccess: publicAccess,
auditService: auditService, auditService: auditService,
} }
} }
@ -58,12 +55,11 @@ func (c *Controller) getRepoCheckAccess(
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
) (*repo.Repository, error) { ) (*types.Repository, error) {
return repo.GetRepoCheckAccess( return repo.GetRepoCheckAccess(
ctx, ctx,
c.repoStore, c.repoStore,
c.authorizer, c.authorizer,
c.publicAccess,
session, session,
repoRef, repoRef,
reqPermission, reqPermission,

View File

@ -35,7 +35,7 @@ func (c *Controller) GeneralFind(
out := GetDefaultGeneralSettings() out := GetDefaultGeneralSettings()
mappings := GetGeneralSettingsMappings(out) mappings := GetGeneralSettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.Repository.ID, mappings...) err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err) return nil, fmt.Errorf("failed to map settings: %w", err)
} }

View File

@ -41,12 +41,12 @@ func (c *Controller) GeneralUpdate(
// read old settings values // read old settings values
old := GetDefaultGeneralSettings() old := GetDefaultGeneralSettings()
oldMappings := GetGeneralSettingsMappings(old) oldMappings := GetGeneralSettingsMappings(old)
err = c.settings.RepoMap(ctx, repo.Repository.ID, oldMappings...) err = c.settings.RepoMap(ctx, repo.ID, oldMappings...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to map settings (old): %w", err) return nil, fmt.Errorf("failed to map settings (old): %w", err)
} }
err = c.settings.RepoSetMany(ctx, repo.Repository.ID, GetGeneralSettingsAsKeyValues(in)...) err = c.settings.RepoSetMany(ctx, repo.ID, GetGeneralSettingsAsKeyValues(in)...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to set settings: %w", err) return nil, fmt.Errorf("failed to set settings: %w", err)
} }
@ -54,16 +54,16 @@ func (c *Controller) GeneralUpdate(
// read all settings and return complete config // read all settings and return complete config
out := GetDefaultGeneralSettings() out := GetDefaultGeneralSettings()
mappings := GetGeneralSettingsMappings(out) mappings := GetGeneralSettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.Repository.ID, mappings...) err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err) return nil, fmt.Errorf("failed to map settings: %w", err)
} }
err = c.auditService.Log(ctx, err = c.auditService.Log(ctx,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Repository.Identifier), audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier),
audit.ActionUpdated, audit.ActionUpdated,
paths.Parent(repo.Repository.Path), paths.Parent(repo.Path),
audit.WithOldObject(old), audit.WithOldObject(old),
audit.WithNewObject(out), audit.WithNewObject(out),
) )

View File

@ -16,7 +16,6 @@ package reposettings
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/audit" "github.com/harness/gitness/audit"
@ -33,8 +32,7 @@ func ProvideController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
repoStore store.RepoStore, repoStore store.RepoStore,
settings *settings.Service, settings *settings.Service,
publicAccess publicaccess.PublicAccess,
auditService audit.Service, auditService audit.Service,
) *Controller { ) *Controller {
return NewController(authorizer, repoStore, settings, publicAccess, auditService) return NewController(authorizer, repoStore, settings, auditService)
} }

View File

@ -146,10 +146,8 @@ func (c *Controller) createSpaceInnerInTX(
} }
} }
if in.IsPublic { if err := c.setSpacePublicAccess(ctx, space, in.IsPublic); err != nil {
if err := c.setPublicSpace(ctx, space); err != nil { return nil, fmt.Errorf("failed to set a space public: %w", err)
return nil, fmt.Errorf("failed to insert a public resource: %w", err)
}
} }
return space, nil return space, nil
@ -189,19 +187,16 @@ func (c *Controller) getSpaceCheckAuthSpaceCreation(
return parentSpace, nil return parentSpace, nil
} }
func (c *Controller) setPublicSpace(ctx context.Context, space *types.Space) error { func (c *Controller) setSpacePublicAccess(
parentSpace, name, err := paths.DisectLeaf(space.Path) ctx context.Context,
if err != nil { space *types.Space,
return fmt.Errorf("failed to disect path '%s': %w", space.Path, err) isPublic bool,
) error {
if isPublic && !c.publicResourceCreationEnabled {
return errPublicSpaceCreationDisabled
} }
scope := &types.Scope{SpacePath: parentSpace} return c.publicAccess.Set(ctx, enum.PublicResourceTypeSpace, space.Path, isPublic)
resource := &types.Resource{
Type: enum.ResourceTypeSpace,
Identifier: name,
}
return c.publicAccess.Set(ctx, scope, resource, true)
} }
func (c *Controller) sanitizeCreateInput(in *CreateInput) error { func (c *Controller) sanitizeCreateInput(in *CreateInput) error {

View File

@ -12,12 +12,29 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package types package space
import "github.com/harness/gitness/types/enum" import (
"context"
"fmt"
// PublicResource defines a public resource info. apiauth "github.com/harness/gitness/app/api/auth"
type PublicResource struct { "github.com/harness/gitness/app/services/publicaccess"
Type enum.PublicResourceType "github.com/harness/gitness/types"
ID int64 )
func GetSpaceOutput(
ctx context.Context,
publicAccess publicaccess.PublicAccess,
space *types.Space,
) (*Space, error) {
isPublic, err := apiauth.CheckSpaceIsPublic(ctx, publicAccess, space)
if err != nil {
return nil, fmt.Errorf("failed to get resource public access mode: %w", err)
}
return &Space{
Space: *space,
IsPublic: isPublic,
}, nil
} }

View File

@ -98,12 +98,10 @@ func (c *Controller) Import(ctx context.Context, session *auth.Session, in *Impo
repoIDs[i] = repo.ID repoIDs[i] = repo.ID
cloneURLs[i] = remoteRepository.CloneURL cloneURLs[i] = remoteRepository.CloneURL
// update public resources if err := c.repoCtrl.SetRepoPublicAccess(ctx, repo, isPublic); err != nil {
if isPublic && c.publicResourceCreationEnabled { return fmt.Errorf("failed to set repo public access: %w", err)
if err := c.repoCtrl.SetPublicRepo(ctx, repo); err != nil {
return fmt.Errorf("failed to set a public repo: %w", err)
}
} }
} }
jobGroupID := fmt.Sprintf("space-import-%d", space.ID) jobGroupID := fmt.Sprintf("space-import-%d", space.ID)

View File

@ -126,11 +126,8 @@ func (c *Controller) ImportRepositories(
return fmt.Errorf("failed to create repository in storage: %w", err) return fmt.Errorf("failed to create repository in storage: %w", err)
} }
// update public resources if err := c.repoCtrl.SetRepoPublicAccess(ctx, repo, isPublic); err != nil {
if isPublic && c.publicResourceCreationEnabled { return fmt.Errorf("failed to set repo public access: %w", err)
if err := c.repoCtrl.SetPublicRepo(ctx, repo); err != nil {
return fmt.Errorf("failed to set a public repo: %w", err)
}
} }
repos = append(repos, repo) repos = append(repos, repo)

View File

@ -47,18 +47,8 @@ func (c *Controller) Update(ctx context.Context, session *auth.Session,
return nil, err return nil, err
} }
isPublic, err := apiauth.CheckSpaceIsPublic(ctx, c.publicAccess, space)
if err != nil {
return nil, fmt.Errorf("failed to get resource public access mode: %w", err)
}
spaceData := &Space{
Space: *space,
IsPublic: isPublic,
}
if !in.hasChanges(space) { if !in.hasChanges(space) {
return spaceData, nil return GetSpaceOutput(ctx, c.publicAccess, space)
} }
if err = c.sanitizeUpdateInput(in); err != nil { if err = c.sanitizeUpdateInput(in); err != nil {
@ -77,10 +67,7 @@ func (c *Controller) Update(ctx context.Context, session *auth.Session,
return nil, err return nil, err
} }
return &Space{ return GetSpaceOutput(ctx, c.publicAccess, space)
Space: *space,
IsPublic: isPublic,
}, nil
} }
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error { func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {

View File

@ -22,7 +22,6 @@ import (
"github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/app/services/webhook"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt" "github.com/harness/gitness/encrypt"
@ -40,7 +39,6 @@ type Controller struct {
repoStore store.RepoStore repoStore store.RepoStore
webhookService *webhook.Service webhookService *webhook.Service
encrypter encrypt.Encrypter encrypter encrypt.Encrypter
publicAccess publicaccess.PublicAccess
} }
func NewController( func NewController(
@ -52,7 +50,6 @@ func NewController(
repoStore store.RepoStore, repoStore store.RepoStore,
webhookService *webhook.Service, webhookService *webhook.Service,
encrypter encrypt.Encrypter, encrypter encrypt.Encrypter,
publicAccess publicaccess.PublicAccess,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
allowLoopback: allowLoopback, allowLoopback: allowLoopback,
@ -63,7 +60,6 @@ func NewController(
repoStore: repoStore, repoStore: repoStore,
webhookService: webhookService, webhookService: webhookService,
encrypter: encrypter, encrypter: encrypter,
publicAccess: publicAccess,
} }
} }

View File

@ -16,7 +16,6 @@ package webhook
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/app/services/webhook"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt" "github.com/harness/gitness/encrypt"
@ -31,10 +30,10 @@ var WireSet = wire.NewSet(
func ProvideController(config webhook.Config, authorizer authz.Authorizer, func ProvideController(config webhook.Config, authorizer authz.Authorizer,
webhookStore store.WebhookStore, webhookExecutionStore store.WebhookExecutionStore, webhookStore store.WebhookStore, webhookExecutionStore store.WebhookExecutionStore,
repoStore store.RepoStore, webhookService *webhook.Service, encrypter encrypt.Encrypter, publicAccess publicaccess.PublicAccess, repoStore store.RepoStore, webhookService *webhook.Service, encrypter encrypt.Encrypter,
) *Controller { ) *Controller {
return NewController( return NewController(
config.AllowLoopback, config.AllowPrivateNetwork, authorizer, config.AllowLoopback, config.AllowPrivateNetwork, authorizer,
webhookStore, webhookExecutionStore, webhookStore, webhookExecutionStore,
repoStore, webhookService, encrypter, publicAccess) repoStore, webhookService, encrypter)
} }

View File

@ -19,12 +19,10 @@ import (
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
// Anonymous is an in-memory principal for users with no auth data. // anonymousPrincipal is an in-memory principal for users with no auth data.
// Authorizer is in charge of handling public access. // Authorizer is in charge of handling anonymouse access.
func Anonymous() *types.Principal { var AnonymousPrincipal = types.Principal{
return &types.Principal{
ID: -1, ID: -1,
UID: "ALL_USERS", UID: "anonymous",
Type: enum.PrincipalTypeUser, Type: enum.PrincipalTypeUser,
} }
}

View File

@ -57,7 +57,7 @@ func (a *JWTAuthenticator) Authenticate(r *http.Request) (*auth.Session, error)
if len(str) == 0 { if len(str) == 0 {
return &auth.Session{ return &auth.Session{
Principal: *auth.Anonymous(), Principal: auth.AnonymousPrincipal,
}, nil }, nil
} }

View File

@ -55,12 +55,12 @@ func (a *MembershipAuthorizer) Check(
resource *types.Resource, resource *types.Resource,
permission enum.Permission, permission enum.Permission,
) (bool, error) { ) (bool, error) {
isPublic, err := a.CheckPublicAccess(ctx, scope, resource, permission) publicAccessAllowed, err := a.CheckPublicAccess(ctx, scope, resource, permission)
if err != nil { if err != nil {
return false, fmt.Errorf("failed to check public access: %w", err) return false, fmt.Errorf("failed to check public access: %w", err)
} }
if isPublic { if publicAccessAllowed {
return true, nil return true, nil
} }

View File

@ -17,6 +17,7 @@ package authz
import ( import (
"context" "context"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
@ -33,11 +34,19 @@ func (a *MembershipAuthorizer) CheckPublicAccess(
return false, nil return false, nil
} }
// public access is enabled on these resource types. pubResType, pubResPath := mapResource(scope, resource)
if resource.Type != enum.ResourceTypeRepo &&
resource.Type != enum.ResourceTypeSpace { return a.publicAccess.Get(ctx, pubResType, pubResPath)
return false, nil
} }
return a.publicAccess.Get(ctx, scope, resource) func mapResource(scope *types.Scope, resource *types.Resource,
) (enum.PublicResourceType, string) {
pubResType := enum.PublicResourceTypeSpace
if resource.Type == enum.ResourceTypeRepo &&
resource.Identifier != "" {
pubResType = enum.PublicResourceTypeRepo
}
return pubResType, paths.Concatenate(scope.SpacePath, resource.Identifier)
} }

View File

@ -21,6 +21,8 @@ import (
"github.com/harness/gitness/app/pipeline/converter/jsonnet" "github.com/harness/gitness/app/pipeline/converter/jsonnet"
"github.com/harness/gitness/app/pipeline/converter/starlark" "github.com/harness/gitness/app/pipeline/converter/starlark"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/types/enum"
) )
const ( const (
@ -31,6 +33,7 @@ const (
type converter struct { type converter struct {
fileService file.Service fileService file.Service
publicaccess publicaccess.PublicAccess
} }
func newConverter(fileService file.Service) Service { func newConverter(fileService file.Service) Service {
@ -40,14 +43,20 @@ func newConverter(fileService file.Service) Service {
func (c *converter) Convert(_ context.Context, args *ConvertArgs) (*file.File, error) { func (c *converter) Convert(_ context.Context, args *ConvertArgs) (*file.File, error) {
path := args.Pipeline.ConfigPath path := args.Pipeline.ConfigPath
// get public access visibility of the repo
repoIsPublic, err := c.publicaccess.Get(context.Background(), enum.PublicResourceTypeRepo, args.Repo.Path)
if err != nil {
return nil, err
}
if isJSONNet(path) { if isJSONNet(path) {
str, err := jsonnet.Parse(args.Repo, args.Pipeline, args.Execution, args.File, c.fileService, jsonnetImportLimit) str, err := jsonnet.Parse(args.Repo, repoIsPublic, args.Pipeline, args.Execution, args.File, c.fileService, jsonnetImportLimit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &file.File{Data: []byte(str)}, nil return &file.File{Data: []byte(str)}, nil
} else if isStarlark(path) { } else if isStarlark(path) {
str, err := starlark.Parse(args.Repo, args.Pipeline, args.Execution, args.File, starlarkStepLimit, starlarkSizeLimit) str, err := starlark.Parse(args.Repo, repoIsPublic, args.Pipeline, args.Execution, args.File, starlarkStepLimit, starlarkSizeLimit)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -23,7 +23,6 @@ import (
"strconv" "strconv"
"strings" "strings"
repoCtrl "github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
@ -37,7 +36,7 @@ const param = "param."
var noContext = context.Background() var noContext = context.Background()
type importer struct { type importer struct {
repo *repoCtrl.Repository repo *types.Repository
execution *types.Execution execution *types.Execution
// jsonnet does not cache file imports and may request // jsonnet does not cache file imports and may request
@ -104,7 +103,8 @@ func (i *importer) Import(importedFrom, importedPath string) (contents jsonnet.C
} }
func Parse( func Parse(
repo *repoCtrl.Repository, repo *types.Repository,
repoIsPublic bool,
pipeline *types.Pipeline, pipeline *types.Pipeline,
execution *types.Execution, execution *types.Execution,
file *file.File, file *file.File,
@ -131,7 +131,7 @@ func Parse(
mapBuild(execution, vm) mapBuild(execution, vm)
} }
if repo != nil { if repo != nil {
mapRepo(repo, pipeline, vm) mapRepo(repo, pipeline, vm, repoIsPublic)
} }
jsonnetFile := file jsonnetFile := file
@ -189,24 +189,24 @@ func mapBuild(v *types.Execution, vm *jsonnet.VM) {
// mapBuild populates repo level variables available to jsonnet templates. // mapBuild populates repo level variables available to jsonnet templates.
// Since we want to maintain compatibility with drone 2.x, the older format // Since we want to maintain compatibility with drone 2.x, the older format
// needs to be maintained (even if the variables do not exist in gitness). // needs to be maintained (even if the variables do not exist in gitness).
func mapRepo(v *repoCtrl.Repository, p *types.Pipeline, vm *jsonnet.VM) { func mapRepo(v *types.Repository, p *types.Pipeline, vm *jsonnet.VM, publicRepo bool) {
namespace := v.Path namespace := v.Path
idx := strings.LastIndex(v.Path, "/") idx := strings.LastIndex(v.Path, "/")
if idx != -1 { if idx != -1 {
namespace = v.Path[:idx] namespace = v.Path[:idx]
} }
// TODO [CODE-1363]: remove after identifier migration. // TODO [CODE-1363]: remove after identifier migration.
vm.ExtVar(repo+"uid", v.Repository.Identifier) vm.ExtVar(repo+"uid", v.Identifier)
vm.ExtVar(repo+"identifier", v.Repository.Identifier) vm.ExtVar(repo+"identifier", v.Identifier)
vm.ExtVar(repo+"name", v.Repository.Identifier) vm.ExtVar(repo+"name", v.Identifier)
vm.ExtVar(repo+"namespace", namespace) vm.ExtVar(repo+"namespace", namespace)
vm.ExtVar(repo+"slug", v.Repository.Path) vm.ExtVar(repo+"slug", v.Path)
vm.ExtVar(repo+"git_http_url", v.Repository.GitURL) vm.ExtVar(repo+"git_http_url", v.GitURL)
vm.ExtVar(repo+"git_ssh_url", v.Repository.GitURL) vm.ExtVar(repo+"git_ssh_url", v.GitURL)
vm.ExtVar(repo+"link", v.Repository.GitURL) vm.ExtVar(repo+"link", v.GitURL)
vm.ExtVar(repo+"branch", v.Repository.DefaultBranch) vm.ExtVar(repo+"branch", v.DefaultBranch)
vm.ExtVar(repo+"config", p.ConfigPath) vm.ExtVar(repo+"config", p.ConfigPath)
vm.ExtVar(repo+"private", strconv.FormatBool(!v.IsPublic)) vm.ExtVar(repo+"private", strconv.FormatBool(!publicRepo))
vm.ExtVar(repo+"visibility", "internal") vm.ExtVar(repo+"visibility", "internal")
vm.ExtVar(repo+"active", strconv.FormatBool(true)) vm.ExtVar(repo+"active", strconv.FormatBool(true))
vm.ExtVar(repo+"trusted", strconv.FormatBool(true)) vm.ExtVar(repo+"trusted", strconv.FormatBool(true))

View File

@ -17,7 +17,6 @@ package converter
import ( import (
"context" "context"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
) )
@ -26,10 +25,11 @@ type (
// ConvertArgs represents a request to the pipeline // ConvertArgs represents a request to the pipeline
// conversion service. // conversion service.
ConvertArgs struct { ConvertArgs struct {
Repo *repo.Repository `json:"repository,omitempty"` Repo *types.Repository `json:"repository,omitempty"`
Pipeline *types.Pipeline `json:"pipeline,omitempty"` Pipeline *types.Pipeline `json:"pipeline,omitempty"`
Execution *types.Execution `json:"execution,omitempty"` Execution *types.Execution `json:"execution,omitempty"`
File *file.File `json:"config,omitempty"` File *file.File `json:"config,omitempty"`
RepoIsPublic bool `json:"repo_is_public,omitempty"`
} }
// Service converts a file which is in starlark/jsonnet form by looking // Service converts a file which is in starlark/jsonnet form by looking

View File

@ -17,7 +17,6 @@ package starlark
import ( import (
"strings" "strings"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
"go.starlark.net/starlark" "go.starlark.net/starlark"
@ -25,15 +24,16 @@ import (
) )
func createArgs( func createArgs(
repo *repo.Repository, repo *types.Repository,
pipeline *types.Pipeline, pipeline *types.Pipeline,
execution *types.Execution, execution *types.Execution,
repoIsPublic bool,
) []starlark.Value { ) []starlark.Value {
args := []starlark.Value{ args := []starlark.Value{
starlarkstruct.FromStringDict( starlarkstruct.FromStringDict(
starlark.String("context"), starlark.String("context"),
starlark.StringDict{ starlark.StringDict{
"repo": starlarkstruct.FromStringDict(starlark.String("repo"), fromRepo(repo, pipeline)), "repo": starlarkstruct.FromStringDict(starlark.String("repo"), fromRepo(repo, pipeline, repoIsPublic)),
"build": starlarkstruct.FromStringDict(starlark.String("build"), fromBuild(execution)), "build": starlarkstruct.FromStringDict(starlark.String("build"), fromBuild(execution)),
}, },
), ),
@ -67,7 +67,7 @@ func fromBuild(v *types.Execution) starlark.StringDict {
} }
} }
func fromRepo(v *repo.Repository, p *types.Pipeline) starlark.StringDict { func fromRepo(v *types.Repository, p *types.Pipeline, publicRepo bool) starlark.StringDict {
namespace := v.Path namespace := v.Path
idx := strings.LastIndex(v.Path, "/") idx := strings.LastIndex(v.Path, "/")
if idx != -1 { if idx != -1 {
@ -76,17 +76,17 @@ func fromRepo(v *repo.Repository, p *types.Pipeline) starlark.StringDict {
return starlark.StringDict{ return starlark.StringDict{
// TODO [CODE-1363]: remove after identifier migration? // TODO [CODE-1363]: remove after identifier migration?
"uid": starlark.String(v.Repository.Identifier), "uid": starlark.String(v.Identifier),
"identifier": starlark.String(v.Repository.Identifier), "identifier": starlark.String(v.Identifier),
"name": starlark.String(v.Repository.Identifier), "name": starlark.String(v.Identifier),
"namespace": starlark.String(namespace), "namespace": starlark.String(namespace),
"slug": starlark.String(v.Repository.Path), "slug": starlark.String(v.Path),
"git_http_url": starlark.String(v.Repository.GitURL), "git_http_url": starlark.String(v.GitURL),
"git_ssh_url": starlark.String(v.Repository.GitURL), "git_ssh_url": starlark.String(v.GitURL),
"link": starlark.String(v.Repository.GitURL), "link": starlark.String(v.GitURL),
"branch": starlark.String(v.Repository.DefaultBranch), "branch": starlark.String(v.DefaultBranch),
"config": starlark.String(p.ConfigPath), "config": starlark.String(p.ConfigPath),
"private": !starlark.Bool(v.IsPublic), "private": !starlark.Bool(publicRepo),
"visibility": starlark.String("internal"), "visibility": starlark.String("internal"),
"active": starlark.Bool(true), "active": starlark.Bool(true),
"trusted": starlark.Bool(true), "trusted": starlark.Bool(true),

View File

@ -18,7 +18,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
@ -57,7 +56,8 @@ var (
) )
func Parse( func Parse(
repo *repo.Repository, repo *types.Repository,
repoIsPublic bool,
pipeline *types.Pipeline, pipeline *types.Pipeline,
execution *types.Execution, execution *types.Execution,
file *file.File, file *file.File,
@ -69,8 +69,8 @@ func Parse(
Load: noLoad, Load: noLoad,
Print: func(_ *starlark.Thread, msg string) { Print: func(_ *starlark.Thread, msg string) {
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
"namespace": repo.Repository.Path, // TODO: update to just be the space "namespace": repo.Path, // TODO: update to just be the space
"name": repo.Repository.Identifier, "name": repo.Identifier,
}).Traceln(msg) }).Traceln(msg)
}, },
} }
@ -96,7 +96,7 @@ func Parse(
// create the input args and invoke the main method // create the input args and invoke the main method
// using the input args. // using the input args.
args := createArgs(repo, pipeline, execution) args := createArgs(repo, pipeline, execution, repoIsPublic)
// set the maximum number of operations in the script. this // set the maximum number of operations in the script. this
// mitigates long running scripts. // mitigates long running scripts.

View File

@ -19,8 +19,8 @@ import (
"fmt" "fmt"
"io" "io"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/git" "github.com/harness/gitness/git"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
@ -35,12 +35,12 @@ func newService(git git.Interface) Service {
func (f *service) Get( func (f *service) Get(
ctx context.Context, ctx context.Context,
repo *repo.Repository, repo *types.Repository,
path string, path string,
ref string, ref string,
) (*File, error) { ) (*File, error) {
readParams := git.ReadParams{ readParams := git.ReadParams{
RepoUID: repo.Repository.GitUID, RepoUID: repo.GitUID,
} }
treeNodeOutput, err := f.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ treeNodeOutput, err := f.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
ReadParams: readParams, ReadParams: readParams,

View File

@ -17,7 +17,7 @@ package file
import ( import (
"context" "context"
"github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/types"
) )
type ( type (
@ -36,6 +36,6 @@ type (
Service interface { Service interface {
// path is the path in the repo to read // path is the path in the repo to read
// ref is the git ref for the repository e.g. refs/heads/master // ref is the git ref for the repository e.g. refs/heads/master
Get(ctx context.Context, repo *repo.Repository, path, ref string) (*File, error) Get(ctx context.Context, repo *types.Repository, path, ref string) (*File, error)
} }
) )

View File

@ -103,7 +103,7 @@ func (e *embedded) Detail(ctx context.Context, stage *drone.Stage) (*client.Cont
return &client.Context{ return &client.Context{
Build: ConvertToDroneBuild(details.Execution), Build: ConvertToDroneBuild(details.Execution),
Repo: ConvertToDroneRepo(details.Repo), Repo: ConvertToDroneRepo(details.Repo, details.RepoIsPublic),
Stage: ConvertToDroneStage(details.Stage), Stage: ConvertToDroneStage(details.Stage),
Secrets: ConvertToDroneSecrets(details.Secrets), Secrets: ConvertToDroneSecrets(details.Secrets),
Config: ConvertToDroneFile(details.Config), Config: ConvertToDroneFile(details.Config),

View File

@ -17,7 +17,6 @@ package manager
import ( import (
"time" "time"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
"github.com/harness/gitness/livelog" "github.com/harness/gitness/livelog"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
@ -208,21 +207,21 @@ func ConvertToDroneBuild(execution *types.Execution) *drone.Build {
} }
} }
func ConvertToDroneRepo(repo *repo.Repository) *drone.Repo { func ConvertToDroneRepo(repo *types.Repository, repoIsPublic bool) *drone.Repo {
return &drone.Repo{ return &drone.Repo{
ID: repo.Repository.ID, ID: repo.ID,
Trusted: true, // as builds are running on user machines, the repo is marked trusted. Trusted: true, // as builds are running on user machines, the repo is marked trusted.
UID: repo.Repository.Identifier, UID: repo.Identifier,
UserID: repo.Repository.CreatedBy, UserID: repo.CreatedBy,
Namespace: repo.Repository.Path, Namespace: repo.Path,
Name: repo.Repository.Identifier, Name: repo.Identifier,
HTTPURL: repo.Repository.GitURL, HTTPURL: repo.GitURL,
Link: repo.Repository.GitURL, Link: repo.GitURL,
Private: !repo.IsPublic, Private: !repoIsPublic,
Created: repo.Repository.Created, Created: repo.Created,
Updated: repo.Repository.Updated, Updated: repo.Updated,
Version: repo.Repository.Version, Version: repo.Version,
Branch: repo.Repository.DefaultBranch, Branch: repo.DefaultBranch,
// TODO: We can get this from configuration once we start populating it. // TODO: We can get this from configuration once we start populating it.
// If this is not set drone runner cancels the build. // If this is not set drone runner cancels the build.
Timeout: int64((10 * time.Hour).Seconds()), Timeout: int64((10 * time.Hour).Seconds()),

View File

@ -23,7 +23,6 @@ import (
"time" "time"
apiauth "github.com/harness/gitness/app/api/auth" apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/bootstrap"
"github.com/harness/gitness/app/jwt" "github.com/harness/gitness/app/jwt"
"github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/converter"
@ -83,7 +82,8 @@ type (
// ExecutionContext represents the minimum amount of information // ExecutionContext represents the minimum amount of information
// required by the runner to execute a build. // required by the runner to execute a build.
ExecutionContext struct { ExecutionContext struct {
Repo *repo.Repository `json:"repository"` Repo *types.Repository `json:"repository"`
RepoIsPublic bool `json:"repository_is_public,omitempty"`
Execution *types.Execution `json:"build"` Execution *types.Execution `json:"build"`
Stage *types.Stage `json:"stage"` Stage *types.Stage `json:"stage"`
Secrets []*types.Secret `json:"secrets"` Secrets []*types.Secret `json:"secrets"`
@ -302,24 +302,14 @@ func (m *Manager) Details(_ context.Context, stageID int64) (*ExecutionContext,
log.Warn().Err(err).Msg("manager: cannot find pipeline") log.Warn().Err(err).Msg("manager: cannot find pipeline")
return nil, err return nil, err
} }
repoBase, err := m.Repos.Find(noContext, execution.RepoID) repo, err := m.Repos.Find(noContext, execution.RepoID)
if err != nil { if err != nil {
log.Warn().Err(err).Msg("manager: cannot find repo") log.Warn().Err(err).Msg("manager: cannot find repo")
return nil, err return nil, err
} }
isPublic, err := apiauth.CheckRepoIsPublic(noContext, m.publicAccess, repoBase)
if err != nil {
return nil, fmt.Errorf("failed to check if repo is public: %w", err)
}
repo := &repo.Repository{
Repository: *repoBase,
IsPublic: isPublic,
}
// Backfill clone URL // Backfill clone URL
repo.Repository.GitURL = m.urlProvider.GenerateContainerGITCloneURL(repo.Repository.Path) repo.GitURL = m.urlProvider.GenerateContainerGITCloneURL(repo.Path)
stages, err := m.Stages.List(noContext, stage.ExecutionID) stages, err := m.Stages.List(noContext, stage.ExecutionID)
if err != nil { if err != nil {
@ -329,12 +319,12 @@ func (m *Manager) Details(_ context.Context, stageID int64) (*ExecutionContext,
execution.Stages = stages execution.Stages = stages
log = log.With(). log = log.With().
Int64("build", execution.Number). Int64("build", execution.Number).
Str("repo", repo.Repository.GetGitUID()). Str("repo", repo.GetGitUID()).
Logger() Logger()
// TODO: Currently we fetch all the secrets from the same space. // TODO: Currently we fetch all the secrets from the same space.
// This logic can be updated when needed. // This logic can be updated when needed.
secrets, err := m.Secrets.ListAll(noContext, repo.Repository.ParentID) secrets, err := m.Secrets.ListAll(noContext, repo.ParentID)
if err != nil { if err != nil {
log.Warn().Err(err).Msg("manager: cannot list secrets") log.Warn().Err(err).Msg("manager: cannot list secrets")
return nil, err return nil, err
@ -347,12 +337,20 @@ func (m *Manager) Details(_ context.Context, stageID int64) (*ExecutionContext,
return nil, err return nil, err
} }
// Get public access settings of the repo
repoIsPublic, err := apiauth.CheckRepoIsPublic(noContext, m.publicAccess, repo)
if err != nil {
log.Warn().Err(err).Msg("manager: cannot check if repo is public")
return nil, err
}
// Convert file contents in case templates are being used. // Convert file contents in case templates are being used.
args := &converter.ConvertArgs{ args := &converter.ConvertArgs{
Repo: repo, Repo: repo,
Pipeline: pipeline, Pipeline: pipeline,
Execution: execution, Execution: execution,
File: file, File: file,
RepoIsPublic: repoIsPublic,
} }
file, err = m.ConverterService.Convert(noContext, args) file, err = m.ConverterService.Convert(noContext, args)
if err != nil { if err != nil {
@ -368,6 +366,7 @@ func (m *Manager) Details(_ context.Context, stageID int64) (*ExecutionContext,
return &ExecutionContext{ return &ExecutionContext{
Repo: repo, Repo: repo,
RepoIsPublic: repoIsPublic,
Execution: execution, Execution: execution,
Stage: stage, Stage: stage,
Secrets: secrets, Secrets: secrets,
@ -376,11 +375,11 @@ func (m *Manager) Details(_ context.Context, stageID int64) (*ExecutionContext,
}, nil }, nil
} }
func (m *Manager) createNetrc(repo *repo.Repository) (*Netrc, error) { func (m *Manager) createNetrc(repo *types.Repository) (*Netrc, error) {
pipelinePrincipal := bootstrap.NewPipelineServiceSession().Principal pipelinePrincipal := bootstrap.NewPipelineServiceSession().Principal
jwt, err := jwt.GenerateWithMembership( jwt, err := jwt.GenerateWithMembership(
pipelinePrincipal.ID, pipelinePrincipal.ID,
repo.Repository.ParentID, repo.ParentID,
pipelineJWTRole, pipelineJWTRole,
pipelineJWTLifetime, pipelineJWTLifetime,
pipelinePrincipal.Salt, pipelinePrincipal.Salt,
@ -389,7 +388,7 @@ func (m *Manager) createNetrc(repo *repo.Repository) (*Netrc, error) {
return nil, fmt.Errorf("failed to create jwt: %w", err) return nil, fmt.Errorf("failed to create jwt: %w", err)
} }
cloneURL, err := url.Parse(repo.Repository.GitURL) cloneURL, err := url.Parse(repo.GitURL)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to parse clone url '%s': %w", cloneURL, err) return nil, fmt.Errorf("failed to parse clone url '%s': %w", cloneURL, err)
} }

View File

@ -15,7 +15,6 @@
package triggerer package triggerer
import ( import (
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/url" "github.com/harness/gitness/app/url"
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
@ -33,11 +32,11 @@ func combine(env ...map[string]string) map[string]string {
} }
func Envs( func Envs(
repo *repo.Repository, repo *types.Repository,
pipeline *types.Pipeline, pipeline *types.Pipeline,
urlProvider url.Provider, urlProvider url.Provider,
) map[string]string { ) map[string]string {
return map[string]string{ return map[string]string{
"DRONE_BUILD_LINK": urlProvider.GenerateUIBuildURL(repo.Repository.Path, pipeline.Identifier, pipeline.Seq), "DRONE_BUILD_LINK": urlProvider.GenerateUIBuildURL(repo.Path, pipeline.Identifier, pipeline.Seq),
} }
} }

View File

@ -22,7 +22,6 @@ import (
"time" "time"
apiauth "github.com/harness/gitness/app/api/auth" apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/pipeline/checks" "github.com/harness/gitness/app/pipeline/checks"
"github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/converter"
"github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/file"
@ -154,19 +153,15 @@ func (t *triggerer) Trigger(
event := string(base.Action.GetTriggerEvent()) event := string(base.Action.GetTriggerEvent())
repoBase, err := t.repoStore.Find(ctx, pipeline.RepoID) repo, err := t.repoStore.Find(ctx, pipeline.RepoID)
if err != nil { if err != nil {
log.Error().Err(err).Msg("could not find repo") log.Error().Err(err).Msg("could not find repo")
return nil, err return nil, err
} }
isPublic, err := apiauth.CheckRepoIsPublic(ctx, t.publicAccess, repoBase)
if err != nil {
return nil, fmt.Errorf("failed to check if repo is public: %w", err)
}
repo := &repo.Repository{ repoIsPublic, err := apiauth.CheckRepoIsPublic(ctx, t.publicAccess, repo)
Repository: *repoBase, if err != nil {
IsPublic: isPublic, return nil, fmt.Errorf("could not check if repo is public: %w", err)
} }
file, err := t.fileService.Get(ctx, repo, pipeline.ConfigPath, base.After) file, err := t.fileService.Get(ctx, repo, pipeline.ConfigPath, base.After)
@ -177,7 +172,7 @@ func (t *triggerer) Trigger(
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
execution := &types.Execution{ execution := &types.Execution{
RepoID: repo.Repository.ID, RepoID: repo.ID,
PipelineID: pipeline.ID, PipelineID: pipeline.ID,
Trigger: base.Trigger, Trigger: base.Trigger,
CreatedBy: base.TriggeredBy, CreatedBy: base.TriggeredBy,
@ -219,6 +214,7 @@ func (t *triggerer) Trigger(
Pipeline: pipeline, Pipeline: pipeline,
Execution: execution, Execution: execution,
File: file, File: file,
RepoIsPublic: repoIsPublic,
} }
file, err = t.converterService.Convert(ctx, args) file, err = t.converterService.Convert(ctx, args)
if err != nil { if err != nil {
@ -265,7 +261,7 @@ func (t *triggerer) Trigger(
log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match action") log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match action")
case skipRef(pipeline, base.Ref): case skipRef(pipeline, base.Ref):
log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match ref") log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match ref")
case skipRepo(pipeline, repo.Repository.Path): case skipRepo(pipeline, repo.Path):
log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match repo") log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match repo")
case skipCron(pipeline, base.Cron): case skipCron(pipeline, base.Cron):
log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match cron job") log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match cron job")
@ -293,7 +289,7 @@ func (t *triggerer) Trigger(
} }
stage := &types.Stage{ stage := &types.Stage{
RepoID: repo.Repository.ID, RepoID: repo.ID,
Number: int64(i + 1), Number: int64(i + 1),
Name: match.Name, Name: match.Name,
Kind: match.Kind, Kind: match.Kind,
@ -346,7 +342,7 @@ func (t *triggerer) Trigger(
} }
} else { } else {
stages, err = parseV1Stages( stages, err = parseV1Stages(
ctx, file.Data, repo, execution, t.templateStore, t.pluginStore) ctx, file.Data, repo, execution, t.templateStore, t.pluginStore, t.publicAccess)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not parse v1 YAML into stages: %w", err) return nil, fmt.Errorf("could not parse v1 YAML into stages: %w", err)
} }
@ -406,10 +402,11 @@ func trunc(s string, i int) string {
func parseV1Stages( func parseV1Stages(
ctx context.Context, ctx context.Context,
data []byte, data []byte,
repo *repo.Repository, repo *types.Repository,
execution *types.Execution, execution *types.Execution,
templateStore store.TemplateStore, templateStore store.TemplateStore,
pluginStore store.PluginStore, pluginStore store.PluginStore,
publicaccess publicaccess.PublicAccess,
) ([]*types.Stage, error) { ) ([]*types.Stage, error) {
stages := []*types.Stage{} stages := []*types.Stage{}
// For V1 YAML, just go through the YAML and create stages serially for now // For V1 YAML, just go through the YAML and create stages serially for now
@ -428,8 +425,14 @@ func parseV1Stages(
return nil, fmt.Errorf("cannot support non-pipeline kinds in v1 at the moment: %w", err) return nil, fmt.Errorf("cannot support non-pipeline kinds in v1 at the moment: %w", err)
} }
// get repo public access
repoIsPublic, err := publicaccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path)
if err != nil {
return nil, fmt.Errorf("could not check repo public access: %w", err)
}
inputParams := map[string]interface{}{} inputParams := map[string]interface{}{}
inputParams["repo"] = inputs.Repo(manager.ConvertToDroneRepo(repo)) inputParams["repo"] = inputs.Repo(manager.ConvertToDroneRepo(repo, repoIsPublic))
inputParams["build"] = inputs.Build(manager.ConvertToDroneBuild(execution)) inputParams["build"] = inputs.Build(manager.ConvertToDroneBuild(execution))
var prevStage string var prevStage string
@ -476,7 +479,7 @@ func parseV1Stages(
status = enum.CIStatusPending status = enum.CIStatusPending
} }
temp := &types.Stage{ temp := &types.Stage{
RepoID: repo.Repository.ID, RepoID: repo.ID,
Number: int64(idx + 1), Number: int64(idx + 1),
Name: stage.Id, // for v1, ID is the unique identifier per stage Name: stage.Id, // for v1, ID is the unique identifier per stage
Created: now, Created: now,

View File

@ -35,7 +35,6 @@ import (
"github.com/harness/gitness/types" "github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
@ -117,16 +116,11 @@ func (r *Repository) RunManyForSpace(
jobDefinitions := make([]job.Definition, len(repos)) jobDefinitions := make([]job.Definition, len(repos))
for i, repository := range repos { for i, repository := range repos {
isPublic, err := apiauth.CheckRepoIsPublic(ctx, r.publicAccess, repository)
if err != nil {
return fmt.Errorf("failed to check repo public visibility: %w", err)
}
repoJobData := Input{ repoJobData := Input{
Identifier: repository.Identifier, Identifier: repository.Identifier,
ID: repository.ID, ID: repository.ID,
Description: repository.Description, Description: repository.Description,
IsPublic: isPublic, IsPublic: false, // todo: use repository.IsPublic once public is available.
HarnessCodeInfo: *harnessCodeInfo, HarnessCodeInfo: *harnessCodeInfo,
} }
@ -193,16 +187,11 @@ func (r *Repository) Handle(ctx context.Context, data string, _ job.ProgressRepo
return "", err return "", err
} }
isPublic, err := apiauth.CheckRepoIsPublic(ctx, r.publicAccess, repository)
if err != nil {
return "", fmt.Errorf("failed to check if repo is public: %w", err)
}
remoteRepo, err := client.CreateRepo(ctx, repo.CreateInput{ remoteRepo, err := client.CreateRepo(ctx, repo.CreateInput{
Identifier: repository.Identifier, Identifier: repository.Identifier,
DefaultBranch: repository.DefaultBranch, DefaultBranch: repository.DefaultBranch,
Description: repository.Description, Description: repository.Description,
IsPublic: isPublic, IsPublic: false, // TODO: use apiauth.CheckRepoIsPublic once public access is deployed on HC.
Readme: false, Readme: false,
License: "", License: "",
GitIgnore: "", GitIgnore: "",

View File

@ -17,7 +17,7 @@ package publicaccess
import ( import (
"context" "context"
"github.com/harness/gitness/types" "github.com/harness/gitness/types/enum"
) )
// PublicAccess is an abstraction of an entity responsible for managing public access to resources. // PublicAccess is an abstraction of an entity responsible for managing public access to resources.
@ -31,8 +31,8 @@ type PublicAccess interface {
*/ */
Get( Get(
ctx context.Context, ctx context.Context,
scope *types.Scope, resourceType enum.PublicResourceType,
resource *types.Resource, resourcePath string,
) (bool, error) ) (bool, error)
/* /*
@ -43,8 +43,8 @@ type PublicAccess interface {
*/ */
Set( Set(
ctx context.Context, ctx context.Context,
scope *types.Scope, resourceType enum.PublicResourceType,
resource *types.Resource, resourcePath string,
enable bool, enable bool,
) error ) error
} }

View File

@ -18,70 +18,52 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
func (s *Service) getPublicResource( func (s *Service) getPublicResource(
ctx context.Context, ctx context.Context,
scope *types.Scope, resourceType enum.PublicResourceType,
resource *types.Resource, resourcePath string,
) (*types.PublicResource, error) { ) (int64, error) {
resType := resource.Type var id int64
// set scope type to space for checks within space scope.
if resource.Identifier == "" {
resType = enum.ResourceTypeSpace
}
var pubRes *types.PublicResource
var err error var err error
switch resType { switch resourceType {
case enum.ResourceTypeRepo: case enum.PublicResourceTypeRepo:
pubRes, err = s.getResourceRepo(ctx, scope, resource) id, err = s.getResourceRepo(ctx, resourcePath)
case enum.ResourceTypeSpace: case enum.PublicResourceTypeSpace:
pubRes, err = s.getResourceSpace(ctx, scope, resource) id, err = s.getResourceSpace(ctx, resourcePath)
default: default:
return nil, fmt.Errorf("invalid public resource type") return 0, fmt.Errorf("invalid public resource type")
} }
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get public resource: %w", err) return 0, fmt.Errorf("failed to get public resource: %w", err)
} }
return pubRes, nil return id, nil
} }
func (s *Service) getResourceRepo( func (s *Service) getResourceRepo(
ctx context.Context, ctx context.Context,
scope *types.Scope, path string,
resource *types.Resource, ) (int64, error) {
) (*types.PublicResource, error) { repo, err := s.repoStore.FindByRef(ctx, path)
repoRef := paths.Concatenate(scope.SpacePath, resource.Identifier)
repo, err := s.repoStore.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err) return 0, fmt.Errorf("failed to find repo: %w", err)
} }
return &types.PublicResource{ return repo.ID, nil
Type: enum.PublicResourceTypeRepo,
ID: repo.ID,
}, nil
} }
func (s *Service) getResourceSpace( func (s *Service) getResourceSpace(
ctx context.Context, ctx context.Context,
scope *types.Scope, path string,
resource *types.Resource, ) (int64, error) {
) (*types.PublicResource, error) { space, err := s.spaceStore.FindByRef(ctx, path)
spaceRef := paths.Concatenate(scope.SpacePath, resource.Identifier)
space, err := s.spaceStore.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return 0, fmt.Errorf("failed to find space: %w", err)
} }
return &types.PublicResource{ return space.ID, nil
Type: enum.PublicResourceTypeSpace,
ID: space.ID,
}, nil
} }

View File

@ -21,22 +21,22 @@ import (
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
gitness_store "github.com/harness/gitness/store" gitness_store "github.com/harness/gitness/store"
"github.com/harness/gitness/types" "github.com/harness/gitness/types/enum"
) )
type Service struct { type Service struct {
publicResourceStore store.PublicResource publicAccessStore store.PublicAccessStore
repoStore store.RepoStore repoStore store.RepoStore
spaceStore store.SpaceStore spaceStore store.SpaceStore
} }
func NewService( func NewService(
publicResourceStore store.PublicResource, publicAccessStore store.PublicAccessStore,
repoStore store.RepoStore, repoStore store.RepoStore,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
) PublicAccess { ) PublicAccess {
return &Service{ return &Service{
publicResourceStore: publicResourceStore, publicAccessStore: publicAccessStore,
repoStore: repoStore, repoStore: repoStore,
spaceStore: spaceStore, spaceStore: spaceStore,
} }
@ -44,15 +44,15 @@ func NewService(
func (s *Service) Get( func (s *Service) Get(
ctx context.Context, ctx context.Context,
scope *types.Scope, resourceType enum.PublicResourceType,
resource *types.Resource, resourcePath string,
) (bool, error) { ) (bool, error) {
pubRes, err := s.getPublicResource(ctx, scope, resource) pubResID, err := s.getPublicResource(ctx, resourceType, resourcePath)
if err != nil { if err != nil {
return false, err return false, err
} }
err = s.publicResourceStore.Find(ctx, pubRes) err = s.publicAccessStore.Find(ctx, resourceType, pubResID)
if errors.Is(err, gitness_store.ErrResourceNotFound) { if errors.Is(err, gitness_store.ErrResourceNotFound) {
return false, nil return false, nil
} }
@ -65,22 +65,22 @@ func (s *Service) Get(
func (s *Service) Set( func (s *Service) Set(
ctx context.Context, ctx context.Context,
scope *types.Scope, resourceType enum.PublicResourceType,
resource *types.Resource, resourcePath string,
enable bool, enable bool,
) error { ) error {
pubRes, err := s.getPublicResource(ctx, scope, resource) pubResID, err := s.getPublicResource(ctx, resourceType, resourcePath)
if err != nil { if err != nil {
return err return err
} }
if enable { if enable {
err := s.publicResourceStore.Create(ctx, pubRes) err := s.publicAccessStore.Create(ctx, resourceType, pubResID)
if errors.Is(err, gitness_store.ErrDuplicate) { if errors.Is(err, gitness_store.ErrDuplicate) {
return nil return nil
} }
return err return err
} else { } else {
return s.publicResourceStore.Delete(ctx, pubRes) return s.publicAccessStore.Delete(ctx, resourceType, pubResID)
} }
} }

View File

@ -25,9 +25,9 @@ var WireSet = wire.NewSet(
) )
func ProvidePublicAccess( func ProvidePublicAccess(
publicResources store.PublicResource, publicAccessStore store.PublicAccessStore,
repoStore store.RepoStore, repoStore store.RepoStore,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
) PublicAccess { ) PublicAccess {
return NewService(publicResources, repoStore, spaceStore) return NewService(publicAccessStore, repoStore, spaceStore)
} }

View File

@ -290,11 +290,11 @@ type (
ListSpaces(ctx context.Context, userID int64, filter types.MembershipSpaceFilter) ([]types.MembershipSpace, error) ListSpaces(ctx context.Context, userID int64, filter types.MembershipSpaceFilter) ([]types.MembershipSpace, error)
} }
// PublicResource defines the publicly accessible resources data storage. // PublicAccessStore defines the publicly accessible resources data storage.
PublicResource interface { PublicAccessStore interface {
Find(ctx context.Context, pubRes *types.PublicResource) error Find(ctx context.Context, typ enum.PublicResourceType, id int64) error
Create(ctx context.Context, pubRes *types.PublicResource) error Create(ctx context.Context, typ enum.PublicResourceType, id int64) error
Delete(ctx context.Context, pubRes *types.PublicResource) error Delete(ctx context.Context, typ enum.PublicResourceType, id int64) error
} }
// TokenStore defines the token data storage. // TokenStore defines the token data storage.

View File

@ -1,28 +1,28 @@
-- copy public repositories -- copy public repositories
ALTER TABLE repositories ADD COLUMN repo_is_public; ALTER TABLE repositories ADD COLUMN repo_is_public BOOLEAN;
UPDATE repositories UPDATE repositories
WHERE repo_id IN ( WHERE repo_id IN (
SELECT public_resource_repo_id SELECT public_access_repo_id
FROM public_resources FROM public_access
WHERE public_resource_repo_id IS NOT NULL; WHERE public_access_repo_id IS NOT NULL;
) SET ) SET
repo_is_public = TRUE; repo_is_public = TRUE;
-- copy public spaces -- copy public spaces
ALTER TABLE spaces ADD COLUMN space_is_public; ALTER TABLE spaces ADD COLUMN space_is_public BOOLEAN;
-- update public resources -- update public access
UPDATE spaces UPDATE spaces
WHERE space_id IN ( WHERE space_id IN (
SELECT public_resource_space_id SELECT public_access_space_id
FROM public_resources FROM public_access
WHERE public_resource_space_id IS NOT NULL; WHERE public_access_space_id IS NOT NULL;
) SET ) SET
sapce_is_public = TRUE; space_is_public = TRUE;
-- clear public_resoureces -- clear public access
DROP INDEX public_resource_space_id_key; DROP INDEX public_access_space_id_key;
DROP INDEX public_resource_repo_id_key; DROP INDEX public_access_repo_id_key;
DROP TABLE public_resources; DROP TABLE public_access;

View File

@ -1,48 +1,44 @@
CREATE TABLE public_resources ( CREATE TABLE public_access (
public_resource_id SERIAL PRIMARY KEY public_access_id SERIAL PRIMARY KEY
,public_resource_space_id INTEGER ,public_access_space_id INTEGER
,public_resource_repo_id INTEGER ,public_access_repo_id INTEGER
,CONSTRAINT fk_public_resource_space_id FOREIGN KEY (public_resource_space_id) ,CONSTRAINT fk_public_access_space_id FOREIGN KEY (public_access_space_id)
REFERENCES spaces (space_id) MATCH SIMPLE REFERENCES spaces (space_id) MATCH SIMPLE
ON UPDATE NO ACTION ON UPDATE NO ACTION
ON DELETE CASCADE ON DELETE CASCADE
,CONSTRAINT fk_public_resource_repo_id FOREIGN KEY (public_resource_repo_id) ,CONSTRAINT fk_public_access_repo_id FOREIGN KEY (public_access_repo_id)
REFERENCES repositories (repo_id) MATCH SIMPLE REFERENCES repositories (repo_id) MATCH SIMPLE
ON UPDATE NO ACTION ON UPDATE NO ACTION
ON DELETE CASCADE ON DELETE CASCADE
); );
CREATE UNIQUE INDEX public_resource_space_id_key CREATE UNIQUE INDEX public_access_space_id_key
ON public_resources(public_resource_space_id) ON public_access(public_access_space_id)
WHERE public_resource_space_id IS NOT NULL; WHERE public_access_space_id IS NOT NULL;
CREATE UNIQUE INDEX public_resource_repo_id_key CREATE UNIQUE INDEX public_access_repo_id_key
ON public_resources(public_resource_repo_id) ON public_access(public_access_repo_id)
WHERE public_resource_repo_id IS NOT NULL; WHERE public_access_repo_id IS NOT NULL;
-- move public repos into public_resource -- move public repos into public_access
INSERT INTO public_resources ( INSERT INTO public_access (
public_resource_space_id public_access_repo_id
,public_resource_repo_id
) )
SELECT SELECT
NULL repo_id
,repo_id
FROM repositories FROM repositories
WHERE repo_is_public = TRUE; WHERE repo_is_public = TRUE;
-- alter repo table -- alter repo table
ALTER TABLE repositories DROP COLUMN repo_is_public; ALTER TABLE repositories DROP COLUMN repo_is_public;
-- move public spaces into public_resource -- move public spaces into public_access
INSERT INTO public_resources ( INSERT INTO public_access (
public_resource_space_id public_access_space_id
,public_resource_repo_id
) )
SELECT SELECT
space_id space_id
,NULL
FROM spaces FROM spaces
WHERE space_is_public = TRUE; WHERE space_is_public = TRUE;

View File

@ -1,28 +1,28 @@
-- copy public repositories -- copy public repositories
ALTER TABLE repositories ADD COLUMN repo_is_public; ALTER TABLE repositories ADD COLUMN repo_is_public BOOLEAN;
UPDATE repositories UPDATE repositories
WHERE repo_id IN ( WHERE repo_id IN (
SELECT public_resource_repo_id SELECT public_access_repo_id
FROM public_resources FROM public_access
WHERE public_resource_repo_id IS NOT NULL; WHERE public_access_repo_id IS NOT NULL;
) SET ) SET
repo_is_public = TRUE; repo_is_public = TRUE;
-- copy public spaces -- copy public spaces
ALTER TABLE spaces ADD COLUMN space_is_public; ALTER TABLE spaces ADD COLUMN space_is_public BOOLEAN;
-- update public resources -- update public access
UPDATE spaces UPDATE spaces
WHERE space_id IN ( WHERE space_id IN (
SELECT public_resource_space_id SELECT public_access_space_id
FROM public_resources FROM public_access
WHERE public_resource_space_id IS NOT NULL; WHERE public_access_space_id IS NOT NULL;
) SET ) SET
sapce_is_public = TRUE; space_is_public = TRUE;
-- clear public_resoureces -- clear public_access
DROP INDEX public_resource_space_id_key; DROP INDEX public_access_space_id_key;
DROP INDEX public_resource_repo_id_key; DROP INDEX public_access_repo_id_key;
DROP TABLE public_resources; DROP TABLE public_access;

View File

@ -1,48 +1,44 @@
CREATE TABLE public_resources ( CREATE TABLE public_access (
public_resource_id INTEGER PRIMARY KEY AUTOINCREMENT public_access_id INTEGER PRIMARY KEY AUTOINCREMENT
,public_resource_space_id INTEGER ,public_access_space_id INTEGER
,public_resource_repo_id INTEGER ,public_access_repo_id INTEGER
,CONSTRAINT fk_public_resource_space_id FOREIGN KEY (public_resource_space_id) ,CONSTRAINT fk_public_access_space_id FOREIGN KEY (public_access_space_id)
REFERENCES spaces (space_id) MATCH SIMPLE REFERENCES spaces (space_id) MATCH SIMPLE
ON UPDATE NO ACTION ON UPDATE NO ACTION
ON DELETE CASCADE ON DELETE CASCADE
,CONSTRAINT fk_public_resource_repo_id FOREIGN KEY (public_resource_repo_id) ,CONSTRAINT fk_public_access_repo_id FOREIGN KEY (public_access_repo_id)
REFERENCES repositories (repo_id) MATCH SIMPLE REFERENCES repositories (repo_id) MATCH SIMPLE
ON UPDATE NO ACTION ON UPDATE NO ACTION
ON DELETE CASCADE ON DELETE CASCADE
); );
CREATE UNIQUE INDEX public_resource_space_id_key CREATE UNIQUE INDEX public_access_space_id_key
ON public_resources(public_resource_space_id) ON public_access(public_access_space_id)
WHERE public_resource_space_id IS NOT NULL; WHERE public_access_space_id IS NOT NULL;
CREATE UNIQUE INDEX public_resource_repo_id_key CREATE UNIQUE INDEX public_access_repo_id_key
ON public_resources(public_resource_repo_id) ON public_access(public_access_repo_id)
WHERE public_resource_repo_id IS NOT NULL; WHERE public_access_repo_id IS NOT NULL;
-- move public repos into public_resource -- move public repos into public_access
INSERT INTO public_resources ( INSERT INTO public_access (
public_resource_space_id public_access_repo_id
,public_resource_repo_id
) )
SELECT SELECT
NULL repo_id
,repo_id
FROM repositories FROM repositories
WHERE repo_is_public = TRUE; WHERE repo_is_public = TRUE;
-- alter repo table -- alter repo table
ALTER TABLE repositories DROP COLUMN repo_is_public; ALTER TABLE repositories DROP COLUMN repo_is_public;
-- move public spaces into public_resource -- move public spaces into public_access
INSERT INTO public_resources ( INSERT INTO public_access (
public_resource_space_id public_access_space_id
,public_resource_repo_id
) )
SELECT SELECT
space_id space_id
,NULL
FROM spaces FROM spaces
WHERE space_is_public = TRUE; WHERE space_is_public = TRUE;

View File

@ -21,56 +21,56 @@ import (
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
"github.com/guregu/null" "github.com/guregu/null"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
) )
var _ store.PublicResource = (*PublicResourcesStore)(nil) var _ store.PublicAccessStore = (*PublicAccessStore)(nil)
// NewPublicResourcesStore returns a new PublicResourcesStore. // NewPublicAccessStore returns a new PublicAccessStore.
func NewPublicResourcesStore(db *sqlx.DB) *PublicResourcesStore { func NewPublicAccessStore(db *sqlx.DB) *PublicAccessStore {
return &PublicResourcesStore{ return &PublicAccessStore{
db: db, db: db,
} }
} }
// PublicResourcesStore implements store.SettingsStore backed by a relational database. // PublicAccessStore implements store.PublicAccessStore backed by a relational database.
type PublicResourcesStore struct { type PublicAccessStore struct {
db *sqlx.DB db *sqlx.DB
} }
type publicResource struct { type publicAccess struct {
ID int64 `db:"public_resource_id"` ID int64 `db:"public_access_id"`
SpaceID null.Int `db:"public_resource_space_id"` SpaceID null.Int `db:"public_access_space_id"`
RepoID null.Int `db:"public_resource_repo_id"` RepoID null.Int `db:"public_access_repo_id"`
} }
const ( const (
publicResourceColumns = ` publicAccessColumns = `
public_resource_id public_access_id
,public_resource_space_id ,public_access_space_id
,public_resource_repo_id ,public_access_repo_id
` `
) )
func (p *PublicResourcesStore) Find( func (p *PublicAccessStore) Find(
ctx context.Context, ctx context.Context,
pubRes *types.PublicResource, typ enum.PublicResourceType,
id int64,
) error { ) error {
stmt := database.Builder. stmt := database.Builder.
Select(publicResourceColumns). Select(publicAccessColumns).
From("public_resources") From("public_access")
switch pubRes.Type { switch typ {
case enum.PublicResourceTypeRepo: case enum.PublicResourceTypeRepo:
stmt = stmt.Where("public_resource_repo_id = ?", pubRes.ID) stmt = stmt.Where("public_access_repo_id = ?", id)
case enum.PublicResourceTypeSpace: case enum.PublicResourceTypeSpace:
stmt = stmt.Where("public_resource_space_id = ?", pubRes.ID) stmt = stmt.Where("public_access_space_id = ?", id)
default: default:
return fmt.Errorf("public resource type %q is not supported", pubRes.Type) return fmt.Errorf("public resource type %q is not supported", typ)
} }
sql, args, err := stmt.ToSql() sql, args, err := stmt.ToSql()
@ -80,7 +80,7 @@ func (p *PublicResourcesStore) Find(
db := dbtx.GetAccessor(ctx, p.db) db := dbtx.GetAccessor(ctx, p.db)
dst := &publicResource{} dst := &publicAccess{}
if err = db.GetContext(ctx, dst, sql, args...); err != nil { if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Select query failed") return database.ProcessSQLErrorf(ctx, err, "Select query failed")
} }
@ -88,25 +88,26 @@ func (p *PublicResourcesStore) Find(
return nil return nil
} }
func (p *PublicResourcesStore) Create( func (p *PublicAccessStore) Create(
ctx context.Context, ctx context.Context,
pubRes *types.PublicResource, typ enum.PublicResourceType,
id int64,
) error { ) error {
stmt := database.Builder. stmt := database.Builder.
Insert(""). Insert("").
Into("public_resources"). Into("public_access").
Columns( Columns(
"public_resource_space_id", "public_access_space_id",
"public_resource_repo_id", "public_access_repo_id",
) )
switch pubRes.Type { switch typ {
case enum.PublicResourceTypeRepo: case enum.PublicResourceTypeRepo:
stmt = stmt.Values(null.Int{}, null.IntFrom(pubRes.ID)) stmt = stmt.Values(null.Int{}, null.IntFrom(id))
case enum.PublicResourceTypeSpace: case enum.PublicResourceTypeSpace:
stmt = stmt.Values(null.IntFrom(pubRes.ID), null.Int{}) stmt = stmt.Values(null.IntFrom(id), null.Int{})
default: default:
return fmt.Errorf("public resource type %q is not supported", pubRes.Type) return fmt.Errorf("public resource type %q is not supported", typ)
} }
sql, args, err := stmt.ToSql() sql, args, err := stmt.ToSql()
@ -123,20 +124,21 @@ func (p *PublicResourcesStore) Create(
return nil return nil
} }
func (p *PublicResourcesStore) Delete( func (p *PublicAccessStore) Delete(
ctx context.Context, ctx context.Context,
pubRes *types.PublicResource, typ enum.PublicResourceType,
id int64,
) error { ) error {
stmt := database.Builder. stmt := database.Builder.
Delete("public_resources") Delete("public_access")
switch pubRes.Type { switch typ {
case enum.PublicResourceTypeRepo: case enum.PublicResourceTypeRepo:
stmt = stmt.Where("public_resource_repo_id = ?", pubRes.ID) stmt = stmt.Where("public_access_repo_id = ?", id)
case enum.PublicResourceTypeSpace: case enum.PublicResourceTypeSpace:
stmt = stmt.Where("public_resource_space_id = ?", pubRes.ID) stmt = stmt.Where("public_access_space_id = ?", id)
default: default:
return fmt.Errorf("public resource type %q is not supported", pubRes.Type) return fmt.Errorf("public resource type %q is not supported", typ)
} }
sql, args, err := stmt.ToSql() sql, args, err := stmt.ToSql()

View File

@ -53,7 +53,7 @@ var WireSet = wire.NewSet(
ProvideWebhookStore, ProvideWebhookStore,
ProvideWebhookExecutionStore, ProvideWebhookExecutionStore,
ProvideSettingsStore, ProvideSettingsStore,
ProvidePublicResourcesStore, ProvidePublicPublicAccessStore,
ProvideCheckStore, ProvideCheckStore,
ProvideConnectorStore, ProvideConnectorStore,
ProvideTemplateStore, ProvideTemplateStore,
@ -249,7 +249,7 @@ func ProvideSettingsStore(db *sqlx.DB) store.SettingsStore {
return NewSettingsStore(db) return NewSettingsStore(db)
} }
// ProvidePublicResourcesStore provides a pulic resources store. // ProvidePublicPublicAccessStore provides a pulic access store.
func ProvidePublicResourcesStore(db *sqlx.DB) store.PublicResource { func ProvidePublicPublicAccessStore(db *sqlx.DB) store.PublicAccessStore {
return NewPublicResourcesStore(db) return NewPublicAccessStore(db)
} }

View File

@ -115,9 +115,9 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
principalInfoCache := cache.ProvidePrincipalInfoCache(principalInfoView) principalInfoCache := cache.ProvidePrincipalInfoCache(principalInfoView)
membershipStore := database.ProvideMembershipStore(db, principalInfoCache, spacePathStore, spaceStore) membershipStore := database.ProvideMembershipStore(db, principalInfoCache, spacePathStore, spaceStore)
permissionCache := authz.ProvidePermissionCache(spaceStore, membershipStore) permissionCache := authz.ProvidePermissionCache(spaceStore, membershipStore)
publicResource := database.ProvidePublicResourcesStore(db) publicAccessStore := database.ProvidePublicPublicAccessStore(db)
repoStore := database.ProvideRepoStore(db, spacePathCache, spacePathStore, spaceStore) repoStore := database.ProvideRepoStore(db, spacePathCache, spacePathStore, spaceStore)
publicAccess := publicaccess.ProvidePublicAccess(publicResource, repoStore, spaceStore) publicAccess := publicaccess.ProvidePublicAccess(publicAccessStore, repoStore, spaceStore)
authorizer := authz.ProvideAuthorizer(permissionCache, spaceStore, publicAccess) authorizer := authz.ProvideAuthorizer(permissionCache, spaceStore, publicAccess)
principalUIDTransformation := store.ProvidePrincipalUIDTransformation() principalUIDTransformation := store.ProvidePrincipalUIDTransformation()
principalStore := database.ProvidePrincipalStore(db, principalUIDTransformation) principalStore := database.ProvidePrincipalStore(db, principalUIDTransformation)
@ -201,7 +201,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
repoIdentifier := check.ProvideRepoIdentifierCheck() repoIdentifier := check.ProvideRepoIdentifierCheck()
repoCheck := repo.ProvideRepoCheck() repoCheck := repo.ProvideRepoCheck()
repoController := repo.ProvideController(config, transactor, provider, authorizer, repoStore, spaceStore, pipelineStore, principalStore, ruleStore, settingsService, principalInfoCache, protectionManager, gitInterface, repository, codeownersService, reporter, indexer, resourceLimiter, lockerLocker, auditService, mutexManager, repoIdentifier, repoCheck, publicAccess) repoController := repo.ProvideController(config, transactor, provider, authorizer, repoStore, spaceStore, pipelineStore, principalStore, ruleStore, settingsService, principalInfoCache, protectionManager, gitInterface, repository, codeownersService, reporter, indexer, resourceLimiter, lockerLocker, auditService, mutexManager, repoIdentifier, repoCheck, publicAccess)
reposettingsController := reposettings.ProvideController(authorizer, repoStore, settingsService, publicAccess, auditService) reposettingsController := reposettings.ProvideController(authorizer, repoStore, settingsService, auditService)
executionStore := database.ProvideExecutionStore(db) executionStore := database.ProvideExecutionStore(db)
checkStore := database.ProvideCheckStore(db, principalInfoCache) checkStore := database.ProvideCheckStore(db, principalInfoCache)
stageStore := database.ProvideStageStore(db) stageStore := database.ProvideStageStore(db)
@ -268,7 +268,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
if err != nil { if err != nil {
return nil, err return nil, err
} }
webhookController := webhook2.ProvideController(webhookConfig, authorizer, webhookStore, webhookExecutionStore, repoStore, webhookService, encrypter, publicAccess) webhookController := webhook2.ProvideController(webhookConfig, authorizer, webhookStore, webhookExecutionStore, repoStore, webhookService, encrypter)
reporter2, err := events4.ProvideReporter(eventsSystem) reporter2, err := events4.ProvideReporter(eventsSystem)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -20,7 +20,7 @@ func (PublicResourceType) Enum() []interface{} {
return toInterfaceSlice(GetAllPublicResourceTypes()) return toInterfaceSlice(GetAllPublicResourceTypes())
} }
var ( const (
PublicResourceTypeRepo PublicResourceType = "repository" PublicResourceTypeRepo PublicResourceType = "repository"
PublicResourceTypeSpace PublicResourceType = "space" PublicResourceTypeSpace PublicResourceType = "space"
) )

View File

@ -70,6 +70,18 @@ func (r Repository) MarshalJSON() ([]byte, error) {
}) })
} }
// Clone makes deep copy of repository object.
func (r Repository) Clone() Repository {
var deleted *int64
if r.Deleted != nil {
id := *r.Deleted
deleted = &id
}
r.Deleted = deleted
return r
}
type RepositorySizeInfo struct { type RepositorySizeInfo struct {
ID int64 `json:"id"` ID int64 `json:"id"`
GitUID string `json:"git_uid"` GitUID string `json:"git_uid"`