repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/create_commit_tag.go
app/api/controller/repo/create_commit_tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // CreateCommitTagInput used for tag creation apis. type CreateCommitTagInput struct { Name string `json:"name"` // Target is the commit (or points to the commit) the new tag will be pointing to. // If no target is provided, the tag points to the same commit as the default branch of the repo. Target string `json:"target"` // Message is the optional message the tag will be created with - if the message is empty // the tag will be lightweight, otherwise it'll be annotated. Message string `json:"message"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } // CreateCommitTag creates a new tag for a repo. func (c *Controller) CreateCommitTag(ctx context.Context, session *auth.Session, repoRef string, in *CreateCommitTagInput, ) (types.CreateCommitTagOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.CreateCommitTagOutput{}, nil, err } // set target to default branch in case no branch or commit was provided if in.Target == "" { in.Target = repo.DefaultBranch } rules, isRepoOwner, err := c.fetchTagRules(ctx, session, repo) if err != nil { return types.CreateCommitTagOutput{}, nil, err } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionCreate, RefType: protection.RefTypeTag, RefNames: []string{in.Name}, }) if err != nil { return types.CreateCommitTagOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { return types.CreateCommitTagOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.CreateCommitTagOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.CreateCommitTagOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } now := time.Now() rpcOut, err := c.git.CreateCommitTag(ctx, &git.CreateCommitTagParams{ WriteParams: writeParams, Name: in.Name, Target: in.Target, Message: in.Message, Tagger: identityFromPrincipal(session.Principal), TaggerDate: &now, }) if err != nil { return types.CreateCommitTagOutput{}, nil, err } commitTag := controller.MapCommitTag(rpcOut.CommitTag) if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeTag, audit.BypassedResourceName, commitTag.Name, audit.BypassAction, audit.BypassActionCreated, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, commitTag.Name, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.CommitTagObject{ TagName: commitTag.Name, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for create tag operation: %s", err) } } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeCreateTag, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create tag operation: %s", err) } return types.CreateCommitTagOutput{ CommitTag: commitTag, DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/soft_delete.go
app/api/controller/repo/soft_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/audit" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" "golang.org/x/exp/slices" ) type SoftDeleteResponse struct { DeletedAt int64 `json:"deleted_at"` } // SoftDelete soft deletes a repo and returns the deletedAt timestamp in epoch format. func (c *Controller) SoftDelete( ctx context.Context, session *auth.Session, repoRef string, ) (*SoftDeleteResponse, error) { // note: can't use c.getRepoCheckAccess because import job for repositories being imported must be cancelled. repoCore, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find the repo for soft delete: %w", err) } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoDelete); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } if err = c.repoCheck.LifecycleRestriction(ctx, session, repoCore); err != nil { return nil, err } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to find the repo by ID: %w", err) } if repo.Deleted != nil { return nil, usererror.BadRequest("Repository has already been deleted") } isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return nil, fmt.Errorf("failed to check current public access status: %w", err) } log.Ctx(ctx).Info(). Int64("repo.id", repo.ID). Str("repo.path", repo.Path). Msg("soft deleting repository") now := time.Now().UnixMilli() if err = c.SoftDeleteNoAuth(ctx, session, repo, now); err != nil { return nil, fmt.Errorf("failed to soft delete repo: %w", err) } err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionDeleted, paths.Parent(repo.Path), audit.WithOldObject(audit.RepositoryObject{ Repository: *repo, IsPublic: isPublic, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for delete repository operation: %s", err) } return &SoftDeleteResponse{DeletedAt: now}, nil } func (c *Controller) SoftDeleteNoAuth( ctx context.Context, session *auth.Session, repo *types.Repository, deletedAt int64, ) error { err := c.publicAccess.Delete(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return fmt.Errorf("failed to delete public access for repo: %w", err) } if slices.Contains(importingStates, repo.State) { c.repoFinder.MarkChanged(ctx, repo.Core()) return c.PurgeNoAuth(ctx, session, repo) } if err := c.repoStore.SoftDelete(ctx, repo, deletedAt); err != nil { return fmt.Errorf("failed to soft delete repo from db: %w", err) } c.repoFinder.MarkChanged(ctx, repo.Core()) if repo.Deleted != nil { c.eventReporter.SoftDeleted(ctx, &repoevents.SoftDeletedPayload{ Base: eventBase(repo.Core(), &session.Principal), RepoPath: repo.Path, Deleted: *repo.Deleted, }) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/delete_commit_tag.go
app/api/controller/repo/delete_commit_tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // DeleteCommitTag deletes a tag from the repo. func (c *Controller) DeleteCommitTag(ctx context.Context, session *auth.Session, repoRef, tagName string, bypassRules bool, dryRunRules bool, ) (types.DeleteCommitTagOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.DeleteCommitTagOutput{}, nil, err } rules, isRepoOwner, err := c.fetchTagRules(ctx, session, repo) if err != nil { return types.DeleteCommitTagOutput{}, nil, err } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: bypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionDelete, RefType: protection.RefTypeTag, RefNames: []string{tagName}, }) if err != nil { return types.DeleteCommitTagOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if dryRunRules { return types.DeleteCommitTagOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.DeleteCommitTagOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.DeleteCommitTagOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } err = c.git.DeleteTag(ctx, &git.DeleteTagParams{ Name: tagName, WriteParams: writeParams, }) if err != nil { return types.DeleteCommitTagOutput{}, nil, err } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeTag, audit.BypassedResourceName, tagName, audit.BypassAction, audit.BypassActionDeleted, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, tagName, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.CommitTagObject{ TagName: tagName, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for delete tag operation: %s", err) } } return types.DeleteCommitTagOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }}, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/purge.go
app/api/controller/repo/purge.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/bootstrap" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/githook" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // Purge removes a repo permanently. func (c *Controller) Purge( ctx context.Context, session *auth.Session, repoRef string, deletedAt int64, ) error { repo, err := c.repoFinder.FindDeletedByRef(ctx, repoRef, deletedAt) if err != nil { return fmt.Errorf("failed to find the repo (deleted at %d): %w", deletedAt, err) } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo.Core(), enum.PermissionRepoDelete); err != nil { return err } if err = c.repoCheck.LifecycleRestriction(ctx, session, repo.Core()); err != nil { return err } log.Ctx(ctx).Info(). Int64("repo.id", repo.ID). Str("repo.path", repo.Path). Msg("purging repository") if repo.Deleted == nil { return usererror.BadRequest("Repository has to be deleted before it can be purged.") } return c.PurgeNoAuth(ctx, session, repo) } func (c *Controller) PurgeNoAuth( ctx context.Context, session *auth.Session, repo *types.Repository, ) error { if repo.State == enum.RepoStateGitImport { log.Ctx(ctx).Info().Msg("repository is importing. cancelling the import job.") err := c.importer.Cancel(ctx, repo) if err != nil { return fmt.Errorf("failed to cancel repository import") } } err := c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.repoStore.ClearForkID(ctx, repo.ID); err != nil { return fmt.Errorf("failed to clear fork ID of forks: %w", err) } if repo.ForkID != 0 { if err := c.repoStore.UpdateNumForks(ctx, repo.ForkID, -1); err != nil { return fmt.Errorf("failed to decrement number of forks of the upstream repository: %w", err) } } if err := c.repoStore.Purge(ctx, repo.ID, repo.Deleted); err != nil { return fmt.Errorf("failed to delete repo from db: %w", err) } return nil }) if err != nil { return fmt.Errorf("failed to delete repo from db: %w", err) } c.repoFinder.MarkChanged(ctx, repo.Core()) if err := c.DeleteGitRepository(ctx, session, repo.GitUID); err != nil { log.Ctx(ctx).Err(err).Msg("failed to remove git repository") } c.eventReporter.Deleted( ctx, &repoevents.DeletedPayload{ Base: eventBase(repo.Core(), &bootstrap.NewSystemServiceSession().Principal), }, ) return nil } func (c *Controller) DeleteGitRepository( ctx context.Context, session *auth.Session, gitUID string, ) error { // create custom write params for delete as repo might or might not exist in db (similar to create). envVars, err := githook.GenerateEnvironmentVariables( ctx, c.urlProvider.GetInternalAPIURL(ctx), 0, // no repoID session.Principal.ID, true, true, ) if err != nil { return fmt.Errorf("failed to generate git hook environment variables: %w", err) } writeParams := git.WriteParams{ Actor: git.Identity{ Name: session.Principal.DisplayName, Email: session.Principal.Email, }, RepoUID: gitUID, EnvVars: envVars, } err = c.git.DeleteRepository(ctx, &git.DeleteRepositoryParams{ WriteParams: writeParams, }) if err != nil && !errors.IsNotFound(err) { return fmt.Errorf("failed to remove git repository %s: %w", gitUID, err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rule_create.go
app/api/controller/repo/rule_create.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleCreate creates a new protection rule for a repo. func (c *Controller) RuleCreate(ctx context.Context, session *auth.Session, repoRef string, in *rules.CreateInput, ) (*types.Rule, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, err } rule, err := c.rulesSvc.Create( ctx, &session.Principal, enum.RuleParentRepo, repo.ID, repo.Identifier, repo.Path, in, ) if err != nil { return nil, fmt.Errorf("failed to create repo-level protection rule: %w", err) } return rule, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/check.go
app/api/controller/repo/check.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" ) type CheckInput struct { ParentRef string `json:"parent_ref"` Identifier string `json:"identifier"` DefaultBranch string `json:"default_branch"` Description string `json:"description"` IsPublic bool `json:"is_public"` IsFork bool `json:"is_fork,omitempty"` UpstreamPath string `json:"upstream_path,omitempty"` CreateFileOptions } // Check defines the interface for adding extra checks during repository operations. type Check interface { // Create allows adding extra check during create repo operations Create(ctx context.Context, session *auth.Session, in *CheckInput) error LifecycleRestriction(ctx context.Context, session *auth.Session, repo *types.RepositoryCore) error }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/git_info_refs.go
app/api/controller/repo/git_info_refs.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "io" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types/enum" ) // GitInfoRefs executes the info refs part of git's smart http protocol. func (c *Controller) GitInfoRefs( ctx context.Context, session *auth.Session, repoRef string, service enum.GitServiceType, gitProtocol string, w io.Writer, ) error { repo, err := c.getRepoCheckAccessForGit(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return fmt.Errorf("failed to verify repo access: %w", err) } if err = c.git.GetInfoRefs(ctx, w, &git.InfoRefsParams{ ReadParams: git.CreateReadParams(repo), // TODO: git shouldn't take a random string here, but instead have accepted enum values. Service: string(service), Options: nil, GitProtocol: gitProtocol, }); err != nil { return fmt.Errorf("failed GetInfoRefs on git: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/default_branch.go
app/api/controller/repo/default_branch.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/audit" "github.com/harness/gitness/contextutil" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type UpdateDefaultBranchInput struct { Name string `json:"name"` } // TODO: handle the racing condition between update/delete default branch requests for a repo. func (c *Controller) UpdateDefaultBranch( ctx context.Context, session *auth.Session, repoRef string, in *UpdateDefaultBranchInput, ) (*RepositoryOutput, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, err } // the max time we give an update default branch to succeed const timeout = 2 * time.Minute // lock concurrent requests for updating the default branch of a repo // requests will wait for previous ones to compelete before proceed unlock, err := c.locker.LockDefaultBranch( ctx, repo.ID, 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 ) if err != nil { return nil, err } defer unlock() writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return nil, fmt.Errorf("failed to create RPC write params: %w", err) } // create new, time-restricted context to guarantee update completion, even if request is canceled. // TODO: a proper error handling solution required. ctx, cancel := contextutil.WithNewTimeout(ctx, timeout) defer cancel() repoFull, err := c.repoStore.Find(ctx, repo.ID) if err != nil { return nil, fmt.Errorf("failed to find repo by ID: %w", err) } err = c.git.UpdateDefaultBranch(ctx, &git.UpdateDefaultBranchParams{ WriteParams: writeParams, BranchName: in.Name, }) if err != nil { return nil, fmt.Errorf("failed to update the repo default branch: %w", err) } var oldName string var repoClone types.Repository repoFull, err = c.repoStore.UpdateOptLock(ctx, repoFull, func(r *types.Repository) error { repoClone = *repoFull oldName = repoFull.DefaultBranch r.DefaultBranch = in.Name return nil }) if err != nil { return nil, fmt.Errorf("failed to update the repo default branch on db:%w", err) } c.repoFinder.MarkChanged(ctx, repo) repoOutput, err := GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repoFull) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier), audit.ActionUpdated, paths.Parent(repo.Path), audit.WithOldObject(audit.RepositoryObject{ Repository: repoClone, IsPublic: repoOutput.IsPublic, }), audit.WithNewObject(audit.RepositoryObject{ Repository: *repoFull, IsPublic: repoOutput.IsPublic, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update default branch operation: %s", err) } c.eventReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{ Base: eventBase(repo, &session.Principal), OldName: oldName, NewName: repoFull.DefaultBranch, }) return repoOutput, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/find.go
app/api/controller/repo/find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // Find finds a repo. func (c *Controller) Find(ctx context.Context, session *auth.Session, repoRef string) (*RepositoryOutput, error) { // note: can't use c.getRepoCheckAccess because even repositories that are currently being imported can be fetched. repoCore, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoView); err != nil { return nil, err } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to fetch repo by ID: %w", err) } // backfill clone url repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) repoOut, err := GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output for repo %q: %w", repo.Path, err) } favoritesMap, err := c.favoriteStore.Map(ctx, session.Principal.ID, enum.ResourceTypeRepo, []int64{repo.ID}) if err != nil { return nil, fmt.Errorf("failed to check if repo %q is marked as favorite: %w", repo.Path, err) } repoOut.IsFavorite = favoritesMap[repo.ID] return repoOut, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/linked_sync.go
app/api/controller/repo/linked_sync.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "slices" "strings" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/hook" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type LinkedSyncInput struct { Branches []string `json:"branches"` } func (in *LinkedSyncInput) sanitize() error { if len(in.Branches) == 0 { return errors.InvalidArgument("Branches cannot be empty.") } for i := range in.Branches { in.Branches[i] = strings.TrimSpace(in.Branches[i]) if in.Branches[i] == "" { return errors.InvalidArgument("Branch name cannot be empty.") } if strings.ContainsAny(in.Branches[i], " :*\t\n\r") { return errors.InvalidArgumentf("Invalid branch name %q.", in.Branches[i]) } } slices.Sort(in.Branches) in.Branches = slices.Compact(in.Branches) return nil } type LinkedSyncOutput struct { Refs []hook.ReferenceUpdate `json:"branches"` } func (c *Controller) LinkedSync( ctx context.Context, session *auth.Session, repoRef string, in *LinkedSyncInput, ) (*LinkedSyncOutput, error) { if err := in.sanitize(); err != nil { return nil, err } repo, err := c.getRepoCheckAccessWithLinked(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, err } if repo.Type != enum.RepoTypeLinked { return nil, errors.InvalidArgument("Repository is not a linked repository.") } refs := make([]string, len(in.Branches)) for i := range in.Branches { refs[i] = api.BranchPrefix + in.Branches[i] } linkedRepo, err := c.linkedRepoStore.Find(ctx, repo.ID) if err != nil { return nil, fmt.Errorf("failed to find linked repository: %w", err) } connector := importer.ConnectorDef{ Path: linkedRepo.ConnectorPath, Identifier: linkedRepo.ConnectorIdentifier, } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return nil, fmt.Errorf("failed to create rpc internal write params: %w", err) } accessInfo, err := c.connectorService.GetAccessInfo(ctx, connector) if err != nil { return nil, fmt.Errorf("failed to get access info: %w", err) } cloneURLWithAuth, err := accessInfo.URLWithCredentials() if err != nil { return nil, errors.InvalidArgument("Failed to get access to repository.") } result, err := c.git.SyncRefs(ctx, &git.SyncRefsParams{ WriteParams: writeParams, Source: cloneURLWithAuth, Refs: refs, }) if err != nil { return nil, fmt.Errorf("failed to synchronize branches: %w", err) } defaultRef := api.BranchPrefix + repo.DefaultBranch updatedDefault := slices.ContainsFunc(result.Refs, func(u hook.ReferenceUpdate) bool { return defaultRef == u.Ref }) if updatedDefault { repoFull, err := c.repoStore.Find(ctx, repo.ID) if err != nil { return nil, fmt.Errorf("failed to find repository: %w", err) } err = c.indexer.Index(ctx, repoFull) if err != nil { log.Ctx(ctx).Warn().Err(err).Msg("failed to index repository") } } return &LinkedSyncOutput{Refs: result.Refs}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_find.go
app/api/controller/repo/label_find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindLabel finds a label for the specified repository. func (c *Controller) FindLabel( ctx context.Context, session *auth.Session, repoRef string, key string, includeValues bool, ) (*types.LabelWithValues, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } var labelWithValues *types.LabelWithValues if includeValues { labelWithValues, err = c.labelSvc.FindWithValues(ctx, nil, &repo.ID, key) if err != nil { return nil, fmt.Errorf("failed to find repo label with values: %w", err) } } else { label, err := c.labelSvc.Find(ctx, nil, &repo.ID, key) if err != nil { return nil, fmt.Errorf("failed to find repo label: %w", err) } labelWithValues = &types.LabelWithValues{ Label: *label, } } return labelWithValues, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_commits.go
app/api/controller/repo/list_commits.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "regexp" "strings" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "golang.org/x/exp/maps" ) // ListCommits lists the commits of a repo. func (c *Controller) ListCommits(ctx context.Context, session *auth.Session, repoRef string, gitRef string, filter *types.CommitFilter, ) (types.ListCommitResponse, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return types.ListCommitResponse{}, err } // set gitRef to default branch in case an empty reference was provided if gitRef == "" { gitRef = repo.DefaultBranch } committerRegex, err := c.contributorsRegex(ctx, filter.Committer, filter.CommitterIDs) if err != nil { return types.ListCommitResponse{}, fmt.Errorf("failed create committer regex: %w", err) } authorRegex, err := c.contributorsRegex(ctx, filter.Author, filter.AuthorIDs) if err != nil { return types.ListCommitResponse{}, fmt.Errorf("failed create author regex: %w", err) } dotRange, err := makeDotRange(filter.After, gitRef, true) if err != nil { return types.ListCommitResponse{}, fmt.Errorf("failed to parse dot range: %w", err) } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dotRange) if err != nil { return types.ListCommitResponse{}, fmt.Errorf("failed to parse dot range: %w", err) } result, err := c.git.ListCommits(ctx, &git.ListCommitsParams{ ReadParams: git.CreateReadParams(repo), GitREF: dotRange.HeadRef, After: dotRange.BaseRef, Page: int32(filter.Page), //nolint:gosec Limit: int32(filter.Limit), //nolint:gosec Path: filter.Path, Since: filter.Since, Until: filter.Until, Committer: committerRegex, Author: authorRegex, IncludeStats: filter.IncludeStats, Regex: true, }) if err != nil { return types.ListCommitResponse{}, err } commits := make([]*types.Commit, len(result.Commits)) for i := range result.Commits { commits[i] = controller.MapCommit(&result.Commits[i]) } err = c.signatureVerifyService.VerifyCommits(ctx, repo.ID, commits) if err != nil { return types.ListCommitResponse{}, fmt.Errorf("failed to verify signature of commits: %w", err) } renameDetailList := make([]types.RenameDetails, len(result.RenameDetails)) for i := range result.RenameDetails { renameDetails := controller.MapRenameDetails(result.RenameDetails[i]) if renameDetails == nil { return types.ListCommitResponse{}, fmt.Errorf("rename details was nil") } renameDetailList[i] = *renameDetails } return types.ListCommitResponse{ Commits: commits, RenameDetails: renameDetailList, TotalCommits: result.TotalCommits, }, nil } func (c *Controller) contributorsRegex( ctx context.Context, identifier string, ids []int64, ) (string, error) { if identifier == "" && len(ids) == 0 { return "", nil } var emailRegex string if len(ids) > 0 { principals, err := c.principalInfoCache.Map(ctx, ids) if err != nil { return "", err } if len(principals) > 0 { parts := make([]string, len(principals)) for i, principal := range maps.Values(principals) { parts[i] = regexp.QuoteMeta(principal.Email) } emailRegex = "\\<(" + strings.Join(parts, "|") + ")\\>" } } var regex string switch { case identifier != "" && emailRegex != "": regex = regexp.QuoteMeta(identifier) + "|" + emailRegex case identifier != "": regex = regexp.QuoteMeta(identifier) case emailRegex != "": regex = emailRegex } return regex, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/content_get.go
app/api/controller/repo/content_get.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "encoding/base64" "fmt" "io" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( // maxGetContentFileSize specifies the maximum number of bytes a file content response contains. // If a file is any larger, the content is truncated. maxGetContentFileSize = 10 * 1024 * 1024 // 10 MB ) type ContentType string const ( ContentTypeFile ContentType = "file" ContentTypeDir ContentType = "dir" ContentTypeSymlink ContentType = "symlink" ContentTypeSubmodule ContentType = "submodule" ) type ContentInfo struct { Type ContentType `json:"type"` SHA string `json:"sha"` Name string `json:"name"` Path string `json:"path"` LatestCommit *types.Commit `json:"latest_commit,omitempty"` } type GetContentOutput struct { ContentInfo Content Content `json:"content"` } // Content restricts the possible types of content returned by the api. type Content interface { isContent() } type FileContent struct { Encoding enum.ContentEncodingType `json:"encoding"` Data string `json:"data"` Size int64 `json:"size"` DataSize int64 `json:"data_size"` LFSObjectID string `json:"lfs_object_id,omitempty"` LFSObjectSize int64 `json:"lfs_object_size,omitempty"` } func (c *FileContent) isContent() {} type SymlinkContent struct { Target string `json:"target"` Size int64 `json:"size"` } func (c *SymlinkContent) isContent() {} type DirContent struct { Entries []ContentInfo `json:"entries"` } func (c *DirContent) isContent() {} type SubmoduleContent struct { URL string `json:"url"` CommitSHA string `json:"commit_sha"` } func (c *SubmoduleContent) isContent() {} // GetContent finds the content of the repo at the given path. // If no gitRef is provided, the content is retrieved from the default branch. func (c *Controller) GetContent(ctx context.Context, session *auth.Session, repoRef string, gitRef string, repoPath string, includeLatestCommit bool, flattenDirectories bool, ) (*GetContentOutput, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } // set gitRef to default branch in case an empty reference was provided if gitRef == "" { gitRef = repo.DefaultBranch } // create read params once readParams := git.CreateReadParams(repo) treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: readParams, GitREF: gitRef, Path: repoPath, IncludeLatestCommit: includeLatestCommit, }) if err != nil { return nil, fmt.Errorf("failed to read tree node: %w", err) } info, err := mapToContentInfo(treeNodeOutput.Node, treeNodeOutput.Commit, includeLatestCommit) if err != nil { return nil, err } var content Content switch info.Type { case ContentTypeDir: content, err = c.getDirContent(ctx, readParams, gitRef, repoPath, flattenDirectories) case ContentTypeFile: content, err = c.getFileContent(ctx, readParams, info.SHA) case ContentTypeSymlink: content, err = c.getSymlinkContent(ctx, readParams, info.SHA) case ContentTypeSubmodule: content, err = c.getSubmoduleContent(ctx, readParams, gitRef, repoPath, info.SHA) default: err = fmt.Errorf("unknown tree node type '%s'", treeNodeOutput.Node.Type) } if err != nil { return nil, err } if info.LatestCommit != nil { err = c.signatureVerifyService.VerifyCommits(ctx, repo.ID, []*types.Commit{info.LatestCommit}) if err != nil { return nil, fmt.Errorf("failed to verify signature of the last commit SHA=%s: %w", info.LatestCommit.SHA.String(), err) } } return &GetContentOutput{ ContentInfo: info, Content: content, }, nil } func (c *Controller) getSubmoduleContent(ctx context.Context, readParams git.ReadParams, gitRef string, repoPath string, commitSHA string, ) (*SubmoduleContent, error) { output, err := c.git.GetSubmodule(ctx, &git.GetSubmoduleParams{ ReadParams: readParams, GitREF: gitRef, Path: repoPath, }) if err != nil { // TODO: handle not found error return nil, fmt.Errorf("failed to get submodule: %w", err) } return &SubmoduleContent{ URL: output.Submodule.URL, CommitSHA: commitSHA, }, nil } func (c *Controller) getFileContent(ctx context.Context, readParams git.ReadParams, blobSHA string, ) (*FileContent, error) { output, err := c.git.GetBlob(ctx, &git.GetBlobParams{ ReadParams: readParams, SHA: blobSHA, SizeLimit: maxGetContentFileSize, }) if err != nil { return nil, fmt.Errorf("failed to get file content: %w", err) } defer func() { if err := output.Content.Close(); err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader.") } }() content, err := io.ReadAll(output.Content) if err != nil { return nil, fmt.Errorf("failed to read blob content: %w", err) } // check if blob is an LFS pointer lfsInfo, ok := parser.IsLFSPointer(ctx, content, output.Size) if ok { return &FileContent{ Size: output.Size, DataSize: output.ContentSize, Encoding: enum.ContentEncodingTypeBase64, Data: base64.StdEncoding.EncodeToString(content), LFSObjectID: lfsInfo.OID, LFSObjectSize: lfsInfo.Size, }, nil } return &FileContent{ Size: output.Size, DataSize: output.ContentSize, Encoding: enum.ContentEncodingTypeBase64, Data: base64.StdEncoding.EncodeToString(content), }, nil } func (c *Controller) getSymlinkContent(ctx context.Context, readParams git.ReadParams, blobSHA string, ) (*SymlinkContent, error) { output, err := c.git.GetBlob(ctx, &git.GetBlobParams{ ReadParams: readParams, SHA: blobSHA, SizeLimit: maxGetContentFileSize, // TODO: do we need to guard against too big symlinks? }) if err != nil { // TODO: handle not found error return nil, fmt.Errorf("failed to get symlink: %w", err) } defer func() { if err := output.Content.Close(); err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader.") } }() content, err := io.ReadAll(output.Content) if err != nil { return nil, fmt.Errorf("failed to read blob content: %w", err) } return &SymlinkContent{ Size: output.Size, Target: string(content), }, nil } func (c *Controller) getDirContent(ctx context.Context, readParams git.ReadParams, gitRef string, repoPath string, flattenDirectories bool, ) (*DirContent, error) { output, err := c.git.ListTreeNodes(ctx, &git.ListTreeNodeParams{ ReadParams: readParams, GitREF: gitRef, Path: repoPath, FlattenDirectories: flattenDirectories, }) if err != nil { // TODO: handle not found error return nil, fmt.Errorf("failed to get content of dir: %w", err) } entries := make([]ContentInfo, len(output.Nodes)) for i, node := range output.Nodes { entries[i], err = mapToContentInfo(node, nil, false) if err != nil { return nil, err } } return &DirContent{ Entries: entries, }, nil } func mapToContentInfo(node git.TreeNode, commit *git.Commit, includeLatestCommit bool) (ContentInfo, error) { typ, err := mapNodeModeToContentType(node.Mode) if err != nil { return ContentInfo{}, err } res := ContentInfo{ Type: typ, SHA: node.SHA, Name: node.Name, Path: node.Path, } // parse commit only if available if commit != nil && includeLatestCommit { res.LatestCommit = controller.MapCommit(commit) } return res, nil } func mapNodeModeToContentType(m git.TreeNodeMode) (ContentType, error) { switch m { case git.TreeNodeModeFile, git.TreeNodeModeExec: return ContentTypeFile, nil case git.TreeNodeModeSymlink: return ContentTypeSymlink, nil case git.TreeNodeModeCommit: return ContentTypeSubmodule, nil case git.TreeNodeModeTree: return ContentTypeDir, nil default: return ContentTypeFile, errors.Internalf(nil, "unsupported tree node mode '%s'", m) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/fork_sync.go
app/api/controller/repo/fork_sync.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type ForkSyncInput struct { Branch string `json:"branch"` BranchCommitSHA sha.SHA `json:"branch_commit_sha"` BranchUpstream string `json:"branch_upstream"` // Can be omitted, defaults to the value of Branch } func (in *ForkSyncInput) sanitize() error { in.Branch = strings.TrimSpace(in.Branch) in.BranchUpstream = strings.TrimSpace(in.BranchUpstream) if in.Branch == "" { return errors.InvalidArgument("Branch name must be provided") } if in.BranchCommitSHA.IsEmpty() { return errors.InvalidArgument("Branch commit SHA must be provided") } return nil } //nolint:gocognit func (c *Controller) ForkSync( ctx context.Context, session *auth.Session, repoRef string, in *ForkSyncInput, ) (*types.ForkSyncOutput, error) { repoForkCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, err } if err := in.sanitize(); err != nil { return nil, err } branchUpstreamName := in.BranchUpstream if branchUpstreamName == "" { branchUpstreamName = in.Branch } branchForkInfo, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: git.CreateReadParams(repoForkCore), Name: in.Branch, Type: gitenum.RefTypeBranch, }) if err != nil { return nil, fmt.Errorf("failed to get repo branch: %w", err) } if !branchForkInfo.SHA.Equal(in.BranchCommitSHA) { return nil, errors.InvalidArgumentf("The commit %s isn't the latest commit on the branch %s", in.BranchCommitSHA, in.Branch) } branchUpstreamSHA, repoUpstreamCore, err := c.fetchUpstreamBranch( ctx, session, repoForkCore, branchUpstreamName, ) if err != nil { return nil, fmt.Errorf("failed to fetch upstream branch: %w", err) } ancestorResult, err := c.git.IsAncestor(ctx, git.IsAncestorParams{ ReadParams: git.CreateReadParams(repoForkCore), AncestorCommitSHA: branchUpstreamSHA, DescendantCommitSHA: branchForkInfo.SHA, }) if err != nil { return nil, fmt.Errorf("failed to check if the upstream commit is ancestor: %w", err) } if ancestorResult.Ancestor { // The branch already contains the latest commit from the upstream repository branch - nothing to do. return &types.ForkSyncOutput{ AlreadyAncestor: true, }, nil } mergeBase, err := c.git.MergeBase(ctx, git.MergeBaseParams{ ReadParams: git.CreateReadParams(repoForkCore), Ref1: branchUpstreamSHA.String(), Ref2: branchForkInfo.SHA.String(), }) if err != nil { return nil, fmt.Errorf("failed to find merge base: %w", err) } var ( message string author *git.Identity committer *git.Identity ) mergeMethod := gitenum.MergeMethodFastForward if !branchForkInfo.SHA.Equal(mergeBase.MergeBaseSHA) { mergeMethod = gitenum.MergeMethodMerge message = fmt.Sprintf("Merge upstream branch '%s' of %s", branchUpstreamName, repoUpstreamCore.Path) committer = controller.SystemServicePrincipalInfo() author = controller.IdentityFromPrincipalInfo(*session.Principal.ToPrincipalInfo()) } var refs []git.RefUpdate headBranchRef, err := git.GetRefPath(in.Branch, gitenum.RefTypeBranch) if err != nil { return nil, fmt.Errorf("failed to generate ref name: %w", err) } refs = append(refs, git.RefUpdate{ Name: headBranchRef, Old: branchForkInfo.SHA, New: sha.SHA{}, // update to the result of the merge }) now := time.Now() writeParams, err := controller.CreateRPCSystemReferencesWriteParams(ctx, c.urlProvider, session, repoForkCore) if err != nil { return nil, fmt.Errorf("failed to create RPC write params: %w", err) } mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{ WriteParams: writeParams, //HeadRepoUID: repoUpstreamCore.GitUID, // TODO: Remove HeadRepoUID! BaseSHA: branchForkInfo.SHA, HeadSHA: branchUpstreamSHA, Message: message, Committer: committer, CommitterDate: &now, Author: author, AuthorDate: &now, Refs: refs, Method: mergeMethod, }) if err != nil { return nil, fmt.Errorf("fork branch sync merge failed: %w", err) } if mergeOutput.MergeSHA.IsEmpty() || len(mergeOutput.ConflictFiles) > 0 { return &types.ForkSyncOutput{ ConflictFiles: mergeOutput.ConflictFiles, Message: fmt.Sprintf("Branch synchronization blocked by conflicting files: %v", mergeOutput.ConflictFiles), }, nil } return &types.ForkSyncOutput{ NewCommitSHA: mergeOutput.MergeSHA, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rebase.go
app/api/controller/repo/rebase.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type RebaseInput struct { BaseBranch string `json:"base_branch"` BaseCommitSHA sha.SHA `json:"base_commit_sha"` HeadBranch string `json:"head_branch"` HeadCommitSHA sha.SHA `json:"head_commit_sha"` DryRun bool `json:"dry_run"` DryRunRules bool `json:"dry_run_rules"` BypassRules bool `json:"bypass_rules"` } func (in *RebaseInput) validate() error { if in.BaseBranch == "" && in.BaseCommitSHA.IsEmpty() { return usererror.BadRequest("Either base branch or base commit SHA name must be provided") } if in.HeadBranch == "" { return usererror.BadRequest("Head branch name must be provided") } if in.HeadCommitSHA.IsEmpty() { return usererror.BadRequest("Head branch commit SHA must be provided") } return nil } // Rebase rebases a branch against (the latest commit from) a different branch. func (c *Controller) Rebase( ctx context.Context, session *auth.Session, repoRef string, in *RebaseInput, ) (*types.RebaseResponse, *types.MergeViolations, error) { if err := in.validate(); err != nil { return nil, nil, err } repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return nil, nil, fmt.Errorf("failed to acquire access to repo: %w", err) } protectionRules, isRepoOwner, err := c.fetchBranchRules(ctx, session, repo) if err != nil { return nil, nil, fmt.Errorf("failed to fetch rules: %w", err) } violations, err := protectionRules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: in.BypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionUpdateForce, RefType: protection.RefTypeBranch, RefNames: []string{in.HeadBranch}, }) if err != nil { return nil, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if in.DryRunRules { // DryRunRules is true: Just return rule violations and don't attempt to rebase. return &types.RebaseResponse{ RuleViolations: violations, DryRunRules: true, }, nil, nil } if protection.IsCritical(violations) { return nil, &types.MergeViolations{ RuleViolations: violations, Message: protection.GenerateErrorMessageForBlockingViolations(violations), }, nil } readParams := git.CreateReadParams(repo) headBranch, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: in.HeadBranch, }) if err != nil { return nil, nil, fmt.Errorf("failed to get head branch: %w", err) } if !headBranch.Branch.SHA.Equal(in.HeadCommitSHA) { return nil, nil, usererror.BadRequestf("The commit %s isn't the latest commit on the branch %s", in.HeadCommitSHA, headBranch.Branch.Name) } baseCommitSHA := in.BaseCommitSHA if baseCommitSHA.IsEmpty() { baseBranch, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: in.BaseBranch, }) if err != nil { return nil, nil, fmt.Errorf("failed to get base branch: %w", err) } baseCommitSHA = baseBranch.Branch.SHA } isAncestor, err := c.git.IsAncestor(ctx, git.IsAncestorParams{ ReadParams: readParams, AncestorCommitSHA: baseCommitSHA, DescendantCommitSHA: headBranch.Branch.SHA, }) if err != nil { return nil, nil, fmt.Errorf("failed check ancestor: %w", err) } if isAncestor.Ancestor { // The head branch already contains the latest commit from the base branch - nothing to do. return &types.RebaseResponse{ AlreadyAncestor: true, RuleViolations: violations, }, nil, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err) } var refs []git.RefUpdate if !in.DryRun { headBranchRef, err := git.GetRefPath(in.HeadBranch, gitenum.RefTypeBranch) if err != nil { return nil, nil, fmt.Errorf("failed to gerenere ref name: %w", err) } refs = append(refs, git.RefUpdate{ Name: headBranchRef, Old: headBranch.Branch.SHA, New: sha.SHA{}, // update to the result of the merge }) } mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{ WriteParams: writeParams, BaseSHA: baseCommitSHA, HeadBranch: in.HeadBranch, Refs: refs, HeadBranchExpectedSHA: in.HeadCommitSHA, Method: gitenum.MergeMethodRebase, }) if err != nil { return nil, nil, fmt.Errorf("rebase execution failed: %w", err) } if in.DryRun { // DryRun is true: Just return rule violations and list of conflicted files. // No reference is updated, so don't return the resulting commit SHA. return &types.RebaseResponse{ RuleViolations: violations, DryRun: true, ConflictFiles: mergeOutput.ConflictFiles, }, nil, nil } if mergeOutput.MergeSHA.IsEmpty() || len(mergeOutput.ConflictFiles) > 0 { return nil, &types.MergeViolations{ ConflictFiles: mergeOutput.ConflictFiles, RuleViolations: violations, Message: fmt.Sprintf("Rebase blocked by conflicting files: %v", mergeOutput.ConflictFiles), }, nil } return &types.RebaseResponse{ NewHeadBranchSHA: mergeOutput.MergeSHA, RuleViolations: violations, }, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rule_list.go
app/api/controller/repo/rule_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleList returns protection rules for a repository. func (c *Controller) RuleList(ctx context.Context, session *auth.Session, repoRef string, inherited bool, filter *types.RuleFilter, ) ([]types.Rule, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, err } list, count, err := c.rulesSvc.List(ctx, repo.ID, enum.RuleParentRepo, inherited, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list repo-level protection rules: %w", err) } return list, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_list.go
app/api/controller/repo/label_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListLabels lists all labels defined for the specified repository. func (c *Controller) ListLabels( ctx context.Context, session *auth.Session, repoRef string, filter *types.LabelFilter, ) ([]*types.Label, int64, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to repo: %w", err) } labels, total, err := c.labelSvc.List(ctx, &repo.ParentID, &repo.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list repo labels: %w", err) } return labels, total, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_delete.go
app/api/controller/repo/label_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // DeleteLabel deletes a label for the specified repository. func (c *Controller) DeleteLabel( ctx context.Context, session *auth.Session, repoRef string, key string, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return fmt.Errorf("failed to acquire access to repo: %w", err) } if err := c.labelSvc.Delete(ctx, nil, &repo.ID, key); err != nil { return fmt.Errorf("failed to delete repo label: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_save.go
app/api/controller/repo/label_save.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // SaveLabel creates or updates a label and possibly label values for the specified repository. func (c *Controller) SaveLabel( ctx context.Context, session *auth.Session, repoRef string, in *types.SaveInput, ) (*types.LabelWithValues, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } labelWithValues, err := c.labelSvc.Save( ctx, session.Principal.ID, nil, &repo.ID, in) if err != nil { return nil, fmt.Errorf("failed to save label: %w", err) } return labelWithValues, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/diff.go
app/api/controller/repo/diff.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "io" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" gittypes "github.com/harness/gitness/git/api" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) RawDiff( ctx context.Context, w io.Writer, session *auth.Session, repoRef string, path string, ignoreWhitespace bool, files ...gittypes.FileDiffRequest, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return err } dotRange, err := parseDotRangePath(path) if err != nil { return err } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dotRange) if err != nil { return fmt.Errorf("failed to fetch diff upstream ref: %w", err) } return c.git.RawDiff(ctx, w, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: dotRange.BaseRef, HeadRef: dotRange.HeadRef, MergeBase: dotRange.MergeBase, IgnoreWhitespace: ignoreWhitespace, }, files...) } func (c *Controller) CommitDiff( ctx context.Context, session *auth.Session, repoRef string, rev string, ignoreWhitespace bool, w io.Writer, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return err } return c.git.CommitDiff(ctx, &git.GetCommitParams{ ReadParams: git.CreateReadParams(repo), Revision: rev, IgnoreWhitespace: ignoreWhitespace, }, w) } func (c *Controller) DiffStats( ctx context.Context, session *auth.Session, repoRef string, path string, ignoreWhitespace bool, ) (types.DiffStats, error) { repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return types.DiffStats{}, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView); err != nil { return types.DiffStats{}, err } dotRange, err := parseDotRangePath(path) if err != nil { return types.DiffStats{}, err } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dotRange) if err != nil { return types.DiffStats{}, fmt.Errorf("failed to fetch diff upstream ref: %w", err) } output, err := c.git.DiffStats(ctx, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: dotRange.BaseRef, HeadRef: dotRange.HeadRef, MergeBase: dotRange.MergeBase, IgnoreWhitespace: ignoreWhitespace, }) if err != nil { return types.DiffStats{}, err } return types.NewDiffStats(output.Commits, output.FilesChanged, output.Additions, output.Deletions), nil } func (c *Controller) Diff( ctx context.Context, session *auth.Session, repoRef string, path string, includePatch bool, ignoreWhitespace bool, files ...gittypes.FileDiffRequest, ) (types.Stream[*git.FileDiff], error) { repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView); err != nil { return nil, err } dotRange, err := parseDotRangePath(path) if err != nil { return nil, err } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dotRange) if err != nil { return nil, fmt.Errorf("failed to fetch diff upstream ref: %w", err) } reader := git.NewStreamReader(c.git.Diff(ctx, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: dotRange.BaseRef, HeadRef: dotRange.HeadRef, MergeBase: dotRange.MergeBase, IncludePatch: includePatch, IgnoreWhitespace: ignoreWhitespace, }, files...)) return reader, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rule_delete.go
app/api/controller/repo/rule_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // RuleDelete deletes a protection rule by identifier. func (c *Controller) RuleDelete(ctx context.Context, session *auth.Session, repoRef string, identifier string, ) error { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return err } err = c.rulesSvc.Delete( ctx, &session.Principal, enum.RuleParentRepo, repo.ID, repo.Identifier, repo.Path, identifier, ) if err != nil { return fmt.Errorf("failed to delete repo-level protection rule: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/no_op_checks.go
app/api/controller/repo/no_op_checks.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" ) var _ Check = (*NoOpRepoChecks)(nil) type NoOpRepoChecks struct { } func NewNoOpRepoChecks() *NoOpRepoChecks { return &NoOpRepoChecks{} } func (c *NoOpRepoChecks) Create(context.Context, *auth.Session, *CheckInput) error { return nil } func (c *NoOpRepoChecks) LifecycleRestriction(context.Context, *auth.Session, *types.RepositoryCore) error { return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/get_commit_divergences.go
app/api/controller/repo/get_commit_divergences.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type GetCommitDivergencesInput struct { // MaxCount restricts the maximum number of diverging commits that are counted. // IMPORTANT: This restricts the total commit count, so a (5, 18) restricted to 10 will return (0, 10) MaxCount int32 `json:"max_count"` Requests []CommitDivergenceRequest `json:"requests"` } // CommitDivergenceRequest contains the refs for which the converging commits should be counted. type CommitDivergenceRequest struct { // From is the ref from which the counting of the diverging commits starts. From string `json:"from"` // To is the ref at which the counting of the diverging commits ends. // If the value is empty the divergence is calculated to the default branch of the repo. To string `json:"to"` } // GetCommitDivergences returns the commit divergences between reference pairs. func (c *Controller) GetCommitDivergences(ctx context.Context, session *auth.Session, repoRef string, in *GetCommitDivergencesInput, ) ([]types.CommitDivergence, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } // if no requests were provided return an empty list if in == nil || len(in.Requests) == 0 { return []types.CommitDivergence{}, nil } // if num of requests > page max return error if len(in.Requests) > request.PerPageMax { return nil, usererror.ErrRequestTooLarge } // map to rpc params options := &git.GetCommitDivergencesParams{ ReadParams: git.CreateReadParams(repo), MaxCount: in.MaxCount, Requests: make([]git.CommitDivergenceRequest, len(in.Requests)), } for i := range in.Requests { options.Requests[i].From = in.Requests[i].From options.Requests[i].To = in.Requests[i].To // backfil default branch if no 'to' was provided if len(options.Requests[i].To) == 0 { options.Requests[i].To = repo.DefaultBranch } err = c.fetchCommitDivergenceObjectsFromUpstream(ctx, session, repo, &options.Requests[i]) if err != nil { return nil, fmt.Errorf("failed to fetch object from upstream: %w", err) } } // TODO: We should cache the responses as times can reach multiple seconds rpcOutput, err := c.git.GetCommitDivergences(ctx, options) if err != nil { return nil, err } // map to output type divergences := make([]types.CommitDivergence, len(rpcOutput.Divergences)) for i := range rpcOutput.Divergences { divergences[i] = types.CommitDivergence(rpcOutput.Divergences[i]) } return divergences, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/delete_branch.go
app/api/controller/repo/delete_branch.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // DeleteBranch deletes a repo branch. func (c *Controller) DeleteBranch(ctx context.Context, session *auth.Session, repoRef string, branchName string, bypassRules, dryRunRules bool, ) (types.DeleteBranchOutput, []types.RuleViolations, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush) if err != nil { return types.DeleteBranchOutput{}, nil, err } // make sure user isn't deleting the default branch // ASSUMPTION: lower layer calls explicit branch api // and 'refs/heads/branch1' would fail if 'branch1' exists. // TODO: Add functional test to ensure the scenario is covered! if branchName == repo.DefaultBranch { return types.DeleteBranchOutput{}, nil, usererror.ErrDefaultBranchCantBeDeleted } rules, isRepoOwner, err := c.fetchBranchRules(ctx, session, repo) if err != nil { return types.DeleteBranchOutput{}, nil, err } violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{ ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs, Actor: &session.Principal, AllowBypass: bypassRules, IsRepoOwner: isRepoOwner, Repo: repo, RefAction: protection.RefActionDelete, RefType: protection.RefTypeBranch, RefNames: []string{branchName}, }) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to verify protection rules: %w", err) } if dryRunRules { return types.DeleteBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ DryRunRules: true, RuleViolations: violations, }, }, nil, nil } if protection.IsCritical(violations) { return types.DeleteBranchOutput{}, violations, nil } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return types.DeleteBranchOutput{}, nil, fmt.Errorf("failed to create RPC write params: %w", err) } err = c.git.DeleteBranch(ctx, &git.DeleteBranchParams{ WriteParams: writeParams, BranchName: branchName, }) if err != nil { return types.DeleteBranchOutput{}, nil, err } if protection.IsBypassed(violations) { err = c.auditService.Log(ctx, session.Principal, audit.NewResource( audit.ResourceTypeRepository, repo.Identifier, audit.RepoPath, repo.Path, audit.BypassedResourceType, audit.BypassedResourceTypeBranch, audit.BypassedResourceName, branchName, audit.BypassAction, audit.BypassActionDeleted, audit.ResourceName, fmt.Sprintf( audit.BypassSHALabelFormat, repo.Identifier, branchName, ), ), audit.ActionBypassed, paths.Parent(repo.Path), audit.WithNewObject(audit.BranchObject{ BranchName: branchName, RepoPath: repo.Path, RuleViolations: violations, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for delete branch operation: %s", err) } } return types.DeleteBranchOutput{ DryRunRulesOutput: types.DryRunRulesOutput{ RuleViolations: violations, }}, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/controller.go
app/api/controller/repo/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "encoding/json" "fmt" "strconv" "strings" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/keywordsearch" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/publickey" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" gitenum "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/lock" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) var errPublicRepoCreationDisabled = usererror.BadRequest("Public repository creation is disabled.") type RepositoryOutput struct { types.Repository IsPublic bool `json:"is_public" yaml:"is_public"` Importing bool `json:"importing" yaml:"-"` Archived bool `json:"archived" yaml:"-"` IsFavorite bool `json:"is_favorite" yaml:"is_favorite"` Upstream *types.RepositoryCore `json:"upstream,omitempty" yaml:"-,omitempty"` } // TODO [CODE-1363]: remove after identifier migration. func (r RepositoryOutput) MarshalJSON() ([]byte, error) { // alias allows us to embed the original object while avoiding an infinite loop of marshaling. type alias RepositoryOutput return json.Marshal(&struct { alias UID string `json:"uid"` }{ alias: (alias)(r), UID: r.Identifier, }) } type Controller struct { defaultBranch string tx dbtx.Transactor urlProvider url.Provider authorizer authz.Authorizer repoStore store.RepoStore linkedRepoStore store.LinkedRepoStore spaceStore store.SpaceStore pipelineStore store.PipelineStore executionStore store.ExecutionStore principalStore store.PrincipalStore ruleStore store.RuleStore checkStore store.CheckStore pullReqStore store.PullReqStore settings *settings.Service principalInfoCache store.PrincipalInfoCache userGroupStore store.UserGroupStore userGroupService usergroup.Service protectionManager *protection.Manager git git.Interface spaceFinder refcache.SpaceFinder repoFinder refcache.RepoFinder importer *importer.JobRepository referenceSync *importer.JobReferenceSync importLinked *importer.JobRepositoryLink codeOwners *codeowners.Service eventReporter *repoevents.Reporter indexer keywordsearch.Indexer resourceLimiter limiter.ResourceLimiter locker *locker.Locker auditService audit.Service mtxManager lock.MutexManager identifierCheck check.RepoIdentifier repoCheck Check publicAccess publicaccess.Service labelSvc *label.Service instrumentation instrument.Service rulesSvc *rules.Service sseStreamer sse.Streamer lfsCtrl *lfs.Controller favoriteStore store.FavoriteStore signatureVerifyService publickey.SignatureVerifyService connectorService importer.ConnectorService } func NewController( config *types.Config, tx dbtx.Transactor, urlProvider url.Provider, authorizer authz.Authorizer, repoStore store.RepoStore, linkedRepoStore store.LinkedRepoStore, spaceStore store.SpaceStore, pipelineStore store.PipelineStore, executionStore store.ExecutionStore, principalStore store.PrincipalStore, ruleStore store.RuleStore, checkStore store.CheckStore, pullReqStore store.PullReqStore, settings *settings.Service, principalInfoCache store.PrincipalInfoCache, protectionManager *protection.Manager, git git.Interface, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, importer *importer.JobRepository, referenceSync *importer.JobReferenceSync, importLinked *importer.JobRepositoryLink, codeOwners *codeowners.Service, eventReporter *repoevents.Reporter, indexer keywordsearch.Indexer, limiter limiter.ResourceLimiter, locker *locker.Locker, auditService audit.Service, mtxManager lock.MutexManager, identifierCheck check.RepoIdentifier, repoCheck Check, publicAccess publicaccess.Service, labelSvc *label.Service, instrumentation instrument.Service, userGroupStore store.UserGroupStore, userGroupService usergroup.Service, rulesSvc *rules.Service, sseStreamer sse.Streamer, lfsCtrl *lfs.Controller, favoriteStore store.FavoriteStore, signatureVerifyService publickey.SignatureVerifyService, connectorService importer.ConnectorService, ) *Controller { return &Controller{ defaultBranch: config.Git.DefaultBranch, tx: tx, urlProvider: urlProvider, authorizer: authorizer, repoStore: repoStore, linkedRepoStore: linkedRepoStore, spaceStore: spaceStore, pipelineStore: pipelineStore, executionStore: executionStore, principalStore: principalStore, ruleStore: ruleStore, checkStore: checkStore, pullReqStore: pullReqStore, settings: settings, principalInfoCache: principalInfoCache, protectionManager: protectionManager, git: git, spaceFinder: spaceFinder, repoFinder: repoFinder, importer: importer, referenceSync: referenceSync, importLinked: importLinked, codeOwners: codeOwners, eventReporter: eventReporter, indexer: indexer, resourceLimiter: limiter, locker: locker, auditService: auditService, mtxManager: mtxManager, identifierCheck: identifierCheck, repoCheck: repoCheck, publicAccess: publicAccess, labelSvc: labelSvc, instrumentation: instrumentation, userGroupStore: userGroupStore, userGroupService: userGroupService, rulesSvc: rulesSvc, sseStreamer: sseStreamer, lfsCtrl: lfsCtrl, favoriteStore: favoriteStore, signatureVerifyService: signatureVerifyService, connectorService: connectorService, } } // getRepoCheckAccess fetches a repo, checks if repo state allows requested permission // and checks if the current user has permission to access it. // //nolint:unparam func (c *Controller) getRepoCheckAccess( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { return GetRepoCheckAccess( ctx, c.repoFinder, c.authorizer, session, repoRef, reqPermission, false, allowedRepoStates..., ) } // getRepoCheckAccessWithLinked fetches a repo, checks if repo state allows requested permission // and checks if the current user has permission to access it. func (c *Controller) getRepoCheckAccessWithLinked( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { return GetRepoCheckAccess( ctx, c.repoFinder, c.authorizer, session, repoRef, reqPermission, true, allowedRepoStates..., ) } // getRepoCheckAccessForGit fetches a repo // and checks if the current user has permission to access it. func (c *Controller) getRepoCheckAccessForGit( ctx context.Context, session *auth.Session, repoRef string, reqPermission enum.Permission, ) (*types.RepositoryCore, error) { return GetRepoCheckAccess( ctx, c.repoFinder, c.authorizer, session, repoRef, reqPermission, false, // importing/migrating states are allowed - we'll block in the pre-receive hook if needed. enum.RepoStateGitImport, enum.RepoStateMigrateDataImport, enum.RepoStateMigrateGitPush, ) } func (c *Controller) getSpaceCheckAuthRepoCreation( ctx context.Context, session *auth.Session, parentRef string, ) (*types.SpaceCore, error) { return GetSpaceCheckAuthRepoCreation(ctx, c.spaceFinder, c.authorizer, session, parentRef) } func ValidateParentRef(parentRef string) error { parentRefAsID, err := strconv.ParseInt(parentRef, 10, 64) if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(parentRef)) == 0) { return errRepositoryRequiresParent } return nil } func eventBase(repo *types.RepositoryCore, principal *types.Principal) repoevents.Base { return repoevents.Base{ RepoID: repo.ID, PrincipalID: principal.ID, } } func (c *Controller) fetchBranchRules( ctx context.Context, session *auth.Session, repo *types.RepositoryCore, ) (protection.BranchProtection, bool, error) { isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo) if err != nil { return nil, false, fmt.Errorf("failed to determine if user is repo owner: %w", err) } protectionRules, err := c.protectionManager.ListRepoBranchRules(ctx, repo.ID) if err != nil { return nil, false, fmt.Errorf("failed to fetch protection rules for the repository: %w", err) } return protectionRules, isRepoOwner, nil } func (c *Controller) fetchTagRules( ctx context.Context, session *auth.Session, repo *types.RepositoryCore, ) (protection.TagProtection, bool, error) { isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo) if err != nil { return nil, false, fmt.Errorf("failed to determine if user is repo owner: %w", err) } protectionRules, err := c.protectionManager.ListRepoTagRules(ctx, repo.ID) if err != nil { return nil, false, fmt.Errorf("failed to fetch protection rules for the repository: %w", err) } return protectionRules, isRepoOwner, nil } func (c *Controller) fetchUpstreamBranch( ctx context.Context, session *auth.Session, repoForkCore *types.RepositoryCore, branchName string, ) (sha.SHA, *types.RepositoryCore, error) { return c.fetchUpstreamObjects( ctx, session, repoForkCore, func(readParams git.ReadParams) (sha.SHA, error) { result, err := c.git.GetRef(ctx, git.GetRefParams{ ReadParams: readParams, Name: branchName, Type: gitenum.RefTypeBranch, }) if err != nil { return sha.SHA{}, fmt.Errorf("failed to fetch branch %s: %w", branchName, err) } return result.SHA, nil }) } func (c *Controller) fetchUpstreamRevision( ctx context.Context, session *auth.Session, repoForkCore *types.RepositoryCore, revision string, ) (sha.SHA, *types.RepositoryCore, error) { return c.fetchUpstreamObjects( ctx, session, repoForkCore, func(readParams git.ReadParams) (sha.SHA, error) { result, err := c.git.ResolveRevision(ctx, git.ResolveRevisionParams{ ReadParams: readParams, Revision: revision, }) if err != nil { return sha.SHA{}, fmt.Errorf("failed to resolve revision %s: %w", revision, err) } return result.SHA, nil }) } func (c *Controller) fetchUpstreamObjects( ctx context.Context, session *auth.Session, repoForkCore *types.RepositoryCore, getSHA func(params git.ReadParams) (sha.SHA, error), ) (sha.SHA, *types.RepositoryCore, error) { if repoForkCore.ForkID == 0 { return sha.None, nil, errors.InvalidArgument("Repository is not a fork.") } repoUpstreamCore, err := c.repoFinder.FindByID(ctx, repoForkCore.ForkID) if err != nil { return sha.None, nil, fmt.Errorf("failed to find upstream repo: %w", err) } if err = apiauth.CheckRepo( ctx, c.authorizer, session, repoUpstreamCore, enum.PermissionRepoView, ); errors.Is(err, apiauth.ErrForbidden) { return sha.None, nil, usererror.BadRequest( "Not enough permissions to view the upstream repository.", ) } else if err != nil { return sha.None, nil, fmt.Errorf("failed to check access to upstream repo: %w", err) } upstreamSHA, err := getSHA(git.CreateReadParams(repoUpstreamCore)) if err != nil { return sha.None, nil, fmt.Errorf("failed to get upstream repo SHA: %w", err) } writeParams, err := controller.CreateRPCSystemReferencesWriteParams(ctx, c.urlProvider, session, repoForkCore) if err != nil { return sha.None, nil, fmt.Errorf("failed to create RPC write params: %w", err) } _, err = c.git.FetchObjects(ctx, &git.FetchObjectsParams{ WriteParams: writeParams, Source: repoUpstreamCore.GitUID, ObjectSHAs: []sha.SHA{upstreamSHA}, }) if err != nil { return sha.None, nil, fmt.Errorf("failed to fetch commit from upstream repo: %w", err) } return upstreamSHA, repoUpstreamCore, nil } func (c *Controller) fetchCommitDivergenceObjectsFromUpstream( ctx context.Context, session *auth.Session, repo *types.RepositoryCore, div *git.CommitDivergenceRequest, ) error { dot, err := makeDotRange(div.To, div.From, true) if err != nil { return fmt.Errorf("failed to make dot range: %w", err) } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dot) if err != nil { return fmt.Errorf("failed to fetch dot range objects: %w", err) } div.To = dot.BaseRef div.From = dot.HeadRef return nil } func (c *Controller) fetchDotRangeObjectsFromUpstream( ctx context.Context, session *auth.Session, repoForkCore *types.RepositoryCore, dotRange *DotRange, ) error { if dotRange.BaseUpstream { refSHA, _, err := c.fetchUpstreamRevision(ctx, session, repoForkCore, dotRange.BaseRef) if err != nil { return fmt.Errorf("failed to fetch upstream objects: %w", err) } dotRange.BaseUpstream = false dotRange.BaseRef = refSHA.String() } if dotRange.HeadUpstream { refSHA, _, err := c.fetchUpstreamRevision(ctx, session, repoForkCore, dotRange.HeadRef) if err != nil { return fmt.Errorf("failed to fetch upstream objects: %w", err) } dotRange.HeadUpstream = false dotRange.HeadRef = refSHA.String() } return nil } const dotRangeUpstreamMarker = "upstream:" type DotRange struct { BaseRef string BaseUpstream bool HeadRef string HeadUpstream bool MergeBase bool } func (r DotRange) String() string { sb := strings.Builder{} if r.BaseUpstream { sb.WriteString(dotRangeUpstreamMarker) } sb.WriteString(r.BaseRef) sb.WriteString("..") if r.MergeBase { sb.WriteByte('.') } if r.HeadUpstream { sb.WriteString(dotRangeUpstreamMarker) } sb.WriteString(r.HeadRef) return sb.String() } func parseDotRangePath(path string) (DotRange, error) { mergeBase := true parts := strings.SplitN(path, "...", 2) if len(parts) != 2 { mergeBase = false parts = strings.SplitN(path, "..", 2) if len(parts) != 2 { return DotRange{}, usererror.BadRequestf("Invalid format %q", path) } } dotRange, err := makeDotRange(parts[0], parts[1], mergeBase) if err != nil { return DotRange{}, err } return dotRange, nil } func makeDotRange(base, head string, mergeBase bool) (DotRange, error) { dotRange := DotRange{ BaseRef: base, HeadRef: head, MergeBase: mergeBase, } dotRange.BaseRef, dotRange.BaseUpstream = strings.CutPrefix(dotRange.BaseRef, dotRangeUpstreamMarker) dotRange.HeadRef, dotRange.HeadUpstream = strings.CutPrefix(dotRange.HeadRef, dotRangeUpstreamMarker) if dotRange.BaseUpstream && dotRange.HeadUpstream { return DotRange{}, usererror.BadRequestf("Only one upstream reference is allowed: %q", dotRange.String()) } return dotRange, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_commit_tags.go
app/api/controller/repo/list_commit_tags.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListCommitTags lists the commit tags of a repo. func (c *Controller) ListCommitTags(ctx context.Context, session *auth.Session, repoRef string, includeCommit bool, filter *types.TagFilter, ) ([]*types.CommitTag, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } result, err := c.git.ListCommitTags(ctx, &git.ListCommitTagsParams{ ReadParams: git.CreateReadParams(repo), IncludeCommit: includeCommit, Query: filter.Query, Sort: mapToRPCTagSortOption(filter.Sort), Order: mapToRPCSortOrder(filter.Order), Page: int32(filter.Page), //nolint:gosec PageSize: int32(filter.Size), //nolint:gosec }) if err != nil { return nil, err } tags := make([]*types.CommitTag, len(result.Tags)) for i := range result.Tags { t := controller.MapCommitTag(result.Tags[i]) tags[i] = &t } verifySession := c.signatureVerifyService.NewVerifySession(repo.ID) err = verifySession.VerifyCommitTags(ctx, tags) if err != nil { return nil, fmt.Errorf("failed to verify tags: %w", err) } commits := make([]*types.Commit, 0, len(tags)) for _, tag := range tags { if tag.Commit != nil { commits = append(commits, tag.Commit) } } err = verifySession.VerifyCommits(ctx, commits) if err != nil { return nil, fmt.Errorf("failed to verify signature of tags' commits: %w", err) } verifySession.StoreSignatures(ctx) return tags, nil } func mapToRPCTagSortOption(o enum.TagSortOption) git.TagSortOption { switch o { case enum.TagSortOptionDate: return git.TagSortOptionDate case enum.TagSortOptionName: return git.TagSortOptionName case enum.TagSortOptionDefault: return git.TagSortOptionDefault default: // no need to error out - just use default for sorting return git.TagSortOptionDefault } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_paths.go
app/api/controller/repo/list_paths.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types/enum" ) type ListPathsOutput struct { Files []string `json:"files,omitempty"` Directories []string `json:"directories,omitempty"` } // ListPaths lists the paths in the repo for a specific revision. func (c *Controller) ListPaths(ctx context.Context, session *auth.Session, repoRef string, gitRef string, includeDirectories bool, ) (ListPathsOutput, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return ListPathsOutput{}, err } // set gitRef to default branch in case an empty reference was provided if gitRef == "" { gitRef = repo.DefaultBranch } rpcOut, err := c.git.ListPaths(ctx, &git.ListPathsParams{ ReadParams: git.CreateReadParams(repo), GitREF: gitRef, IncludeDirectories: includeDirectories, }) if err != nil { return ListPathsOutput{}, fmt.Errorf("failed to list git paths: %w", err) } return ListPathsOutput{ Files: rpcOut.Files, Directories: rpcOut.Directories, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/merge_check.go
app/api/controller/repo/merge_check.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/types/enum" ) type MergeCheck struct { Mergeable bool `json:"mergeable"` ConflictFiles []string `json:"conflict_files,omitempty"` } func (c *Controller) MergeCheck( ctx context.Context, session *auth.Session, repoRef string, diffPath string, ) (MergeCheck, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return MergeCheck{}, err } dotRange, err := parseDotRangePath(diffPath) if err != nil { return MergeCheck{}, err } err = c.fetchDotRangeObjectsFromUpstream(ctx, session, repo, &dotRange) if err != nil { return MergeCheck{}, fmt.Errorf("failed to fetch diff upstream ref: %w", err) } readParams := git.CreateReadParams(repo) baseResult, err := c.git.ResolveRevision(ctx, git.ResolveRevisionParams{ ReadParams: readParams, Revision: dotRange.BaseRef, }) if err != nil { return MergeCheck{}, fmt.Errorf("failed to resolve base revision %s: %w", dotRange.BaseRef, err) } headResult, err := c.git.ResolveRevision(ctx, git.ResolveRevisionParams{ ReadParams: readParams, Revision: dotRange.HeadRef, }) if err != nil { return MergeCheck{}, fmt.Errorf("failed to resolve head revision %s: %w", dotRange.HeadRef, err) } writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return MergeCheck{}, fmt.Errorf("failed to create rpc write params: %w", err) } mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{ WriteParams: writeParams, BaseSHA: baseResult.SHA, HeadSHA: headResult.SHA, }) if err != nil { // git.Merge works with commits and error is not user-friendly // and here we are modify base-ref and head-ref with user input // values. if uErr := api.AsUnrelatedHistoriesError(err); uErr != nil { uErr.BaseRef = dotRange.BaseRef uErr.HeadRef = dotRange.HeadRef return MergeCheck{}, uErr } return MergeCheck{}, fmt.Errorf("merge check execution failed: %w", err) } if len(mergeOutput.ConflictFiles) > 0 { return MergeCheck{ Mergeable: false, ConflictFiles: mergeOutput.ConflictFiles, }, nil } c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeBranchMergableUpdated, mergeOutput) return MergeCheck{ Mergeable: true, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/list_service_accounts.go
app/api/controller/repo/list_service_accounts.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListServiceAccounts lists the service accounts of a repo. func (c *Controller) ListServiceAccounts( ctx context.Context, session *auth.Session, repoRef string, inherited bool, opts *types.PrincipalFilter, ) ([]*types.ServiceAccountInfo, int64, error) { repo, err := GetRepoCheckServiceAccountAccess( ctx, session, c.authorizer, repoRef, enum.PermissionServiceAccountView, c.repoFinder, c.repoStore, c.spaceStore) if err != nil { return nil, 0, fmt.Errorf("access check failed: %w", err) } repoParentInfo := &types.ServiceAccountParentInfo{ ID: repo.ID, Type: enum.ParentResourceTypeRepo, } var parentInfos []*types.ServiceAccountParentInfo if inherited { ancestorIDs, err := c.spaceStore.GetAncestorIDs(ctx, repo.ParentID) if err != nil { return nil, 0, fmt.Errorf("failed to get parent space ids: %w", err) } parentInfos = make([]*types.ServiceAccountParentInfo, len(ancestorIDs)+1) for i := range ancestorIDs { parentInfos[i] = &types.ServiceAccountParentInfo{ Type: enum.ParentResourceTypeSpace, ID: ancestorIDs[i], } } parentInfos[len(parentInfos)-1] = repoParentInfo } else { parentInfos = make([]*types.ServiceAccountParentInfo, 1) parentInfos[0] = repoParentInfo } var accounts []*types.ServiceAccount var count int64 err = c.tx.WithTx(ctx, func(ctx context.Context) error { accounts, err = c.principalStore.ListServiceAccounts(ctx, parentInfos, opts) if err != nil { return fmt.Errorf("failed to list service accounts: %w", err) } if opts.Page == 1 && len(accounts) < opts.Size { count = int64(len(accounts)) return nil } count, err = c.principalStore.CountServiceAccounts(ctx, parentInfos, opts) if err != nil { return fmt.Errorf("failed to count pull requests: %w", err) } return nil }, dbtx.TxDefaultReadOnly) if err != nil { return nil, 0, err } infos := make([]*types.ServiceAccountInfo, len(accounts)) for i := range accounts { infos[i] = accounts[i].ToServiceAccountInfo() } return infos, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/content_paths_details.go
app/api/controller/repo/content_paths_details.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type PathsDetailsInput struct { Paths []string `json:"paths"` } type PathsDetailsOutput struct { Details []types.PathDetails `json:"details"` } // PathsDetails finds the additional info about the provided paths of the repo. // If no gitRef is provided, the content is retrieved from the default branch. func (c *Controller) PathsDetails(ctx context.Context, session *auth.Session, repoRef string, gitRef string, input PathsDetailsInput, ) (PathsDetailsOutput, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return PathsDetailsOutput{}, err } if len(input.Paths) == 0 { return PathsDetailsOutput{}, nil } const maxInputPaths = 50 if len(input.Paths) > maxInputPaths { return PathsDetailsOutput{}, usererror.BadRequestf("Maximum number of elements in the Paths array is %d", maxInputPaths) } // set gitRef to default branch in case an empty reference was provided if gitRef == "" { gitRef = repo.DefaultBranch } result, err := c.git.PathsDetails(ctx, git.PathsDetailsParams{ ReadParams: git.CreateReadParams(repo), GitREF: gitRef, Paths: input.Paths, }) if err != nil { return PathsDetailsOutput{}, err } commits := make([]*types.Commit, 0, len(result.Details)) output := PathsDetailsOutput{ Details: make([]types.PathDetails, len(result.Details)), } for i, d := range result.Details { lastCommit := controller.MapCommit(d.LastCommit) output.Details[i] = types.PathDetails{ Path: d.Path, LastCommit: lastCommit, } if lastCommit != nil { commits = append(commits, lastCommit) } } err = c.signatureVerifyService.VerifyCommits(ctx, repo.ID, commits) if err != nil { return PathsDetailsOutput{}, fmt.Errorf("failed to verify signature of commits: %w", err) } return output, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/update_public_access.go
app/api/controller/repo/update_public_access.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/audit" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type UpdatePublicAccessInput struct { IsPublic bool `json:"is_public"` } func (c *Controller) UpdatePublicAccess( ctx context.Context, session *auth.Session, repoRef string, in *UpdatePublicAccessInput, ) (*RepositoryOutput, error) { repoCore, err := c.getRepoCheckAccessWithLinked(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, err } parentPath, _, err := paths.DisectLeaf(repoCore.Path) if err != nil { return nil, fmt.Errorf("failed to disect path %q: %w", repoCore.Path, err) } isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentPath) if err != nil { return nil, fmt.Errorf( "failed to check if public access is supported for parent space %q: %w", parentPath, err, ) } if in.IsPublic && !isPublicAccessSupported { return nil, errPublicRepoCreationDisabled } isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repoCore.Path) if err != nil { return nil, fmt.Errorf("failed to check current public access status: %w", err) } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to find repo by ID: %w", err) } // no op if isPublic == in.IsPublic { repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, isPublic, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } return repoOutput, nil } if err = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, in.IsPublic); err != nil { return nil, fmt.Errorf("failed to update repo public access: %w", err) } // backfill GitURL repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionUpdated, paths.Parent(repo.Path), audit.WithOldObject(audit.RepositoryObject{ Repository: *repo, IsPublic: isPublic, }), audit.WithNewObject(audit.RepositoryObject{ Repository: *repo, IsPublic: in.IsPublic, }), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository operation: %s", err) } c.eventReporter.PublicAccessChanged(ctx, &repoevents.PublicAccessChangedPayload{ Base: eventBase(repo.Core(), &session.Principal), OldIsPublic: isPublic, NewIsPublic: in.IsPublic, }) repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, in.IsPublic, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } return repoOutput, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/label_define.go
app/api/controller/repo/label_define.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // DefineLabel defines a new label for the specified repository. func (c *Controller) DefineLabel( ctx context.Context, session *auth.Session, repoRef string, in *types.DefineLabelInput, ) (*types.Label, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to repo: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Define( ctx, session.Principal.ID, nil, &repo.ID, in) if err != nil { return nil, fmt.Errorf("failed to create repo label: %w", err) } return label, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/create_fork.go
app/api/controller/repo/create_fork.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "database/sql" "encoding/json" "fmt" "strings" "time" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/auth" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/audit" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type CreateForkInput struct { ParentRef string `json:"parent_ref"` Identifier string `json:"identifier"` ForkBranch string `json:"fork_branch"` IsPublic *bool `json:"is_public"` } func (in *CreateForkInput) sanitize() error { in.ParentRef = strings.TrimSpace(in.ParentRef) in.Identifier = strings.TrimSpace(in.Identifier) in.ForkBranch = strings.TrimSpace(in.ForkBranch) if in.ParentRef == "" { return errors.InvalidArgument("Parent space is mandatory.") } if in.Identifier == "" { return errors.InvalidArgument("Identifier is mandatory.") } return nil } //nolint:gocognit func (c *Controller) CreateFork( ctx context.Context, session *auth.Session, repoRef string, in *CreateForkInput, ) (*RepositoryOutput, error) { repoUpstreamCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } if repoUpstreamCore.Type == enum.RepoTypeLinked { return nil, errors.Forbidden("A linked repository can't be forked") } if err := in.sanitize(); err != nil { return nil, err } repoUpstream, err := c.repoStore.Find(ctx, repoUpstreamCore.ID) if err != nil { return nil, fmt.Errorf("failed to find the upstream repo: %w", err) } if repoUpstream.IsEmpty { return nil, errors.InvalidArgument("Can not fork an empty repository.") } parentSpace, err := c.getSpaceCheckAuthRepoCreation(ctx, session, in.ParentRef) if err != nil { return nil, err } isUpstreamPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repoUpstream.Path) if err != nil { return nil, fmt.Errorf("failed to get repo public access: %w", err) } var isForkPublic bool if in.IsPublic == nil { isForkPublic = isUpstreamPublic } else { isForkPublic = *in.IsPublic } if isForkPublic { if !isUpstreamPublic { return nil, errors.InvalidArgument("Can not create a public fork from a private repository.") } isPublicAccessSupported, err := c.publicAccess. IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentSpace.Path) if err != nil { return nil, fmt.Errorf( "failed to check if public access is supported for parent space %q: %w", parentSpace.Path, err, ) } if !isPublicAccessSupported { return nil, errPublicRepoCreationDisabled } } defaultBranch := repoUpstream.DefaultBranch if in.ForkBranch != "" && repoUpstream.DefaultBranch != in.ForkBranch { _, err := c.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: git.CreateReadParams(repoUpstream), BranchName: in.ForkBranch, }) if err != nil { if errors.IsNotFound(err) { return nil, errors.InvalidArgument("Fork branch not found.") } return nil, fmt.Errorf("failed to get branch: %w", err) } defaultBranch = in.ForkBranch } err = c.repoCheck.Create(ctx, session, &CheckInput{ ParentRef: parentSpace.Path, Identifier: in.Identifier, DefaultBranch: defaultBranch, Description: repoUpstream.Description, IsPublic: isForkPublic, IsFork: true, UpstreamPath: repoUpstream.Path, CreateFileOptions: CreateFileOptions{}, }) if err != nil { return nil, err } gitForkRepo, _, err := c.createGitRepository( ctx, session, in.Identifier, repoUpstream.Description, defaultBranch, CreateFileOptions{}, ) if err != nil { return nil, fmt.Errorf("error creating repository on git: %w", err) } var repoFork *types.Repository err = c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.resourceLimiter.RepoCount(ctx, parentSpace.ID, 1); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } // lock the space for update during repo creation to prevent racing conditions with space soft delete. _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) if err != nil { return fmt.Errorf("failed to find the parent space: %w", err) } repoUpstream, err = c.repoStore.Find(ctx, repoUpstream.ID) if err != nil { return fmt.Errorf("failed to find the upstream repo: %w", err) } now := time.Now().UnixMilli() repoFork = &types.Repository{ Version: 0, ParentID: parentSpace.ID, Identifier: in.Identifier, GitUID: gitForkRepo.UID, Description: repoUpstream.Description, CreatedBy: session.Principal.ID, Created: now, Updated: now, LastGITPush: now, ForkID: repoUpstream.ID, DefaultBranch: defaultBranch, IsEmpty: false, State: enum.RepoStateGitImport, Tags: json.RawMessage(`{}`), } err = c.repoStore.Create(ctx, repoFork) if err != nil { return fmt.Errorf("failed to create fork repository: %w", err) } err = c.repoStore.UpdateNumForks(ctx, repoUpstream.ID, 1) if err != nil { return fmt.Errorf("failed to increment number of forks in upstream repository: %w", err) } return nil }, sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { // best effort cleanup if dErr := c.DeleteGitRepository(ctx, session, gitForkRepo.UID); dErr != nil { log.Ctx(ctx).Warn().Err(dErr).Msg("failed to delete repo for cleanup") } return nil, err } // revert this when import fetches LFS objects if err := c.settings.RepoSet(ctx, repoFork.ID, settings.KeyGitLFSEnabled, false); err != nil { log.Warn().Err(err).Msg("failed to disable Git LFS in repository settings") } err = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repoFork.Path, isForkPublic) if err != nil { if dErr := c.publicAccess.Delete(ctx, enum.PublicResourceTypeRepo, repoFork.Path); dErr != nil { return nil, fmt.Errorf("failed to set repo public access (and public access cleanup: %w): %w", dErr, err) } // only cleanup repo itself if cleanup of public access succeeded (to avoid leaking public access) if dErr := c.PurgeNoAuth(ctx, session, repoFork); dErr != nil { return nil, fmt.Errorf("failed to set repo public access (and repo purge: %w): %w", dErr, err) } return nil, fmt.Errorf("failed to set repo public access (successful cleanup): %w", err) } // backfil GitURL repoFork.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repoFork.Path) repoFork.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repoFork.Path) repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, isForkPublic, repoFork) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repoFork.Identifier), audit.ActionCreated, paths.Parent(repoFork.Path), audit.WithNewObject(audit.RepositoryObject{ Repository: repoOutput.Repository, IsPublic: repoOutput.IsPublic, }), ) if err != nil { log.Ctx(ctx).Warn().Err(err). Msg("failed to insert audit log for create fork repository operation") } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeRepositoryCreate, Principal: session.Principal.ToPrincipalInfo(), Path: repoFork.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repoFork.ID, instrument.PropertyRepositoryName: repoFork.Identifier, instrument.PropertyRepositoryCreationType: instrument.CreationTypeCreate, }, }) if err != nil { log.Ctx(ctx).Warn().Err(err). Msg("failed to insert instrumentation record for create fork repository operation") } c.eventReporter.Created(ctx, &repoevents.CreatedPayload{ Base: eventBase(repoFork.Core(), &session.Principal), IsPublic: isForkPublic, }) var refSpecType importer.RefSpecType var ref string if in.ForkBranch != "" { refSpecType = importer.RefSpecTypeReference ref = "refs/heads/" + in.ForkBranch } else { refSpecType = importer.RefSpecTypeBranchesAndTags } err = c.referenceSync.Run(ctx, repoUpstream.ID, repoFork.ID, refSpecType, ref, ref) if err != nil { log.Ctx(ctx).Err(err).Msg("failed to start job for repository reference sync") } return repoOutput, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/raw.go
app/api/controller/repo/raw.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "bytes" "context" "fmt" "io" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type RawContent struct { Data io.ReadCloser Size int64 SHA sha.SHA } // Raw finds the file of the repo at the given path and returns its raw content. // If no gitRef is provided, the content is retrieved from the default branch. func (c *Controller) Raw(ctx context.Context, session *auth.Session, repoRef string, gitRef string, path string, ) (*RawContent, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } // set gitRef to default branch in case an empty reference was provided if gitRef == "" { gitRef = repo.DefaultBranch } // create read params once readParams := git.CreateReadParams(repo) treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: readParams, GitREF: gitRef, Path: path, IncludeLatestCommit: false, }) if err != nil { return nil, fmt.Errorf("failed to read tree node: %w", err) } // viewing Raw content is only supported for blob content if treeNodeOutput.Node.Type != git.TreeNodeTypeBlob { return nil, usererror.BadRequestf( "Object in '%s' at '/%s' is of type '%s'. Only objects of type %s support raw viewing.", gitRef, path, treeNodeOutput.Node.Type, git.TreeNodeTypeBlob) } blobReader, err := c.git.GetBlob(ctx, &git.GetBlobParams{ ReadParams: readParams, SHA: treeNodeOutput.Node.SHA, SizeLimit: 0, // no size limit, we stream whatever data there is }) if err != nil { return nil, fmt.Errorf("failed to read blob: %w", err) } gitLFSEnabled, err := settings.RepoGet( ctx, c.settings, repo.ID, settings.KeyGitLFSEnabled, settings.DefaultGitLFSEnabled, ) if err != nil { return nil, fmt.Errorf("failed to check settings for Git LFS enabled: %w", err) } if !gitLFSEnabled { return &RawContent{ Data: blobReader.Content, Size: blobReader.ContentSize, SHA: blobReader.SHA, }, nil } // check if blob is an LFS pointer headerContent, err := io.ReadAll(io.LimitReader(blobReader.Content, parser.LfsPointerMaxSize)) if err != nil { return nil, fmt.Errorf("failed to read content: %w", err) } lfsInfo, ok := parser.IsLFSPointer(ctx, headerContent, blobReader.Size) if ok { lfsContent, err := c.lfsCtrl.DownloadNoAuth(ctx, repo.ID, lfsInfo.OID) if err == nil { return &RawContent{ Data: lfsContent, Size: lfsInfo.Size, SHA: blobReader.SHA, }, nil } if !errors.Is(err, gitness_store.ErrResourceNotFound) { return nil, fmt.Errorf("failed to download LFS file: %w", err) } } return &RawContent{ Data: &types.MultiReadCloser{ Reader: io.MultiReader(bytes.NewBuffer(headerContent), blobReader.Content), CloseFunc: blobReader.Content.Close, }, Size: blobReader.ContentSize, SHA: blobReader.SHA, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/import_progress.go
app/api/controller/repo/import_progress.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "errors" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/job" "github.com/harness/gitness/types/enum" ) // ImportProgress returns progress of the import job. func (c *Controller) ImportProgress(ctx context.Context, session *auth.Session, repoRef string, ) (job.Progress, error) { // note: can't use c.getRepoCheckAccess because this needs to fetch a repo being imported. repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return job.Progress{}, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView); err != nil { return job.Progress{}, err } progress, err := c.importer.GetProgress(ctx, repo) if errors.Is(err, importer.ErrNotFound) { return job.Progress{}, usererror.NotFound("No recent or ongoing import found for repository.") } if err != nil { return job.Progress{}, fmt.Errorf("failed to retrieve import progress: %w", err) } return progress, err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/rule_update.go
app/api/controller/repo/rule_update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleUpdate updates an existing protection rule for a repository. func (c *Controller) RuleUpdate(ctx context.Context, session *auth.Session, repoRef string, identifier string, in *rules.UpdateInput, ) (*types.Rule, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) if err != nil { return nil, err } rule, err := c.rulesSvc.Update( ctx, &session.Principal, enum.RuleParentRepo, repo.ID, repo.Identifier, repo.Path, identifier, in, ) if err != nil { return nil, fmt.Errorf("failed to update repo-level protection rule by identifier: %w", err) } return rule, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/update.go
app/api/controller/repo/update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "encoding/json" "fmt" "strings" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" repoevents "github.com/harness/gitness/app/events/repo" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/audit" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" "golang.org/x/exp/slices" ) // UpdateInput is used for updating a repo. type UpdateInput struct { Description *string `json:"description"` State *enum.RepoState `json:"state"` Tags *types.RepoTags `json:"tags"` } var allowedRepoStateTransitions = map[enum.RepoState][]enum.RepoState{ enum.RepoStateActive: {enum.RepoStateArchived, enum.RepoStateMigrateDataImport}, enum.RepoStateArchived: {enum.RepoStateActive}, enum.RepoStateMigrateDataImport: {enum.RepoStateActive}, enum.RepoStateMigrateGitPush: {enum.RepoStateActive, enum.RepoStateMigrateDataImport}, } // Update updates a repository. func (c *Controller) Update(ctx context.Context, session *auth.Session, repoRef string, in *UpdateInput, ) (*RepositoryOutput, error) { repoCore, err := GetRepo(ctx, c.repoFinder, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo: %w", err) } var additionalAllowedRepoStates []enum.RepoState if in.State != nil { additionalAllowedRepoStates = []enum.RepoState{ enum.RepoStateArchived, enum.RepoStateMigrateDataImport, enum.RepoStateMigrateGitPush} } err = apiauth.CheckRepoState(ctx, session, repoCore, enum.PermissionRepoEdit, additionalAllowedRepoStates...) if err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoEdit); err != nil { return nil, fmt.Errorf("access check failed: %w", err) } repo, err := c.repoStore.Find(ctx, repoCore.ID) if err != nil { return nil, fmt.Errorf("failed to find repository by ID: %w", err) } if err = c.sanitizeUpdateInput(in); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } if !in.hasChanges(repo) { return GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repo) } if err = c.repoCheck.LifecycleRestriction(ctx, session, repoCore); err != nil { return nil, err } if in.State != nil && !slices.Contains(allowedRepoStateTransitions[repo.State], *in.State) { return nil, usererror.BadRequestf("Changing the state of a repository from %s to %s is not allowed.", repo.State, *in.State) } var repoClone types.Repository repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(repo *types.Repository) error { repoClone = *repo // update values only if provided if in.Description != nil { repo.Description = *in.Description } if in.State != nil { repo.State = *in.State } if in.Tags != nil { tags, _ := json.Marshal(in.Tags) repo.Tags = tags } return nil }) if err != nil { return nil, fmt.Errorf("failed to update the repo: %w", err) } c.repoFinder.MarkChanged(ctx, repo.Core()) err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier), audit.ActionUpdated, paths.Parent(repo.Path), audit.WithOldObject(repoClone), audit.WithNewObject(repo), ) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository operation: %s", err) } // backfill repo url repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) if repo.State != repoClone.State { c.eventReporter.StateChanged(ctx, &repoevents.StateChangedPayload{ Base: eventBase(repo.Core(), &session.Principal), OldState: repoClone.State, NewState: repo.State, }) } return GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repo) } func (in *UpdateInput) hasChanges(repo *types.Repository) bool { if in.Description != nil && *in.Description != repo.Description { return true } if in.State != nil && *in.State != repo.State { return true } if hasTagChanges(in, repo) { return true } return false } func hasTagChanges(in *UpdateInput, repo *types.Repository) bool { if in.Tags == nil { return false } var repoTags map[string]string _ = json.Unmarshal(repo.Tags, &repoTags) if len(*in.Tags) != len(repoTags) { return true } for key, value := range *in.Tags { if repoValue, exists := repoTags[key]; !exists || repoValue != value { return true } } return false } func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error { if in.Description != nil { *in.Description = strings.TrimSpace(*in.Description) if err := check.Description(*in.Description); err != nil { return err } } if in.Tags == nil { return nil } err := in.Tags.Sanitize() if err != nil { return fmt.Errorf("failed to sanitize tags: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/import.go
app/api/controller/repo/import.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/audit" "github.com/rs/zerolog/log" ) type ImportInput struct { ParentRef string `json:"parent_ref"` // TODO [CODE-1363]: remove after identifier migration. UID string `json:"uid" deprecated:"true"` Identifier string `json:"identifier"` Description string `json:"description"` Provider importer.Provider `json:"provider"` ProviderRepo string `json:"provider_repo"` Pipelines importer.PipelineOption `json:"pipelines"` } // Import creates a new empty repository and starts git import to it from a remote repository. func (c *Controller) Import(ctx context.Context, session *auth.Session, in *ImportInput) (*RepositoryOutput, error) { if err := c.sanitizeImportInput(in, session); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } parentSpace, err := c.getSpaceCheckAuthRepoCreation(ctx, session, in.ParentRef) if err != nil { return nil, err } remoteRepository, provider, err := importer.LoadRepositoryFromProvider(ctx, in.Provider, in.ProviderRepo) if err != nil { return nil, err } repo, isPublic := remoteRepository.ToRepo( parentSpace.ID, parentSpace.Path, in.Identifier, in.Description, &session.Principal, ) err = c.tx.WithTx(ctx, func(ctx context.Context) error { if err := c.resourceLimiter.RepoCount(ctx, parentSpace.ID, 1); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } // lock the space for update during repo creation to prevent racing conditions with space soft delete. _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) if err != nil { return fmt.Errorf("failed to find the parent space: %w", err) } err = c.repoStore.Create(ctx, repo) if err != nil { return fmt.Errorf("failed to create repository in storage: %w", err) } err = c.importer.Run(ctx, provider, repo, isPublic, remoteRepository.CloneURL, in.Pipelines, ) if err != nil { return fmt.Errorf("failed to start import repository job: %w", err) } return nil }) if err != nil { return nil, err } repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionCreated, paths.Parent(repo.Path), audit.WithNewObject(audit.RepositoryObject{ Repository: *repo, IsPublic: false, }), ) if err != nil { log.Warn().Msgf("failed to insert audit log for import repository operation: %s", err) } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeRepositoryCreate, Principal: session.Principal.ToPrincipalInfo(), Path: repo.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyRepositoryCreationType: instrument.CreationTypeImport, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for import repository operation: %s", err) } repoOutput, err := GetRepoOutputWithAccess(ctx, c.repoFinder, false, repo) if err != nil { return nil, fmt.Errorf("failed to get repo output: %w", err) } return repoOutput, nil } func (c *Controller) sanitizeImportInput(in *ImportInput, session *auth.Session) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.UID } if err := ValidateParentRef(in.ParentRef); err != nil { return err } if err := c.identifierCheck(in.Identifier, session); err != nil { return err } if in.Pipelines == "" { in.Pipelines = importer.PipelineOptionConvert } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/git_service_pack.go
app/api/controller/repo/git_service_pack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "fmt" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/types/enum" ) // GitServicePack executes the service pack part of git's smart http protocol (receive-/upload-pack). func (c *Controller) GitServicePack( ctx context.Context, session *auth.Session, repoRef string, options api.ServicePackOptions, ) error { isWriteOperation := false permission := enum.PermissionRepoView // receive-pack is the server receiving data - aka the client pushing data. if options.Service == enum.GitServiceTypeReceivePack { isWriteOperation = true permission = enum.PermissionRepoPush } repo, err := c.getRepoCheckAccessForGit(ctx, session, repoRef, permission) if err != nil { return fmt.Errorf("failed to verify repo access: %w", err) } params := &git.ServicePackParams{ // TODO: git shouldn't take a random string here, but instead have accepted enum values. ServicePackOptions: options, } // setup read/writeparams depending on whether it's a write operation if isWriteOperation { var writeParams git.WriteParams writeParams, err = controller.CreateRPCExternalWriteParams(ctx, c.urlProvider, session, repo) if err != nil { return fmt.Errorf("failed to create RPC write params: %w", err) } params.WriteParams = &writeParams } else { readParams := git.CreateReadParams(repo) params.ReadParams = &readParams } if err = c.git.ServicePack(ctx, params); err != nil { return fmt.Errorf("failed service pack operation %q on git: %w", options.Service, err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/repo/codeowner_validate.go
app/api/controller/repo/codeowner_validate.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package repo import ( "context" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) CodeOwnersValidate( ctx context.Context, session *auth.Session, repoRef string, ref string, ) (*types.CodeOwnersValidation, error) { repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) if err != nil { return nil, err } if ref == "" { ref = repo.DefaultBranch } violations, err := c.codeOwners.Validate(ctx, repo, ref) if err != nil { return nil, err } return violations, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/wire.go
app/api/controller/infraprovider/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/refcache" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, infraproviderSvc *infraprovider.Service, ) *Controller { return NewController(authorizer, spaceFinder, infraproviderSvc) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/create_config.go
app/api/controller/infraprovider/create_config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) // CreateConfig creates a new infra provider config. func (c *Controller) CreateConfig( ctx context.Context, session auth.Session, in ConfigInput, ) (*types.InfraProviderConfig, error) { if err := c.sanitizeCreateInput(in); err != nil { return nil, fmt.Errorf("invalid input: %w", err) } parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef) if err != nil { return nil, fmt.Errorf("failed to find parent by ref %q : %w", in.SpaceRef, err) } if err = apiauth.CheckInfraProvider( ctx, c.authorizer, &session, parentSpace.Path, NoResourceIdentifier, enum.PermissionInfraProviderEdit, ); err != nil { return nil, err } now := time.Now().UnixMilli() infraProviderConfig := c.MapToInfraProviderConfig(in, parentSpace, now) err = c.infraproviderSvc.CreateConfig(ctx, infraProviderConfig) if err != nil { return nil, fmt.Errorf("unable to create the infraprovider: %q %w", infraProviderConfig.Identifier, err) } return infraProviderConfig, nil } func (c *Controller) MapToInfraProviderConfig( in ConfigInput, space *types.SpaceCore, now int64, ) *types.InfraProviderConfig { return &types.InfraProviderConfig{ Identifier: in.Identifier, Name: in.Name, SpaceID: space.ID, SpacePath: space.Path, Type: in.Type, Created: now, Updated: now, Metadata: in.Metadata, } } func (c *Controller) sanitizeCreateInput(in ConfigInput) error { if err := check.Identifier(in.Identifier); err != nil { return err } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/list_resources.go
app/api/controller/infraprovider/list_resources.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListResources retrieves all resources for an infrastructure provider. func (c *Controller) ListResources( ctx context.Context, session *auth.Session, spaceRef, infraProviderIdentifier string, ) ([]*types.InfraProviderResource, error) { // Find the space for authorization checks space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("failed to find space: %w", err) } // Check authorization err = apiauth.CheckInfraProvider(ctx, c.authorizer, session, space.Path, "", enum.PermissionInfraProviderView) if err != nil { return nil, fmt.Errorf("failed to authorize: %w", err) } // Find the infra provider config using the correct method config, err := c.infraproviderSvc.Find(ctx, space, infraProviderIdentifier) if err != nil { return nil, fmt.Errorf("failed to find infra provider: %w", err) } // The config from Find() already has its resources populated, so we can just use them // Create pointers for the resources from the populated config resources := make([]*types.InfraProviderResource, len(config.Resources)) for i := range config.Resources { resources[i] = &config.Resources[i] } return resources, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/find.go
app/api/controller/infraprovider/find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" ) func (c *Controller) Find( ctx context.Context, _ *auth.Session, spaceRef string, identifier string, ) (*types.InfraProviderConfig, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("failed to find space: %w", err) } // todo: add acl check with PermissionInfraProviderView once infra provider resource is added to access control // err = apiauth.CheckGitspace(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionGitspaceView) // if err != nil { // return nil, fmt.Errorf("failed to authorize: %w", err) // } return c.infraproviderSvc.Find(ctx, space, identifier) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/delete_resource.go
app/api/controller/infraprovider/delete_resource.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) func (c *Controller) DeleteResource( ctx context.Context, session *auth.Session, spaceID int64, infraProviderConfigIdentifier string, infraProviderResourceIdentifier string, ) error { space, err := c.spaceFinder.FindByID(ctx, spaceID) if err != nil { return fmt.Errorf("failed to find space: %w", err) } err = apiauth.CheckInfraProvider( ctx, c.authorizer, session, space.Path, "", enum.PermissionInfraProviderDelete, ) if err != nil { return fmt.Errorf("failed to authorize: %w", err) } return c.infraproviderSvc.DeleteResource(ctx, spaceID, infraProviderConfigIdentifier, infraProviderResourceIdentifier, true) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/list.go
app/api/controller/infraprovider/list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) List( ctx context.Context, session *auth.Session, spaceRef string, applyACLFilter bool, ) ([]*types.InfraProviderConfig, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("failed to find space: %w", err) } err = apiauth.CheckInfraProvider(ctx, c.authorizer, session, space.Path, "", enum.PermissionInfraProviderView) if err != nil { return nil, fmt.Errorf("failed to authorize: %w", err) } filter := types.InfraProviderConfigFilter{ SpaceIDs: []int64{space.ID}, ApplyResourcesACL: applyACLFilter, } return c.infraproviderSvc.List(ctx, &filter) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/create_resources.go
app/api/controller/infraprovider/create_resources.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) func (c *Controller) CreateTemplate( ctx context.Context, session *auth.Session, in *TemplateInput, configIdentifier string, spaceRef string, ) (*types.InfraProviderTemplate, error) { now := time.Now().UnixMilli() parentSpace, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("failed to find parent by ref: %w", err) } if err = apiauth.CheckInfraProvider( ctx, c.authorizer, session, parentSpace.Path, NoResourceIdentifier, enum.PermissionInfraProviderEdit, ); err != nil { return nil, err } infraProviderConfig, err := c.infraproviderSvc.Find(ctx, parentSpace, configIdentifier) if err != nil { return nil, fmt.Errorf("failed to find infraprovider config by ref: %w", err) } providerTemplate := &types.InfraProviderTemplate{ Identifier: in.Identifier, InfraProviderConfigIdentifier: infraProviderConfig.Identifier, InfraProviderConfigID: infraProviderConfig.ID, Description: in.Description, Data: in.Data, Version: 0, SpaceID: parentSpace.ID, SpacePath: parentSpace.Path, Created: now, Updated: now, } err = c.infraproviderSvc.CreateTemplate(ctx, providerTemplate) if err != nil { return nil, err } return providerTemplate, nil } func (c *Controller) CreateResources( ctx context.Context, session auth.Session, in []ResourceInput, configIdentifier string, spaceRef string, ) ([]types.InfraProviderResource, error) { if err := c.sanitizeResourceInput(in); err != nil { return nil, fmt.Errorf("invalid input: %w", err) } now := time.Now().UnixMilli() space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("failed to find parent by ref: %w", err) } if err = apiauth.CheckInfraProvider( ctx, c.authorizer, &session, space.Path, NoResourceIdentifier, enum.PermissionInfraProviderEdit, ); err != nil { return nil, err } resources := c.MapToResourceEntity(in, space, now) err = c.infraproviderSvc.CreateResources(ctx, space.ID, resources, configIdentifier) if err != nil { return nil, err } return resources, nil } func (c *Controller) MapToResourceEntity( in []ResourceInput, space *types.SpaceCore, now int64, ) []types.InfraProviderResource { var resources []types.InfraProviderResource for _, res := range in { infraProviderResource := types.InfraProviderResource{ UID: res.Identifier, InfraProviderType: res.InfraProviderType, Name: res.Name, SpaceID: space.ID, CPU: res.CPU, Memory: res.Memory, Disk: res.Disk, Network: res.Network, Region: res.Region, Metadata: res.Metadata, Created: now, Updated: now, SpacePath: space.Path, } resources = append(resources, infraProviderResource) } return resources } func (c *Controller) sanitizeResourceInput(in []ResourceInput) error { for _, resource := range in { if err := check.Identifier(resource.Identifier); err != nil { return err } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/controller.go
app/api/controller/infraprovider/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/types/enum" ) const NoResourceIdentifier = "" type ConfigInput struct { Identifier string `json:"identifier" yaml:"identifier"` SpaceRef string `json:"space_ref" yaml:"space_ref"` Name string `json:"name" yaml:"name"` Type enum.InfraProviderType `json:"type" yaml:"type"` Metadata map[string]any `json:"metadata" yaml:"metadata"` } type ResourceInput struct { Identifier string `json:"identifier" yaml:"identifier"` Name string `json:"name" yaml:"name"` InfraProviderType enum.InfraProviderType `json:"infra_provider_type" yaml:"infra_provider_type"` CPU *string `json:"cpu" yaml:"cpu"` Memory *string `json:"memory" yaml:"memory"` Disk *string `json:"disk" yaml:"disk"` Network *string `json:"network" yaml:"network"` Region string `json:"region" yaml:"region"` Metadata map[string]string `json:"metadata" yaml:"metadata"` GatewayHost *string `json:"gateway_host" yaml:"gateway_host"` GatewayPort *string `json:"gateway_port" yaml:"gateway_port"` } type AutoCreateInput struct { Config ConfigInput `json:"config" yaml:"config"` Resources []ResourceInput `json:"resources" yaml:"resources"` } type TemplateInput struct { Identifier string `json:"identifier" yaml:"identifier"` Description string `json:"description" yaml:"description"` Data string `json:"data" yaml:"data"` } type Controller struct { authorizer authz.Authorizer spaceFinder refcache.SpaceFinder infraproviderSvc *infraprovider.Service } func NewController( authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, infraproviderSvc *infraprovider.Service, ) *Controller { return &Controller{ authorizer: authorizer, spaceFinder: spaceFinder, infraproviderSvc: infraproviderSvc, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/infraprovider/delete_config.go
app/api/controller/infraprovider/delete_config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package infraprovider import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) func (c *Controller) DeleteConfig( ctx context.Context, session *auth.Session, spaceRef string, identifier string, ) error { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return fmt.Errorf("failed to find space: %w", err) } err = apiauth.CheckInfraProvider(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionInfraProviderDelete) if err != nil { return fmt.Errorf("failed to authorize: %w", err) } return c.infraproviderSvc.DeleteConfig(ctx, space, identifier, true) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/wire.go
app/api/controller/serviceaccount/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types/check" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( NewController, ) func ProvideController(principalUIDCheck check.PrincipalUID, authorizer authz.Authorizer, principalStore store.PrincipalStore, spaceStore store.SpaceStore, repoStore store.RepoStore, tokenStore store.TokenStore) *Controller { return NewController(principalUIDCheck, authorizer, principalStore, spaceStore, repoStore, tokenStore) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/create.go
app/api/controller/serviceaccount/create.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" "fmt" "strings" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" "github.com/dchest/uniuri" gonanoid "github.com/matoous/go-nanoid/v2" ) var ( serviceAccountUIDAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789" serviceAccountUIDLength = 16 ) type CreateInput struct { Email string `json:"email"` DisplayName string `json:"display_name"` ParentType enum.ParentResourceType `json:"parent_type"` ParentID int64 `json:"parent_id"` } // Create creates a new service account. func (c *Controller) Create(ctx context.Context, session *auth.Session, in *CreateInput) (*types.ServiceAccount, error) { // Ensure principal has required permissions on parent (ensures that parent exists) // since it's a create, we use don't pass a resource name. if err := apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, in.ParentType, in.ParentID, "", enum.PermissionServiceAccountEdit); err != nil { return nil, err } uid, err := generateServiceAccountUID(in.ParentType, in.ParentID) if err != nil { return nil, fmt.Errorf("failed to generate service account UID: %w", err) } // TODO: There's a chance of duplicate error - we should retry? return c.CreateNoAuth(ctx, in, uid) } /* * CreateNoAuth creates a new service account without auth checks. * WARNING: Never call as part of user flow. * * Note: take uid separately to allow internally created non-random uids. */ func (c *Controller) CreateNoAuth(ctx context.Context, in *CreateInput, uid string) (*types.ServiceAccount, error) { if err := c.sanitizeCreateInput(in, uid); err != nil { return nil, fmt.Errorf("invalid input: %w", err) } sa := &types.ServiceAccount{ UID: uid, Email: in.Email, DisplayName: in.DisplayName, Salt: uniuri.NewLen(uniuri.UUIDLen), Created: time.Now().UnixMilli(), Updated: time.Now().UnixMilli(), ParentType: in.ParentType, ParentID: in.ParentID, } err := c.principalStore.CreateServiceAccount(ctx, sa) if err != nil { return nil, err } return sa, nil } func (c *Controller) sanitizeCreateInput(in *CreateInput, uid string) error { if err := c.principalUIDCheck(uid); err != nil { return err } in.Email = strings.TrimSpace(in.Email) if err := check.Email(in.Email); err != nil { return err } in.DisplayName = strings.TrimSpace(in.DisplayName) if err := check.DisplayName(in.DisplayName); err != nil { return err } if err := check.ServiceAccountParent(in.ParentType, in.ParentID); err != nil { //nolint:revive return err } return nil } // generateServiceAccountUID generates a new unique UID for a service account // NOTE: // This method generates 36^10 = ~8*10^24 unique UIDs per parent. // This should be enough for a very low chance of duplications. // // NOTE: // We generate it automatically to ensure unique UIDs on principals. // The downside is that they don't have very userfriendly handlers - though that should be okay for service accounts. // The other option would be take it as an input, but a globally unique uid of a service account // which itself is scoped to a space / repo might be weird. func generateServiceAccountUID(parentType enum.ParentResourceType, parentID int64) (string, error) { nid, err := gonanoid.Generate(serviceAccountUIDAlphabet, serviceAccountUIDLength) if err != nil { return "", err } return fmt.Sprintf("sa-%s-%d-%s", string(parentType), parentID, nid), nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/delete.go
app/api/controller/serviceaccount/delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // Delete deletes a service account. func (c *Controller) Delete(ctx context.Context, session *auth.Session, saUID string) error { sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) if err != nil { return err } // Ensure principal has required permissions on parent (ensures that parent exists) if err = apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, sa.ParentType, sa.ParentID, sa.UID, enum.PermissionServiceAccountDelete); err != nil { return err } return c.principalStore.DeleteServiceAccount(ctx, sa.ID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/find.go
app/api/controller/serviceaccount/find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // Find tries to find the provided service account. func (c *Controller) Find( ctx context.Context, session *auth.Session, saUID string, ) (*types.ServiceAccount, error) { sa, err := c.FindNoAuth(ctx, saUID) if err != nil { return nil, err } // Ensure principal has required permissions on parent (ensures that parent exists) if err = apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, sa.ParentType, sa.ParentID, sa.UID, enum.PermissionServiceAccountView); err != nil { return nil, err } return sa, nil } /* * FindNoAuth finds a service account without auth checks. * WARNING: Never call as part of user flow. */ func (c *Controller) FindNoAuth(ctx context.Context, saUID string) (*types.ServiceAccount, error) { return findServiceAccountFromUID(ctx, c.principalStore, saUID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/create_token.go
app/api/controller/serviceaccount/create_token.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" "fmt" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/token" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) type CreateTokenInput struct { // TODO [CODE-1363]: remove after identifier migration. UID string `json:"uid" deprecated:"true"` Identifier string `json:"identifier"` Lifetime *time.Duration `json:"lifetime"` } // CreateToken creates a new service account access token. func (c *Controller) CreateToken( ctx context.Context, session *auth.Session, saUID string, in *CreateTokenInput, ) (*types.TokenResponse, error) { if err := c.sanitizeCreateTokenInput(in); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) if err != nil { return nil, err } // Ensure principal has required permissions on parent (ensures that parent exists) if err = apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, sa.ParentType, sa.ParentID, sa.UID, enum.PermissionServiceAccountEdit); err != nil { return nil, err } token, jwtToken, err := token.CreateSAT( ctx, c.tokenStore, &session.Principal, sa, in.Identifier, in.Lifetime, ) if err != nil { return nil, err } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil } func (c *Controller) sanitizeCreateTokenInput(in *CreateTokenInput) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.UID } if err := check.Identifier(in.Identifier); err != nil { return err } //nolint:revive if err := check.TokenLifetime(in.Lifetime, true); err != nil { return err } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/delete_token.go
app/api/controller/serviceaccount/delete_token.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // DeleteToken deletes a token of a service account. func (c *Controller) DeleteToken( ctx context.Context, session *auth.Session, saUID string, identifier string, ) error { sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) if err != nil { return err } // Ensure principal has required permissions on parent (ensures that parent exists) if err = apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, sa.ParentType, sa.ParentID, sa.UID, enum.PermissionServiceAccountEdit); err != nil { return err } token, err := c.tokenStore.FindByIdentifier(ctx, sa.ID, identifier) if err != nil { return err } // Ensure sat belongs to service account if token.Type != enum.TokenTypeSAT || token.PrincipalID != sa.ID { log.Warn().Msg("Principal tried to delete token that doesn't belong to the service account") // throw a not found error - no need for user to know about token? return usererror.ErrNotFound } return c.tokenStore.Delete(ctx, token.ID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/controller.go
app/api/controller/serviceaccount/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" ) type Controller struct { principalUIDCheck check.PrincipalUID authorizer authz.Authorizer principalStore store.PrincipalStore spaceStore store.SpaceStore repoStore store.RepoStore tokenStore store.TokenStore } func NewController(principalUIDCheck check.PrincipalUID, authorizer authz.Authorizer, principalStore store.PrincipalStore, spaceStore store.SpaceStore, repoStore store.RepoStore, tokenStore store.TokenStore) *Controller { return &Controller{ principalUIDCheck: principalUIDCheck, authorizer: authorizer, principalStore: principalStore, spaceStore: spaceStore, repoStore: repoStore, tokenStore: tokenStore, } } func findServiceAccountFromUID(ctx context.Context, principalStore store.PrincipalStore, saUID string) (*types.ServiceAccount, error) { return principalStore.FindServiceAccountByUID(ctx, saUID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/serviceaccount/list_token.go
app/api/controller/serviceaccount/list_token.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package serviceaccount import ( "context" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListTokens lists all tokens of a service account. func (c *Controller) ListTokens(ctx context.Context, session *auth.Session, saUID string) ([]*types.Token, error) { sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) if err != nil { return nil, err } // Ensure principal has required permissions on parent (ensures that parent exists) if err = apiauth.CheckServiceAccount(ctx, c.authorizer, session, c.spaceStore, c.repoStore, sa.ParentType, sa.ParentID, sa.UID, enum.PermissionServiceAccountView); err != nil { return nil, err } return c.tokenStore.List(ctx, sa.ID, enum.TokenTypeSAT) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/wire.go
app/api/controller/trigger/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController( authorizer authz.Authorizer, triggerStore store.TriggerStore, pipelineStore store.PipelineStore, repoFinder refcache.RepoFinder, ) *Controller { return NewController(authorizer, triggerStore, pipelineStore, repoFinder) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/create.go
app/api/controller/trigger/create.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) // TODO: Add more as needed. type CreateInput struct { Description string `json:"description"` // TODO [CODE-1363]: remove after identifier migration. UID string `json:"uid" deprecated:"true"` Identifier string `json:"identifier"` Secret string `json:"secret"` Disabled bool `json:"disabled"` Actions []enum.TriggerAction `json:"actions"` } func (c *Controller) Create( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, in *CreateInput, ) (*types.Trigger, error) { if err := c.sanitizeCreateInput(in); err != nil { return nil, fmt.Errorf("invalid input: %w", err) } repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineEdit) if err != nil { return nil, err } pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier) if err != nil { return nil, fmt.Errorf("failed to find pipeline: %w", err) } now := time.Now().UnixMilli() trigger := &types.Trigger{ Description: in.Description, Disabled: in.Disabled, Secret: in.Secret, CreatedBy: session.Principal.ID, RepoID: repo.ID, Actions: deduplicateActions(in.Actions), Identifier: in.Identifier, PipelineID: pipeline.ID, Created: now, Updated: now, Version: 0, } err = c.triggerStore.Create(ctx, trigger) if err != nil { return nil, fmt.Errorf("trigger creation failed: %w", err) } return trigger, nil } func (c *Controller) sanitizeCreateInput(in *CreateInput) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.UID } if err := check.Description(in.Description); err != nil { return err } if err := checkSecret(in.Secret); err != nil { return err } if err := checkActions(in.Actions); err != nil { return err } if err := check.Identifier(in.Identifier); err != nil { //nolint:revive return err } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/delete.go
app/api/controller/trigger/delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) func (c *Controller) Delete( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, triggerIdentifier string, ) error { repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineEdit) if err != nil { return err } pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier) if err != nil { return fmt.Errorf("failed to find pipeline: %w", err) } err = c.triggerStore.DeleteByIdentifier(ctx, pipeline.ID, triggerIdentifier) if err != nil { return fmt.Errorf("could not delete trigger: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/find.go
app/api/controller/trigger/find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) Find( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, triggerIdentifier string, ) (*types.Trigger, error) { repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineView) if err != nil { return nil, err } pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier) if err != nil { return nil, fmt.Errorf("failed to find pipeline: %w", err) } trigger, err := c.triggerStore.FindByIdentifier(ctx, pipeline.ID, triggerIdentifier) if err != nil { return nil, fmt.Errorf("failed to find trigger %s: %w", triggerIdentifier, err) } return trigger, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/list.go
app/api/controller/trigger/list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) List( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, filter types.ListQueryFilter, ) ([]*types.Trigger, int64, error) { repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineView) if err != nil { return nil, 0, err } pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier) if err != nil { return nil, 0, fmt.Errorf("failed to find pipeline: %w", err) } count, err := c.triggerStore.Count(ctx, pipeline.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to count triggers in space: %w", err) } triggers, err := c.triggerStore.List(ctx, pipeline.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list triggers: %w", err) } return triggers, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/controller.go
app/api/controller/trigger/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type Controller struct { authorizer authz.Authorizer triggerStore store.TriggerStore pipelineStore store.PipelineStore repoFinder refcache.RepoFinder } func NewController( authorizer authz.Authorizer, triggerStore store.TriggerStore, pipelineStore store.PipelineStore, repoFinder refcache.RepoFinder, ) *Controller { return &Controller{ authorizer: authorizer, triggerStore: triggerStore, pipelineStore: pipelineStore, repoFinder: repoFinder, } } // getRepoCheckPipelineAccess fetches a repo, checks if the permission is allowed based on the repo state, // and checks if the current user has permission to access pipelines of the repo. // //nolint:unparam func (c *Controller) getRepoCheckPipelineAccess( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, reqPermission enum.Permission, allowedRepoStates ...enum.RepoState, ) (*types.RepositoryCore, error) { repo, err := c.repoFinder.FindByRef(ctx, repoRef) if err != nil { return nil, fmt.Errorf("failed to find repo by ref: %w", err) } if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil { return nil, err } err = apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path, pipelineIdentifier, reqPermission) if err != nil { return nil, fmt.Errorf("failed to authorize: %w", err) } return repo, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/update.go
app/api/controller/trigger/update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "context" "fmt" "strings" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) // UpdateInput is used for updating a trigger. type UpdateInput struct { Description *string `json:"description"` // TODO [CODE-1363]: remove after identifier migration. UID *string `json:"uid" deprecated:"true"` Identifier *string `json:"identifier"` Actions []enum.TriggerAction `json:"actions"` Secret *string `json:"secret"` Disabled *bool `json:"disabled"` // can be nil, so keeping it a pointer } func (c *Controller) Update( ctx context.Context, session *auth.Session, repoRef string, pipelineIdentifier string, triggerIdentifier string, in *UpdateInput, ) (*types.Trigger, error) { if err := c.sanitizeUpdateInput(in); err != nil { return nil, fmt.Errorf("invalid input: %w", err) } repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineEdit) if err != nil { return nil, err } pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier) if err != nil { return nil, fmt.Errorf("failed to find pipeline: %w", err) } trigger, err := c.triggerStore.FindByIdentifier(ctx, pipeline.ID, triggerIdentifier) if err != nil { return nil, fmt.Errorf("failed to find trigger: %w", err) } return c.triggerStore.UpdateOptLock(ctx, trigger, func(original *types.Trigger) error { if in.Identifier != nil { original.Identifier = *in.Identifier } if in.Description != nil { original.Description = *in.Description } if in.Actions != nil { original.Actions = deduplicateActions(in.Actions) } if in.Secret != nil { original.Secret = *in.Secret } if in.Disabled != nil { original.Disabled = *in.Disabled } return nil }) } func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == nil { in.Identifier = in.UID } if in.Identifier != nil { if err := check.Identifier(*in.Identifier); err != nil { return err } } if in.Description != nil { *in.Description = strings.TrimSpace(*in.Description) if err := check.Description(*in.Description); err != nil { return err } } if in.Secret != nil { if err := checkSecret(*in.Secret); err != nil { return err } } if in.Actions != nil { if err := checkActions(in.Actions); err != nil { return err } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/trigger/common.go
app/api/controller/trigger/common.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trigger import ( "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) const ( // triggerMaxSecretLength defines the max allowed length of a trigger secret. // TODO: Check whether this is sufficient for other SCM providers once we // add support. For now it's good to have a limit and increase if needed. triggerMaxSecretLength = 4096 ) // checkSecret validates the secret of a trigger. func checkSecret(secret string) error { if len(secret) > triggerMaxSecretLength { return check.NewValidationErrorf("The secret of a trigger can be at most %d characters long.", triggerMaxSecretLength) } return nil } // checkActions validates the trigger actions. func checkActions(actions []enum.TriggerAction) error { // ignore duplicates here, should be deduplicated later for _, action := range actions { if _, ok := action.Sanitize(); !ok { return check.NewValidationErrorf("The provided trigger action '%s' is invalid.", action) } } return nil } // deduplicateActions de-duplicates the actions provided by in the trigger. func deduplicateActions(in []enum.TriggerAction) []enum.TriggerAction { if len(in) == 0 { return []enum.TriggerAction{} } actionSet := make(map[enum.TriggerAction]struct{}) out := make([]enum.TriggerAction, 0, len(in)) for _, action := range in { if _, ok := actionSet[action]; ok { continue } actionSet[action] = struct{}{} out = append(out, action) } return out }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_value_define.go
app/api/controller/space/label_value_define.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // DefineLabelValue defines a new label value for the specified space and label. func (c *Controller) DefineLabelValue( ctx context.Context, session *auth.Session, spaceRef string, key string, in *types.DefineValueInput, ) (*types.LabelValue, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Find(ctx, &space.ID, nil, key) if err != nil { return nil, fmt.Errorf("failed to find repo label: %w", err) } value, err := c.labelSvc.DefineValue(ctx, session.Principal.ID, label.ID, in) if err != nil { return nil, fmt.Errorf("failed to create space label value: %w", err) } return value, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/import_repositories.go
app/api/controller/space/import_repositories.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "errors" "fmt" "time" "github.com/harness/gitness/app/api/controller/limiter" repoctrl "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/audit" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/rs/zerolog/log" ) type ImportRepositoriesInput struct { ProviderInput } type ImportRepositoriesOutput struct { ImportingRepos []*repoctrl.RepositoryOutput `json:"importing_repos"` } // ImportRepositories imports repositories into an existing space. // //nolint:gocognit func (c *Controller) ImportRepositories( ctx context.Context, session *auth.Session, spaceRef string, in *ImportRepositoriesInput, ) (ImportRepositoriesOutput, error) { space, err := c.getSpaceCheckAuthRepoCreation(ctx, session, spaceRef) if err != nil { return ImportRepositoriesOutput{}, err } remoteRepositories, provider, err := importer.LoadRepositoriesFromProviderSpace(ctx, in.Provider, in.ProviderSpace) if err != nil { return ImportRepositoriesOutput{}, err } if len(remoteRepositories) == 0 { return ImportRepositoriesOutput{}, usererror.BadRequestf("Found no repositories in %q", in.ProviderSpace) } repos := make([]*types.Repository, 0, len(remoteRepositories)) repoIDs := make([]int64, 0, len(remoteRepositories)) repoIsPublicVals := make([]bool, 0, len(remoteRepositories)) cloneURLs := make([]string, 0, len(remoteRepositories)) for _, remoteRepository := range remoteRepositories { repo, isPublic := remoteRepository.ToRepo( space.ID, space.Path, remoteRepository.Identifier, "", &session.Principal, ) if err := c.repoIdentifierCheck(repo.Identifier, session); err != nil { return ImportRepositoriesOutput{}, fmt.Errorf("failed to sanitize the repo %s: %w", repo.Identifier, err) } repos = append(repos, repo) repoIsPublicVals = append(repoIsPublicVals, isPublic) cloneURLs = append(cloneURLs, remoteRepository.CloneURL) } err = c.tx.WithTx(ctx, func(ctx context.Context) error { // lock the space for update during repo creation to prevent racing conditions with space soft delete. _, err = c.spaceStore.FindForUpdate(ctx, space.ID) if err != nil { return fmt.Errorf("failed to find the parent space: %w", err) } if err := c.resourceLimiter.RepoCount( ctx, space.ID, len(remoteRepositories)); err != nil { return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } for _, repo := range repos { err = c.repoStore.Create(ctx, repo) if errors.Is(err, store.ErrDuplicate) { return fmt.Errorf("failed to create duplicate repo %s", repo.Identifier) } else if err != nil { return fmt.Errorf("failed to create repository in storage: %w", err) } repoIDs = append(repoIDs, repo.ID) } if len(repoIDs) == 0 { return nil } jobGroupID := fmt.Sprintf("space-import-%d", space.ID) err = c.importer.RunMany(ctx, jobGroupID, provider, repoIDs, repoIsPublicVals, cloneURLs, in.Pipelines, ) if err != nil { return fmt.Errorf("failed to start import repository jobs: %w", err) } return nil }) if err != nil { return ImportRepositoriesOutput{}, err } reposOut := make([]*repoctrl.RepositoryOutput, len(repos)) for i, repo := range repos { reposOut[i], err = repoctrl.GetRepoOutputWithAccess(ctx, c.repoFinder, false, repo) if err != nil { return ImportRepositoriesOutput{}, fmt.Errorf("failed to get repo output: %w", err) } err = c.auditService.Log(ctx, session.Principal, audit.NewResource(audit.ResourceTypeRepository, repo.Identifier), audit.ActionCreated, paths.Parent(repo.Path), audit.WithNewObject(audit.RepositoryObject{ Repository: *repo, IsPublic: false, // in import we configure public access and create a new audit log. }), ) if err != nil { log.Warn().Msgf("failed to insert audit log for import repository operation: %s", err) } err = c.instrumentation.Track(ctx, instrument.Event{ Type: instrument.EventTypeRepositoryCreate, Principal: session.Principal.ToPrincipalInfo(), Timestamp: time.Now(), Path: space.Path, Properties: map[instrument.Property]any{ instrument.PropertyRepositoryID: repo.ID, instrument.PropertyRepositoryName: repo.Identifier, instrument.PropertyRepositoryCreationType: instrument.CreationTypeImport, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for import repository operation: %s", err) } } return ImportRepositoriesOutput{ImportingRepos: reposOut}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/wire.go
app/api/controller/space/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/exporter" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/importer" infraprovider2 "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/app/services/space" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController(config *types.Config, tx dbtx.Transactor, urlProvider url.Provider, sseStreamer sse.Streamer, identifierCheck check.SpaceIdentifier, authorizer authz.Authorizer, spacePathStore store.SpacePathStore, pipelineStore store.PipelineStore, secretStore store.SecretStore, connectorStore store.ConnectorStore, templateStore store.TemplateStore, spaceStore store.SpaceStore, repoStore store.RepoStore, principalStore store.PrincipalStore, repoCtrl *repo.Controller, membershipStore store.MembershipStore, prListService *pullreq.ListService, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, importer *importer.JobRepository, exporter *exporter.Repository, limiter limiter.ResourceLimiter, publicAccess publicaccess.Service, auditService audit.Service, gitspaceService *gitspace.Service, labelSvc *label.Service, instrumentation instrument.Service, executionStore store.ExecutionStore, rulesSvc *rules.Service, usageMetricStore store.UsageMetricStore, repoIdentifierCheck check.RepoIdentifier, infraProviderSvc *infraprovider2.Service, favoriteStore store.FavoriteStore, spaceSvc *space.Service, ) *Controller { return NewController(config, tx, urlProvider, sseStreamer, identifierCheck, authorizer, spacePathStore, pipelineStore, secretStore, connectorStore, templateStore, spaceStore, repoStore, principalStore, repoCtrl, membershipStore, prListService, spaceFinder, repoFinder, importer, exporter, limiter, publicAccess, auditService, gitspaceService, labelSvc, instrumentation, executionStore, rulesSvc, usageMetricStore, repoIdentifierCheck, infraProviderSvc, favoriteStore, spaceSvc, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_value_delete.go
app/api/controller/space/label_value_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // DeleteLabelValue deletes a label value for the specified space. func (c *Controller) DeleteLabelValue( ctx context.Context, session *auth.Session, spaceRef string, key string, value string, ) error { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return fmt.Errorf("failed to acquire access to space: %w", err) } if err := c.labelSvc.DeleteValue(ctx, &space.ID, nil, key, value); err != nil { return fmt.Errorf("failed to delete space label value: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/create.go
app/api/controller/space/create.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "strconv" "strings" "time" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) var ( errParentIDNegative = usererror.BadRequest( "Parent ID has to be either zero for a root space or greater than zero for a child space.") ) type CreateInput struct { ParentRef string `json:"parent_ref"` // TODO [CODE-1363]: remove after identifier migration. UID string `json:"uid" deprecated:"true"` Identifier string `json:"identifier"` Description string `json:"description"` IsPublic bool `json:"is_public"` } // Create creates a new space. // //nolint:gocognit // refactor if required func (c *Controller) Create( ctx context.Context, session *auth.Session, in *CreateInput, ) (*SpaceOutput, error) { if err := c.sanitizeCreateInput(in); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } parentSpace, err := c.getSpaceCheckAuthSpaceCreation(ctx, session, in.ParentRef) if err != nil { return nil, err } isPublicAccessSupported, err := c.publicAccess. IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentSpace.Path) if err != nil { return nil, fmt.Errorf( "failed to check if public access is supported for parent space %q: %w", parentSpace.Path, err, ) } if in.IsPublic && !isPublicAccessSupported { return nil, errPublicSpaceCreationDisabled } var space *types.Space err = c.tx.WithTx(ctx, func(ctx context.Context) error { space, err = c.createSpaceInnerInTX(ctx, session, parentSpace.ID, in) return err }) if err != nil { return nil, err } err = c.publicAccess.Set(ctx, enum.PublicResourceTypeSpace, space.Path, in.IsPublic) if err != nil { if dErr := c.publicAccess.Delete(ctx, enum.PublicResourceTypeSpace, space.Path); dErr != nil { return nil, fmt.Errorf("failed to set space public access (and public access cleanup: %w): %w", dErr, err) } // only cleanup space itself if cleanup of public access succeeded or we risk leaking public access if dErr := c.PurgeNoAuth(ctx, session, space); dErr != nil { return nil, fmt.Errorf("failed to set space public access (and space purge: %w): %w", dErr, err) } return nil, fmt.Errorf("failed to set space public access (successful cleanup): %w", err) } return GetSpaceOutput(ctx, c.publicAccess, space) } func (c *Controller) createSpaceInnerInTX( ctx context.Context, session *auth.Session, parentID int64, in *CreateInput, ) (*types.Space, error) { spacePath := in.Identifier if parentID > 0 { // (re-)read parent path in transaction to ensure correctness parentPath, err := c.spacePathStore.FindPrimaryBySpaceID(ctx, parentID) if err != nil { return nil, fmt.Errorf("failed to find primary path for parent '%d': %w", parentID, err) } spacePath = paths.Concatenate(parentPath.Value, in.Identifier) // ensure path is within accepted depth! err = check.PathDepth(spacePath, true) if err != nil { return nil, fmt.Errorf("path is invalid: %w", err) } } now := time.Now().UnixMilli() space := &types.Space{ Version: 0, ParentID: parentID, Identifier: in.Identifier, Description: in.Description, Path: spacePath, CreatedBy: session.Principal.ID, Created: now, Updated: now, } err := c.spaceStore.Create(ctx, space) if err != nil { return nil, fmt.Errorf("space creation failed: %w", err) } pathSegment := &types.SpacePathSegment{ Identifier: space.Identifier, IsPrimary: true, SpaceID: space.ID, ParentID: parentID, CreatedBy: space.CreatedBy, Created: now, Updated: now, } err = c.spacePathStore.InsertSegment(ctx, pathSegment) if err != nil { return nil, fmt.Errorf("failed to insert primary path segment: %w", err) } // add space membership to top level space only (as the user doesn't have inherited permissions already) if parentID == 0 { membership := &types.Membership{ MembershipKey: types.MembershipKey{ SpaceID: space.ID, PrincipalID: session.Principal.ID, }, Role: enum.MembershipRoleSpaceOwner, // membership has been created by the system CreatedBy: bootstrap.NewSystemServiceSession().Principal.ID, Created: now, Updated: now, } err = c.membershipStore.Create(ctx, membership) if err != nil { return nil, fmt.Errorf("failed to make user owner of the space: %w", err) } } return space, nil } func (c *Controller) sanitizeCreateInput(in *CreateInput) error { // TODO [CODE-1363]: remove after identifier migration. if in.Identifier == "" { in.Identifier = in.UID } if len(in.ParentRef) > 0 && !c.nestedSpacesEnabled { // TODO (Nested Spaces): Remove once support is added return errNestedSpacesNotSupported } parentRefAsID, err := strconv.ParseInt(in.ParentRef, 10, 64) if err == nil && parentRefAsID < 0 { return errParentIDNegative } isRoot := (err == nil && parentRefAsID == 0) || (len(strings.TrimSpace(in.ParentRef)) == 0) if err := c.identifierCheck(in.Identifier, isRoot); err != nil { return err } in.Description = strings.TrimSpace(in.Description) if err := check.Description(in.Description); err != nil { //nolint:revive return err } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_update.go
app/api/controller/space/label_update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateLabel updates a label for the specified space. func (c *Controller) UpdateLabel( ctx context.Context, session *auth.Session, spaceRef string, key string, in *types.UpdateLabelInput, ) (*types.Label, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Update(ctx, session.Principal.ID, &space.ID, nil, key, in) if err != nil { return nil, fmt.Errorf("failed to update space label: %w", err) } return label, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_connectors.go
app/api/controller/space/list_connectors.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListConnectors lists the connectors in a space. func (c *Controller) ListConnectors( ctx context.Context, session *auth.Session, spaceRef string, filter types.ListQueryFilter, ) ([]*types.Connector, int64, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, 0, fmt.Errorf("failed to find parent space: %w", err) } err = apiauth.CheckConnector( ctx, c.authorizer, session, space.Path, "", enum.PermissionConnectorView, ) if err != nil { return nil, 0, fmt.Errorf("could not authorize: %w", err) } count, err := c.connectorStore.Count(ctx, space.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to count connectors in space: %w", err) } connectors, err := c.connectorStore.List(ctx, space.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list connectors: %w", err) } return connectors, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_pipelines.go
app/api/controller/space/list_pipelines.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListPipelines lists the pipelines in a space. func (c *Controller) ListPipelines( ctx context.Context, session *auth.Session, spaceRef string, filter types.ListPipelinesFilter, ) ([]*types.Pipeline, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionPipelineView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } var count int64 var pipelines []*types.Pipeline err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { pipelines, err = c.pipelineStore.ListInSpace(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to list pipelines in space: %w", err) } pipelineIDs := make([]int64, len(pipelines)) for i, pipeline := range pipelines { pipelineIDs[i] = pipeline.ID } execs, err := c.executionStore.ListByPipelineIDs(ctx, pipelineIDs, filter.LastExecutions) if err != nil { return fmt.Errorf("failed to list executions by pipeline IDs: %w", err) } for _, pipeline := range pipelines { pipeline.LastExecutions = execs[pipeline.ID] } if filter.Page == 1 && len(pipelines) < filter.Size { count = int64(len(pipelines)) return nil } count, err = c.pipelineStore.CountInSpace(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to count pipelines in space: %w", err) } return }, dbtx.TxDefaultReadOnly) if err != nil { return pipelines, count, fmt.Errorf("failed to list pipelines in space: %w", err) } return pipelines, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/helper.go
app/api/controller/space/helper.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // GetSpaceCheckAuth checks whether the user has the requested permission on the provided space and returns the space. func GetSpaceCheckAuth( ctx context.Context, spaceFinder refcache.SpaceFinder, authorizer authz.Authorizer, session *auth.Session, spaceRef string, permission enum.Permission, ) (*types.SpaceCore, error) { space, err := spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, fmt.Errorf("parent space not found: %w", err) } err = apiauth.CheckSpace(ctx, authorizer, session, space, permission) if err != nil { return nil, fmt.Errorf("auth check failed: %w", err) } return space, nil } func GetSpaceOutput( ctx context.Context, publicAccess publicaccess.Service, space *types.Space, ) (*SpaceOutput, error) { isPublic, err := publicAccess.Get(ctx, enum.PublicResourceTypeSpace, space.Path) if err != nil { return nil, fmt.Errorf("failed to get resource public access mode: %w", err) } return &SpaceOutput{ Space: *space, IsPublic: isPublic, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/rule_find.go
app/api/controller/space/rule_find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleFind returns the protection rule by identifier. func (c *Controller) RuleFind(ctx context.Context, session *auth.Session, spaceRef string, identifier string, ) (*types.Rule, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } rule, err := c.rulesSvc.Find(ctx, enum.RuleParentSpace, space.ID, identifier) if err != nil { return nil, fmt.Errorf("failed to find space-level protection rule by identifier: %w", err) } return rule, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_value_update.go
app/api/controller/space/label_value_update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // UpdateLabelValue updates a label value for the specified space and label. func (c *Controller) UpdateLabelValue( ctx context.Context, session *auth.Session, spaceRef string, key string, value string, in *types.UpdateValueInput, ) (*types.LabelValue, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } label, err := c.labelSvc.Find(ctx, &space.ID, nil, key) if err != nil { return nil, fmt.Errorf("failed to find space label: %w", err) } labelValue, err := c.labelSvc.UpdateValue( ctx, session.Principal.ID, label.ID, value, in) if err != nil { return nil, fmt.Errorf("failed to update space label value: %w", err) } return labelValue, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/restore.go
app/api/controller/space/restore.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "errors" "fmt" "math" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) type RestoreInput struct { NewIdentifier *string `json:"new_identifier,omitempty"` NewParentRef *string `json:"new_parent_ref,omitempty"` // Reference of the new parent space } var errSpacePathInvalid = usererror.BadRequest("Space ref or identifier is invalid.") func (c *Controller) Restore( ctx context.Context, session *auth.Session, spaceRef string, deletedAt int64, in *RestoreInput, ) (*SpaceOutput, error) { if err := c.sanitizeRestoreInput(in); err != nil { return nil, fmt.Errorf("failed to sanitize restore input: %w", err) } space, err := c.spaceStore.FindByRefAndDeletedAt(ctx, spaceRef, deletedAt) if err != nil { return nil, fmt.Errorf("failed to find the space: %w", err) } // check view permission on the original ref. err = apiauth.CheckSpace(ctx, c.authorizer, session, space.Core(), enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to authorize on space restore: %w", err) } parentSpace, err := c.getParentSpace(ctx, space, in.NewParentRef) if err != nil { return nil, fmt.Errorf("failed to get space parent: %w", err) } // check create permissions within the parent space scope. if err = apiauth.CheckSpaceScope( ctx, c.authorizer, session, parentSpace.Core(), enum.ResourceTypeSpace, enum.PermissionSpaceEdit, ); err != nil { return nil, fmt.Errorf("authorization failed on space restore: %w", err) } spacePath := paths.Concatenate(parentSpace.Path, space.Identifier) if in.NewIdentifier != nil { spacePath = paths.Concatenate(parentSpace.Path, *in.NewIdentifier) } err = c.tx.WithTx(ctx, func(ctx context.Context) error { space, err = c.restoreSpaceInnerInTx( ctx, space, deletedAt, in.NewIdentifier, &parentSpace.ID, spacePath) return err }) if err != nil { return nil, fmt.Errorf("failed to restore space in a tnx: %w", err) } // restored spaces will be private since public access data has deleted upon deletion. return &SpaceOutput{ Space: *space, IsPublic: false, }, nil } func (c *Controller) restoreSpaceInnerInTx( ctx context.Context, space *types.Space, deletedAt int64, newIdentifier *string, newParentID *int64, spacePath string, ) (*types.Space, error) { // restore the target space restoredSpace, err := c.restoreNoAuth(ctx, space, newIdentifier, newParentID) if err != nil { return nil, fmt.Errorf("failed to restore space: %w", err) } if err = check.PathDepth(restoredSpace.Path, true); err != nil { return nil, fmt.Errorf("path is invalid: %w", err) } repoCount, err := c.repoStore.Count( ctx, space.ID, &types.RepoFilter{DeletedAt: &deletedAt, Recursive: true}, ) if err != nil { return nil, fmt.Errorf("failed to count repos in space recursively: %w", err) } if err := c.resourceLimiter.RepoCount(ctx, space.ID, int(repoCount)); err != nil { return nil, fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached) } filter := &types.SpaceFilter{ Page: 1, Size: math.MaxInt, Query: "", Order: enum.OrderDesc, Sort: enum.SpaceAttrCreated, DeletedAt: &deletedAt, Recursive: true, } subSpaces, err := c.spaceStore.List(ctx, space.ID, filter) if err != nil { return nil, fmt.Errorf("failed to list space sub spaces recursively: %w", err) } var subspacePath string for _, subspace := range subSpaces { // check the path depth before restore nested subspaces. subspacePath = subspace.Path[len(space.Path):] if err = check.PathDepth(paths.Concatenate(spacePath, subspacePath), true); err != nil { return nil, fmt.Errorf("path is invalid: %w", err) } // identifier and parent ID of sub spaces shouldn't change. _, err = c.restoreNoAuth(ctx, subspace, nil, nil) if err != nil { return nil, fmt.Errorf("failed to restore subspace: %w", err) } } if err := c.restoreRepositoriesNoAuth(ctx, space.ID, deletedAt); err != nil { return nil, fmt.Errorf("failed to restore space repositories: %w", err) } return restoredSpace, nil } func (c *Controller) restoreNoAuth( ctx context.Context, space *types.Space, newIdentifier *string, newParentID *int64, ) (*types.Space, error) { space, err := c.spaceStore.Restore(ctx, space, newIdentifier, newParentID) if err != nil { return nil, fmt.Errorf("failed to restore the space: %w", err) } now := time.Now().UnixMilli() pathSegment := &types.SpacePathSegment{ Identifier: space.Identifier, IsPrimary: true, SpaceID: space.ID, ParentID: space.ParentID, CreatedBy: space.CreatedBy, Created: now, Updated: now, } err = c.spacePathStore.InsertSegment(ctx, pathSegment) if errors.Is(err, store.ErrDuplicate) { return nil, usererror.BadRequest(fmt.Sprintf("A primary path already exists for %s.", space.Identifier)) } if err != nil { return nil, fmt.Errorf("failed to insert space path on restore: %w", err) } return space, nil } func (c *Controller) restoreRepositoriesNoAuth( ctx context.Context, spaceID int64, deletedAt int64, ) error { filter := &types.RepoFilter{ Page: 1, Size: int(math.MaxInt), Query: "", Order: enum.OrderAsc, Sort: enum.RepoAttrNone, DeletedAt: &deletedAt, Recursive: true, } repos, err := c.repoStore.List(ctx, spaceID, filter) if err != nil { return fmt.Errorf("failed to list space repositories: %w", err) } for _, repo := range repos { _, err = c.repoCtrl.RestoreNoAuth(ctx, repo, nil, repo.ParentID) if err != nil { return fmt.Errorf("failed to restore repository: %w", err) } } return nil } func (c *Controller) getParentSpace( ctx context.Context, space *types.Space, newParentRef *string, ) (*types.Space, error) { var parentSpace *types.Space var err error if newParentRef == nil { if space.ParentID == 0 { return &types.Space{}, nil } parentSpace, err = c.spaceStore.Find(ctx, space.ParentID) if err != nil { return nil, fmt.Errorf("failed to find the space parent %d", space.ParentID) } return parentSpace, nil } // the provided new reference for space parent must exist. parentSpace, err = c.spaceStore.FindByRef(ctx, *newParentRef) if err != nil { return nil, fmt.Errorf("failed to find the parent space by ref '%s': %w - returning usererror %w", *newParentRef, err, errSpacePathInvalid) } return parentSpace, nil } func (c *Controller) sanitizeRestoreInput(in *RestoreInput) error { if in.NewParentRef == nil { return nil } if len(*in.NewParentRef) > 0 && !c.nestedSpacesEnabled { return errNestedSpacesNotSupported } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/move.go
app/api/controller/space/move.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // MoveInput is used for moving a space. type MoveInput struct { // TODO [CODE-1363]: remove after identifier migration. UID *string `json:"uid" deprecated:"true"` Identifier *string `json:"identifier"` // ParentRef can be either a space ID or space path ParentRef *string `json:"parent_ref"` } func (i *MoveInput) hasChanges( space *types.Space, currentParentSpace *types.SpaceCore, targetParentSpace *types.SpaceCore, ) bool { if i.Identifier != nil && *i.Identifier != space.Identifier { return true } if i.ParentRef != nil && targetParentSpace.ID != currentParentSpace.ID { return true } return false } // Move moves a space to a new identifier. // //nolint:gocognit // refactor if needed func (c *Controller) Move( ctx context.Context, session *auth.Session, spaceRef string, in *MoveInput, ) (*SpaceOutput, error) { spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if err = c.sanitizeMoveInput(in, spaceCore.ParentID == 0); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } space, err := c.spaceStore.Find(ctx, spaceCore.ID) if err != nil { return nil, fmt.Errorf("failed to find space by ID: %w", err) } currentParentSpace, err := c.spaceFinder.FindByID(ctx, space.ParentID) if err != nil { return nil, fmt.Errorf("failed to find current parent space: %w", err) } targetParentSpace := currentParentSpace if in.ParentRef != nil { targetParentSpace, err = c.getSpaceCheckAuthSpaceCreation(ctx, session, *in.ParentRef) if err != nil { return nil, fmt.Errorf("failed to access target parent space: %w", err) } } // exit early if there are no changes if !in.hasChanges(space, currentParentSpace, targetParentSpace) { return GetSpaceOutput(ctx, c.publicAccess, space) } if err = c.spaceSvc.MoveNoAuth( ctx, session, space, in.Identifier, targetParentSpace.Path, ); err != nil { return nil, err } return GetSpaceOutput(ctx, c.publicAccess, space) } func (c *Controller) sanitizeMoveInput(in *MoveInput, isRoot bool) error { if in.Identifier == nil { in.Identifier = in.UID } if in.Identifier != nil { if err := c.identifierCheck(*in.Identifier, isRoot); err != nil { return err } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_value_list.go
app/api/controller/space/label_value_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListLabelValues lists all label values defined in the specified space. func (c *Controller) ListLabelValues( ctx context.Context, session *auth.Session, spaceRef string, key string, filter types.ListQueryFilter, ) ([]*types.LabelValue, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } values, count, err := c.labelSvc.ListValues(ctx, &space.ID, nil, key, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list space label values: %w", err) } return values, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/soft_delete.go
app/api/controller/space/soft_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "time" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type SoftDeleteResponse struct { DeletedAt int64 `json:"deleted_at"` } // SoftDelete marks deleted timestamp for the space and all its subspaces and repositories inside. func (c *Controller) SoftDelete( ctx context.Context, session *auth.Session, spaceRef string, ) (*SoftDeleteResponse, error) { spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceDelete) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } space, err := c.spaceStore.Find(ctx, spaceCore.ID) if err != nil { return nil, fmt.Errorf("failed to find space by ID: %w", err) } return c.SoftDeleteNoAuth(ctx, session, space) } // SoftDeleteNoAuth soft deletes the space - no authorization is verified. // WARNING For internal calls only. func (c *Controller) SoftDeleteNoAuth( ctx context.Context, session *auth.Session, space *types.Space, ) (*SoftDeleteResponse, error) { err := c.publicAccess.Delete(ctx, enum.PublicResourceTypeSpace, space.Path) if err != nil { return nil, fmt.Errorf("failed to delete public access for space: %w", err) } var deletedAt int64 err = c.tx.WithTx(ctx, func(ctx context.Context) error { _, err := c.spaceStore.FindForUpdate(ctx, space.ID) if err != nil { return fmt.Errorf("failed to lock the space for update: %w", err) } deletedAt = time.Now().UnixMilli() err = c.spaceSvc.SoftDeleteInner(ctx, session, space, deletedAt) return err }) if err != nil { return nil, fmt.Errorf("failed to soft delete the space: %w", err) } c.spaceFinder.MarkChanged(ctx, space.Core()) return &SoftDeleteResponse{DeletedAt: deletedAt}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/purge.go
app/api/controller/space/purge.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "math" "time" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/contextutil" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // Purge deletes the space and all its subspaces and repositories permanently. func (c *Controller) Purge( ctx context.Context, session *auth.Session, spaceRef string, deletedAt int64, ) error { space, err := c.spaceStore.FindByRefAndDeletedAt(ctx, spaceRef, deletedAt) if err != nil { return err } // authz will check the permission within the first existing parent since space was deleted. // purge top level space is limited to admin only. err = apiauth.CheckSpace(ctx, c.authorizer, session, space.Core(), enum.PermissionSpaceDelete) if err != nil { return fmt.Errorf("failed to authorize on space purge: %w", err) } return c.PurgeNoAuth(ctx, session, space) } // PurgeNoAuth purges the space - no authorization is verified. // WARNING For internal calls only. func (c *Controller) PurgeNoAuth( ctx context.Context, session *auth.Session, space *types.Space, ) error { // the max time we give a purge space to succeed const timeout = 15 * time.Minute // create new, time-restricted context to guarantee space purge completion, even if request is canceled. ctx, cancel := contextutil.WithNewTimeout(ctx, timeout) defer cancel() var toBeDeletedRepos []*types.Repository var err error err = c.tx.WithTx(ctx, func(ctx context.Context) error { toBeDeletedRepos, err = c.purgeSpaceInnerInTx(ctx, space.ID, *space.Deleted) return err }) if err != nil { return fmt.Errorf("failed to purge space %d in a tnx: %w", space.ID, err) } // permanently purge all repositories in the space and its subspaces after successful space purge tnx. // cleanup will handle failed repository deletions. for _, repo := range toBeDeletedRepos { err := c.repoCtrl.DeleteGitRepository(ctx, session, repo.GitUID) if err != nil { log.Ctx(ctx).Warn().Err(err). Str("repo_identifier", repo.Identifier). Int64("repo_id", repo.ID). Int64("repo_parent_id", repo.ParentID). Msg("failed to delete repository") } } return nil } func (c *Controller) purgeSpaceInnerInTx( ctx context.Context, spaceID int64, deletedAt int64, ) ([]*types.Repository, error) { filter := &types.RepoFilter{ Page: 1, Size: int(math.MaxInt), Query: "", Order: enum.OrderAsc, Sort: enum.RepoAttrDeleted, DeletedBeforeOrAt: &deletedAt, Recursive: true, } repos, err := c.repoStore.List(ctx, spaceID, filter) if err != nil { return nil, fmt.Errorf("failed to list space repositories: %w", err) } // purge cascade deletes all the child spaces from DB. err = c.spaceStore.Purge(ctx, spaceID, &deletedAt) if err != nil { return nil, fmt.Errorf("spaceStore failed to delete space %d: %w", spaceID, err) } return repos, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/rule_create.go
app/api/controller/space/rule_create.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleCreate creates a new protection rule for a space. func (c *Controller) RuleCreate(ctx context.Context, session *auth.Session, spaceRef string, in *rules.CreateInput, ) (*types.Rule, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } rule, err := c.rulesSvc.Create( ctx, &session.Principal, enum.RuleParentSpace, space.ID, space.Identifier, space.Path, in, ) if err != nil { return nil, fmt.Errorf("failed to create space-level protection rule: %w", err) } return rule, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/membership_update.go
app/api/controller/space/membership_update.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type MembershipUpdateInput struct { Role enum.MembershipRole `json:"role"` } func (in *MembershipUpdateInput) Validate() error { if in.Role == "" { return usererror.BadRequest("Role must be provided") } role, ok := in.Role.Sanitize() if !ok { msg := fmt.Sprintf("Provided role '%s' is not suppored. Valid values are: %v", in.Role, enum.MembershipRoles) return usererror.BadRequest(msg) } in.Role = role return nil } // MembershipUpdate changes the role of an existing membership. func (c *Controller) MembershipUpdate(ctx context.Context, session *auth.Session, spaceRef string, userUID string, in *MembershipUpdateInput, ) (*types.MembershipUser, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } err = in.Validate() if err != nil { return nil, err } user, err := c.principalStore.FindUserByUID(ctx, userUID) if err != nil { return nil, fmt.Errorf("failed to find user by uid: %w", err) } membership, err := c.membershipStore.FindUser(ctx, types.MembershipKey{ SpaceID: space.ID, PrincipalID: user.ID, }) if err != nil { return nil, fmt.Errorf("failed to find membership for update: %w", err) } if membership.Role == in.Role { return membership, nil } membership.Role = in.Role err = c.membershipStore.Update(ctx, &membership.Membership) if err != nil { return nil, fmt.Errorf("failed to update membership") } return membership, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_secrets.go
app/api/controller/space/list_secrets.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListSecrets lists the secrets in a space. func (c *Controller) ListSecrets( ctx context.Context, session *auth.Session, spaceRef string, filter types.ListQueryFilter, ) ([]*types.Secret, int64, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, 0, fmt.Errorf("failed to find parent space: %w", err) } err = apiauth.CheckSecret( ctx, c.authorizer, session, space.Path, "", enum.PermissionSecretView, ) if err != nil { return nil, 0, fmt.Errorf("could not authorize: %w", err) } var count int64 var secrets []*types.Secret err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { count, err = c.secretStore.Count(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to count child executions: %w", err) } secrets, err = c.secretStore.List(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to list child executions: %w", err) } return }, dbtx.TxDefaultReadOnly) if err != nil { return secrets, count, fmt.Errorf("failed to list secrets: %w", err) } return secrets, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_repositories.go
app/api/controller/space/list_repositories.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" repoCtrl "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListRepositories lists the repositories of a space. func (c *Controller) ListRepositories( ctx context.Context, session *auth.Session, spaceRef string, filter *types.RepoFilter, ) ([]*repoCtrl.RepositoryOutput, int64, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, 0, err } if err = apiauth.CheckSpaceScope( ctx, c.authorizer, session, space, enum.ResourceTypeRepo, enum.PermissionRepoView, ); err != nil { return nil, 0, err } return c.ListRepositoriesNoAuth(ctx, session.Principal.ID, space.ID, filter) } // ListRepositoriesNoAuth list repositories WITHOUT checking for PermissionRepoView. func (c *Controller) ListRepositoriesNoAuth( ctx context.Context, principalID int64, spaceID int64, filter *types.RepoFilter, ) ([]*repoCtrl.RepositoryOutput, int64, error) { var ( repos []*types.Repository count int64 ) err := c.tx.WithTx(ctx, func(ctx context.Context) (err error) { count, err = c.repoStore.Count(ctx, spaceID, filter) if err != nil { return fmt.Errorf("failed to count child repos for space %d: %w", spaceID, err) } repos, err = c.repoStore.List(ctx, spaceID, filter) if err != nil { return fmt.Errorf("failed to list child repos for space %d: %w", spaceID, err) } return nil }, dbtx.TxDefaultReadOnly) if err != nil { return nil, 0, err } if len(repos) == 0 { return []*repoCtrl.RepositoryOutput{}, 0, nil } favoritesMap := make(map[int64]bool) // We will initialize favoritesMap only in the case when favorites filter is not applied // and use the session's principal id in the case to populate the favoritesMap. // TODO: [CODE-4005] fix the filters to either add OnlyFavorites as boolean or use OnlyFavoritesFor everywhere. if filter.OnlyFavoritesFor == nil { // Get repo IDs repoIDs := make([]int64, len(repos)) for i, repo := range repos { repoIDs[i] = repo.ID } // Get favorites favoritesMap, err = c.favoriteStore.Map(ctx, principalID, enum.ResourceTypeRepo, repoIDs) if err != nil { return nil, 0, fmt.Errorf("fetch favorite repos for principal %d failed: %w", principalID, err) } } reposOut := make([]*repoCtrl.RepositoryOutput, len(repos)) for idx, repo := range repos { // backfill URLs repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) repoOut, err := repoCtrl.GetRepoOutput(ctx, c.publicAccess, c.repoFinder, repo) if err != nil { return nil, 0, fmt.Errorf("failed to get repo %q output: %w", repo.Path, err) } // We will populate the IsFavorite as true if the favorites filter is applied // otherwise take the value out from the favoritesMap. repoOut.IsFavorite = filter.OnlyFavoritesFor != nil || favoritesMap[repo.ID] reposOut[idx] = repoOut } return reposOut, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/find.go
app/api/controller/space/find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // Find finds a space. func (c *Controller) Find(ctx context.Context, session *auth.Session, spaceRef string) (*SpaceOutput, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } spaceFull, err := c.spaceStore.Find(ctx, space.ID) if err != nil { return nil, fmt.Errorf("failed to find space by ID: %w", err) } return GetSpaceOutput(ctx, c.publicAccess, spaceFull) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_find.go
app/api/controller/space/label_find.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // FindLabel finds a label for the specified space. func (c *Controller) FindLabel( ctx context.Context, session *auth.Session, spaceRef string, key string, includeValues bool, ) (*types.LabelWithValues, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } var labelWithValues *types.LabelWithValues if includeValues { labelWithValues, err = c.labelSvc.FindWithValues(ctx, &space.ID, nil, key) if err != nil { return nil, fmt.Errorf("failed to find space label with values: %w", err) } } else { label, err := c.labelSvc.Find(ctx, &space.ID, nil, key) if err != nil { return nil, fmt.Errorf("failed to find space label: %w", err) } labelWithValues = &types.LabelWithValues{ Label: *label, } } return labelWithValues, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/export_progress.go
app/api/controller/space/export_progress.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/exporter" "github.com/harness/gitness/job" "github.com/harness/gitness/types/enum" "github.com/pkg/errors" ) type ExportProgressOutput struct { Repos []job.Progress `json:"repos"` } // ExportProgress returns progress of the export job. func (c *Controller) ExportProgress(ctx context.Context, session *auth.Session, spaceRef string, ) (ExportProgressOutput, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return ExportProgressOutput{}, fmt.Errorf("failed to acquire access to space: %w", err) } progress, err := c.exporter.GetProgressForSpace(ctx, space.ID) if errors.Is(err, exporter.ErrNotFound) { return ExportProgressOutput{}, usererror.NotFound("No recent or ongoing export found for space.") } if err != nil { return ExportProgressOutput{}, fmt.Errorf("failed to retrieve export progress: %w", err) } return ExportProgressOutput{Repos: progress}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/rule_list.go
app/api/controller/space/rule_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // RuleList returns protection rules for a repository. func (c *Controller) RuleList(ctx context.Context, session *auth.Session, spaceRef string, inherited bool, filter *types.RuleFilter, ) ([]types.Rule, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } list, count, err := c.rulesSvc.List(ctx, space.ID, enum.RuleParentSpace, inherited, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list space-level protection rules: %w", err) } return list, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/pr_count.go
app/api/controller/space/pr_count.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // CountPullReqs returns the number of pull requests from the provided space that matches the criteria. func (c *Controller) CountPullReqs( ctx context.Context, session *auth.Session, spaceRef string, includeSubspaces bool, filter *types.PullReqFilter, ) (int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return 0, fmt.Errorf("failed to acquire access to space: %w", err) } count, err := c.prListService.CountForSpace(ctx, space, includeSubspaces, filter) if err != nil { return 0, fmt.Errorf("failed to fetch pull requests from space: %w", err) } return count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_list.go
app/api/controller/space/label_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListLabels lists all labels defined for the specified space. func (c *Controller) ListLabels( ctx context.Context, session *auth.Session, spaceRef string, filter *types.LabelFilter, ) ([]*types.Label, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } labels, total, err := c.labelSvc.List(ctx, &space.ID, nil, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list space labels: %w", err) } return labels, total, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_delete.go
app/api/controller/space/label_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // DeleteLabel deletes a label for the specified space. func (c *Controller) DeleteLabel( ctx context.Context, session *auth.Session, spaceRef string, key string, ) error { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return fmt.Errorf("failed to acquire access to space: %w", err) } if err := c.labelSvc.Delete(ctx, &space.ID, nil, key); err != nil { return fmt.Errorf("failed to delete space label: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_save.go
app/api/controller/space/label_save.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // SaveLabel defines a new label for the specified space. func (c *Controller) SaveLabel( ctx context.Context, session *auth.Session, spaceRef string, in *types.SaveInput, ) (*types.LabelWithValues, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } if err := in.Sanitize(); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } labelWithValues, err := c.labelSvc.Save( ctx, session.Principal.ID, &space.ID, nil, in) if err != nil { return nil, fmt.Errorf("failed to save label: %w", err) } return labelWithValues, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_executions.go
app/api/controller/space/list_executions.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListExecutions lists the executions in a space. func (c *Controller) ListExecutions( ctx context.Context, session *auth.Session, spaceRef string, filter types.ListExecutionsFilter, ) ([]*types.Execution, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionPipelineView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } var count int64 var executions []*types.Execution err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) { executions, err = c.executionStore.ListInSpace(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to list executions in space: %w", err) } if filter.Page == 1 && len(executions) < filter.Size { count = int64(len(executions)) return nil } count, err = c.executionStore.CountInSpace(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to count executions in space: %w", err) } return }, dbtx.TxDefaultReadOnly) if err != nil { return nil, 0, fmt.Errorf("failed to list executions in space: %w", err) } return executions, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/membership_list.go
app/api/controller/space/membership_list.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // MembershipList lists all space memberships. func (c *Controller) MembershipList(ctx context.Context, session *auth.Session, spaceRef string, filter types.MembershipUserFilter, ) ([]types.MembershipUser, int64, error) { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) if err != nil { return nil, 0, fmt.Errorf("failed to acquire access to space: %w", err) } var memberships []types.MembershipUser var membershipsCount int64 err = c.tx.WithTx(ctx, func(ctx context.Context) error { memberships, err = c.membershipStore.ListUsers(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to list memberships for space: %w", err) } if filter.Page == 1 && len(memberships) < filter.Size { membershipsCount = int64(len(memberships)) return nil } membershipsCount, err = c.membershipStore.CountUsers(ctx, space.ID, filter) if err != nil { return fmt.Errorf("failed to count memberships for space: %w", err) } return nil }, dbtx.TxDefaultReadOnly) if err != nil { return nil, 0, err } return memberships, membershipsCount, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/rule_delete.go
app/api/controller/space/rule_delete.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types/enum" ) // RuleDelete deletes a protection rule by identifier. func (c *Controller) RuleDelete(ctx context.Context, session *auth.Session, spaceRef string, identifier string, ) error { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return fmt.Errorf("failed to acquire access to space: %w", err) } err = c.rulesSvc.Delete( ctx, &session.Principal, enum.RuleParentSpace, space.ID, space.Identifier, space.Path, identifier, ) if err != nil { return fmt.Errorf("failed to delete space-level protection rule: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/controller.go
app/api/controller/space/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "encoding/json" "fmt" "strconv" "strings" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/api/controller/limiter" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/exporter" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/rules" "github.com/harness/gitness/app/services/space" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) var ( // TODO (Nested Spaces): Remove once full support is added errNestedSpacesNotSupported = usererror.BadRequestf("Nested spaces are not supported.") errPublicSpaceCreationDisabled = usererror.BadRequestf("Public space creation is disabled.") ) //nolint:revive type SpaceOutput struct { types.Space IsPublic bool `json:"is_public" yaml:"is_public"` } // TODO [CODE-1363]: remove after identifier migration. func (s SpaceOutput) MarshalJSON() ([]byte, error) { // alias allows us to embed the original object while avoiding an infinite loop of marshaling. type alias SpaceOutput return json.Marshal(&struct { alias UID string `json:"uid"` }{ alias: (alias)(s), UID: s.Identifier, }) } type Controller struct { nestedSpacesEnabled bool tx dbtx.Transactor urlProvider url.Provider sseStreamer sse.Streamer identifierCheck check.SpaceIdentifier authorizer authz.Authorizer spacePathStore store.SpacePathStore pipelineStore store.PipelineStore secretStore store.SecretStore connectorStore store.ConnectorStore templateStore store.TemplateStore spaceStore store.SpaceStore repoStore store.RepoStore principalStore store.PrincipalStore repoCtrl *repo.Controller membershipStore store.MembershipStore prListService *pullreq.ListService spaceFinder refcache.SpaceFinder repoFinder refcache.RepoFinder importer *importer.JobRepository exporter *exporter.Repository resourceLimiter limiter.ResourceLimiter publicAccess publicaccess.Service auditService audit.Service gitspaceSvc *gitspace.Service labelSvc *label.Service instrumentation instrument.Service executionStore store.ExecutionStore rulesSvc *rules.Service usageMetricStore store.UsageMetricStore repoIdentifierCheck check.RepoIdentifier infraProviderSvc *infraprovider.Service favoriteStore store.FavoriteStore spaceSvc *space.Service } func NewController(config *types.Config, tx dbtx.Transactor, urlProvider url.Provider, sseStreamer sse.Streamer, identifierCheck check.SpaceIdentifier, authorizer authz.Authorizer, spacePathStore store.SpacePathStore, pipelineStore store.PipelineStore, secretStore store.SecretStore, connectorStore store.ConnectorStore, templateStore store.TemplateStore, spaceStore store.SpaceStore, repoStore store.RepoStore, principalStore store.PrincipalStore, repoCtrl *repo.Controller, membershipStore store.MembershipStore, prListService *pullreq.ListService, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, importer *importer.JobRepository, exporter *exporter.Repository, limiter limiter.ResourceLimiter, publicAccess publicaccess.Service, auditService audit.Service, gitspaceSvc *gitspace.Service, labelSvc *label.Service, instrumentation instrument.Service, executionStore store.ExecutionStore, rulesSvc *rules.Service, usageMetricStore store.UsageMetricStore, repoIdentifierCheck check.RepoIdentifier, infraProviderSvc *infraprovider.Service, favoriteStore store.FavoriteStore, spaceSvc *space.Service, ) *Controller { return &Controller{ nestedSpacesEnabled: config.NestedSpacesEnabled, tx: tx, urlProvider: urlProvider, sseStreamer: sseStreamer, identifierCheck: identifierCheck, authorizer: authorizer, spacePathStore: spacePathStore, pipelineStore: pipelineStore, secretStore: secretStore, connectorStore: connectorStore, templateStore: templateStore, spaceStore: spaceStore, repoStore: repoStore, principalStore: principalStore, repoCtrl: repoCtrl, membershipStore: membershipStore, prListService: prListService, spaceFinder: spaceFinder, repoFinder: repoFinder, importer: importer, exporter: exporter, resourceLimiter: limiter, publicAccess: publicAccess, auditService: auditService, gitspaceSvc: gitspaceSvc, labelSvc: labelSvc, instrumentation: instrumentation, executionStore: executionStore, rulesSvc: rulesSvc, usageMetricStore: usageMetricStore, repoIdentifierCheck: repoIdentifierCheck, infraProviderSvc: infraProviderSvc, favoriteStore: favoriteStore, spaceSvc: spaceSvc, } } // getSpaceCheckAuth checks whether the user has the requested permission on the provided space and returns the space. func (c *Controller) getSpaceCheckAuth( ctx context.Context, session *auth.Session, spaceRef string, permission enum.Permission, ) (*types.SpaceCore, error) { return GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission) } func (c *Controller) getSpaceCheckAuthRepoCreation( ctx context.Context, session *auth.Session, parentRef string, ) (*types.SpaceCore, error) { return repo.GetSpaceCheckAuthRepoCreation(ctx, c.spaceFinder, c.authorizer, session, parentRef) } func (c *Controller) getSpaceCheckAuthSpaceCreation( ctx context.Context, session *auth.Session, parentRef string, ) (*types.SpaceCore, error) { parentRefAsID, err := strconv.ParseInt(parentRef, 10, 64) if (parentRefAsID <= 0 && err == nil) || (len(strings.TrimSpace(parentRef)) == 0) { // TODO: Restrict top level space creation - should be move to authorizer? if auth.IsAnonymousSession(session) { return nil, fmt.Errorf("anonymous user not allowed to create top level spaces: %w", usererror.ErrUnauthorized) } return &types.SpaceCore{}, nil } parentSpace, err := c.spaceFinder.FindByRef(ctx, parentRef) if err != nil { return nil, fmt.Errorf("failed to get parent space: %w", err) } if err = apiauth.CheckSpaceScope( ctx, c.authorizer, session, parentSpace, enum.ResourceTypeSpace, enum.PermissionSpaceEdit, ); err != nil { return nil, fmt.Errorf("authorization failed: %w", err) } return parentSpace, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/export.go
app/api/controller/space/export.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "errors" "fmt" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/services/exporter" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type ExportInput struct { AccountID string `json:"account_id"` OrgIdentifier string `json:"org_identifier"` ProjectIdentifier string `json:"project_identifier"` Token string `json:"token"` } // Export creates a new empty repository in harness code and does git push to it. func (c *Controller) Export(ctx context.Context, session *auth.Session, spaceRef string, in *ExportInput) error { space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) if err != nil { return fmt.Errorf("failed to acquire access to space: %w", err) } err = c.sanitizeExportInput(in) if err != nil { return fmt.Errorf("failed to sanitize input: %w", err) } providerInfo := &exporter.HarnessCodeInfo{ AccountID: in.AccountID, ProjectIdentifier: in.ProjectIdentifier, OrgIdentifier: in.OrgIdentifier, Token: in.Token, } var repos []*types.Repository page := 1 for { reposInPage, err := c.repoStore.List( ctx, space.ID, &types.RepoFilter{Size: 200, Page: page, Order: enum.OrderDesc}) if err != nil { return err } if len(reposInPage) == 0 { break } page++ repos = append(repos, reposInPage...) } err = c.tx.WithTx(ctx, func(ctx context.Context) error { err = c.exporter.RunManyForSpace(ctx, space.ID, repos, providerInfo) if errors.Is(err, exporter.ErrJobRunning) { return usererror.ConflictWithPayload("Export already in progress") } if err != nil { return fmt.Errorf("failed to start export repository job: %w", err) } return nil }) if err != nil { return err } return nil } func (c *Controller) sanitizeExportInput(in *ExportInput) error { if in.AccountID == "" { return usererror.BadRequest("Account ID must be provided") } if in.OrgIdentifier == "" { return usererror.BadRequest("Organization identifier must be provided") } if in.ProjectIdentifier == "" { return usererror.BadRequest("Project identifier must be provided") } if in.Token == "" { return usererror.BadRequest("Token for Harness Code must be provided") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/usage.go
app/api/controller/space/usage.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/errors" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // GetUsageMetrics returns usage metrics for root space. func (c *Controller) GetUsageMetrics( ctx context.Context, session *auth.Session, spaceRef string, startDate int64, endDate int64, ) (*types.UsageMetric, error) { rootSpaceRef, sub, err := paths.DisectRoot(spaceRef) if sub != "" { return nil, errors.InvalidArgumentf( "metric api can be used only within %q space: please remove %q part", rootSpaceRef, sub, ) } if err != nil { return nil, fmt.Errorf("could not find root space: %w", err) } space, err := c.getSpaceCheckAuth(ctx, session, rootSpaceRef, enum.PermissionSpaceView) if err != nil { return nil, fmt.Errorf("failed to acquire access to space: %w", err) } metric, err := c.usageMetricStore.GetMetrics( ctx, space.ID, startDate, endDate, ) if err != nil { return nil, fmt.Errorf("failed to retrieve usage metrics: %w", err) } return metric, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_templates.go
app/api/controller/space/list_templates.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package space import ( "context" "fmt" apiauth "github.com/harness/gitness/app/api/auth" "github.com/harness/gitness/app/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // ListTemplates lists the templates in a space. func (c *Controller) ListTemplates( ctx context.Context, session *auth.Session, spaceRef string, filter types.ListQueryFilter, ) ([]*types.Template, int64, error) { space, err := c.spaceFinder.FindByRef(ctx, spaceRef) if err != nil { return nil, 0, fmt.Errorf("failed to find parent space: %w", err) } err = apiauth.CheckTemplate( ctx, c.authorizer, session, space.Path, "", enum.PermissionTemplateView, ) if err != nil { return nil, 0, fmt.Errorf("could not authorize: %w", err) } count, err := c.templateStore.Count(ctx, space.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to count templates in the space: %w", err) } templates, err := c.templateStore.List(ctx, space.ID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to list templates: %w", err) } return templates, count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false