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/api.go | app/api/api.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 api
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/tx.go | app/api/controller/tx.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 controller
import (
"context"
"errors"
"github.com/harness/gitness/store"
"github.com/harness/gitness/store/database/dbtx"
)
// TxOptionRetryCount transaction option allows setting number of transaction executions reties.
// A transaction started with TxOptLock will be automatically retried in case of version conflict error.
type TxOptionRetryCount int
// TxOptionResetFunc transaction provides a function that will be executed before the transaction retry.
// A transaction started with TxOptLock will be automatically retried in case of version conflict error.
type TxOptionResetFunc func()
// TxOptLock runs the provided function inside a database transaction. If optimistic lock error occurs
// during the operation, the function will retry the whole transaction again (to the maximum of 5 times,
// but this can be overridden by providing an additional TxOptionRetryCount option).
func TxOptLock(ctx context.Context,
tx dbtx.Transactor,
txFn func(ctx context.Context) error,
opts ...any,
) (err error) {
tries := 5
var resetFuncs []func()
for _, opt := range opts {
if n, ok := opt.(TxOptionRetryCount); ok {
tries = int(n)
}
if fn, ok := opt.(TxOptionResetFunc); ok {
resetFuncs = append(resetFuncs, fn)
}
}
for try := 0; try < tries; try++ {
err = tx.WithTx(ctx, txFn, opts...)
if !errors.Is(err, store.ErrVersionConflict) {
break
}
for _, fn := range resetFuncs {
fn()
}
}
return
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/util.go | app/api/controller/util.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 controller
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/bootstrap"
"github.com/harness/gitness/app/githook"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/git"
"github.com/harness/gitness/types"
)
// createRPCWriteParams creates base write parameters for git write operations.
// TODO: this function should be in git package and should accept params as interface (contract).
func createRPCWriteParams(
ctx context.Context,
urlProvider url.Provider,
session *auth.Session,
repo *types.RepositoryCore,
disabled bool,
isInternal bool,
) (git.WriteParams, error) {
// generate envars (add everything githook CLI needs for execution)
envVars, err := githook.GenerateEnvironmentVariables(
ctx,
urlProvider.GetInternalAPIURL(ctx),
repo.ID,
session.Principal.ID,
disabled,
isInternal,
)
if err != nil {
return git.WriteParams{}, fmt.Errorf("failed to generate git hook environment variables: %w", err)
}
return git.WriteParams{
Actor: git.Identity{
Name: session.Principal.DisplayName,
Email: session.Principal.Email,
},
RepoUID: repo.GitUID,
EnvVars: envVars,
}, nil
}
// CreateRPCExternalWriteParams creates base write parameters for git external write operations.
// External write operations are direct git pushes.
func CreateRPCExternalWriteParams(
ctx context.Context,
urlProvider url.Provider,
session *auth.Session,
repo *types.RepositoryCore,
) (git.WriteParams, error) {
return createRPCWriteParams(ctx, urlProvider, session, repo, false, false)
}
// CreateRPCInternalWriteParams creates base write parameters for git internal write operations.
// Internal write operations are git pushes that originate from the Harness server.
func CreateRPCInternalWriteParams(
ctx context.Context,
urlProvider url.Provider,
session *auth.Session,
repo *types.RepositoryCore,
) (git.WriteParams, error) {
return createRPCWriteParams(ctx, urlProvider, session, repo, false, true)
}
// CreateRPCSystemReferencesWriteParams creates base write parameters for write operations
// on system references (e.g. pullreq references).
func CreateRPCSystemReferencesWriteParams(
ctx context.Context,
urlProvider url.Provider,
session *auth.Session,
repo *types.RepositoryCore,
) (git.WriteParams, error) {
return createRPCWriteParams(ctx, urlProvider, session, repo, true, true)
}
func MapBranch(b git.Branch) (types.Branch, error) {
return types.Branch{
Name: b.Name,
SHA: b.SHA,
Commit: MapCommit(b.Commit),
}, nil
}
func MapCommit(c *git.Commit) *types.Commit {
if c == nil {
return nil
}
return &types.Commit{
SHA: c.SHA,
TreeSHA: c.TreeSHA,
ParentSHAs: c.ParentSHAs,
Title: c.Title,
Message: c.Message,
Author: MapSignature(c.Author),
Committer: MapSignature(c.Committer),
SignedData: (*types.SignedData)(c.SignedData),
Stats: mapStats(c),
}
}
func MapCommitTag(t git.CommitTag) types.CommitTag {
var tagger *types.Signature
if t.Tagger != nil {
tagger = &types.Signature{}
*tagger = MapSignature(*t.Tagger)
}
return types.CommitTag{
Name: t.Name,
SHA: t.SHA,
IsAnnotated: t.IsAnnotated,
Title: t.Title,
Message: t.Message,
Tagger: tagger,
SignedData: (*types.SignedData)(t.SignedData),
Commit: MapCommit(t.Commit),
}
}
func mapStats(c *git.Commit) *types.CommitStats {
if len(c.FileStats) == 0 {
return nil
}
var insertions int64
var deletions int64
for _, stat := range c.FileStats {
insertions += stat.Insertions
deletions += stat.Deletions
}
return &types.CommitStats{
Total: types.ChangeStats{
Insertions: insertions,
Deletions: deletions,
Changes: insertions + deletions,
},
Files: mapFileStats(c),
}
}
func mapFileStats(c *git.Commit) []types.CommitFileStats {
fileStats := make([]types.CommitFileStats, len(c.FileStats))
for i, fStat := range c.FileStats {
fileStats[i] = types.CommitFileStats{
Path: fStat.Path,
OldPath: fStat.OldPath,
Status: fStat.Status,
ChangeStats: types.ChangeStats{
Insertions: fStat.Insertions,
Deletions: fStat.Deletions,
Changes: fStat.Insertions + fStat.Deletions,
},
}
}
return fileStats
}
func MapRenameDetails(c *git.RenameDetails) *types.RenameDetails {
if c == nil {
return nil
}
return &types.RenameDetails{
OldPath: c.OldPath,
NewPath: c.NewPath,
CommitShaBefore: c.CommitShaBefore.String(),
CommitShaAfter: c.CommitShaAfter.String(),
}
}
func MapSignature(s git.Signature) types.Signature {
return types.Signature{
Identity: types.Identity(s.Identity),
When: s.When,
}
}
func IdentityFromPrincipalInfo(p types.PrincipalInfo) *git.Identity {
return &git.Identity{
Name: p.DisplayName,
Email: p.Email,
}
}
func SystemServicePrincipalInfo() *git.Identity {
return IdentityFromPrincipalInfo(*bootstrap.NewSystemServiceSession().Principal.ToPrincipalInfo())
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/logs/wire.go | app/api/controller/logs/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 logs
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/livelog"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
authorizer authz.Authorizer,
executionStore store.ExecutionStore,
pipelineStore store.PipelineStore,
stageStore store.StageStore,
stepStore store.StepStore,
logStore store.LogStore,
logStream livelog.LogStream,
repoFinder refcache.RepoFinder,
) *Controller {
return NewController(authorizer, executionStore,
pipelineStore, stageStore, stepStore, logStore, logStream, 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/logs/tail.go | app/api/controller/logs/tail.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 logs
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/livelog"
"github.com/harness/gitness/types/enum"
)
func (c *Controller) Tail(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
executionNum int64,
stageNum int,
stepNum int,
) (<-chan *livelog.Line, <-chan error, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, nil, fmt.Errorf("failed to find repo by ref: %w", err)
}
err = apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path, pipelineIdentifier, enum.PermissionPipelineView)
if err != nil {
return nil, nil, fmt.Errorf("failed to authorize pipeline: %w", err)
}
pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier)
if err != nil {
return nil, nil, fmt.Errorf("failed to find pipeline: %w", err)
}
execution, err := c.executionStore.FindByNumber(ctx, pipeline.ID, executionNum)
if err != nil {
return nil, nil, fmt.Errorf("failed to find execution: %w", err)
}
stage, err := c.stageStore.FindByNumber(ctx, execution.ID, stageNum)
if err != nil {
return nil, nil, fmt.Errorf("failed to find stage: %w", err)
}
step, err := c.stepStore.FindByNumber(ctx, stage.ID, stepNum)
if err != nil {
return nil, nil, fmt.Errorf("failed to find step: %w", err)
}
linec, errc := c.logStream.Tail(ctx, step.ID)
return linec, errc, 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/logs/find.go | app/api/controller/logs/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 logs
import (
"bytes"
"context"
"encoding/json"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/livelog"
"github.com/harness/gitness/types/enum"
)
func (c *Controller) Find(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
executionNum int64,
stageNum int,
stepNum int,
) ([]*livelog.Line, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ref: %w", err)
}
err = apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path, pipelineIdentifier, enum.PermissionPipelineView)
if err != nil {
return nil, fmt.Errorf("failed to authorize pipeline: %w", err)
}
pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, pipelineIdentifier)
if err != nil {
return nil, fmt.Errorf("failed to find pipeline: %w", err)
}
execution, err := c.executionStore.FindByNumber(ctx, pipeline.ID, executionNum)
if err != nil {
return nil, fmt.Errorf("failed to find execution: %w", err)
}
stage, err := c.stageStore.FindByNumber(ctx, execution.ID, stageNum)
if err != nil {
return nil, fmt.Errorf("failed to find stage: %w", err)
}
step, err := c.stepStore.FindByNumber(ctx, stage.ID, stepNum)
if err != nil {
return nil, fmt.Errorf("failed to find step: %w", err)
}
rc, err := c.logStore.Find(ctx, step.ID)
if err != nil {
return nil, fmt.Errorf("could not find logs: %w", err)
}
defer rc.Close()
lines := []*livelog.Line{}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(rc)
if err != nil {
return nil, fmt.Errorf("failed to read from buffer: %w", err)
}
err = json.Unmarshal(buf.Bytes(), &lines)
if err != nil {
return nil, fmt.Errorf("could not unmarshal logs: %w", err)
}
return lines, 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/logs/controller.go | app/api/controller/logs/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 logs
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/livelog"
)
type Controller struct {
authorizer authz.Authorizer
executionStore store.ExecutionStore
pipelineStore store.PipelineStore
stageStore store.StageStore
stepStore store.StepStore
logStore store.LogStore
logStream livelog.LogStream
repoFinder refcache.RepoFinder
}
func NewController(
authorizer authz.Authorizer,
executionStore store.ExecutionStore,
pipelineStore store.PipelineStore,
stageStore store.StageStore,
stepStore store.StepStore,
logStore store.LogStore,
logStream livelog.LogStream,
repoFinder refcache.RepoFinder,
) *Controller {
return &Controller{
authorizer: authorizer,
executionStore: executionStore,
pipelineStore: pipelineStore,
stageStore: stageStore,
stepStore: stepStore,
logStore: logStore,
logStream: logStream,
repoFinder: 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/system/wire.go | app/api/controller/system/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 system
import (
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
NewController,
)
func ProvideController(principalStore store.PrincipalStore, config *types.Config) *Controller {
return NewController(principalStore, config)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/system/controller.go | app/api/controller/system/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 system
import (
"context"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
)
type Controller struct {
principalStore store.PrincipalStore
config *types.Config
}
func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {
return &Controller{
principalStore: principalStore,
config: config,
}
}
func (c *Controller) IsUserSignupAllowed(ctx context.Context) (bool, error) {
usrCount, err := c.principalStore.CountUsers(ctx, &types.UserFilter{})
if err != nil {
return false, err
}
return usrCount == 0 || c.config.UserSignupEnabled, 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/service/wire.go | app/api/controller/service/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 service
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) *Controller {
return NewController(principalUIDCheck, authorizer, principalStore)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/service/create.go | app/api/controller/service/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 service
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"
)
// CreateInput is the input used for create operations.
type CreateInput struct {
UID string `json:"uid"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
}
// Create creates a new service.
func (c *Controller) Create(ctx context.Context, session *auth.Session, in *CreateInput) (*types.Service, error) {
// Ensure principal has required permissions (service is global, no explicit resource)
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeService,
}
if err := apiauth.Check(ctx, c.authorizer, session, scope, resource, enum.PermissionServiceEdit); err != nil {
return nil, err
}
return c.CreateNoAuth(ctx, in, false)
}
/*
* CreateNoAuth creates a new service without auth checks.
* WARNING: Never call as part of user flow.
*
* Note: take admin separately to avoid potential vulnerabilities for user calls.
*/
func (c *Controller) CreateNoAuth(ctx context.Context, in *CreateInput, admin bool) (*types.Service, error) {
if err := c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
svc := &types.Service{
UID: in.UID,
Email: in.Email,
DisplayName: in.DisplayName,
Admin: admin,
Salt: uniuri.NewLen(uniuri.UUIDLen),
Created: time.Now().UnixMilli(),
Updated: time.Now().UnixMilli(),
}
err := c.principalStore.CreateService(ctx, svc)
if err != nil {
return nil, err
}
return svc, nil
}
func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
if err := c.principalUIDCheck(in.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 { //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/service/delete.go | app/api/controller/service/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 service
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.
*/
func (c *Controller) Delete(ctx context.Context, session *auth.Session,
serviceUID string) error {
svc, err := findServiceFromUID(ctx, c.principalStore, serviceUID)
if err != nil {
return err
}
// Ensure principal has required permissions on parent
if err = apiauth.CheckService(ctx, c.authorizer, session, svc, enum.PermissionServiceDelete); err != nil {
return err
}
return c.principalStore.DeleteService(ctx, svc.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/service/find.go | app/api/controller/service/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 service
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.
func (c *Controller) Find(ctx context.Context, session *auth.Session,
serviceUID string) (*types.Service, error) {
svc, err := c.FindNoAuth(ctx, serviceUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckService(ctx, c.authorizer, session, svc, enum.PermissionServiceView); err != nil {
return nil, err
}
return svc, nil
}
/*
* FindNoAuth finds a service without auth checks.
* WARNING: Never call as part of user flow.
*/
func (c *Controller) FindNoAuth(ctx context.Context, serviceUID string) (*types.Service, error) {
return findServiceFromUID(ctx, c.principalStore, serviceUID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/service/list.go | app/api/controller/service/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 service
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"
)
// List lists all services of the system.
func (c *Controller) List(ctx context.Context, session *auth.Session) (int64, []*types.Service, error) {
// Ensure principal has required permissions (service is global, no explicit resource)
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeService,
}
if err := apiauth.Check(ctx, c.authorizer, session, scope, resource, enum.PermissionServiceView); err != nil {
return 0, nil, err
}
count, err := c.principalStore.CountServices(ctx)
if err != nil {
return 0, nil, fmt.Errorf("failed to count services: %w", err)
}
repos, err := c.principalStore.ListServices(ctx)
if err != nil {
return 0, nil, fmt.Errorf("failed to list services: %w", err)
}
return count, 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/service/controller.go | app/api/controller/service/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 service
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
}
func NewController(principalUIDCheck check.PrincipalUID, authorizer authz.Authorizer,
principalStore store.PrincipalStore) *Controller {
return &Controller{
principalUIDCheck: principalUIDCheck,
authorizer: authorizer,
principalStore: principalStore,
}
}
func findServiceFromUID(ctx context.Context,
principalStore store.PrincipalStore,
serviceUID string,
) (*types.Service, error) {
return principalStore.FindServiceByUID(ctx, serviceUID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/service/update_admin.go | app/api/controller/service/update_admin.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 service
import (
"context"
"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/enum"
)
// UpdateAdmin updates the admin state of a service.
func (c *Controller) UpdateAdmin(ctx context.Context, session *auth.Session,
serviceUID string, admin bool) (*types.Service, error) {
sbc, err := findServiceFromUID(ctx, c.principalStore, serviceUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckService(ctx, c.authorizer, session, sbc, enum.PermissionServiceEditAdmin); err != nil {
return nil, err
}
sbc.Admin = admin
sbc.Updated = time.Now().UnixMilli()
err = c.principalStore.UpdateService(ctx, sbc)
if err != nil {
return nil, err
}
return sbc, 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/service/update.go | app/api/controller/service/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 service
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/gotidy/ptr"
)
// UpdateInput store infos to update an existing service.
type UpdateInput struct {
Email *string `json:"email"`
DisplayName *string `json:"display_name"`
}
// Update updates the provided service.
func (c *Controller) Update(ctx context.Context, session *auth.Session,
serviceUID string, in *UpdateInput) (*types.Service, error) {
svc, err := findServiceFromUID(ctx, c.principalStore, serviceUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckService(ctx, c.authorizer, session, svc, enum.PermissionServiceEdit); err != nil {
return nil, err
}
if err = c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
if in.Email != nil {
svc.DisplayName = ptr.ToString(in.Email)
}
if in.DisplayName != nil {
svc.DisplayName = ptr.ToString(in.DisplayName)
}
svc.Updated = time.Now().UnixMilli()
err = c.principalStore.UpdateService(ctx, svc)
if err != nil {
return nil, err
}
return svc, nil
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
if in.Email != nil {
*in.Email = strings.TrimSpace(*in.Email)
if err := check.Email(*in.Email); err != nil {
return err
}
}
if in.DisplayName != nil {
*in.DisplayName = strings.TrimSpace(*in.DisplayName)
if err := check.DisplayName(*in.DisplayName); 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/plugin/wire.go | app/api/controller/plugin/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 plugin
import (
"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(pluginStore store.PluginStore) *Controller {
return NewController(pluginStore)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/plugin/list.go | app/api/controller/plugin/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 plugin
import (
"context"
"fmt"
"github.com/harness/gitness/types"
)
// List lists all the global plugins.
// Since this just lists the schema of plugins, it does not require any
// specific authorization. Plugins are available globally so they are not
// associated with any space.
func (c *Controller) List(
ctx context.Context,
filter types.ListQueryFilter,
) ([]*types.Plugin, int64, error) {
plugins, err := c.pluginStore.List(ctx, filter)
if err != nil {
return nil, 0, fmt.Errorf("failed to list plugins: %w", err)
}
if len(plugins) < filter.Size {
return plugins, int64(len(plugins)), nil
}
count, err := c.pluginStore.Count(ctx, filter)
if err != nil {
return nil, 0, fmt.Errorf("failed to count plugins: %w", err)
}
return plugins, 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/plugin/controller.go | app/api/controller/plugin/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 plugin
import (
"github.com/harness/gitness/app/store"
)
type Controller struct {
pluginStore store.PluginStore
}
func NewController(
pluginStore store.PluginStore,
) *Controller {
return &Controller{
pluginStore: pluginStore,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/user/find_email.go | app/api/controller/user/find_email.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 user
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"
)
/*
* FindEmail tries to find the provided user using email.
*/
func (c *Controller) FindEmail(ctx context.Context, session *auth.Session,
email string) (*types.User, error) {
user, err := findUserFromEmail(ctx, c.principalStore, email)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserView); err != nil {
return nil, err
}
return user, 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/user/wire.go | app/api/controller/user/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 user
import (
"github.com/harness/gitness/app/auth/authz"
userevents "github.com/harness/gitness/app/events/user"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types/check"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
tx dbtx.Transactor,
principalUIDCheck check.PrincipalUID,
authorizer authz.Authorizer,
principalStore store.PrincipalStore,
tokenStore store.TokenStore,
membershipStore store.MembershipStore,
publicKeyStore store.PublicKeyStore,
publicKeySubKeyStore store.PublicKeySubKeyStore,
gitSignatureResultStore store.GitSignatureResultStore,
eventReporter *userevents.Reporter,
repoFinder refcache.RepoFinder,
favoriteStore store.FavoriteStore,
) *Controller {
return NewController(
tx,
principalUIDCheck,
authorizer,
principalStore,
tokenStore,
membershipStore,
publicKeyStore,
publicKeySubKeyStore,
gitSignatureResultStore,
eventReporter,
repoFinder,
favoriteStore)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/user/publickey_edit.go | app/api/controller/user/publickey_edit.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 user
import (
"context"
"fmt"
"time"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type UpdatePublicKeyInput struct {
RevocationReason *enum.RevocationReason `json:"revocation_reason"`
ValidFrom *int64 `json:"valid_from"`
ValidTo *int64 `json:"valid_to"`
}
func (in *UpdatePublicKeyInput) Sanitize() error {
if in.RevocationReason != nil {
if _, ok := in.RevocationReason.Sanitize(); !ok {
return errors.InvalidArgument("invalid public key revocation reason")
}
if in.ValidFrom != nil || in.ValidTo != nil {
return errors.InvalidArgument("must either revoke the key or update its validity period")
}
}
if in.ValidFrom != nil && in.ValidTo != nil {
if *in.ValidFrom > *in.ValidTo {
return errors.InvalidArgument("invalid validity period")
}
}
return nil
}
func (c *Controller) UpdatePublicKey(
ctx context.Context,
session *auth.Session,
userUID string,
identifier string,
in *UpdatePublicKeyInput,
) (*types.PublicKey, error) {
user, err := c.principalStore.FindUserByUID(ctx, userUID)
if err != nil {
return nil, fmt.Errorf("failed to fetch user by uid: %w", err)
}
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return nil, fmt.Errorf("access check failed: %w", err)
}
if err := in.Sanitize(); err != nil {
return nil, err
}
key, err := c.publicKeyStore.FindByIdentifier(ctx, user.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find public key by identifier: %w", err)
}
if key.RevocationReason != nil {
if in.ValidFrom != nil || in.ValidTo != nil {
return nil, errors.InvalidArgument("can't update the validity period of revoked keys")
}
if *key.RevocationReason == enum.RevocationReasonCompromised {
return nil, errors.InvalidArgument("can't update the revocation reason of compromised keys")
}
}
var (
changedRevocationReason bool
changedValidityPeriod bool
)
if in.RevocationReason != nil &&
(key.RevocationReason == nil || *key.RevocationReason != *in.RevocationReason) {
now := time.Now().UnixMilli()
key.RevocationReason = in.RevocationReason
if key.ValidTo == nil || *key.ValidTo > now {
key.ValidTo = &now
}
changedRevocationReason = true
}
isTimestampChanged := func(ts1, ts2 *int64) bool {
return ts1 != nil && ts2 != nil && *ts1 != *ts2 ||
ts1 == nil && ts2 != nil ||
ts1 != nil && ts2 == nil
}
if in.ValidFrom != nil {
if *in.ValidFrom == 0 { // zero means clear
in.ValidFrom = nil
}
if isTimestampChanged(key.ValidFrom, in.ValidFrom) {
key.ValidFrom = in.ValidFrom
changedValidityPeriod = true
}
}
if in.ValidTo != nil {
if *in.ValidTo == 0 { // zero means clear
in.ValidTo = nil
}
if isTimestampChanged(key.ValidTo, in.ValidTo) {
key.ValidTo = in.ValidTo
changedValidityPeriod = true
}
}
if !changedRevocationReason && !changedValidityPeriod {
return key, nil
}
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
err = c.publicKeyStore.Update(ctx, key)
if err != nil {
return fmt.Errorf("failed to update public key: %w", err)
}
if changedRevocationReason && *key.RevocationReason == enum.RevocationReasonCompromised {
switch key.Scheme {
case enum.PublicKeySchemePGP:
subKeys, err := c.publicKeySubKeyStore.List(ctx, key.ID)
if err != nil {
return fmt.Errorf("failed to list subkeys: %w", err)
}
err = c.gitSignatureResultStore.UpdateAll(
ctx,
enum.GitSignatureRevoked,
key.PrincipalID,
subKeys,
nil)
if err != nil {
return fmt.Errorf("failed to revoke all PGP signatures for keys %v: %w", subKeys, err)
}
case enum.PublicKeySchemeSSH:
fingerprints := []string{key.Fingerprint}
err := c.gitSignatureResultStore.UpdateAll(
ctx,
enum.GitSignatureRevoked,
key.PrincipalID,
nil,
fingerprints)
if err != nil {
return fmt.Errorf("failed to revoke all SSH signatures for key %v: %w", fingerprints, err)
}
}
}
return nil
})
if err != nil {
return nil, err
}
return key, 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/user/create.go | app/api/controller/user/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 user
import (
"context"
"fmt"
"strings"
"time"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
userevents "github.com/harness/gitness/app/events/user"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
"github.com/dchest/uniuri"
"golang.org/x/crypto/bcrypt"
)
// CreateInput is the input used for create operations.
// On purpose don't expose admin, has to be enabled explicitly.
type CreateInput struct {
UID string `json:"uid"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
// Create creates a new user.
func (c *Controller) Create(ctx context.Context, session *auth.Session, in *CreateInput) (*types.User, error) {
// Ensure principal has required permissions (user is global, no explicit resource)
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeUser,
}
if err := apiauth.Check(ctx, c.authorizer, session, scope, resource, enum.PermissionUserEdit); err != nil {
return nil, err
}
user, err := c.CreateNoAuth(ctx, in, false)
if err != nil {
return nil, fmt.Errorf("failed to create user: %w", err)
}
c.eventReporter.Created(ctx, &userevents.CreatedPayload{
Base: userevents.Base{
PrincipalID: session.Principal.ID,
},
CreatedPrincipalID: user.ID,
})
return user, nil
}
// CreateNoAuth creates a new user without auth checks.
// WARNING: Never call as part of user flow.
//
// Note: take admin separately to avoid potential vulnerabilities for user calls.
func (c *Controller) CreateNoAuth(ctx context.Context, in *CreateInput, admin bool) (*types.User, error) {
if err := c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
hash, err := hashPassword([]byte(in.Password), bcrypt.DefaultCost)
if err != nil {
return nil, fmt.Errorf("failed to create hash: %w", err)
}
user := &types.User{
UID: in.UID,
DisplayName: in.DisplayName,
Email: in.Email,
Password: string(hash),
Salt: uniuri.NewLen(uniuri.UUIDLen),
Created: time.Now().UnixMilli(),
Updated: time.Now().UnixMilli(),
Admin: admin,
}
err = c.principalStore.CreateUser(ctx, user)
if err != nil {
return nil, err
}
uCount, err := c.principalStore.CountUsers(ctx, &types.UserFilter{})
if err != nil {
return nil, err
}
// first 'user' principal will be admin by default.
if uCount == 1 {
user.Admin = true
err = c.principalStore.UpdateUser(ctx, user)
if err != nil {
return nil, err
}
}
return user, nil
}
func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
if err := c.principalUIDCheck(in.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
}
//nolint:revive
if err := check.Password(in.Password); 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/user/publickey_list.go | app/api/controller/user/publickey_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 user
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"
)
func (c *Controller) ListPublicKeys(
ctx context.Context,
session *auth.Session,
userUID string,
filter *types.PublicKeyFilter,
) ([]types.PublicKey, int, error) {
user, err := c.principalStore.FindUserByUID(ctx, userUID)
if err != nil {
return nil, 0, fmt.Errorf("failed to fetch user by uid: %w", err)
}
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserView); err != nil {
return nil, 0, err
}
var (
list []types.PublicKey
count int
)
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
list, err = c.publicKeyStore.List(ctx, &user.ID, filter)
if err != nil {
return fmt.Errorf("failed to list public keys for user: %w", err)
}
if filter.Page == 1 && len(list) < filter.Size {
count = len(list)
return nil
}
count, err = c.publicKeyStore.Count(ctx, &user.ID, filter)
if err != nil {
return fmt.Errorf("failed to count public keys for user: %w", err)
}
return nil
}, dbtx.TxDefaultReadOnly)
if err != nil {
return nil, 0, 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/user/delete.go | app/api/controller/user/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 user
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/types"
"github.com/harness/gitness/types/enum"
)
// Delete deletes a user.
func (c *Controller) Delete(ctx context.Context, session *auth.Session,
userUID string) error {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return err
}
// Fail if the user being deleted is the only admin in DB
if user.Admin {
admUsrCount, err := c.principalStore.CountUsers(ctx, &types.UserFilter{Admin: true})
if err != nil {
return fmt.Errorf("failed to check admin user count: %w", err)
}
if admUsrCount == 1 {
return usererror.BadRequest("Cannot delete the only admin user")
}
}
// Ensure principal has required permissions on parent
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserDelete); err != nil {
return err
}
return c.principalStore.DeleteUser(ctx, user.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/user/register.go | app/api/controller/user/register.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 user
import (
"context"
"fmt"
"github.com/harness/gitness/app/api/controller/system"
"github.com/harness/gitness/app/api/usererror"
userevents "github.com/harness/gitness/app/events/user"
"github.com/harness/gitness/app/token"
"github.com/harness/gitness/types"
)
type RegisterInput struct {
Email string `json:"email"`
DisplayName string `json:"display_name"`
UID string `json:"uid"`
Password string `json:"password"`
}
// Register creates a new user and returns a new session token on success.
// This doesn't require auth, but has limited functionalities (unable to create admin user for example).
func (c *Controller) Register(ctx context.Context, sysCtrl *system.Controller,
in *RegisterInput) (*types.TokenResponse, error) {
signUpAllowed, err := sysCtrl.IsUserSignupAllowed(ctx)
if err != nil {
return nil, err
}
if !signUpAllowed {
return nil, usererror.Forbidden("User sign-up is disabled")
}
user, err := c.CreateNoAuth(ctx, &CreateInput{
UID: in.UID,
Email: in.Email,
DisplayName: in.DisplayName,
Password: in.Password,
}, false)
if err != nil {
return nil, fmt.Errorf("failed to create user: %w", err)
}
// TODO: how should we name session tokens?
token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register")
if err != nil {
return nil, fmt.Errorf("failed to create token after successful user creation: %w", err)
}
c.eventReporter.Registered(ctx, &userevents.RegisteredPayload{
Base: userevents.Base{PrincipalID: user.ID},
})
return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, 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/user/find.go | app/api/controller/user/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 user
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 user.
*/
func (c *Controller) Find(ctx context.Context, session *auth.Session,
userUID string) (*types.User, error) {
user, err := c.FindNoAuth(ctx, userUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserView); err != nil {
return nil, err
}
return user, nil
}
/*
* FindNoAuth finds a user without auth checks.
* WARNING: Never call as part of user flow.
*/
func (c *Controller) FindNoAuth(ctx context.Context, userUID string) (*types.User, error) {
return findUserFromUID(ctx, c.principalStore, userUID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/user/create_favorite.go | app/api/controller/user/create_favorite.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 user
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) CreateFavorite(
ctx context.Context,
session *auth.Session,
in *types.FavoriteResource,
) (*types.FavoriteResource, error) {
switch in.Type { // nolint:exhaustive
case enum.ResourceTypeRepo:
repo, err := c.repoFinder.FindByID(ctx, in.ID)
if err != nil {
return nil, fmt.Errorf("couldn't fetch repo for the user: %w", err)
}
if err = apiauth.CheckRepo(
ctx,
c.authorizer,
session,
repo,
enum.PermissionRepoView); err != nil {
return nil, err
}
in.ID = repo.ID
default:
return nil, fmt.Errorf("resource not onboarded to favorites: %s", in.Type)
}
if err := c.favoriteStore.Create(ctx, session.Principal.ID, in); err != nil {
return nil, fmt.Errorf("failed to mark %s %d as favorite: %w", in.Type, in.ID, err)
}
return in, 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/user/logout.go | app/api/controller/user/logout.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 user
import (
"context"
"errors"
"fmt"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types/enum"
)
var ()
// Logout searches for the user's token present in the request and proceeds to delete it.
// If no user was present, a usererror.ErrUnauthorized is returned.
func (c *Controller) Logout(ctx context.Context, session *auth.Session) error {
var (
tokenID int64
tokenType enum.TokenType
)
if session == nil {
return usererror.ErrUnauthorized
}
switch t := session.Metadata.(type) {
case *auth.TokenMetadata:
tokenID = t.TokenID
tokenType = t.TokenType
default:
return errors.New("provided jwt doesn't support logout")
}
if tokenType != enum.TokenTypeSession {
return usererror.BadRequestf("Unsupported logout token type %v", tokenType)
}
err := c.tokenStore.Delete(ctx, tokenID)
if err != nil {
return fmt.Errorf("failed to delete token from store: %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/user/delete_favorite.go | app/api/controller/user/delete_favorite.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 user
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) DeleteFavorite(
ctx context.Context,
session *auth.Session,
in *types.FavoriteResource,
) error {
switch in.Type { // nolint:exhaustive
case enum.ResourceTypeRepo:
repo, err := c.repoFinder.FindByID(ctx, in.ID)
if err != nil {
return fmt.Errorf("couldn't fetch repo for the user: %w", err)
}
if err = apiauth.CheckRepo(
ctx,
c.authorizer,
session,
repo,
enum.PermissionRepoView); err != nil {
return err
}
in.ID = repo.ID
default:
return fmt.Errorf("resource not onboarded to favorites: %s", in.Type)
}
if err := c.favoriteStore.Delete(ctx, session.Principal.ID, in); 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/user/delete_token.go | app/api/controller/user/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 user
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 user.
*/
func (c *Controller) DeleteToken(
ctx context.Context,
session *auth.Session,
userUID string,
tokenType enum.TokenType,
tokenIdentifier string) error {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return err
}
token, err := c.tokenStore.FindByIdentifier(ctx, user.ID, tokenIdentifier)
if err != nil {
return err
}
// Ensure token type matches the requested type and is a valid user token type
if !isUserTokenType(token.Type) || token.Type != tokenType {
// throw a not found error - no need for user to know about token.
return usererror.ErrNotFound
}
// Ensure token belongs to user.
if token.PrincipalID != user.ID {
log.Warn().Msg("Principal tried to delete token that doesn't belong to the user")
// 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/user/list.go | app/api/controller/user/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 user
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"
)
/*
* List lists all users of the system.
*/
func (c *Controller) List(ctx context.Context, session *auth.Session,
filter *types.UserFilter) ([]*types.User, int64, error) {
// Ensure principal has required permissions (user is global, no explicit resource)
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeUser,
}
if err := apiauth.Check(ctx, c.authorizer, session, scope, resource, enum.PermissionUserView); err != nil {
return nil, 0, err
}
count, err := c.principalStore.CountUsers(ctx, filter)
if err != nil {
return nil, 0, fmt.Errorf("failed to count users: %w", err)
}
repos, err := c.principalStore.ListUsers(ctx, filter)
if err != nil {
return nil, 0, fmt.Errorf("failed to list users: %w", err)
}
return repos, 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/user/list_tokens.go | app/api/controller/user/list_tokens.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 user
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"
"github.com/harness/gitness/types/enum"
)
/*
* ListTokens lists all tokens of a user.
*/
func (c *Controller) ListTokens(ctx context.Context, session *auth.Session,
userUID string, tokenType enum.TokenType) ([]*types.Token, error) {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserView); err != nil {
return nil, err
}
if !isUserTokenType(tokenType) {
return nil, usererror.ErrBadRequest
}
return c.tokenStore.List(ctx, user.ID, tokenType)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/user/create_access_token.go | app/api/controller/user/create_access_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 user
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 user access token.
*/
func (c *Controller) CreateAccessToken(
ctx context.Context,
session *auth.Session,
userUID string,
in *CreateTokenInput,
) (*types.TokenResponse, error) {
if err := c.sanitizeCreateTokenInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return nil, err
}
token, jwtToken, err := token.CreatePAT(
ctx,
c.tokenStore,
&session.Principal,
user,
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/user/membership_spaces.go | app/api/controller/user/membership_spaces.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 user
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"
)
// MembershipSpaces lists all spaces in which the user is a member.
func (c *Controller) MembershipSpaces(ctx context.Context,
session *auth.Session,
userUID string,
filter types.MembershipSpaceFilter,
) ([]types.MembershipSpace, int64, error) {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return nil, 0, fmt.Errorf("failed to find user by UID: %w", err)
}
// Ensure principal has required permissions.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserView); err != nil {
return nil, 0, err
}
var membershipSpaces []types.MembershipSpace
var membershipsCount int64
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
membershipSpaces, err = c.membershipStore.ListSpaces(ctx, user.ID, filter)
if err != nil {
return fmt.Errorf("failed to list membership spaces for user: %w", err)
}
if filter.Page == 1 && len(membershipSpaces) < filter.Size {
membershipsCount = int64(len(membershipSpaces))
return nil
}
membershipsCount, err = c.membershipStore.CountSpaces(ctx, user.ID, filter)
if err != nil {
return fmt.Errorf("failed to count memberships for user: %w", err)
}
return nil
}, dbtx.TxDefaultReadOnly)
if err != nil {
return nil, 0, err
}
return membershipSpaces, 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/user/controller.go | app/api/controller/user/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 user
import (
"context"
"github.com/harness/gitness/app/auth/authz"
userevents "github.com/harness/gitness/app/events/user"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
"golang.org/x/crypto/bcrypt"
)
type Controller struct {
tx dbtx.Transactor
principalUIDCheck check.PrincipalUID
authorizer authz.Authorizer
principalStore store.PrincipalStore
tokenStore store.TokenStore
membershipStore store.MembershipStore
publicKeyStore store.PublicKeyStore
publicKeySubKeyStore store.PublicKeySubKeyStore
gitSignatureResultStore store.GitSignatureResultStore
eventReporter *userevents.Reporter
repoFinder refcache.RepoFinder
favoriteStore store.FavoriteStore
}
func NewController(
tx dbtx.Transactor,
principalUIDCheck check.PrincipalUID,
authorizer authz.Authorizer,
principalStore store.PrincipalStore,
tokenStore store.TokenStore,
membershipStore store.MembershipStore,
publicKeyStore store.PublicKeyStore,
publicKeySubKeyStore store.PublicKeySubKeyStore,
gitSignatureResultStore store.GitSignatureResultStore,
eventReporter *userevents.Reporter,
repoFinder refcache.RepoFinder,
favoriteStore store.FavoriteStore,
) *Controller {
return &Controller{
tx: tx,
principalUIDCheck: principalUIDCheck,
authorizer: authorizer,
principalStore: principalStore,
tokenStore: tokenStore,
membershipStore: membershipStore,
publicKeyStore: publicKeyStore,
publicKeySubKeyStore: publicKeySubKeyStore,
gitSignatureResultStore: gitSignatureResultStore,
eventReporter: eventReporter,
repoFinder: repoFinder,
favoriteStore: favoriteStore,
}
}
var hashPassword = bcrypt.GenerateFromPassword
func findUserFromUID(ctx context.Context,
principalStore store.PrincipalStore, userUID string,
) (*types.User, error) {
return principalStore.FindUserByUID(ctx, userUID)
}
func findUserFromEmail(ctx context.Context,
principalStore store.PrincipalStore, email string,
) (*types.User, error) {
return principalStore.FindUserByEmail(ctx, email)
}
func isUserTokenType(tokenType enum.TokenType) bool {
return tokenType == enum.TokenTypePAT || tokenType == enum.TokenTypeSession
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/user/login.go | app/api/controller/user/login.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 user
import (
"context"
"errors"
"github.com/harness/gitness/app/api/usererror"
userevents "github.com/harness/gitness/app/events/user"
"github.com/harness/gitness/app/token"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/bcrypt"
)
type LoginInput struct {
LoginIdentifier string `json:"login_identifier"`
Password string `json:"password"`
}
// Login attempts to login as a specific user - returns the session token if successful.
func (c *Controller) Login(
ctx context.Context,
in *LoginInput,
) (*types.TokenResponse, error) {
// no auth check required, password is used for it.
user, err := findUserFromUID(ctx, c.principalStore, in.LoginIdentifier)
if errors.Is(err, store.ErrResourceNotFound) {
user, err = findUserFromEmail(ctx, c.principalStore, in.LoginIdentifier)
}
// always return not found for security reasons.
if err != nil {
log.Ctx(ctx).Debug().Err(err).
Msgf("failed to retrieve user %q during login (returning ErrNotFound).", in.LoginIdentifier)
return nil, usererror.ErrNotFound
}
err = bcrypt.CompareHashAndPassword(
[]byte(user.Password),
[]byte(in.Password),
)
if err != nil {
log.Debug().Err(err).
Str("user_uid", user.UID).
Msg("invalid password")
return nil, usererror.ErrNotFound
}
tokenIdentifier := token.GenerateIdentifier("login")
token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, tokenIdentifier)
if err != nil {
return nil, err
}
c.eventReporter.LoggedIn(ctx, &userevents.LoggedInPayload{
Base: userevents.Base{PrincipalID: user.ID},
})
return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, 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/user/publickey_create.go | app/api/controller/user/publickey_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 user
import (
"context"
"fmt"
"strings"
"time"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/publickey"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
type CreatePublicKeyInput struct {
Identifier string `json:"identifier"`
Usage enum.PublicKeyUsage `json:"usage"`
Scheme enum.PublicKeyScheme `json:"scheme"`
Content string `json:"content"`
}
func (in *CreatePublicKeyInput) Sanitize() error {
if err := check.Identifier(in.Identifier); err != nil {
return err
}
if _, ok := in.Usage.Sanitize(); !ok {
return errors.InvalidArgument("invalid value for public key usage")
}
if _, ok := in.Scheme.Sanitize(); !ok {
return errors.InvalidArgument("invalid value for public key scheme")
}
in.Content = strings.TrimSpace(in.Content)
if in.Content == "" {
return errors.InvalidArgument("public key not provided")
}
return nil
}
func (c *Controller) CreatePublicKey(
ctx context.Context,
session *auth.Session,
userUID string,
in *CreatePublicKeyInput,
) (*types.PublicKey, error) {
user, err := c.principalStore.FindUserByUID(ctx, userUID)
if err != nil {
return nil, fmt.Errorf("failed to fetch user by uid: %w", err)
}
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return nil, err
}
if err := in.Sanitize(); err != nil {
return nil, err
}
key, err := publickey.ParseString(in.Content, &session.Principal)
if err != nil {
return nil, errors.InvalidArgument("unrecognized key content")
}
if in.Scheme != "" && key.Scheme() != in.Scheme {
return nil, errors.InvalidArgumentf("key is not a valid %s key", in.Scheme)
}
switch key.Scheme() {
case enum.PublicKeySchemeSSH:
if in.Usage == "" {
in.Usage = enum.PublicKeyUsageAuth // backward compatibility, default usage for SSH is auth only
}
case enum.PublicKeySchemePGP:
if in.Usage == "" {
in.Usage = enum.PublicKeyUsageSign
} else if in.Usage != enum.PublicKeyUsageSign {
return nil, errors.InvalidArgument(
"invalid key usage: PGP keys can only be used for verification of signatures")
}
default:
return nil, errors.InvalidArgument("unrecognized public key scheme")
}
now := time.Now().UnixMilli()
k := &types.PublicKey{
PrincipalID: user.ID,
Created: now,
Verified: nil, // the key is created as unverified
Identifier: in.Identifier,
Usage: in.Usage,
Fingerprint: key.Fingerprint(),
Content: in.Content,
Comment: key.Comment(),
Type: key.Type(),
Scheme: key.Scheme(),
ValidFrom: key.ValidFrom(),
ValidTo: key.ValidTo(),
RevocationReason: key.RevocationReason(),
Metadata: key.Metadata(),
}
keyIDs := key.KeyIDs()
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
if err := c.checkKeyExistence(ctx, user.ID, key, k); err != nil {
return err
}
if err = c.publicKeyStore.Create(ctx, k); err != nil {
return fmt.Errorf("failed to insert public key: %w", err)
}
if err = c.publicKeySubKeyStore.Create(ctx, k.ID, keyIDs); err != nil {
return fmt.Errorf("failed to insert public key subkey: %w", err)
}
// If the uploaded key (or a subkey) is revoked (only possible with PGP keys) with reason=compromised
// then we revoke all existing signatures in the DB signed with the key.
compromisedKeyIDs := key.CompromisedIDs()
if len(compromisedKeyIDs) > 0 {
if err = c.gitSignatureResultStore.UpdateAll(
ctx,
enum.GitSignatureRevoked,
user.ID,
compromisedKeyIDs, nil,
); err != nil {
return fmt.Errorf("failed to revoke all PGP signatures signed with compromised keys %v: %w",
compromisedKeyIDs, err)
}
}
return nil
})
if err != nil {
return nil, err
}
return k, nil
}
func (c *Controller) checkKeyExistence(
ctx context.Context,
userID int64,
key publickey.KeyInfo,
k *types.PublicKey,
) error {
schemes := []enum.PublicKeyScheme{key.Scheme()}
switch key.Scheme() {
case enum.PublicKeySchemeSSH:
// For SSH keys we don't allow the same key twice, even for two different users.
// The fingerprint field is indexed in the DB, but it's not a unique index.
existingKeys, err := c.publicKeyStore.ListByFingerprint(ctx, k.Fingerprint, nil, nil, schemes)
if err != nil {
return fmt.Errorf("failed to read keys by fingerprint: %w", err)
}
for _, existingKey := range existingKeys {
if key.Matches(existingKey.Content) {
return errors.InvalidArgument("key is already in use")
}
}
case enum.PublicKeySchemePGP:
// For PGP keys we don't allow the same key twice for the same user.
existingKeys, err := c.publicKeyStore.ListByFingerprint(ctx, k.Fingerprint, &userID, nil, schemes)
if err != nil {
return fmt.Errorf("failed to read keys by userID and fingerprint: %w", err)
}
if len(existingKeys) > 0 {
return errors.InvalidArgument("key is already in use")
}
}
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/user/update_admin.go | app/api/controller/user/update_admin.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 user
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"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type UpdateAdminInput struct {
Admin bool `json:"admin"`
}
// UpdateAdmin updates the admin state of a user.
func (c *Controller) UpdateAdmin(ctx context.Context, session *auth.Session,
userUID string, request *UpdateAdminInput) (*types.User, error) {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEditAdmin); err != nil {
return nil, err
}
// Fail if the user being updated is the only admin in DB.
if user.Admin && !request.Admin {
admUsrCount, err := c.principalStore.CountUsers(ctx, &types.UserFilter{Admin: true})
if err != nil {
return nil, fmt.Errorf("failed to check admin user count: %w", err)
}
if admUsrCount <= 1 {
return nil, usererror.BadRequest("System requires at least one admin user")
}
}
user.Admin = request.Admin
user.Updated = time.Now().UnixMilli()
err = c.principalStore.UpdateUser(ctx, user)
if err != nil {
return nil, err
}
return user, 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/user/publickey_delete.go | app/api/controller/user/publickey_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 user
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) DeletePublicKey(
ctx context.Context,
session *auth.Session,
userUID string,
identifier string,
) error {
user, err := c.principalStore.FindUserByUID(ctx, userUID)
if err != nil {
return fmt.Errorf("failed to fetch user by uid: %w", err)
}
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return err
}
err = c.publicKeyStore.DeleteByIdentifier(ctx, user.ID, identifier)
if err != nil {
return fmt.Errorf("failed to delete public key by id: %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/user/update.go | app/api/controller/user/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 user
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"
"golang.org/x/crypto/bcrypt"
)
// UpdateInput store infos to update an existing user.
type UpdateInput struct {
Email *string `json:"email"`
Password *string `json:"password"`
DisplayName *string `json:"display_name"`
}
// Update updates the provided user.
func (c *Controller) Update(ctx context.Context, session *auth.Session,
userUID string, in *UpdateInput) (*types.User, error) {
user, err := findUserFromUID(ctx, c.principalStore, userUID)
if err != nil {
return nil, err
}
// Ensure principal has required permissions on parent.
if err = apiauth.CheckUser(ctx, c.authorizer, session, user, enum.PermissionUserEdit); err != nil {
return nil, err
}
if err = c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
if in.DisplayName != nil {
user.DisplayName = *in.DisplayName
}
if in.Email != nil {
user.Email = *in.Email
}
if in.Password != nil {
var hash []byte
hash, err = hashPassword([]byte(*in.Password), bcrypt.DefaultCost)
if err != nil {
return nil, fmt.Errorf("failed to hash password: %w", err)
}
user.Password = string(hash)
}
user.Updated = time.Now().UnixMilli()
err = c.principalStore.UpdateUser(ctx, user)
if err != nil {
return nil, err
}
return user, nil
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
if in.Email != nil {
*in.Email = strings.TrimSpace(*in.Email)
if err := check.Email(*in.Email); err != nil {
return err
}
}
if in.DisplayName != nil {
*in.DisplayName = strings.TrimSpace(*in.DisplayName)
if err := check.DisplayName(*in.DisplayName); err != nil {
return err
}
}
if in.Password != nil {
if err := check.Password(*in.Password); 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/usergroup/wire.go | app/api/controller/usergroup/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 usergroup
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/usergroup"
"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(
userGroupStore store.UserGroupStore,
spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
authorizer authz.Authorizer,
searchSvc usergroup.Service,
) *Controller {
return NewController(userGroupStore, spaceStore, spaceFinder, authorizer, searchSvc)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/usergroup/list.go | app/api/controller/usergroup/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 usergroup
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,
filter *types.ListQueryFilter,
spaceRef string,
) ([]*types.UserGroupInfo, error) {
space, err := getSpaceCheckAuth(
ctx, c.spaceFinder, c.authorizer, session, spaceRef, enum.PermissionSpaceView,
)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
userGroupInfos, err := c.userGroupService.List(ctx, filter, space)
if err != nil {
return nil, fmt.Errorf("failed to search user groups: %w", err)
}
return userGroupInfos, 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/usergroup/controller.go | app/api/controller/usergroup/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 usergroup
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/services/usergroup"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type Controller struct {
userGroupStore store.UserGroupStore
spaceStore store.SpaceStore
spaceFinder refcache.SpaceFinder
authorizer authz.Authorizer
userGroupService usergroup.Service
}
func NewController(
userGroupStore store.UserGroupStore,
spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
authorizer authz.Authorizer,
userGroupService usergroup.Service,
) *Controller {
return &Controller{
userGroupStore: userGroupStore,
spaceStore: spaceStore,
spaceFinder: spaceFinder,
authorizer: authorizer,
userGroupService: userGroupService,
}
}
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
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/secret/wire.go | app/api/controller/secret/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 secret
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
encrypter encrypt.Encrypter,
secretStore store.SecretStore,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
) *Controller {
return NewController(authorizer, encrypter, secretStore, spaceFinder)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/secret/create.go | app/api/controller/secret/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 secret
import (
"context"
"fmt"
"strconv"
"strings"
"time"
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/encrypt"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
var (
// errSecretRequiresParent if the user tries to create a secret without a parent space.
errSecretRequiresParent = usererror.BadRequest(
"Parent space required - standalone secret are not supported.")
)
type CreateInput struct {
Description string `json:"description"`
SpaceRef string `json:"space_ref"` // Ref of the parent space
// TODO [CODE-1363]: remove after identifier migration.
UID string `json:"uid" deprecated:"true"`
Identifier string `json:"identifier"`
Data string `json:"data"`
}
func (c *Controller) Create(ctx context.Context, session *auth.Session, in *CreateInput) (*types.Secret, error) {
if err := c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err)
}
err = apiauth.CheckSecret(
ctx,
c.authorizer,
session,
parentSpace.Path,
"",
enum.PermissionSecretEdit,
)
if err != nil {
return nil, err
}
var secret *types.Secret
now := time.Now().UnixMilli()
secret = &types.Secret{
CreatedBy: session.Principal.ID,
Description: in.Description,
Data: in.Data,
SpaceID: parentSpace.ID,
Identifier: in.Identifier,
Created: now,
Updated: now,
Version: 0,
}
secret, err = enc(c.encrypter, secret)
if err != nil {
return nil, fmt.Errorf("could not encrypt secret: %w", err)
}
err = c.secretStore.Create(ctx, secret)
if err != nil {
return nil, fmt.Errorf("secret creation failed: %w", err)
}
return secret, nil
}
func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
// TODO [CODE-1363]: remove after identifier migration.
if in.Identifier == "" {
in.Identifier = in.UID
}
parentRefAsID, err := strconv.ParseInt(in.SpaceRef, 10, 64)
if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(in.SpaceRef)) == 0) {
return errSecretRequiresParent
}
if err := check.Identifier(in.Identifier); err != nil {
return err
}
in.Description = strings.TrimSpace(in.Description)
return check.Description(in.Description)
}
// helper function returns the same secret with encrypted data.
func enc(encrypt encrypt.Encrypter, secret *types.Secret) (*types.Secret, error) {
if secret == nil {
return nil, fmt.Errorf("cannot encrypt a nil secret")
}
s := *secret
ciphertext, err := encrypt.Encrypt(secret.Data)
if err != nil {
return nil, err
}
s.Data = string(ciphertext)
return &s, nil
}
// helper function returns the same secret with decrypted data.
func Dec(encrypt encrypt.Encrypter, secret *types.Secret) (*types.Secret, error) {
if secret == nil {
return nil, fmt.Errorf("cannot decrypt a nil secret")
}
s := *secret
plaintext, err := encrypt.Decrypt([]byte(secret.Data))
if err != nil {
return nil, err
}
s.Data = plaintext
return &s, 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/secret/delete.go | app/api/controller/secret/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 secret
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) Delete(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.CheckSecret(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionSecretDelete)
if err != nil {
return fmt.Errorf("failed to authorize: %w", err)
}
err = c.secretStore.DeleteByIdentifier(ctx, space.ID, identifier)
if err != nil {
return fmt.Errorf("could not delete secret: %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/secret/find.go | app/api/controller/secret/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 secret
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) Find(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) (*types.Secret, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckSecret(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionSecretView)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
secret, err := c.secretStore.FindByIdentifier(ctx, space.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find secret: %w", err)
}
secret, err = Dec(c.encrypter, secret)
if err != nil {
return nil, fmt.Errorf("could not decrypt secret: %w", err)
}
return secret, 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/secret/controller.go | app/api/controller/secret/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 secret
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt"
)
type Controller struct {
encrypter encrypt.Encrypter
secretStore store.SecretStore
authorizer authz.Authorizer
spaceFinder refcache.SpaceFinder
}
func NewController(
authorizer authz.Authorizer,
encrypter encrypt.Encrypter,
secretStore store.SecretStore,
spaceFinder refcache.SpaceFinder,
) *Controller {
return &Controller{
encrypter: encrypter,
secretStore: secretStore,
authorizer: authorizer,
spaceFinder: spaceFinder,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/secret/update.go | app/api/controller/secret/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 secret
import (
"context"
"fmt"
"strings"
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"
)
// UpdateInput is used for updating a repo.
type UpdateInput struct {
// TODO [CODE-1363]: remove after identifier migration.
UID *string `json:"uid" deprecated:"true"`
Identifier *string `json:"identifier"`
Description *string `json:"description"`
Data *string `json:"data"`
}
func (c *Controller) Update(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
in *UpdateInput,
) (*types.Secret, error) {
if err := c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckSecret(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionSecretEdit)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
secret, err := c.secretStore.FindByIdentifier(ctx, space.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find secret: %w", err)
}
return c.secretStore.UpdateOptLock(ctx, secret, func(original *types.Secret) error {
if in.Identifier != nil {
original.Identifier = *in.Identifier
}
if in.Description != nil {
original.Description = *in.Description
}
if in.Data != nil {
data, err := c.encrypter.Encrypt(*in.Data)
if err != nil {
return fmt.Errorf("could not encrypt secret: %w", err)
}
original.Data = string(data)
}
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
}
}
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/connector/wire.go | app/api/controller/connector/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 connector
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/connector"
"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(
connectorStore store.ConnectorStore,
connectorService *connector.Service,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
) *Controller {
return NewController(authorizer, connectorStore, connectorService, spaceFinder)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/connector/create.go | app/api/controller/connector/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 connector
import (
"context"
"fmt"
"strconv"
"strings"
"time"
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"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
var (
// errConnectorRequiresParent if the user tries to create a connector without a parent space.
errConnectorRequiresParent = usererror.BadRequest(
"Parent space required - standalone connector are not supported.")
)
type CreateInput struct {
Description string `json:"description"`
SpaceRef string `json:"space_ref"` // Ref of the parent space
Identifier string `json:"identifier"`
Type enum.ConnectorType `json:"type"`
types.ConnectorConfig
}
func (c *Controller) Create(
ctx context.Context,
session *auth.Session,
in *CreateInput,
) (*types.Connector, error) {
if err := in.validate(); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err)
}
err = apiauth.CheckConnector(
ctx,
c.authorizer,
session,
parentSpace.Path,
"",
enum.PermissionConnectorEdit,
)
if err != nil {
return nil, err
}
now := time.Now().UnixMilli()
connector := &types.Connector{
Description: in.Description,
CreatedBy: session.Principal.ID,
Type: in.Type,
SpaceID: parentSpace.ID,
Identifier: in.Identifier,
Created: now,
Updated: now,
Version: 0,
ConnectorConfig: in.ConnectorConfig,
}
err = c.connectorStore.Create(ctx, connector)
if err != nil {
return nil, fmt.Errorf("connector creation failed: %w", err)
}
return connector, nil
}
func (in *CreateInput) validate() error {
parentRefAsID, err := strconv.ParseInt(in.SpaceRef, 10, 64)
if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(in.SpaceRef)) == 0) {
return errConnectorRequiresParent
}
// check that the connector type is valid
if _, ok := in.Type.Sanitize(); !ok {
return usererror.BadRequest("Invalid connector type")
}
// if the connector type is valid, validate the connector config
if err := in.ConnectorConfig.Validate(in.Type); err != nil {
return usererror.BadRequest(fmt.Sprintf("invalid connector config: %s", err.Error()))
}
if err := check.Identifier(in.Identifier); err != nil {
return err
}
in.Description = strings.TrimSpace(in.Description)
return check.Description(in.Description)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/connector/delete.go | app/api/controller/connector/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 connector
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) Delete(
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.CheckConnector(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionConnectorDelete)
if err != nil {
return fmt.Errorf("failed to authorize: %w", err)
}
err = c.connectorStore.DeleteByIdentifier(ctx, space.ID, identifier)
if err != nil {
return fmt.Errorf("could not delete connector: %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/connector/find.go | app/api/controller/connector/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 connector
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) Find(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) (*types.Connector, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckConnector(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionConnectorView)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
connector, err := c.connectorStore.FindByIdentifier(ctx, space.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find connector: %w", err)
}
return connector, 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/connector/controller.go | app/api/controller/connector/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 connector
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/connector"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
)
type Controller struct {
connectorStore store.ConnectorStore
connectorService *connector.Service
spaceFinder refcache.SpaceFinder
authorizer authz.Authorizer
}
func NewController(
authorizer authz.Authorizer,
connectorStore store.ConnectorStore,
connectorService *connector.Service,
spaceFinder refcache.SpaceFinder,
) *Controller {
return &Controller{
connectorStore: connectorStore,
connectorService: connectorService,
spaceFinder: spaceFinder,
authorizer: authorizer,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/connector/test.go | app/api/controller/connector/test.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 connector
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/enum"
"github.com/rs/zerolog/log"
)
func (c *Controller) Test(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) (types.ConnectorTestResponse, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return types.ConnectorTestResponse{}, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckConnector(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionConnectorAccess)
if err != nil {
return types.ConnectorTestResponse{}, fmt.Errorf("failed to authorize: %w", err)
}
connector, err := c.connectorStore.FindByIdentifier(ctx, space.ID, identifier)
if err != nil {
return types.ConnectorTestResponse{}, fmt.Errorf("failed to find connector: %w", err)
}
resp, err := c.connectorService.Test(ctx, connector)
if err != nil {
return types.ConnectorTestResponse{}, err
}
// Try to update connector last test information in DB. Log but ignore errors
_, err = c.connectorStore.UpdateOptLock(ctx, connector, func(original *types.Connector) error {
original.LastTestErrorMsg = resp.ErrorMsg
original.LastTestStatus = resp.Status
original.LastTestAttempt = time.Now().UnixMilli()
return nil
})
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to update test connection information in connector")
}
return resp, 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/connector/update.go | app/api/controller/connector/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 connector
import (
"context"
"fmt"
"strings"
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"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
// UpdateInput is used for updating a connector.
type UpdateInput struct {
Identifier *string `json:"identifier"`
Description *string `json:"description"`
*types.ConnectorConfig
}
func (c *Controller) Update(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
in *UpdateInput,
) (*types.Connector, error) {
if err := in.validate(); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckConnector(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionConnectorEdit)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
connector, err := c.connectorStore.FindByIdentifier(ctx, space.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find connector: %w", err)
}
return c.connectorStore.UpdateOptLock(ctx, connector, func(original *types.Connector) error {
if in.Identifier != nil {
original.Identifier = *in.Identifier
}
if in.Description != nil {
original.Description = *in.Description
}
// TODO: See if this can be made better. The PATCH API supports partial updates so
// currently we keep all the top level fields the same unless they are explicitly provided.
// The connector config is a nested field so we only check whether it's provided at the top level, and not
// all the fields inside the config. Maybe PUT/POST would be a better option here?
// We can revisit this once we start adding more connectors.
if in.ConnectorConfig != nil {
if err := in.ConnectorConfig.Validate(connector.Type); err != nil {
return usererror.BadRequestf("Failed to validate connector config: %s", err.Error())
}
original.ConnectorConfig = *in.ConnectorConfig
}
return nil
})
}
func (in *UpdateInput) validate() error {
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
}
}
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/execution/wire.go | app/api/controller/execution/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 execution
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/pipeline/canceler"
"github.com/harness/gitness/app/pipeline/commit"
"github.com/harness/gitness/app/pipeline/triggerer"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
tx dbtx.Transactor,
authorizer authz.Authorizer,
executionStore store.ExecutionStore,
checkStore store.CheckStore,
canceler canceler.Canceler,
commitService commit.Service,
triggerer triggerer.Triggerer,
stageStore store.StageStore,
pipelineStore store.PipelineStore,
repoFinder refcache.RepoFinder,
) *Controller {
return NewController(tx, authorizer, executionStore, checkStore,
canceler, commitService, triggerer, stageStore, 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/execution/create.go | app/api/controller/execution/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 execution
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/pipeline/triggerer"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/drone/go-scm/scm"
)
func (c *Controller) Create(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
branch string,
) (*types.Execution, error) {
repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, pipelineIdentifier, enum.PermissionPipelineExecute)
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)
}
// If the branch is empty, use the default branch specified in the pipeline.
// It that is also empty, use the repo default branch.
if branch == "" {
branch = pipeline.DefaultBranch
if branch == "" {
branch = repo.DefaultBranch
}
}
// expand the branch to a git reference.
ref := scm.ExpandRef(branch, "refs/heads")
// Fetch the commit information from the commits service.
commit, err := c.commitService.FindRef(ctx, repo, ref)
if err != nil {
return nil, fmt.Errorf("failed to fetch commit: %w", err)
}
// Create manual hook for execution.
hook := &triggerer.Hook{
Trigger: session.Principal.UID, // who/what triggered the build, different from commit author
AuthorLogin: commit.Author.Identity.Name,
TriggeredBy: session.Principal.ID,
AuthorName: commit.Author.Identity.Name,
AuthorEmail: commit.Author.Identity.Email,
Ref: ref,
Message: commit.Message,
Title: commit.Title,
Before: commit.SHA.String(),
After: commit.SHA.String(),
Sender: session.Principal.UID,
Source: branch,
Target: branch,
Params: map[string]string{},
Timestamp: commit.Author.When.UnixMilli(),
}
// Trigger the execution
return c.triggerer.Trigger(ctx, pipeline, hook)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/execution/cancel.go | app/api/controller/execution/cancel.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 execution
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/pipeline/checks"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
func (c *Controller) Cancel(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
executionNum int64,
) (*types.Execution, error) {
repo, err := c.getRepoCheckPipelineAccess(
ctx,
session,
repoRef,
pipelineIdentifier,
enum.PermissionPipelineExecute,
)
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)
}
execution, err := c.executionStore.FindByNumber(ctx, pipeline.ID, executionNum)
if err != nil {
return nil, fmt.Errorf("failed to find execution %d: %w", executionNum, err)
}
err = c.canceler.Cancel(ctx, repo, execution)
if err != nil {
return nil, fmt.Errorf("unable to cancel execution: %w", err)
}
// Write to the checks store, log and ignore on errors
err = checks.Write(ctx, c.checkStore, execution, pipeline)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("could not update status check")
}
return execution, 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/execution/delete.go | app/api/controller/execution/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 execution
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,
executionNum int64,
) error {
repo, err := c.getRepoCheckPipelineAccess(
ctx,
session,
repoRef,
pipelineIdentifier,
enum.PermissionPipelineDelete,
)
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.executionStore.Delete(ctx, pipeline.ID, executionNum)
if err != nil {
return fmt.Errorf("could not delete execution: %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/execution/find.go | app/api/controller/execution/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 execution
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,
executionNum int64,
) (*types.Execution, 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)
}
execution, err := c.executionStore.FindByNumber(ctx, pipeline.ID, executionNum)
if err != nil {
return nil, fmt.Errorf("failed to find execution %d: %w", executionNum, err)
}
stages, err := c.stageStore.ListWithSteps(ctx, execution.ID)
if err != nil {
return nil, fmt.Errorf("could not query stage information for execution %d: %w",
executionNum, err)
}
// Add stages information to the execution
execution.Stages = stages
return execution, 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/execution/list.go | app/api/controller/execution/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 execution
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"
)
func (c *Controller) List(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
pagination types.Pagination,
) ([]*types.Execution, 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)
}
var count int64
var executions []*types.Execution
err = c.tx.WithTx(ctx, func(ctx context.Context) (err error) {
count, err = c.executionStore.Count(ctx, pipeline.ID)
if err != nil {
return fmt.Errorf("failed to count child executions: %w", err)
}
executions, err = c.executionStore.List(ctx, pipeline.ID, pagination)
if err != nil {
return fmt.Errorf("failed to list child executions: %w", err)
}
return
}, dbtx.TxDefaultReadOnly)
if err != nil {
return executions, count, fmt.Errorf("failed to fetch list: %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/execution/controller.go | app/api/controller/execution/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 execution
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/pipeline/canceler"
"github.com/harness/gitness/app/pipeline/commit"
"github.com/harness/gitness/app/pipeline/triggerer"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type Controller struct {
tx dbtx.Transactor
authorizer authz.Authorizer
executionStore store.ExecutionStore
checkStore store.CheckStore
canceler canceler.Canceler
commitService commit.Service
triggerer triggerer.Triggerer
stageStore store.StageStore
pipelineStore store.PipelineStore
repoFinder refcache.RepoFinder
}
func NewController(
tx dbtx.Transactor,
authorizer authz.Authorizer,
executionStore store.ExecutionStore,
checkStore store.CheckStore,
canceler canceler.Canceler,
commitService commit.Service,
triggerer triggerer.Triggerer,
stageStore store.StageStore,
pipelineStore store.PipelineStore,
repoFinder refcache.RepoFinder,
) *Controller {
return &Controller{
tx: tx,
authorizer: authorizer,
executionStore: executionStore,
checkStore: checkStore,
canceler: canceler,
commitService: commitService,
triggerer: triggerer,
stageStore: stageStore,
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 belong to it.
//
//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/limiter/wire.go | app/api/controller/limiter/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 limiter
import (
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideLimiter,
ProvideGitspaceLimiter,
)
func ProvideLimiter() (ResourceLimiter, error) {
return NewResourceLimiter(), nil
}
func ProvideGitspaceLimiter() Gitspace {
return NewUnlimitedUsage()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/limiter/limiter.go | app/api/controller/limiter/limiter.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 limiter
import (
"context"
"github.com/harness/gitness/errors"
)
var ErrMaxNumReposReached = errors.New("maximum number of repositories reached")
var ErrMaxRepoSizeReached = errors.New("maximum size of repository reached")
// ResourceLimiter is an interface for managing resource limitation.
type ResourceLimiter interface {
// RepoCount allows the creation of a specified number of repositories.
RepoCount(ctx context.Context, spaceID int64, count int) error
// RepoSize allows repository growth up to a limit for the given repoID.
RepoSize(ctx context.Context, repoID int64) error
}
var _ ResourceLimiter = Unlimited{}
type Unlimited struct {
}
// NewResourceLimiter creates a new instance of ResourceLimiter.
func NewResourceLimiter() ResourceLimiter {
return Unlimited{}
}
func (Unlimited) RepoCount(context.Context, int64, int) error {
return nil
}
func (Unlimited) RepoSize(context.Context, int64) 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/limiter/gitspace.go | app/api/controller/limiter/gitspace.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 limiter
import (
"context"
"github.com/harness/gitness/types/enum"
)
// Gitspace is an interface for managing gitspace limitations.
type Gitspace interface {
// Usage checks if the total usage for the root space and all sub-spaces is under a limit.
Usage(ctx context.Context, spaceID int64, infraProviderType enum.InfraProviderType) error
}
var _ Gitspace = (*UnlimitedUsage)(nil)
type UnlimitedUsage struct {
}
// NewUnlimitedUsage creates a new instance of UnlimitedGitspace.
func NewUnlimitedUsage() Gitspace {
return UnlimitedUsage{}
}
func (UnlimitedUsage) Usage(_ context.Context, _ int64, _ enum.InfraProviderType) 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/githook/git.go | app/api/controller/githook/git.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 githook
import (
"context"
"github.com/harness/gitness/git"
"github.com/harness/gitness/git/api"
)
// RestrictedGIT is a git client that is restricted to a subset of operations of git.Interface
// which can be executed on quarantine data that is part of git-hooks (e.g. pre-receive, update, ..)
// and don't alter the repo (so only read operations).
// NOTE: While it doesn't apply to all git-hooks (e.g. post-receive), we still use the interface across the board
// to "soft enforce" no write operations being executed as part of githooks.
type RestrictedGIT interface {
IsAncestor(ctx context.Context, params git.IsAncestorParams) (git.IsAncestorOutput, error)
ScanSecrets(ctx context.Context, param *git.ScanSecretsParams) (*git.ScanSecretsOutput, error)
GetBranch(ctx context.Context, params *git.GetBranchParams) (*git.GetBranchOutput, error)
Diff(ctx context.Context, in *git.DiffParams, files ...api.FileDiffRequest) (<-chan *git.FileDiff, <-chan error)
GetBlob(ctx context.Context, params *git.GetBlobParams) (*git.GetBlobOutput, error)
ProcessPreReceiveObjects(
ctx context.Context,
params git.ProcessPreReceiveObjectsParams,
) (git.ProcessPreReceiveObjectsOutput, error)
MergeBase(ctx context.Context, params git.MergeBaseParams) (git.MergeBaseOutput, 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/githook/wire.go | app/api/controller/githook/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 githook
import (
"github.com/harness/gitness/app/api/controller/limiter"
"github.com/harness/gitness/app/auth/authz"
eventsgit "github.com/harness/gitness/app/events/git"
eventsrepo "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/refcache"
"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/git"
"github.com/harness/gitness/git/hook"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideController,
ProvideFactory,
)
func ProvideFactory() hook.ClientFactory {
return &ControllerClientFactory{
// fields are set in ProvideController to avoid import
githookCtrl: nil,
git: nil,
}
}
func ProvideController(
authorizer authz.Authorizer,
principalStore store.PrincipalStore,
repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
gitReporter *eventsgit.Reporter,
repoReporter *eventsrepo.Reporter,
git git.Interface,
pullreqStore store.PullReqStore,
urlProvider url.Provider,
protectionManager *protection.Manager,
githookFactory hook.ClientFactory,
limiter limiter.ResourceLimiter,
settings *settings.Service,
preReceiveExtender PreReceiveExtender,
updateExtender UpdateExtender,
postReceiveExtender PostReceiveExtender,
sseStreamer sse.Streamer,
lfsStore store.LFSObjectStore,
auditService audit.Service,
userGroupService usergroup.Service,
) *Controller {
ctrl := NewController(
authorizer,
principalStore,
repoStore,
repoFinder,
gitReporter,
repoReporter,
pullreqStore,
urlProvider,
protectionManager,
limiter,
settings,
preReceiveExtender,
updateExtender,
postReceiveExtender,
sseStreamer,
lfsStore,
auditService,
userGroupService,
)
// TODO: improve wiring if possible
if fct, ok := githookFactory.(*ControllerClientFactory); ok {
fct.githookCtrl = ctrl
fct.git = git
}
return ctrl
}
var ExtenderWireSet = wire.NewSet(
ProvidePreReceiveExtender,
ProvideUpdateExtender,
ProvidePostReceiveExtender,
)
func ProvidePreReceiveExtender() (PreReceiveExtender, error) {
return NewPreReceiveExtender(), nil
}
func ProvideUpdateExtender() (UpdateExtender, error) {
return NewUpdateExtender(), nil
}
func ProvidePostReceiveExtender() (PostReceiveExtender, error) {
return NewPostReceiveExtender(), 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/githook/post_receive.go | app/api/controller/githook/post_receive.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 githook
import (
"context"
"fmt"
"slices"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/bootstrap"
gitevents "github.com/harness/gitness/app/events/git"
repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git"
gitapi "github.com/harness/gitness/git/api"
gitenum "github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
)
const (
// gitReferenceNamePrefixBranch is the prefix of references of type branch.
gitReferenceNamePrefixBranch = "refs/heads/"
// gitReferenceNamePrefixTag is the prefix of references of type tag.
gitReferenceNamePrefixTag = "refs/tags/"
// gitReferenceNamePrefixTag is the prefix of pull req references.
gitReferenceNamePullReq = "refs/pullreq/"
)
// refForcePushMap stores branch refs that were force pushed.
type refForcePushMap map[string]struct{}
// PostReceive executes the post-receive hook for a git repository.
func (c *Controller) PostReceive(
ctx context.Context,
rgit RestrictedGIT,
session *auth.Session,
in types.GithookPostReceiveInput,
) (hook.Output, error) {
repoCore, err := c.getRepoCheckAccess(ctx, session, in.RepoID, enum.PermissionRepoPush)
if err != nil {
return hook.Output{}, err
}
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return hook.Output{}, err
}
// create output object and have following messages fill its messages
out := hook.Output{}
defer func() {
logOutputFor(ctx, "post-receive", out)
}()
// update default branch based on ref update info on empty repos.
// as the branch could be different than the configured default value.
c.handleEmptyRepoPush(ctx, repo, in.PostReceiveInput, &out)
// always update last git push time - best effort
c.updateLastGITPushTime(ctx, repo)
// report ref events if repo is in an active state - best effort
forcePushStatus := make(refForcePushMap)
if repo.State == enum.RepoStateActive {
forcePushStatus = c.reportReferenceEvents(ctx, rgit, repo, in.PrincipalID, in.PostReceiveInput)
}
// handle branch updates related to PRs - best effort
c.handlePRMessaging(ctx, rgit, repo, in.PostReceiveInput, &out)
err = c.postReceiveExtender.Extend(ctx, rgit, session, repo.Core(), in, &out)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to extend post-receive hook: %w", err)
}
c.logForcePush(ctx, repo, in.PrincipalID, in.RefUpdates, forcePushStatus)
c.repoReporter.Pushed(ctx, &repoevents.PushedPayload{
Base: repoevents.Base{
RepoID: in.RepoID,
PrincipalID: in.PrincipalID,
},
})
return out, nil
}
// reportReferenceEvents is reporting reference events to the event system.
// NOTE: keep best effort for now as it doesn't change the outcome of the git operation.
// TODO: in the future we might want to think about propagating errors so user is aware of events not being triggered.
func (c *Controller) reportReferenceEvents(
ctx context.Context,
rgit RestrictedGIT,
repo *types.Repository,
principalID int64,
in hook.PostReceiveInput,
) refForcePushMap {
forcePushStatus := make(refForcePushMap)
for _, refUpdate := range in.RefUpdates {
switch {
case strings.HasPrefix(refUpdate.Ref, gitReferenceNamePrefixBranch):
if forced := c.reportBranchEvent(ctx, rgit, repo, principalID, in.Environment, refUpdate); forced {
forcePushStatus[refUpdate.Ref] = struct{}{}
}
case strings.HasPrefix(refUpdate.Ref, gitReferenceNamePrefixTag):
c.reportTagEvent(ctx, repo, principalID, refUpdate)
default:
// Ignore any other references in post-receive
}
}
return forcePushStatus
}
func (c *Controller) reportBranchEvent(
ctx context.Context,
rgit RestrictedGIT,
repo *types.Repository,
principalID int64,
env hook.Environment,
branchUpdate hook.ReferenceUpdate,
) bool {
var forced bool
switch {
case branchUpdate.Old.IsNil():
payload := &gitevents.BranchCreatedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: branchUpdate.Ref,
SHA: branchUpdate.New.String(),
}
c.gitReporter.BranchCreated(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeBranchCreated, payload)
case branchUpdate.New.IsNil():
payload := &gitevents.BranchDeletedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: branchUpdate.Ref,
SHA: branchUpdate.Old.String(),
}
c.gitReporter.BranchDeleted(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeBranchDeleted, payload)
default:
// A force update event might trigger some additional operations that aren't required
// for ordinary updates (force pushes alter the commit history of a branch).
var err error
forced, err = isForcePush(ctx, rgit, repo.GitUID, env.AlternateObjectDirs, branchUpdate)
if err != nil {
// In case of an error consider this a forced update. In post-update the branch has already been updated,
// so there's less harm in declaring the update as forced.
forced = true
log.Ctx(ctx).Warn().Err(err).
Str("ref", branchUpdate.Ref).
Msg("failed to check ancestor")
}
payload := &gitevents.BranchUpdatedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: branchUpdate.Ref,
OldSHA: branchUpdate.Old.String(),
NewSHA: branchUpdate.New.String(),
Forced: forced,
}
c.gitReporter.BranchUpdated(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeBranchUpdated, payload)
}
return forced
}
func (c *Controller) reportTagEvent(
ctx context.Context,
repo *types.Repository,
principalID int64,
tagUpdate hook.ReferenceUpdate,
) {
switch {
case tagUpdate.Old.IsNil():
payload := &gitevents.TagCreatedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: tagUpdate.Ref,
SHA: tagUpdate.New.String(),
}
c.gitReporter.TagCreated(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeTagCreated, payload)
case tagUpdate.New.IsNil():
payload := &gitevents.TagDeletedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: tagUpdate.Ref,
SHA: tagUpdate.Old.String(),
}
c.gitReporter.TagDeleted(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeTagDeleted, payload)
default:
payload := &gitevents.TagUpdatedPayload{
RepoID: repo.ID,
PrincipalID: principalID,
Ref: tagUpdate.Ref,
OldSHA: tagUpdate.Old.String(),
NewSHA: tagUpdate.New.String(),
// tags can only be force updated!
Forced: true,
}
c.gitReporter.TagUpdated(ctx, payload)
c.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeTagUpdated, payload)
}
}
// handlePRMessaging checks any single branch push for pr information and returns an according response if needed.
// TODO: If it is a new branch, or an update on a branch without any PR, it also sends out an SSE for pr creation.
func (c *Controller) handlePRMessaging(
ctx context.Context,
rgit RestrictedGIT,
sourceRepo *types.Repository,
in hook.PostReceiveInput,
out *hook.Output,
) {
// skip anything that was a batch push / isn't branch related / isn't updating/creating a branch.
if len(in.RefUpdates) != 1 ||
!strings.HasPrefix(in.RefUpdates[0].Ref, gitReferenceNamePrefixBranch) ||
in.RefUpdates[0].New.IsNil() {
return
}
// for now we only care about first branch that was pushed.
refUpdate := in.RefUpdates[0]
branchName := refUpdate.Ref[len(gitReferenceNamePrefixBranch):]
newSHA := refUpdate.New
c.suggestPullRequest(ctx, rgit, sourceRepo, branchName, newSHA, out)
// TODO: store latest pushed branch for user in cache and send out SSE
}
func (c *Controller) suggestPullRequest(
ctx context.Context,
rgit RestrictedGIT,
sourceRepo *types.Repository,
branchName string,
newSHA sha.SHA,
out *hook.Output,
) {
// Find the most recent few open PRs created from this branch.
prs, err := c.pullreqStore.List(ctx, &types.PullReqFilter{
Page: 1,
Size: 10,
SourceRepoID: sourceRepo.ID,
SourceBranch: branchName,
// we only care about open PRs - merged/closed will lead to "create new PR" message
States: []enum.PullReqState{enum.PullReqStateOpen},
Order: enum.OrderDesc,
Sort: enum.PullReqSortCreated,
// don't care about the PR description, omit it from the response
ExcludeDescription: true,
})
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf(
"failed to find pullrequests for branch '%s' originating from repo '%s'",
branchName,
sourceRepo.Path,
)
return
}
slices.Reverse(prs) // Use ascending order for message output.
// For already existing PRs, check if the merge base is still unique and if there are PR with non-unique merge base
// print them to users terminal to inform about pending closure.
var prsNonUniqueMergeBase []*types.PullReq
for _, pr := range prs {
if pr.SourceRepoID == nil || *pr.SourceRepoID != pr.TargetRepoID {
continue
}
var targetBranch string
targetBranch, err = git.GetRefPath(pr.TargetBranch, gitenum.RefTypeBranch)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf(
"failed to create target reference from target branch'%s' originating from repo '%s'",
pr.TargetBranch,
sourceRepo.Path,
)
continue
}
_, err = rgit.MergeBase(ctx, git.MergeBaseParams{
ReadParams: git.ReadParams{RepoUID: sourceRepo.GitUID},
Ref1: targetBranch,
Ref2: newSHA.String(),
})
if errors.IsInvalidArgument(err) || gitapi.IsUnrelatedHistoriesError(err) {
prsNonUniqueMergeBase = append(prsNonUniqueMergeBase, pr)
continue
}
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf(
"failed to find merge base for PR #%d originating from repo '%s'",
pr.Number,
sourceRepo.Path,
)
continue
}
}
msgs, err := c.getNonUniqueMergeBasePRsMessages(ctx, sourceRepo, branchName, prsNonUniqueMergeBase)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to get messages for open pull request")
return
}
if len(msgs) > 0 {
out.Messages = append(out.Messages, msgs...)
return
}
// For already existing PRs, print them to users terminal for easier access.
msgs, err = c.getOpenPRsMessages(ctx, sourceRepo, branchName, prs)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to get messages for open pull request")
return
}
if len(msgs) > 0 {
out.Messages = append(out.Messages, msgs...)
return
}
if branchName == sourceRepo.DefaultBranch {
// Don't suggest a pull request if this is a push to the default branch.
return
}
// This is a new PR!
out.Messages = append(out.Messages,
fmt.Sprintf("Create a pull request for %q by visiting:", branchName),
" "+c.urlProvider.GenerateUICompareURL(ctx, sourceRepo.Path, sourceRepo.DefaultBranch, branchName),
)
}
func (c *Controller) getOpenPRsMessages(
ctx context.Context,
sourceRepo *types.Repository,
branchName string,
prs []*types.PullReq,
) ([]string, error) {
if len(prs) == 0 {
return nil, nil
}
msgs := make([]string, 0, 2*len(prs)+1)
if len(prs) == 1 {
msgs = append(msgs, fmt.Sprintf("Branch %q has an open PR:", branchName))
} else {
msgs = append(msgs, fmt.Sprintf("Branch %q has open PRs:", branchName))
}
msgs, err := c.appendPRs(ctx, prs, sourceRepo, msgs)
if err != nil {
return nil, fmt.Errorf("failed to append PRs: %w", err)
}
return msgs, nil
}
func (c *Controller) getNonUniqueMergeBasePRsMessages(
ctx context.Context,
sourceRepo *types.Repository,
branchName string,
prs []*types.PullReq,
) ([]string, error) {
if len(prs) == 0 {
return nil, nil
}
msgs := make([]string, 0, 2*len(prs)+1)
if len(prs) == 1 {
msgs = append(msgs,
fmt.Sprintf("Branch %q has an open PR that would be closed because non-unique merge base:", branchName))
} else {
msgs = append(msgs,
fmt.Sprintf("Branch %q has open PRs that would be closed because non-unique merge base:", branchName))
}
msgs, err := c.appendPRs(ctx, prs, sourceRepo, msgs)
if err != nil {
return nil, fmt.Errorf("failed to append PRs: %w", err)
}
return msgs, nil
}
func (c *Controller) appendPRs(
ctx context.Context,
prs []*types.PullReq,
sourceRepo *types.Repository,
msgs []string,
) ([]string, error) {
for _, pr := range prs {
path := sourceRepo.Path
if pr.TargetRepoID != *pr.SourceRepoID {
targetRepo, err := c.repoFinder.FindByID(ctx, pr.TargetRepoID)
if err != nil {
return nil, fmt.Errorf("failed to find target repo by ID: %w", err)
}
path = targetRepo.Path
}
msgs = append(msgs, fmt.Sprintf(" (#%d) %s", pr.Number, pr.Title))
msgs = append(msgs, " "+c.urlProvider.GenerateUIPRURL(ctx, path, pr.Number))
}
return msgs, nil
}
// handleEmptyRepoPush updates repo default branch on empty repos if push contains branches.
func (c *Controller) handleEmptyRepoPush(
ctx context.Context,
repo *types.Repository,
in hook.PostReceiveInput,
out *hook.Output,
) {
if !repo.IsEmpty {
return
}
var newDefaultBranch string
// update default branch if corresponding branch does not exist
for _, refUpdate := range in.RefUpdates {
if strings.HasPrefix(refUpdate.Ref, gitReferenceNamePrefixBranch) && !refUpdate.New.IsNil() {
branchName := refUpdate.Ref[len(gitReferenceNamePrefixBranch):]
if branchName == repo.DefaultBranch {
newDefaultBranch = branchName
break
}
// use the first pushed branch if default branch is not present.
if newDefaultBranch == "" {
newDefaultBranch = branchName
}
}
}
if newDefaultBranch == "" {
out.Error = ptr.String(usererror.ErrEmptyRepoNeedsBranch.Error())
return
}
oldName := repo.DefaultBranch
var err error
repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error {
r.IsEmpty = false
r.DefaultBranch = newDefaultBranch
return nil
})
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to update the repo default branch to %s and is_empty to false",
newDefaultBranch)
return
}
c.repoFinder.MarkChanged(ctx, repo.Core())
if repo.DefaultBranch != oldName {
c.repoReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{
Base: repoevents.Base{
RepoID: repo.ID,
PrincipalID: bootstrap.NewSystemServiceSession().Principal.ID,
},
OldName: oldName,
NewName: repo.DefaultBranch,
})
}
}
// updateLastGITPushTime updates the repo's last git push time.
func (c *Controller) updateLastGITPushTime(
ctx context.Context,
repo *types.Repository,
) {
newRepo, err := c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error {
r.LastGITPush = time.Now().UnixMilli()
return nil
})
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to update last git push time for repo %q", repo.Path)
return
}
*repo = *newRepo
}
// logForcePush detects and logs force pushes to the default branch.
func (c *Controller) logForcePush(
ctx context.Context,
repo *types.Repository,
principalID int64,
refUpdates []hook.ReferenceUpdate,
forcePushStatus refForcePushMap,
) {
if repo.DefaultBranch == "" {
return
}
defaultBranchRef := gitReferenceNamePrefixBranch + repo.DefaultBranch
_, exists := forcePushStatus[defaultBranchRef]
if !exists {
return
}
var defaultBranchUpdate *hook.ReferenceUpdate
for i := range refUpdates {
if refUpdates[i].Ref == defaultBranchRef && !refUpdates[i].New.IsNil() {
defaultBranchUpdate = &refUpdates[i]
break
}
}
if defaultBranchUpdate == nil {
return
}
principal, err := c.principalStore.Find(ctx, principalID)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to find principal who force pushed to default branch")
return
}
err = c.auditService.Log(ctx,
*principal,
audit.NewResource(
audit.ResourceTypeRepository,
repo.Identifier,
audit.RepoPath,
repo.Path,
audit.BypassedResourceType,
audit.BypassedResourceTypeCommit,
audit.ResourceName,
fmt.Sprintf(
audit.BypassSHALabelFormat,
repo.DefaultBranch,
defaultBranchUpdate.New.String()[0:6],
),
),
audit.ActionForcePush,
paths.Parent(repo.Path),
audit.WithOldObject(audit.CommitObject{
CommitSHA: defaultBranchUpdate.Old.String(),
RepoPath: repo.Path,
}),
audit.WithNewObject(audit.CommitObject{
CommitSHA: defaultBranchUpdate.New.String(),
RepoPath: repo.Path,
}),
)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to insert audit log for force push")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/githook/print.go | app/api/controller/githook/print.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 githook
import (
"fmt"
"time"
"github.com/harness/gitness/git"
"github.com/harness/gitness/git/hook"
"github.com/fatih/color"
)
var (
colorScanHeader = color.New(color.FgHiWhite, color.Underline)
colorScanSummary = color.New(color.FgHiRed, color.Bold)
colorScanSummaryNoFindings = color.New(color.FgHiGreen, color.Bold)
)
func printScanSecretsFindings(
output *hook.Output,
findings []secretFinding,
multipleRefs bool,
duration time.Duration,
) {
findingsCnt := len(findings)
// no results? output success and continue
if findingsCnt == 0 {
output.Messages = append(
output.Messages,
colorScanSummaryNoFindings.Sprintf("No secrets found")+
fmt.Sprintf(" in %s", duration.Round(time.Millisecond)),
"", "", // add two empty lines for making it visually more consumable
)
return
}
output.Messages = append(
output.Messages,
colorScanHeader.Sprintf(
"Push contains %s:",
singularOrPlural("secret", findingsCnt > 1),
),
"", // add empty line for making it visually more consumable
)
for _, finding := range findings {
headerTxt := fmt.Sprintf("%s in %s:%d", finding.RuleID, finding.File, finding.StartLine)
if finding.StartLine != finding.EndLine {
headerTxt += fmt.Sprintf("-%d", finding.EndLine)
}
if multipleRefs {
headerTxt += fmt.Sprintf(" [%s]", finding.Ref)
}
output.Messages = append(
output.Messages,
fmt.Sprintf(" %s", headerTxt),
fmt.Sprintf(" Secret: %s", finding.Secret),
fmt.Sprintf(" Commit: %s", finding.Commit),
fmt.Sprintf(" Details: %s", finding.Description),
fmt.Sprintf(" Fingerprint: %s", finding.Fingerprint),
"", // add empty line for making it visually more consumable
)
}
output.Messages = append(
output.Messages,
colorScanSummary.Sprintf(
"%d %s found",
findingsCnt,
singularOrPlural("secret", findingsCnt > 1),
)+fmt.Sprintf(" in %s", FMTDuration(time.Millisecond)),
"", "", // add two empty lines for making it visually more consumable
)
}
func FMTDuration(d time.Duration) string {
const secondsRounding = time.Second / time.Duration(10)
switch {
case d <= time.Millisecond:
// keep anything under a millisecond untouched
case d < time.Second:
d = d.Round(time.Millisecond) // round under a second to millisecondss
case d < time.Minute:
d = d.Round(secondsRounding) // round under a minute to .1 precision
default:
d = d.Round(time.Second) // keep rest at second precision
}
return d.String()
}
func printOversizeFiles(
output *hook.Output,
oversizeFiles []git.FileInfo,
total int64,
sizeLimit int64,
) {
output.Messages = append(
output.Messages,
colorScanHeader.Sprintf(
"Push contains files exceeding the size limit:",
),
"", // add empty line for making it visually more consumable
)
for _, file := range oversizeFiles {
output.Messages = append(
output.Messages,
fmt.Sprintf(" %s", file.SHA),
fmt.Sprintf(" Size: %dB", file.Size),
"", // add empty line for making it visually more consumable
)
}
output.Messages = append(
output.Messages,
colorScanSummary.Sprintf(
"%d %s found exceeding the size limit of %dB",
total, singularOrPlural("file", total > 1), sizeLimit,
),
"", "", // add two empty lines for making it visually more consumable
)
}
func printCommitterMismatch(
output *hook.Output,
commitInfos []git.CommitInfo,
principalEmail string,
total int64,
) {
output.Messages = append(
output.Messages,
colorScanHeader.Sprintf(
"Push contains commits where committer is not the authenticated user (%s):",
principalEmail,
),
"", // add empty line for making it visually more consumable
)
for _, info := range commitInfos {
output.Messages = append(
output.Messages,
fmt.Sprintf(" %s Committer: %s", info.SHA, info.Committer),
"", // add empty line for making it visually more consumable
)
}
output.Messages = append(
output.Messages,
colorScanSummary.Sprintf(
"%d %s found not matching the authenticated user (%s)",
total, singularOrPlural("commit", total > 1), principalEmail,
),
"", "", // add two empty lines for making it visually more consumable
)
}
func printLFSPointers(
output *hook.Output,
lfsInfos []git.LFSInfo,
total int64,
) {
output.Messages = append(
output.Messages,
colorScanHeader.Sprintf(
"Push references unknown LFS objects:",
),
"", // add empty line for making it visually more consumable
)
for _, info := range lfsInfos {
output.Messages = append(
output.Messages,
fmt.Sprintf(" Object ID: %s", info.ObjID),
fmt.Sprintf(" File SHA : %s", info.SHA),
"", // add empty line for making it visually more consumable
)
}
output.Messages = append(
output.Messages,
colorScanSummary.Sprintf(
"%d %s missing",
total, singularOrPlural("LFS object", total > 1),
),
"", "", // add two empty lines for making it visually more consumable
)
}
func singularOrPlural(noun string, plural bool) string {
if plural {
return noun + "s"
}
return noun
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/githook/client.go | app/api/controller/githook/client.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 githook
import (
"context"
"errors"
"fmt"
"github.com/harness/gitness/app/githook"
"github.com/harness/gitness/git"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
)
var _ hook.ClientFactory = (*ControllerClientFactory)(nil)
var _ hook.Client = (*ControllerClient)(nil)
// ControllerClientFactory creates clients that directly call the controller to execute githooks.
type ControllerClientFactory struct {
githookCtrl *Controller
git git.Interface
}
func (f *ControllerClientFactory) NewClient(envVars map[string]string) (hook.Client, error) {
payload, err := hook.LoadPayloadFromMap[githook.Payload](envVars)
if err != nil {
return nil, fmt.Errorf("failed to load payload from provided map of environment variables: %w", err)
}
// ensure we return disabled message in case it's explicitly disabled
if payload.Disabled {
return hook.NewNoopClient([]string{"hook disabled"}), nil
}
if err := payload.Validate(); err != nil {
return nil, fmt.Errorf("payload validation failed: %w", err)
}
return &ControllerClient{
baseInput: githook.GetInputBaseFromPayload(payload),
githookCtrl: f.githookCtrl,
git: f.git,
}, nil
}
// ControllerClient directly calls the controller to execute githooks.
type ControllerClient struct {
baseInput types.GithookInputBase
githookCtrl *Controller
git RestrictedGIT
}
func (c *ControllerClient) PreReceive(
ctx context.Context,
in hook.PreReceiveInput,
) (hook.Output, error) {
log.Ctx(ctx).Debug().Int64("repo_id", c.baseInput.RepoID).Msg("calling pre-receive")
out, err := c.githookCtrl.PreReceive(
ctx,
c.git, // Harness doesn't require any custom git connector.
nil, // TODO: update once githooks are auth protected
types.GithookPreReceiveInput{
GithookInputBase: c.baseInput,
PreReceiveInput: in,
},
)
if err != nil {
return hook.Output{}, translateControllerError(err)
}
return out, nil
}
func (c *ControllerClient) Update(
ctx context.Context,
in hook.UpdateInput,
) (hook.Output, error) {
log.Ctx(ctx).Debug().Int64("repo_id", c.baseInput.RepoID).Msg("calling update")
out, err := c.githookCtrl.Update(
ctx,
c.git, // Harness doesn't require any custom git connector.
nil, // TODO: update once githooks are auth protected
types.GithookUpdateInput{
GithookInputBase: c.baseInput,
UpdateInput: in,
},
)
if err != nil {
return hook.Output{}, translateControllerError(err)
}
return out, nil
}
func (c *ControllerClient) PostReceive(
ctx context.Context,
in hook.PostReceiveInput,
) (hook.Output, error) {
log.Ctx(ctx).Debug().Int64("repo_id", c.baseInput.RepoID).Msg("calling post-receive")
out, err := c.githookCtrl.PostReceive(
ctx,
c.git, // Harness doesn't require any custom git connector.
nil, // TODO: update once githooks are auth protected
types.GithookPostReceiveInput{
GithookInputBase: c.baseInput,
PostReceiveInput: in,
},
)
if err != nil {
return hook.Output{}, translateControllerError(err)
}
return out, nil
}
func translateControllerError(err error) error {
if errors.Is(err, store.ErrResourceNotFound) {
return hook.ErrNotFound
}
return 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/githook/pre_receive_scan_secrets.go | app/api/controller/githook/pre_receive_scan_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 githook
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/git"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/logging"
"github.com/harness/gitness/types"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
)
type secretFinding struct {
git.ScanSecretsFinding
Ref string
}
func (c *Controller) scanSecrets(
ctx context.Context,
rgit RestrictedGIT,
repo *types.RepositoryCore,
scanningEnabled bool,
violationsInput *protection.PushViolationsInput,
in types.GithookPreReceiveInput,
output *hook.Output,
) error {
if !scanningEnabled {
var err error
scanningEnabled, err = settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeySecretScanningEnabled,
settings.DefaultSecretScanningEnabled,
)
if err != nil {
return fmt.Errorf("failed to check settings whether secret scanning is enabled: %w", err)
}
}
if !scanningEnabled {
return nil
}
// scan for secrets
startTime := time.Now()
findings, err := scanSecretsInternal(
ctx,
rgit,
repo,
in,
)
if err != nil {
return fmt.Errorf("failed to scan for git leaks: %w", err)
}
// always print result (handles both no results and results found)
printScanSecretsFindings(output, findings, len(in.RefUpdates) > 1, time.Since(startTime))
// this will be removed when secret scanning check will be moved to push protection
if len(findings) > 0 && violationsInput == nil {
errMsg := fmt.Sprintf("Found %d secret(s) in your code. Push rejected.", len(findings))
output.Error = ptr.String(errMsg)
}
if violationsInput != nil {
violationsInput.SecretScanningEnabled = scanningEnabled
violationsInput.FoundSecretCount = len(findings)
}
return nil
}
func scanSecretsInternal(ctx context.Context,
rgit RestrictedGIT,
repo *types.RepositoryCore,
in types.GithookPreReceiveInput,
) ([]secretFinding, error) {
var baseRevFallBack *string
findings := []secretFinding{}
for _, refUpdate := range in.RefUpdates {
ctx := logging.NewContext(ctx, loggingWithRefUpdate(refUpdate))
log := log.Ctx(ctx)
if refUpdate.New.IsNil() {
log.Debug().Msg("skip deleted reference")
continue
}
// in case the branch was just created - fallback to compare against latest default branch.
baseRev := refUpdate.Old.String() + "^{commit}" //nolint:goconst
rev := refUpdate.New.String() + "^{commit}" //nolint:goconst
//nolint:nestif
if refUpdate.Old.IsNil() {
if baseRevFallBack == nil {
fallbackSHA, fallbackAvailable, err := GetBaseSHAForScanningChanges(
ctx,
rgit,
repo,
in.Environment,
in.RefUpdates,
refUpdate,
)
if err != nil {
return nil, fmt.Errorf("failed to get fallback sha: %w", err)
}
if fallbackAvailable {
log.Debug().Msgf("found fallback sha %q", fallbackSHA)
baseRevFallBack = ptr.String(fallbackSHA.String())
} else {
log.Debug().Msg("no fallback sha available, do full scan instead")
baseRevFallBack = ptr.String("")
}
}
log.Debug().Msgf("new reference, use rev %q as base for secret scanning", *baseRevFallBack)
baseRev = *baseRevFallBack
}
log.Debug().Msg("scan for secrets")
scanSecretsOut, err := rgit.ScanSecrets(ctx, &git.ScanSecretsParams{
ReadParams: git.ReadParams{
RepoUID: repo.GitUID,
AlternateObjectDirs: in.Environment.AlternateObjectDirs,
},
BaseRev: baseRev,
Rev: rev,
GitleaksIgnorePath: git.DefaultGitleaksIgnorePath,
})
if err != nil {
return nil, fmt.Errorf("failed to detect secret leaks: %w", err)
}
if len(scanSecretsOut.Findings) == 0 {
log.Debug().Msg("no new secrets found")
continue
}
log.Debug().Msgf("found %d new secrets", len(scanSecretsOut.Findings))
for _, finding := range scanSecretsOut.Findings {
findings = append(findings, secretFinding{
ScanSecretsFinding: finding,
Ref: refUpdate.Ref,
})
}
}
if len(findings) > 0 {
log.Ctx(ctx).Debug().Msgf("found total of %d new secrets", len(findings))
}
return findings, 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/githook/pre_receive.go | app/api/controller/githook/pre_receive.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 githook
import (
"context"
"fmt"
"strings"
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/services/protection"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
"github.com/rs/zerolog"
"golang.org/x/exp/slices"
)
// allowedRepoStatesForPush lists repository states that git push is allowed for internal and external calls.
var allowedRepoStatesForPush = []enum.RepoState{enum.RepoStateActive, enum.RepoStateMigrateGitPush}
// PreReceive executes the pre-receive hook for a git repository.
func (c *Controller) PreReceive(
ctx context.Context,
rgit RestrictedGIT,
session *auth.Session,
in types.GithookPreReceiveInput,
) (hook.Output, error) {
output := hook.Output{}
defer func() {
logOutputFor(ctx, "pre-receive", output)
}()
repo, err := c.getRepoCheckAccess(ctx, session, in.RepoID, enum.PermissionRepoPush)
if err != nil {
return hook.Output{}, err
}
if !in.Internal && repo.Type == enum.RepoTypeLinked {
output.Error = ptr.String("Push not allowed to a linked repository")
return output, nil
}
if !in.Internal && !slices.Contains(allowedRepoStatesForPush, repo.State) {
output.Error = ptr.String(fmt.Sprintf("Push not allowed when repository is in '%s' state", repo.State))
return output, nil
}
if err := c.limiter.RepoSize(ctx, in.RepoID); err != nil {
return hook.Output{}, fmt.Errorf(
"resource limit exceeded: %w", limiter.ErrMaxRepoSizeReached,
)
}
forced := make([]bool, len(in.RefUpdates))
for i, refUpdate := range in.RefUpdates {
forced[i], err = isForcePush(
ctx, rgit, repo.GitUID, in.Environment.AlternateObjectDirs, refUpdate,
)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to check branch ancestor: %w", err)
}
}
refUpdates := groupRefsByAction(in.RefUpdates, forced)
if slices.Contains(refUpdates.branches.deleted, repo.DefaultBranch) {
// Default branch mustn't be deleted.
output.Error = ptr.String(usererror.ErrDefaultBranchCantBeDeleted.Error())
return output, nil
}
// For external calls (git pushes) block modification of pullreq references.
if !in.Internal && c.blockPullReqRefUpdate(refUpdates, repo.State) {
output.Error = ptr.String(usererror.ErrPullReqRefsCantBeModified.Error())
return output, nil
}
protectionRules, err := c.protectionManager.ListRepoRules(
ctx, repo.ID, protection.TypeBranch, protection.TypeTag, protection.TypePush,
)
if err != nil {
return hook.Output{}, fmt.Errorf(
"failed to fetch protection rules for the repository: %w", err,
)
}
var principal *types.Principal
repoActive := repo.State == enum.RepoStateActive
if repoActive {
// TODO: use store.PrincipalInfoCache once we abstracted principals.
principal, err = c.principalStore.Find(ctx, in.PrincipalID)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to find inner principal with id %d: %w", in.PrincipalID, err)
}
}
var ruleViolations []types.RuleViolations
var isRepoOwner bool
// For internal calls - through the application interface (API) - no need to verify protection rules.
if !in.Internal && repoActive {
dummySession := &auth.Session{Principal: *principal, Metadata: nil}
isRepoOwner, err = apiauth.IsRepoOwner(ctx, c.authorizer, dummySession, repo)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to determine if user is repo owner: %w", err)
}
ruleViolations, err = c.checkProtectionRules(
ctx, dummySession, repo, refUpdates, protectionRules, isRepoOwner,
)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to check protection rules: %w", err)
}
if output.Error != nil {
return output, nil
}
}
err = c.preReceiveExtender.Extend(ctx, rgit, session, repo, in, &output)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to extend pre-receive hook: %w", err)
}
if output.Error != nil {
return output, nil
}
if repoActive {
// check secret scanning apart from push rules as it is enabled in repository settings.
err = c.scanSecrets(ctx, rgit, repo, false, nil, in, &output)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to scan secrets: %w", err)
}
if output.Error != nil {
return output, nil
}
violations, err := c.processPushProtection(
ctx, rgit, repo, principal, isRepoOwner, refUpdates, protectionRules, in, &output,
)
if err != nil {
return hook.Output{}, err
}
ruleViolations = append(ruleViolations, violations...)
processRuleViolations(&output, ruleViolations)
}
return output, nil
}
// processPushProtection handles push protection verification for active repositories.
func (c *Controller) processPushProtection(
ctx context.Context,
rgit RestrictedGIT,
repo *types.RepositoryCore,
principal *types.Principal,
isRepoOwner bool,
refUpdates changedRefs,
protectionRules []types.RuleInfoInternal,
in types.GithookPreReceiveInput,
output *hook.Output,
) ([]types.RuleViolations, error) {
pushProtection := c.protectionManager.FilterCreatePushProtection(protectionRules)
out, _, err := pushProtection.PushVerify(
ctx,
protection.PushVerifyInput{
ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs,
Actor: principal,
IsRepoOwner: isRepoOwner,
RepoID: repo.ID,
RepoIdentifier: repo.Identifier,
},
)
if err != nil {
return nil, fmt.Errorf("failed to verify git objects: %w", err)
}
if len(out.Protections) == 0 {
// No push protections to verify.
return []types.RuleViolations{}, nil
}
violationsInput := &protection.PushViolationsInput{
ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs,
Actor: principal,
IsRepoOwner: isRepoOwner,
Protections: out.Protections,
}
err = c.scanSecrets(ctx, rgit, repo, out.SecretScanningEnabled, violationsInput, in, output)
if err != nil {
return nil, fmt.Errorf("failed to scan secrets: %w", err)
}
if err = c.processObjects(
ctx, rgit,
repo, principal, refUpdates,
out.FileSizeLimit, out.PrincipalCommitterMatch, violationsInput,
in, output,
); err != nil {
return nil, fmt.Errorf("failed to process pre-receive objects: %w", err)
}
var violations []types.RuleViolations
if violationsInput.HasViolations() {
pushViolations, err := pushProtection.Violations(ctx, violationsInput)
if err != nil {
return nil, fmt.Errorf("failed to backfill violations: %w", err)
}
violations = pushViolations.Violations
}
return violations, nil
}
func (c *Controller) blockPullReqRefUpdate(refUpdates changedRefs, state enum.RepoState) bool {
if state == enum.RepoStateMigrateGitPush {
return false
}
fn := func(ref string) bool {
return strings.HasPrefix(ref, gitReferenceNamePullReq)
}
return slices.ContainsFunc(refUpdates.other.created, fn) ||
slices.ContainsFunc(refUpdates.other.deleted, fn) ||
slices.ContainsFunc(refUpdates.other.updated, fn) ||
slices.ContainsFunc(refUpdates.other.forced, fn)
}
func (c *Controller) checkProtectionRules(
ctx context.Context,
session *auth.Session,
repo *types.RepositoryCore,
refUpdates changedRefs,
protectionRules []types.RuleInfoInternal,
isRepoOwner bool,
) ([]types.RuleViolations, error) {
branchProtection := c.protectionManager.FilterCreateBranchProtection(protectionRules)
tagProtection := c.protectionManager.FilterCreateTagProtection(protectionRules)
var ruleViolations []types.RuleViolations
var errCheckAction error
//nolint:unparam
checkAction := func(
refProtection protection.RefProtection,
refAction protection.RefAction,
refType protection.RefType,
names []string,
) {
if errCheckAction != nil || len(names) == 0 {
return
}
violations, err := refProtection.RefChangeVerify(ctx, protection.RefChangeVerifyInput{
ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs,
Actor: &session.Principal,
AllowBypass: true,
IsRepoOwner: isRepoOwner,
Repo: repo,
RefAction: refAction,
RefType: refType,
RefNames: names,
})
if err != nil {
errCheckAction = fmt.Errorf("failed to verify protection rules for git push: %w", err)
return
}
ruleViolations = append(ruleViolations, violations...)
}
checkAction(
branchProtection, protection.RefActionCreate,
protection.RefTypeBranch, refUpdates.branches.created,
)
checkAction(
branchProtection, protection.RefActionDelete,
protection.RefTypeBranch, refUpdates.branches.deleted,
)
checkAction(
branchProtection, protection.RefActionUpdate,
protection.RefTypeBranch, refUpdates.branches.updated,
)
checkAction(
branchProtection, protection.RefActionUpdateForce,
protection.RefTypeBranch, refUpdates.branches.forced,
)
checkAction(
tagProtection, protection.RefActionCreate,
protection.RefTypeTag, refUpdates.tags.created,
)
checkAction(
tagProtection, protection.RefActionDelete,
protection.RefTypeTag, refUpdates.tags.deleted,
)
checkAction(
tagProtection, protection.RefActionUpdateForce,
protection.RefTypeTag, refUpdates.tags.forced,
)
if errCheckAction != nil {
return nil, errCheckAction
}
return ruleViolations, nil
}
func processRuleViolations(
output *hook.Output,
ruleViolations []types.RuleViolations,
) {
if len(ruleViolations) == 0 {
return
}
var criticalViolation bool
for _, ruleViolation := range ruleViolations {
criticalViolation = criticalViolation || ruleViolation.IsCritical()
for _, violation := range ruleViolation.Violations {
var message string
if ruleViolation.Bypassed {
message = fmt.Sprintf("Bypassed rule %q: %s", ruleViolation.Rule.Identifier, violation.Message)
} else {
message = fmt.Sprintf("Rule %q violation: %s", ruleViolation.Rule.Identifier, violation.Message)
}
output.Messages = append(output.Messages, message)
}
}
if criticalViolation {
output.Error = ptr.String("Blocked by protection rules.")
}
}
type changes struct {
created []string
deleted []string
updated []string
forced []string
}
func (c *changes) groupByAction(
refUpdate hook.ReferenceUpdate,
name string,
forced bool,
) {
switch {
case refUpdate.Old.IsNil():
c.created = append(c.created, name)
case refUpdate.New.IsNil():
c.deleted = append(c.deleted, name)
case forced:
c.forced = append(c.forced, name)
default:
c.updated = append(c.updated, name)
}
}
type changedRefs struct {
branches changes
tags changes
other changes
}
func (c *changedRefs) hasOnlyDeletedBranches() bool {
if len(c.branches.created) > 0 || len(c.branches.updated) > 0 || len(c.branches.forced) > 0 {
return false
}
return true
}
func isBranch(ref string) bool {
return strings.HasPrefix(ref, gitReferenceNamePrefixBranch)
}
func isTag(ref string) bool {
return strings.HasPrefix(ref, gitReferenceNamePrefixTag)
}
func groupRefsByAction(refUpdates []hook.ReferenceUpdate, forced []bool) (c changedRefs) {
for i, refUpdate := range refUpdates {
switch {
case isBranch(refUpdate.Ref):
branchName := refUpdate.Ref[len(gitReferenceNamePrefixBranch):]
c.branches.groupByAction(refUpdate, branchName, forced[i])
case isTag(refUpdate.Ref):
tagName := refUpdate.Ref[len(gitReferenceNamePrefixTag):]
c.tags.groupByAction(refUpdate, tagName, forced[i])
default:
c.other.groupByAction(refUpdate, refUpdate.Ref, false)
}
}
return
}
func loggingWithRefUpdate(refUpdate hook.ReferenceUpdate) func(c zerolog.Context) zerolog.Context {
return func(c zerolog.Context) zerolog.Context {
return c.Str("ref", refUpdate.Ref).Str("old_sha", refUpdate.Old.String()).Str("new_sha", refUpdate.New.String())
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/githook/controller.go | app/api/controller/githook/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 githook
import (
"context"
"fmt"
"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"
gitevents "github.com/harness/gitness/app/events/git"
repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/refcache"
"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"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
type Controller struct {
authorizer authz.Authorizer
principalStore store.PrincipalStore
repoStore store.RepoStore
repoFinder refcache.RepoFinder
gitReporter *gitevents.Reporter
repoReporter *repoevents.Reporter
pullreqStore store.PullReqStore
urlProvider url.Provider
protectionManager *protection.Manager
limiter limiter.ResourceLimiter
settings *settings.Service
preReceiveExtender PreReceiveExtender
updateExtender UpdateExtender
postReceiveExtender PostReceiveExtender
sseStreamer sse.Streamer
lfsStore store.LFSObjectStore
auditService audit.Service
userGroupService usergroup.Service
}
func NewController(
authorizer authz.Authorizer,
principalStore store.PrincipalStore,
repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
gitReporter *gitevents.Reporter,
repoReporter *repoevents.Reporter,
pullreqStore store.PullReqStore,
urlProvider url.Provider,
protectionManager *protection.Manager,
limiter limiter.ResourceLimiter,
settings *settings.Service,
preReceiveExtender PreReceiveExtender,
updateExtender UpdateExtender,
postReceiveExtender PostReceiveExtender,
sseStreamer sse.Streamer,
lfsStore store.LFSObjectStore,
auditService audit.Service,
userGroupService usergroup.Service,
) *Controller {
return &Controller{
authorizer: authorizer,
principalStore: principalStore,
repoStore: repoStore,
repoFinder: repoFinder,
gitReporter: gitReporter,
repoReporter: repoReporter,
pullreqStore: pullreqStore,
urlProvider: urlProvider,
protectionManager: protectionManager,
limiter: limiter,
settings: settings,
preReceiveExtender: preReceiveExtender,
updateExtender: updateExtender,
postReceiveExtender: postReceiveExtender,
sseStreamer: sseStreamer,
lfsStore: lfsStore,
auditService: auditService,
userGroupService: userGroupService,
}
}
func (c *Controller) getRepoCheckAccess(
ctx context.Context,
_ *auth.Session,
repoID int64,
_ enum.Permission,
) (*types.RepositoryCore, error) {
if repoID < 1 {
return nil, usererror.BadRequest("A valid repository reference must be provided.")
}
repo, err := c.repoFinder.FindByID(ctx, repoID)
if err != nil {
return nil, fmt.Errorf("failed to find repo with id %d: %w", repoID, err)
}
// repo state check is done in pre-receive.
// TODO: execute permission check. block anything but Harness service?
return repo, nil
}
// GetBaseSHAForScanningChanges returns the commit sha to which the new sha of the reference
// should be compared against when scanning incoming changes.
// NOTE: If no such a sha exists, then (sha.None, false, nil) is returned.
// This will happen in case the default branch doesn't exist yet.
func GetBaseSHAForScanningChanges(
ctx context.Context,
rgit RestrictedGIT,
repo *types.RepositoryCore,
env hook.Environment,
refUpdates []hook.ReferenceUpdate,
findBaseFor hook.ReferenceUpdate,
) (sha.SHA, bool, error) {
// always return old SHA of ref if possible (even if ref was deleted, that's on the caller)
if !findBaseFor.Old.IsNil() {
return findBaseFor.Old, true, nil
}
// reference is just being created.
// For now we use default branch as a fallback (can be optimized to most recent commit on reference that exists)
dfltBranchFullRef := api.BranchPrefix + repo.DefaultBranch
for _, refUpdate := range refUpdates {
if refUpdate.Ref != dfltBranchFullRef {
continue
}
// default branch is being updated as part of push - make sure we use OLD default branch sha for comparison
if !refUpdate.Old.IsNil() {
return refUpdate.Old, true, nil
}
// default branch is being created - no fallback available
return sha.None, false, nil
}
// read default branch from git
dfltBranchOut, err := rgit.GetBranch(ctx, &git.GetBranchParams{
ReadParams: git.ReadParams{
RepoUID: repo.GitUID,
AlternateObjectDirs: env.AlternateObjectDirs,
},
BranchName: repo.DefaultBranch,
})
if errors.IsNotFound(err) {
// this happens for empty repo's where the default branch wasn't created yet.
return sha.None, false, nil
}
if err != nil {
return sha.None, false, fmt.Errorf("failed to get default branch from git: %w", err)
}
return dfltBranchOut.Branch.SHA, true, nil
}
func isForcePush(
ctx context.Context,
rgit RestrictedGIT,
gitUID string,
alternateObjectDirs []string,
refUpdate hook.ReferenceUpdate,
) (bool, error) {
if refUpdate.Old.IsNil() || refUpdate.New.IsNil() {
return false, nil
}
if isTag(refUpdate.Ref) {
return true, nil
}
result, err := rgit.IsAncestor(ctx, git.IsAncestorParams{
ReadParams: git.ReadParams{
RepoUID: gitUID,
AlternateObjectDirs: alternateObjectDirs,
},
AncestorCommitSHA: refUpdate.Old,
DescendantCommitSHA: refUpdate.New,
})
if err != nil {
return false, err
}
return !result.Ancestor, nil
}
func logOutputFor(ctx context.Context, hookName string, output hook.Output) {
event := log.Ctx(ctx).Info()
if output.Error != nil {
event = event.Str("output.error", *output.Error)
}
if len(output.Messages) > 0 {
filteredMsgs := make([]string, 0, len(output.Messages)/2+1)
for _, msg := range output.Messages {
if msg == "" {
continue
}
filteredMsgs = append(filteredMsgs, msg)
}
const maxMessageLines = 16
if len(filteredMsgs) > maxMessageLines {
filteredMsgs = append(filteredMsgs[:maxMessageLines], fmt.Sprintf("... %d more", len(filteredMsgs)-maxMessageLines))
}
event = event.Strs("output.messages", filteredMsgs)
}
event.Msgf("%s hook output", hookName)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/githook/pre_receive_process.go | app/api/controller/githook/pre_receive_process.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 githook
import (
"context"
"fmt"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/git"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types"
"github.com/gotidy/ptr"
)
func (c *Controller) processObjects(
ctx context.Context,
rgit RestrictedGIT,
repo *types.RepositoryCore,
principal *types.Principal,
refUpdates changedRefs,
sizeLimit int64,
principalCommitterMatch bool,
violationsInput *protection.PushViolationsInput,
in types.GithookPreReceiveInput,
output *hook.Output,
) error {
if refUpdates.hasOnlyDeletedBranches() {
return nil
}
// TODO: Remove this once push rules implementation and migration are complete.
settingsSizeLimit, err := settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeyFileSizeLimit,
settings.DefaultFileSizeLimit,
)
if err != nil {
return fmt.Errorf("failed to check settings for file size limit: %w", err)
}
if sizeLimit == 0 || (settingsSizeLimit > 0 && sizeLimit > settingsSizeLimit) {
sizeLimit = settingsSizeLimit
}
// TODO: Remove this once push rules implementation and migration are complete.
if !principalCommitterMatch {
principalCommitterMatch, err = settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeyPrincipalCommitterMatch,
settings.DefaultPrincipalCommitterMatch,
)
if err != nil {
return fmt.Errorf("failed to check settings for principal committer match: %w", err)
}
}
gitLFSEnabled, err := settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeyGitLFSEnabled,
settings.DefaultGitLFSEnabled,
)
if err != nil {
return fmt.Errorf("failed to check settings for Git LFS enabled: %w", err)
}
if sizeLimit == 0 && !principalCommitterMatch && !gitLFSEnabled {
return nil
}
preReceiveObjsIn := git.ProcessPreReceiveObjectsParams{
ReadParams: git.ReadParams{
RepoUID: repo.GitUID,
AlternateObjectDirs: in.Environment.AlternateObjectDirs,
},
}
if sizeLimit > 0 {
preReceiveObjsIn.FindOversizeFilesParams = &git.FindOversizeFilesParams{
SizeLimit: sizeLimit,
}
}
if principalCommitterMatch && principal != nil && !in.Internal {
preReceiveObjsIn.FindCommitterMismatchParams = &git.FindCommitterMismatchParams{
PrincipalEmail: principal.Email,
}
}
if gitLFSEnabled {
preReceiveObjsIn.FindLFSPointersParams = &git.FindLFSPointersParams{}
}
preReceiveObjsOut, err := rgit.ProcessPreReceiveObjects(
ctx,
preReceiveObjsIn,
)
if err != nil {
return fmt.Errorf("failed to process pre-receive objects: %w", err)
}
if preReceiveObjsOut.FindOversizeFilesOutput != nil &&
len(preReceiveObjsOut.FindOversizeFilesOutput.FileInfos) > 0 {
printOversizeFiles(
output,
preReceiveObjsOut.FindOversizeFilesOutput.FileInfos,
preReceiveObjsOut.FindOversizeFilesOutput.Total,
sizeLimit,
)
}
if preReceiveObjsOut.FindCommitterMismatchOutput != nil &&
len(preReceiveObjsOut.FindCommitterMismatchOutput.CommitInfos) > 0 {
printCommitterMismatch(
output,
preReceiveObjsOut.FindCommitterMismatchOutput.CommitInfos,
preReceiveObjsIn.FindCommitterMismatchParams.PrincipalEmail,
preReceiveObjsOut.FindCommitterMismatchOutput.Total,
)
}
if preReceiveObjsOut.FindLFSPointersOutput != nil &&
len(preReceiveObjsOut.FindLFSPointersOutput.LFSInfos) > 0 {
objIDs := make([]string, len(preReceiveObjsOut.FindLFSPointersOutput.LFSInfos))
for i, info := range preReceiveObjsOut.FindLFSPointersOutput.LFSInfos {
objIDs[i] = info.ObjID
}
existingObjs, err := c.lfsStore.FindMany(ctx, in.RepoID, objIDs)
if err != nil {
return fmt.Errorf("failed to find lfs objects: %w", err)
}
//nolint:lll
if len(existingObjs) != len(objIDs) {
output.Error = ptr.String(
"Changes blocked by unknown Git LFS objects. Please try `git lfs push --all` or check if LFS is setup properly.")
printLFSPointers(
output,
preReceiveObjsOut.FindLFSPointersOutput.LFSInfos,
preReceiveObjsOut.FindLFSPointersOutput.Total,
)
}
}
violationsInput.FileSizeLimit = sizeLimit
violationsInput.FindOversizeFilesOutput = preReceiveObjsOut.FindOversizeFilesOutput
violationsInput.PrincipalCommitterMatch = principalCommitterMatch
if preReceiveObjsOut.FindCommitterMismatchOutput != nil {
violationsInput.CommitterMismatchCount = preReceiveObjsOut.FindCommitterMismatchOutput.Total
}
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/githook/extender.go | app/api/controller/githook/extender.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 githook
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types"
)
type PreReceiveExtender interface {
Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookPreReceiveInput,
*hook.Output,
) error
}
type UpdateExtender interface {
Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookUpdateInput,
*hook.Output,
) error
}
type PostReceiveExtender interface {
Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookPostReceiveInput,
*hook.Output,
) error
}
type NoOpPreReceiveExtender struct {
}
func NewPreReceiveExtender() PreReceiveExtender {
return NoOpPreReceiveExtender{}
}
func (NoOpPreReceiveExtender) Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookPreReceiveInput,
*hook.Output,
) error {
return nil
}
type NoOpUpdateExtender struct {
}
func NewUpdateExtender() UpdateExtender {
return NoOpUpdateExtender{}
}
func (NoOpUpdateExtender) Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookUpdateInput,
*hook.Output,
) error {
return nil
}
type NoOpPostReceiveExtender struct {
}
func NewPostReceiveExtender() PostReceiveExtender {
return NoOpPostReceiveExtender{}
}
func (NoOpPostReceiveExtender) Extend(
context.Context,
RestrictedGIT,
*auth.Session,
*types.RepositoryCore,
types.GithookPostReceiveInput,
*hook.Output,
) 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/githook/update.go | app/api/controller/githook/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 githook
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// Update executes the update hook for a git repository.
func (c *Controller) Update(
ctx context.Context,
rgit RestrictedGIT,
session *auth.Session,
in types.GithookUpdateInput,
) (hook.Output, error) {
repo, err := c.getRepoCheckAccess(ctx, session, in.RepoID, enum.PermissionRepoPush)
if err != nil {
return hook.Output{}, err
}
output := hook.Output{}
err = c.updateExtender.Extend(ctx, rgit, session, repo, in, &output)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to extend update hook: %w", err)
}
// We currently don't have any update action (nothing planned as of now)
return hook.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/gitspace/wire.go | app/api/controller/gitspace/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 gitspace
import (
"github.com/harness/gitness/app/api/controller/limiter"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/gitspace/logutil"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/services/gitspace"
"github.com/harness/gitness/app/services/gitspacesettings"
"github.com/harness/gitness/app/services/infraprovider"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
tx dbtx.Transactor,
authorizer authz.Authorizer,
infraProviderSvc *infraprovider.Service,
spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
eventStore store.GitspaceEventStore,
statefulLogger *logutil.StatefulLogger,
scm *scm.SCM,
gitspaceSvc *gitspace.Service,
gitspaceLimiter limiter.Gitspace,
repoFinder refcache.RepoFinder,
settingsService gitspacesettings.Service,
) *Controller {
return NewController(
tx,
authorizer,
infraProviderSvc,
spaceStore,
spaceFinder,
eventStore,
statefulLogger,
scm,
gitspaceSvc,
gitspaceLimiter,
repoFinder,
settingsService,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/gitspace/create.go | app/api/controller/gitspace/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 gitspace
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"time"
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/paths"
"github.com/harness/gitness/app/services/gitspace"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
gonanoid "github.com/matoous/go-nanoid"
)
const (
defaultResourceIdentifier = "default"
maxGitspaceConfigIdentifierPrefixLength = 50
suffixLen = 6
)
var (
// ErrGitspaceRequiresParent if the user tries to create a secret without a parent space.
ErrGitspaceRequiresParent = usererror.BadRequest(
"Parent space required - standalone gitspace are not supported.")
)
// CreateInput is the input used for create operations.
type CreateInput struct {
Identifier string `json:"identifier"`
Name string `json:"name"`
SpaceRef string `json:"space_ref"` // Ref of the parent space
IDE enum.IDEType `json:"ide"`
InfraProviderConfigIdentifier string `json:"infra_provider_config_identifier"`
ResourceIdentifier string `json:"resource_identifier"`
ResourceSpaceRef string `json:"resource_space_ref"`
CodeRepoURL string `json:"code_repo_url"`
CodeRepoType enum.GitspaceCodeRepoType `json:"code_repo_type"`
CodeRepoRef *string `json:"code_repo_ref"`
Branch string `json:"branch"`
DevcontainerPath *string `json:"devcontainer_path"`
Metadata map[string]string `json:"metadata"`
SSHTokenIdentifier string `json:"ssh_token_identifier"`
AIAgents []enum.AIAgent `json:"ai_agents"`
}
// Create creates a new gitspace.
func (c *Controller) Create(
ctx context.Context,
session *auth.Session,
in *CreateInput,
) (*types.GitspaceConfig, error) {
space, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err)
}
if err = c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
if err = apiauth.CheckGitspace(
ctx,
c.authorizer,
session,
space.Path,
"",
enum.PermissionGitspaceCreate); err != nil {
return nil, err
}
// check if it's an internal repo
if in.CodeRepoType == enum.CodeRepoTypeGitness && *in.CodeRepoRef != "" {
repo, err := c.repoFinder.FindByRef(ctx, *in.CodeRepoRef)
if err != nil {
return nil, fmt.Errorf("couldn't fetch repo for the user: %w", err)
}
if err = apiauth.CheckRepo(
ctx,
c.authorizer,
session,
repo,
enum.PermissionRepoView); err != nil {
return nil, err
}
}
identifier, err := buildIdentifier(in.Identifier)
if err != nil {
return nil, fmt.Errorf("could not generate identifier for gitspace config : %q %w", in.Identifier, err)
}
now := time.Now().UnixMilli()
var gitspaceConfig *types.GitspaceConfig
// assume resource to be in same space if it's not explicitly specified.
if in.ResourceSpaceRef == "" {
rootSpaceRef, _, err := paths.DisectRoot(in.SpaceRef)
if err != nil {
return nil, fmt.Errorf("unable to find root space path for %s: %w", in.SpaceRef, err)
}
in.ResourceSpaceRef = rootSpaceRef
}
resourceIdentifier := in.ResourceIdentifier
resourceSpace, err := c.spaceFinder.FindByRef(ctx, in.ResourceSpaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err)
}
if err = apiauth.CheckInfraProvider(
ctx,
c.authorizer,
session,
resourceSpace.Path,
"",
enum.PermissionInfraProviderView); err != nil {
return nil, err
}
// TODO: Temp fix to ensure the gitspace creation doesnt fail. Once the FE starts sending this field in the
// request, remove this.
if in.InfraProviderConfigIdentifier == "" {
in.InfraProviderConfigIdentifier = defaultResourceIdentifier
}
infraProviderResource, err := c.createOrFindInfraProviderResource(ctx, resourceSpace, resourceIdentifier,
in.InfraProviderConfigIdentifier, now)
if err != nil {
return nil, err
}
err = c.gitspaceLimiter.Usage(ctx, space.ID, infraProviderResource.InfraProviderType)
if err != nil {
return nil, err
}
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
codeRepo := types.CodeRepo{
URL: in.CodeRepoURL,
Ref: in.CodeRepoRef,
Type: in.CodeRepoType,
Branch: in.Branch,
DevcontainerPath: in.DevcontainerPath,
}
principal := session.Principal
principalID := principal.ID
user := types.GitspaceUser{
Identifier: principal.UID,
Email: principal.Email,
DisplayName: principal.DisplayName,
ID: &principalID}
gitspaceConfig = &types.GitspaceConfig{
Identifier: identifier,
Name: in.Name,
IDE: in.IDE,
State: enum.GitspaceStateUninitialized,
SpaceID: space.ID,
SpacePath: space.Path,
Created: now,
Updated: now,
SSHTokenIdentifier: in.SSHTokenIdentifier,
AIAgents: in.AIAgents,
CodeRepo: codeRepo,
GitspaceUser: user,
}
gitspaceConfig.InfraProviderResource = *infraProviderResource
if err = c.settingsService.ValidateGitspaceConfigCreate(
ctx, *infraProviderResource, *gitspaceConfig); err != nil {
return err
}
err = c.gitspaceSvc.Create(ctx, gitspaceConfig)
if err != nil {
return fmt.Errorf("failed to create gitspace config for : %q %w", identifier, err)
}
return nil
})
if err != nil {
return nil, err
}
gitspaceConfig.BranchURL = c.gitspaceSvc.GetBranchURL(ctx, gitspaceConfig)
return gitspaceConfig, nil
}
func (c *Controller) createOrFindInfraProviderResource(
ctx context.Context,
resourceSpace *types.SpaceCore,
resourceIdentifier string,
infraProviderConfigIdentifier string,
now int64,
) (*types.InfraProviderResource, error) {
var resource *types.InfraProviderResource
var err error
resource, err = c.infraProviderSvc.FindResourceByConfigAndIdentifier(ctx, resourceSpace.ID,
infraProviderConfigIdentifier, resourceIdentifier)
if ((err != nil && errors.Is(err, store.ErrResourceNotFound)) || resource == nil) &&
resourceIdentifier == defaultResourceIdentifier {
resource, err = c.autoCreateDefaultResource(ctx, resourceSpace, now)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, fmt.Errorf("could not find infra provider resource : %q %w", resourceIdentifier, err)
}
return resource, err
}
func (c *Controller) autoCreateDefaultResource(
ctx context.Context,
currentSpace *types.SpaceCore,
now int64,
) (*types.InfraProviderResource, error) {
rootSpace, err := c.spaceStore.GetRootSpace(ctx, currentSpace.ID)
if err != nil {
return nil, fmt.Errorf("could not get root space for space %s while autocreating default docker "+
"resource: %w", currentSpace.Path, err)
}
defaultDockerConfig := &types.InfraProviderConfig{
Identifier: defaultResourceIdentifier,
Name: "default docker infrastructure",
Type: enum.InfraProviderTypeDocker,
SpaceID: rootSpace.ID,
SpacePath: rootSpace.Path,
Created: now,
Updated: now,
}
defaultResource := types.InfraProviderResource{
UID: defaultResourceIdentifier,
Name: "Standard Docker Resource",
InfraProviderConfigIdentifier: defaultDockerConfig.Identifier,
InfraProviderType: enum.InfraProviderTypeDocker,
CPU: wrapString("any"),
Memory: wrapString("any"),
Disk: wrapString("any"),
Network: wrapString("standard"),
SpaceID: rootSpace.ID,
SpacePath: rootSpace.Path,
Created: now,
Updated: now,
}
defaultDockerConfig.Resources = []types.InfraProviderResource{defaultResource}
err = c.infraProviderSvc.CreateConfigAndResources(ctx, defaultDockerConfig)
if err != nil {
return nil, fmt.Errorf("could not auto-create the infra provider: %w", err)
}
resource, err := c.infraProviderSvc.FindResourceByConfigAndIdentifier(ctx, rootSpace.ID,
defaultDockerConfig.Identifier, defaultResourceIdentifier)
if err != nil {
return nil, fmt.Errorf("could not find infra provider resource : %q %w", defaultResourceIdentifier, err)
}
return resource, nil
}
func wrapString(str string) *string {
return &str
}
func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
if err := check.Identifier(in.ResourceIdentifier); err != nil {
return err
}
parentRefAsID, err := strconv.ParseInt(in.SpaceRef, 10, 64)
if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(in.SpaceRef)) == 0) {
return ErrGitspaceRequiresParent
}
return nil
}
func buildIdentifier(identifier string) (string, error) {
toLower := strings.ToLower(identifier)
err := validateIdentifier(toLower)
if err != nil {
return "", err
}
suffixUID, err := gonanoid.Generate(gitspace.AllowedUIDAlphabet, suffixLen)
if err != nil {
return "", fmt.Errorf("could not generate UID for gitspace config: %q %w", toLower, err)
}
return toLower + "-" + suffixUID, nil
}
func validateIdentifier(identifier string) error {
invalidCharPattern := regexp.MustCompile(`[^a-z0-9-]`)
if invalidCharPattern.MatchString(identifier) {
return usererror.BadRequestf("Identifier %q contains invalid characters: only lowercase letters, "+
"digits, and hyphens are allowed", identifier)
}
if len(identifier) > maxGitspaceConfigIdentifierPrefixLength {
return fmt.Errorf("identifier %q length should be upto 50 characters, is %d characters",
identifier, len(identifier))
}
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/gitspace/logs_stream.go | app/api/controller/gitspace/logs_stream.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 gitspace
import (
"context"
"encoding/json"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/sse"
"github.com/harness/gitness/livelog"
"github.com/harness/gitness/types/enum"
)
func (c *Controller) LogsStream(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) (<-chan *sse.Event, <-chan error, error) {
err := apiauth.CheckGitspace(ctx, c.authorizer, session, spaceRef, identifier, enum.PermissionGitspaceView)
if err != nil {
return nil, nil, fmt.Errorf("failed to authorize: %w", err)
}
gitspaceConfig, err := c.gitspaceSvc.FindWithLatestInstanceWithSpacePath(ctx, spaceRef, identifier)
if err != nil {
return nil, nil, fmt.Errorf("failed to find gitspace config: %w", err)
}
linec, errc := c.statefulLogger.TailLogStream(ctx, gitspaceConfig.ID)
if linec == nil {
return nil, nil, fmt.Errorf("log stream not present, failed to tail log stream")
}
evenc := make(chan *sse.Event)
errch := make(chan error)
go func() {
defer close(evenc)
defer close(errch)
for {
select {
case <-ctx.Done():
return
case line, ok := <-linec:
if !ok {
return
}
event := sse.Event{
Type: enum.SSETypeLogLineAppended,
Data: marshalLine(line),
}
evenc <- &event
case err = <-errc:
if err != nil {
errch <- err
return
}
}
}
}()
return evenc, errch, nil
}
func marshalLine(line *livelog.Line) []byte {
data, _ := json.Marshal(line)
return data
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/gitspace/delete.go | app/api/controller/gitspace/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 gitspace
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) Delete(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) error {
err := apiauth.CheckGitspace(ctx, c.authorizer, session, spaceRef, identifier, enum.PermissionGitspaceDelete)
if err != nil {
return fmt.Errorf("failed to authorize: %w", err)
}
return c.gitspaceSvc.DeleteGitspaceByIdentifier(ctx, spaceRef, 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/gitspace/action.go | app/api/controller/gitspace/action.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 gitspace
import (
"context"
"fmt"
"strconv"
"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"
)
type ActionInput struct {
Action enum.GitspaceActionType `json:"action"`
Identifier string `json:"-"`
SpaceRef string `json:"-"` // Ref of the parent space
}
func (c *Controller) Action(
ctx context.Context,
session *auth.Session,
in *ActionInput,
) (*types.GitspaceConfig, error) {
if err := c.sanitizeActionInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
space, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckGitspace(ctx, c.authorizer, session, space.Path, in.Identifier, enum.PermissionGitspaceUse)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
gitspaceConfig, err := c.gitspaceSvc.FindWithLatestInstance(ctx, space.ID, in.Identifier)
if err != nil {
return nil, fmt.Errorf("failed to find gitspace config: %w", err)
}
// check if it's an internal repo
if gitspaceConfig.CodeRepo.Type == enum.CodeRepoTypeGitness {
if gitspaceConfig.CodeRepo.Ref == nil {
return nil, fmt.Errorf("couldn't fetch repo for the user, no ref found: %w", err)
}
repo, err := c.repoFinder.FindByRef(ctx, *gitspaceConfig.CodeRepo.Ref)
if err != nil {
return nil, fmt.Errorf("couldn't fetch repo for the user: %w", err)
}
if err = apiauth.CheckRepo(
ctx,
c.authorizer,
session,
repo,
enum.PermissionRepoView); err != nil {
return nil, err
}
}
gitspaceConfig.BranchURL = c.gitspaceSvc.GetBranchURL(ctx, gitspaceConfig)
// All the actions should be idempotent.
switch in.Action {
case enum.GitspaceActionTypeStart:
err = c.gitspaceLimiter.Usage(ctx, space.ID, gitspaceConfig.InfraProviderResource.InfraProviderType)
if err != nil {
return nil, err
}
c.gitspaceSvc.EmitGitspaceConfigEvent(ctx, *gitspaceConfig, enum.GitspaceEventTypeGitspaceActionStart)
if err = c.gitspaceSvc.StartGitspaceAction(ctx, *gitspaceConfig); err == nil {
gitspaceConfig.State = enum.GitspaceStateStarting
}
return gitspaceConfig, err
case enum.GitspaceActionTypeStop:
c.gitspaceSvc.EmitGitspaceConfigEvent(ctx, *gitspaceConfig, enum.GitspaceEventTypeGitspaceActionStop)
if err = c.gitspaceSvc.StopGitspaceAction(ctx, *gitspaceConfig, time.Now()); err == nil {
gitspaceConfig.State = enum.GitspaceStateStopping
}
return gitspaceConfig, err
case enum.GitspaceActionTypeReset:
c.gitspaceSvc.EmitGitspaceConfigEvent(ctx, *gitspaceConfig, enum.GitspaceEventTypeGitspaceActionReset)
if err = c.gitspaceSvc.ResetGitspaceAction(ctx, *gitspaceConfig); err == nil {
gitspaceConfig.State = enum.GitSpaceStateCleaning
}
return gitspaceConfig, err
default:
return nil, fmt.Errorf("unknown action %s on gitspace : %s", string(in.Action), gitspaceConfig.Identifier)
}
}
func (c *Controller) sanitizeActionInput(in *ActionInput) error {
if err := check.Identifier(in.Identifier); err != nil {
return err
}
parentRefAsID, err := strconv.ParseInt(in.SpaceRef, 10, 64)
if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(in.SpaceRef)) == 0) {
return ErrGitspaceRequiresParent
}
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/gitspace/find_all.go | app/api/controller/gitspace/find_all.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 gitspace
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
)
func (c *Controller) FindAllInSameScope(
ctx context.Context,
// todo: integrate with access control.
_ *auth.Session,
spaceRef string,
identifiers []string,
) ([]types.GitspaceConfig, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
gitspaceConfigs, err := c.gitspaceSvc.FindAllByIdentifier(ctx, space.ID, identifiers)
if err != nil {
return nil, fmt.Errorf("failed to find gitspaces: %w", err)
}
return gitspaceConfigs, 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/gitspace/find.go | app/api/controller/gitspace/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 gitspace
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) Find(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
) (*types.GitspaceConfig, error) {
err := apiauth.CheckGitspace(ctx, c.authorizer, session, spaceRef, identifier, enum.PermissionGitspaceView)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
res, err := c.gitspaceSvc.FindWithLatestInstanceWithSpacePath(ctx, spaceRef, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find gitspace: %w", err)
}
return res, 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/gitspace/lookup_repo.go | app/api/controller/gitspace/lookup_repo.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 gitspace
import (
"context"
"fmt"
"net/url"
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/gitspace/scm"
"github.com/harness/gitness/types/enum"
)
type LookupRepoInput struct {
SpaceRef string `json:"space_ref"` // Ref of the parent space
URL string `json:"url"`
RepoType enum.GitspaceCodeRepoType `json:"repo_type"`
}
var (
ErrInvalidURL = usererror.BadRequest(
"The URL specified is not valid format.")
ErrRepoMissing = usererror.BadRequest(
"There must be URL or Ref specified fir repo.")
ErrBadURLScheme = usererror.BadRequest("The URL is missing scheme, it must start with http or https")
)
func (c *Controller) LookupRepo(
ctx context.Context,
session *auth.Session,
in *LookupRepoInput,
) (*scm.CodeRepositoryResponse, error) {
if err := c.sanitizeLookupRepoInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err)
}
space, err := c.spaceFinder.FindByRef(ctx, in.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)
}
repositoryRequest := scm.CodeRepositoryRequest{
URL: in.URL,
UserIdentifier: session.Principal.UID,
SpacePath: space.Path,
RepoType: in.RepoType,
UserID: session.Principal.ID,
}
codeRepositoryResponse, err := c.scm.CheckValidCodeRepo(ctx, repositoryRequest)
if err != nil {
return nil, err
}
return codeRepositoryResponse, nil
}
func (c *Controller) sanitizeLookupRepoInput(in *LookupRepoInput) error {
if in.RepoType == "" && in.URL == "" {
return ErrRepoMissing
}
parsedURL, err := url.Parse(in.URL)
if err != nil {
return ErrInvalidURL
}
if parsedURL.Scheme == "" {
return ErrBadURLScheme
}
if _, err := url.ParseRequestURI(parsedURL.RequestURI()); 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/gitspace/controller.go | app/api/controller/gitspace/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 gitspace
import (
"github.com/harness/gitness/app/api/controller/limiter"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/gitspace/logutil"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/services/gitspace"
"github.com/harness/gitness/app/services/gitspacesettings"
"github.com/harness/gitness/app/services/infraprovider"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database/dbtx"
)
type Controller struct {
authorizer authz.Authorizer
infraProviderSvc *infraprovider.Service
spaceStore store.SpaceStore
spaceFinder refcache.SpaceFinder
gitspaceEventStore store.GitspaceEventStore
tx dbtx.Transactor
statefulLogger *logutil.StatefulLogger
scm *scm.SCM
gitspaceSvc *gitspace.Service
gitspaceLimiter limiter.Gitspace
repoFinder refcache.RepoFinder
settingsService gitspacesettings.Service
}
func NewController(
tx dbtx.Transactor,
authorizer authz.Authorizer,
infraProviderSvc *infraprovider.Service,
spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
gitspaceEventStore store.GitspaceEventStore,
statefulLogger *logutil.StatefulLogger,
scm *scm.SCM,
gitspaceSvc *gitspace.Service,
gitspaceLimiter limiter.Gitspace,
repoFinder refcache.RepoFinder,
settingsService gitspacesettings.Service,
) *Controller {
return &Controller{
tx: tx,
authorizer: authorizer,
infraProviderSvc: infraProviderSvc,
spaceStore: spaceStore,
spaceFinder: spaceFinder,
gitspaceEventStore: gitspaceEventStore,
statefulLogger: statefulLogger,
scm: scm,
gitspaceSvc: gitspaceSvc,
gitspaceLimiter: gitspaceLimiter,
repoFinder: repoFinder,
settingsService: settingsService,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/gitspace/events.go | app/api/controller/gitspace/events.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 gitspace
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/enum"
)
var eventMessageMap map[enum.GitspaceEventType]string
func init() {
eventMessageMap = enum.EventsMessageMapping()
}
func (c *Controller) Events(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
page int,
limit int,
) ([]*types.GitspaceEventResponse, int, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, 0, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckGitspace(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionGitspaceView)
if err != nil {
return nil, 0, fmt.Errorf("failed to authorize: %w", err)
}
pagination := types.Pagination{
Page: page,
Size: limit,
}
skipEvents := []enum.GitspaceEventType{
enum.GitspaceEventTypeInfraCleanupStart,
enum.GitspaceEventTypeInfraCleanupCompleted,
enum.GitspaceEventTypeInfraCleanupFailed,
}
filter := &types.GitspaceEventFilter{
Pagination: pagination,
QueryKey: identifier,
SkipEvents: skipEvents,
}
events, count, err := c.gitspaceEventStore.List(ctx, filter)
if err != nil {
return nil, 0, fmt.Errorf("failed to list gitspace events for identifier %s: %w", identifier, err)
}
var result = make([]*types.GitspaceEventResponse, len(events))
for index, event := range events {
gitspaceEventResponse := &types.GitspaceEventResponse{
GitspaceEvent: *event,
Message: eventMessageMap[event.Event],
EventTime: time.Unix(0, event.Timestamp).Format(time.RFC3339Nano)}
result[index] = gitspaceEventResponse
}
return result, 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/gitspace/list_all.go | app/api/controller/gitspace/list_all.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 gitspace
import (
"context"
"errors"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// ListAllGitspaces all the gitspace with given filter.
// DO NOT USE allSpaceIDs = true for cde-manager. This arg is used only in gitness to list all the gitspaces in gitness
// for all. This is useful to list all the gitspaces in OSS for IDE plugins.
func (c *Controller) ListAllGitspaces( // nolint:gocognit
ctx context.Context,
session *auth.Session,
filter types.GitspaceFilter,
allSpaceIDs bool,
) ([]*types.GitspaceConfig, error) {
if allSpaceIDs {
leafSpaceIDs, err := c.fetchAllLeafSpaceIDs(ctx)
if err != nil {
return nil, err
}
filter.SpaceIDs = leafSpaceIDs
}
var result []*types.GitspaceConfig
err := c.tx.WithTx(ctx, func(ctx context.Context) (err error) {
allGitspaceConfigs, _, _, err := c.gitspaceSvc.ListGitspacesWithInstance(ctx, filter, false)
if err != nil {
return fmt.Errorf("failed to list gitspace configs: %w", err)
}
var spacesMap = make(map[int64]string)
for idx := range allGitspaceConfigs {
if spacesMap[allGitspaceConfigs[idx].SpaceID] == "" {
space, findSpaceErr := c.spaceFinder.FindByRef(ctx, allGitspaceConfigs[idx].SpacePath)
if findSpaceErr != nil {
if !errors.Is(findSpaceErr, store.ErrResourceNotFound) {
return fmt.Errorf(
"error fetching space %d: %w", allGitspaceConfigs[idx].SpaceID, findSpaceErr)
}
continue
}
spacesMap[allGitspaceConfigs[idx].SpaceID] = space.Path
}
}
authorizedSpaceIDs, err := c.getAuthorizedSpaces(ctx, session, spacesMap)
if err != nil {
return err
}
finalGitspaceConfigs := c.filter(allGitspaceConfigs, authorizedSpaceIDs)
result = finalGitspaceConfigs
return nil
}, dbtx.TxDefaultReadOnly)
if err != nil {
return nil, err
}
return result, nil
}
func (c *Controller) fetchAllLeafSpaceIDs(ctx context.Context) ([]int64, error) {
opts := &types.SpaceFilter{}
rootSpaces, err := c.spaceStore.GetAllRootSpaces(ctx, opts)
if err != nil {
return nil, fmt.Errorf("failed to get root spaces: %w", err)
}
var leafSpaceIDs []int64
for _, rootSpace := range rootSpaces {
spaceIDs, err := c.spaceStore.GetDescendantsIDs(ctx, rootSpace.ID)
if err != nil {
if !errors.Is(err, store.ErrResourceNotFound) {
return nil, fmt.Errorf("failed to get descendants ids: %w", err)
}
}
leafSpaceIDs = append(leafSpaceIDs, spaceIDs...)
}
return leafSpaceIDs, nil
}
func (c *Controller) filter(
allGitspaceConfigs []*types.GitspaceConfig,
authorizedSpaceIDs map[int64]bool,
) []*types.GitspaceConfig {
return c.getAuthorizedGitspaceConfigs(allGitspaceConfigs, authorizedSpaceIDs)
}
func (c *Controller) getAuthorizedGitspaceConfigs(
allGitspaceConfigs []*types.GitspaceConfig,
authorizedSpaceIDs map[int64]bool,
) []*types.GitspaceConfig {
var authorizedGitspaceConfigs = make([]*types.GitspaceConfig, 0)
for idx := range allGitspaceConfigs {
if authorizedSpaceIDs[allGitspaceConfigs[idx].SpaceID] {
authorizedGitspaceConfigs = append(authorizedGitspaceConfigs, allGitspaceConfigs[idx])
}
}
return authorizedGitspaceConfigs
}
func (c *Controller) getAuthorizedSpaces(
ctx context.Context,
session *auth.Session,
spacesMap map[int64]string,
) (map[int64]bool, error) {
var authorizedSpaceIDs = make(map[int64]bool, 0)
for spaceID, spacePath := range spacesMap {
err := apiauth.CheckGitspace(
ctx, c.authorizer, session, spacePath, "", enum.PermissionGitspaceView,
)
if err != nil && !apiauth.IsNoAccess(err) {
return nil, fmt.Errorf("failed to check gitspace auth for space ID %d: %w", spaceID, err)
}
authorizedSpaceIDs[spaceID] = true
}
return authorizedSpaceIDs, 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/gitspace/update.go | app/api/controller/gitspace/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 gitspace
import (
"context"
"fmt"
"strconv"
"strings"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/gitspace/common"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths"
gitnessTypes "github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
// UpdateInput is used for updating a gitspace.
type UpdateInput struct {
IDE enum.IDEType `json:"ide"`
ResourceIdentifier string `json:"resource_identifier"`
ResourceSpaceRef string `json:"resource_space_ref"`
Name string `json:"name"`
SSHTokenIdentifier string `json:"ssh_token_identifier"`
Identifier string `json:"-"`
SpaceRef string `json:"-"`
}
func (c *Controller) Update(
ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
in *UpdateInput,
) (*gitnessTypes.GitspaceConfig, error) {
in.SpaceRef = spaceRef
in.Identifier = identifier
if err := c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
err := apiauth.CheckGitspace(ctx, c.authorizer, session, spaceRef, identifier, enum.PermissionGitspaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
gitspaceConfig, err := c.gitspaceSvc.FindWithLatestInstanceWithSpacePath(ctx, spaceRef, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find gitspace config: %w", err)
}
// Check the gitspace state. Update can be done only in stopped, error or uninitialized state
currentState := gitspaceConfig.State
if currentState != enum.GitspaceStateStopped &&
currentState != enum.GitspaceStateUninitialized {
return nil, usererror.BadRequest(
"Gitspace update can only be performed when gitspace is stopped or uninitialized",
)
}
c.updateIDE(in, gitspaceConfig)
if err := c.handleSSHToken(in, gitspaceConfig); err != nil {
return nil, err
}
if err := c.updateResourceIdentifier(ctx, in, gitspaceConfig); err != nil {
return nil, err
}
// TODO Update with proper locks
err = c.gitspaceSvc.UpdateConfig(ctx, gitspaceConfig)
if err != nil {
return nil, fmt.Errorf("failed to update gitspace config: %w", err)
}
return gitspaceConfig, nil
}
func (c *Controller) updateIDE(in *UpdateInput, gitspaceConfig *gitnessTypes.GitspaceConfig) {
if in.IDE != "" && in.IDE != gitspaceConfig.IDE {
gitspaceConfig.IDE = in.IDE
gitspaceConfig.IsMarkedForReset = true
}
// Always clear SSH token if IDE is VS Code Web
if gitspaceConfig.IDE == enum.IDETypeVSCodeWeb {
gitspaceConfig.SSHTokenIdentifier = ""
}
}
func (c *Controller) handleSSHToken(in *UpdateInput, gitspaceConfig *gitnessTypes.GitspaceConfig) error {
if in.SSHTokenIdentifier != "" {
if gitspaceConfig.IDE == enum.IDETypeVSCodeWeb {
return usererror.BadRequest("SSH token should not be sent with VS Code Web IDE")
}
// For other IDEs, update the token
if in.SSHTokenIdentifier != gitspaceConfig.SSHTokenIdentifier {
gitspaceConfig.SSHTokenIdentifier = in.SSHTokenIdentifier
gitspaceConfig.IsMarkedForReset = true
}
}
return nil
}
func (c *Controller) updateResourceIdentifier(
ctx context.Context,
in *UpdateInput,
gitspaceConfig *gitnessTypes.GitspaceConfig,
) error {
// Handle resource identifier update similar to create, but only if provided
if in.ResourceIdentifier == "" || in.ResourceIdentifier == gitspaceConfig.InfraProviderResource.UID {
return nil
}
if gitspaceConfig.InfraProviderResource.UID == "default" {
return usererror.BadRequest("The default resource cannot be updated in harness open source")
}
// Set resource space reference if not provided
if in.ResourceSpaceRef == "" {
rootSpaceRef, _, err := paths.DisectRoot(in.SpaceRef)
if err != nil {
return fmt.Errorf("unable to find root space path for %s: %w", in.SpaceRef, err)
}
in.ResourceSpaceRef = rootSpaceRef
}
// Find spaces and resources
existingResource, newResource, err := c.getResources(ctx, in, gitspaceConfig)
if err != nil {
return err
}
// Validate the resource spec change
markForInfraReset, err := common.IsResourceSpecChangeAllowed(existingResource, newResource)
if err != nil {
return err
}
gitspaceConfig.IsMarkedForInfraReset = gitspaceConfig.IsMarkedForInfraReset || markForInfraReset
gitspaceConfig.InfraProviderResource = *newResource
return nil
}
func (c *Controller) getResources(
ctx context.Context,
in *UpdateInput,
gitspaceConfig *gitnessTypes.GitspaceConfig,
) (*gitnessTypes.InfraProviderResource, *gitnessTypes.InfraProviderResource, error) {
// Get existing resource space and resource
existingSpace, err := c.spaceFinder.FindByRef(
ctx,
gitspaceConfig.InfraProviderResource.SpacePath,
)
if err != nil {
return nil, nil, fmt.Errorf("failed to find resource space: %w", err)
}
existingResource, err := c.infraProviderSvc.FindResourceByConfigAndIdentifier(
ctx,
existingSpace.ID,
gitspaceConfig.InfraProviderResource.InfraProviderConfigIdentifier,
gitspaceConfig.InfraProviderResource.UID,
)
if err != nil {
return nil, nil, fmt.Errorf(
"could not find existing infra provider resource: %w",
err,
)
}
// Get new resource space and resource
newSpace, err := c.spaceFinder.FindByRef(
ctx,
in.ResourceSpaceRef,
)
if err != nil {
return nil, nil, fmt.Errorf("failed to find resource space: %w", err)
}
newResource, err := c.infraProviderSvc.FindResourceByConfigAndIdentifier(
ctx,
newSpace.ID,
gitspaceConfig.InfraProviderResource.InfraProviderConfigIdentifier,
in.ResourceIdentifier,
)
if err != nil {
return nil, nil, fmt.Errorf(
"could not find infra provider resource %q: %w",
in.ResourceIdentifier,
err,
)
}
return existingResource, newResource, nil
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
parentRefAsID, err := strconv.ParseInt(in.SpaceRef, 10, 64)
if (err == nil && parentRefAsID <= 0) || (len(strings.TrimSpace(in.SpaceRef)) == 0) {
return ErrGitspaceRequiresParent
}
//nolint:revive
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/gitspace/common/resource_validation.go | app/api/controller/gitspace/common/resource_validation.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 common
import (
"context"
"fmt"
"strconv"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
)
// FilterResourcesByCompatibility filters resources based on compatibility with a reference resource.
// It removes any resources that are not compatible according to the IsResourceSpecChangeAllowed criteria.
func FilterResourcesByCompatibility(
ctx context.Context,
filteredResources []*types.InfraProviderResource,
referenceResource *types.InfraProviderResource,
) ([]*types.InfraProviderResource, error) {
if referenceResource == nil {
return nil, fmt.Errorf("referenceResource cannot be nil")
}
compatibleResources := make([]*types.InfraProviderResource, 0)
// Now filter based on compatibility
for _, resource := range filteredResources {
// Skip the current resource itself
if resource.UID == referenceResource.UID {
continue
}
_, err := IsResourceSpecChangeAllowed(referenceResource, resource)
if err != nil {
log.Ctx(ctx).Debug().
Err(err).
Str("resource_id", resource.UID).
Str("reference_id", referenceResource.UID).
Msg("resource compatibility check failed")
} else {
compatibleResources = append(compatibleResources, resource)
}
}
return compatibleResources, nil
}
// IsResourceSpecChangeAllowed checks if the new resource specs are valid and determines if a hard reset is needed.
// Returns (markForHardReset, error) where error contains details about why the validation failed.
func IsResourceSpecChangeAllowed(
existingResource *types.InfraProviderResource,
newResource *types.InfraProviderResource,
) (bool, error) {
// If either resource is nil, we can't compare properly
if existingResource == nil || newResource == nil {
return false, fmt.Errorf("cannot validate resource change: missing resource information")
}
// Validate region is the same
if existingResource.Region != newResource.Region {
return false, usererror.BadRequestf(
"region mismatch: current region '%s' does not match target region '%s'",
existingResource.Region, newResource.Region)
}
// Check zone from metadata if available
existingZone, existingHasZone := existingResource.Metadata["zone"]
newZone, newHasZone := newResource.Metadata["zone"]
// If both resources have zone info, they must match
if existingHasZone && newHasZone && existingZone != newZone {
return false, usererror.BadRequestf(
"zone mismatch: current zone '%s' does not match target zone '%s'",
existingZone, newZone,
)
}
markForInfraReset := false
// Check boot disk changes
needsHardReset, err := validateBootDiskChanges(existingResource.Metadata, newResource.Metadata)
if err != nil {
return false, err
}
if needsHardReset {
markForInfraReset = true
}
// Check persistent disk changes
needsHardReset, err = validatePersistentDiskChanges(existingResource.Metadata, newResource.Metadata)
if err != nil {
return false, err
}
if needsHardReset {
markForInfraReset = true
}
// Check machine type changes
machineTypeResetNeeded := validateMachineTypeChanges(existingResource.Metadata, newResource.Metadata)
markForInfraReset = markForInfraReset || machineTypeResetNeeded
// All checks passed
return markForInfraReset, nil
}
// validatePersistentDiskChanges checks if persistent disk changes are valid and if they require a hard reset.
// Returns (needsHardReset, error).
func validatePersistentDiskChanges(existingMeta, newMeta map[string]string) (bool, error) {
existingDisk, existingOK := existingMeta["persistent_disk_size"]
newDisk, newOK := newMeta["persistent_disk_size"]
if !existingOK || !newOK {
return false, fmt.Errorf(
"invalid persistent disk size format: cannot parse persistent disk sizes for comparison")
}
markForHardReset, err := checkPersistentDiskSizeChange(existingDisk, newDisk)
if err != nil {
return false, err
}
existingDiskType, existingOK := existingMeta["persistent_disk_type"]
newDiskType, newOK := newMeta["persistent_disk_type"]
if !existingOK || !newOK {
return false, fmt.Errorf(
"invalid persistent disk type format: cannot parse persistent disk types for comparison")
}
if existingDiskType != newDiskType {
return false, usererror.BadRequestf(
"persistent disk type change not allowed: from '%s' to '%s'",
existingDiskType, newDiskType)
}
return markForHardReset, nil
}
// validateMachineTypeChanges checks if machine type changes require a hard reset.
// Returns needsHardReset.
func validateMachineTypeChanges(existingMeta, newMeta map[string]string) bool {
existingMachine, existingOK := existingMeta["machine_type"]
newMachine, newOK := newMeta["machine_type"]
if existingOK && newOK && existingMachine != newMachine {
return true
}
return false
}
// validateBootDiskChanges checks if boot disk changes are valid and if they require a hard reset.
// Returns (needsHardReset, error).
func validateBootDiskChanges(existingMeta, newMeta map[string]string) (bool, error) {
markForHardReset := false
// Check boot disk size changes
existingBoot, existingOK := existingMeta["boot_disk_size"]
newBoot, newOK := newMeta["boot_disk_size"]
if !existingOK || !newOK {
return false, fmt.Errorf(
"invalid boot disk size format: cannot parse boot disk sizes for comparison")
}
existingVal, eErr := strconv.Atoi(existingBoot)
newVal, nErr := strconv.Atoi(newBoot)
if eErr != nil || nErr != nil {
return false, fmt.Errorf(
"invalid boot disk size format: cannot parse boot disk sizes for comparison")
}
if newVal != existingVal {
markForHardReset = true
}
// Check boot disk type changes
existingBootType, existingOK := existingMeta["boot_disk_type"]
newBootType, newOK := newMeta["boot_disk_type"]
if !existingOK || !newOK {
return false, fmt.Errorf(
"invalid boot disk type format: cannot parse boot disk types for comparison")
}
if existingBootType != newBootType {
markForHardReset = true
}
return markForHardReset, nil
}
// checkPersistentDiskSizeChange compares existing and new persistent disk sizes.
// and determines if the change is allowed and if hard reset is needed.
// Returns (needsHardReset, error).
//
//nolint:unparam // the bool return value is kept for future extension
func checkPersistentDiskSizeChange(existingDisk, newDisk string) (bool, error) {
existingVal, eErr := strconv.Atoi(existingDisk)
if eErr != nil {
return false, fmt.Errorf("invalid disk size format: cannot parse existing disk size: %w", eErr)
}
newVal, nErr := strconv.Atoi(newDisk)
if nErr != nil {
return false, fmt.Errorf("invalid disk size format: cannot parse new disk size: %w", nErr)
}
// Disallow any changes to persistent disk size
if newVal != existingVal {
return false, fmt.Errorf(
"changing persistent disk size is not allowed: from %d to %d",
existingVal, newVal)
}
// Equal sizes, no hard reset needed
return false, 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/reposettings/general_find.go | app/api/controller/reposettings/general_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 reposettings
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types/enum"
)
// GeneralFind returns the general settings of a repo.
func (c *Controller) GeneralFind(
ctx context.Context,
session *auth.Session,
repoRef string,
) (*GeneralSettings, error) {
// migrating repos need to adjust repo settings (like file-size-limit) during the migration.
var additionalAllowedRepoStates = []enum.RepoState{enum.RepoStateMigrateGitPush}
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView, additionalAllowedRepoStates...)
if err != nil {
return nil, err
}
out := GetDefaultGeneralSettings()
mappings := GetGeneralSettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err)
}
return out, 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/reposettings/wire.go | app/api/controller/reposettings/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 reposettings
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/audit"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
authorizer authz.Authorizer,
repoFinder refcache.RepoFinder,
settings *settings.Service,
auditService audit.Service,
) *Controller {
return NewController(authorizer, repoFinder, settings, auditService)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/reposettings/general.go | app/api/controller/reposettings/general.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 reposettings
import (
"github.com/harness/gitness/app/services/settings"
"github.com/gotidy/ptr"
)
// GeneralSettings represent the general repository settings as exposed externally.
type GeneralSettings struct {
FileSizeLimit *int64 `json:"file_size_limit" yaml:"file_size_limit" description:"file size limit in bytes"`
GitLFSEnabled *bool `json:"git_lfs_enabled" yaml:"git_lfs_enabled"`
}
func GetDefaultGeneralSettings() *GeneralSettings {
return &GeneralSettings{
FileSizeLimit: ptr.Int64(settings.DefaultFileSizeLimit),
GitLFSEnabled: ptr.Bool(settings.DefaultGitLFSEnabled),
}
}
func GetGeneralSettingsMappings(s *GeneralSettings) []settings.SettingHandler {
return []settings.SettingHandler{
settings.Mapping(settings.KeyFileSizeLimit, s.FileSizeLimit),
settings.Mapping(settings.KeyGitLFSEnabled, s.GitLFSEnabled),
}
}
func GetGeneralSettingsAsKeyValues(s *GeneralSettings) []settings.KeyValue {
kvs := make([]settings.KeyValue, 0, 1)
if s.FileSizeLimit != nil {
kvs = append(kvs, settings.KeyValue{
Key: settings.KeyFileSizeLimit,
Value: s.FileSizeLimit,
})
}
if s.GitLFSEnabled != nil {
kvs = append(kvs, settings.KeyValue{
Key: settings.KeyGitLFSEnabled,
Value: s.GitLFSEnabled,
})
}
return kvs
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/reposettings/security_find.go | app/api/controller/reposettings/security_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 reposettings
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types/enum"
)
// SecurityFind returns the security settings of a repo.
func (c *Controller) SecurityFind(
ctx context.Context,
session *auth.Session,
repoRef string,
) (*SecuritySettings, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView)
if err != nil {
return nil, err
}
out := GetDefaultSecuritySettings()
mappings := GetSecuritySettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err)
}
return out, 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/reposettings/general_update.go | app/api/controller/reposettings/general_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 reposettings
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
// GeneralUpdate updates the general settings of the repo.
func (c *Controller) GeneralUpdate(
ctx context.Context,
session *auth.Session,
repoRef string,
in *GeneralSettings,
) (*GeneralSettings, error) {
// migrating repos need to adjust repo settings (like file-size-limit) during the migration.
var additionalAllowedRepoStates = []enum.RepoState{enum.RepoStateMigrateGitPush}
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit, additionalAllowedRepoStates...)
if err != nil {
return nil, err
}
// read old settings values
old := GetDefaultGeneralSettings()
oldMappings := GetGeneralSettingsMappings(old)
err = c.settings.RepoMap(ctx, repo.ID, oldMappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings (old): %w", err)
}
err = c.settings.RepoSetMany(ctx, repo.ID, GetGeneralSettingsAsKeyValues(in)...)
if err != nil {
return nil, fmt.Errorf("failed to set settings: %w", err)
}
// read all settings and return complete config
out := GetDefaultGeneralSettings()
mappings := GetGeneralSettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err)
}
err = c.auditService.Log(ctx,
session.Principal,
audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier),
audit.ActionUpdated,
paths.Parent(repo.Path),
audit.WithOldObject(old),
audit.WithNewObject(out),
)
if err != nil {
log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository settings operation: %s", err)
}
return out, 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/reposettings/security_update.go | app/api/controller/reposettings/security_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 reposettings
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
// SecurityUpdate updates the security settings of the repo.
func (c *Controller) SecurityUpdate(
ctx context.Context,
session *auth.Session,
repoRef string,
in *SecuritySettings,
) (*SecuritySettings, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil {
return nil, err
}
// read old settings values
old := GetDefaultSecuritySettings()
oldMappings := GetSecuritySettingsMappings(old)
err = c.settings.RepoMap(ctx, repo.ID, oldMappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings (old): %w", err)
}
err = c.settings.RepoSetMany(ctx, repo.ID, GetSecuritySettingsAsKeyValues(in)...)
if err != nil {
return nil, fmt.Errorf("failed to set settings: %w", err)
}
// read all settings and return complete config
out := GetDefaultSecuritySettings()
mappings := GetSecuritySettingsMappings(out)
err = c.settings.RepoMap(ctx, repo.ID, mappings...)
if err != nil {
return nil, fmt.Errorf("failed to map settings: %w", err)
}
err = c.auditService.Log(ctx,
session.Principal,
audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier),
audit.ActionUpdated,
paths.Parent(repo.Path),
audit.WithOldObject(old),
audit.WithNewObject(out),
)
if err != nil {
log.Ctx(ctx).Warn().Msgf("failed to insert audit log for update repository settings operation: %s", err)
}
return out, 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/reposettings/controller.go | app/api/controller/reposettings/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 reposettings
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/repo"
"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/services/settings"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type Controller struct {
authorizer authz.Authorizer
repoFinder refcache.RepoFinder
settings *settings.Service
auditService audit.Service
}
func NewController(
authorizer authz.Authorizer,
repoFinder refcache.RepoFinder,
settings *settings.Service,
auditService audit.Service,
) *Controller {
return &Controller{
authorizer: authorizer,
repoFinder: repoFinder,
settings: settings,
auditService: auditService,
}
}
// getRepoCheckAccess fetches a repo, checks if operation is allowed given the repo state
// and checks if the current user has permission to access it.
func (c *Controller) getRepoCheckAccess(
ctx context.Context,
session *auth.Session,
repoRef string,
reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState,
) (*types.RepositoryCore, error) {
repo, err := repo.GetRepo(ctx, c.repoFinder, repoRef)
if err != nil {
return nil, err
}
if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil {
return nil, err
}
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil {
return nil, fmt.Errorf("access check failed: %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/reposettings/security.go | app/api/controller/reposettings/security.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 reposettings
import (
"github.com/harness/gitness/app/services/settings"
"github.com/gotidy/ptr"
)
// SecuritySettings represents the security related part of repository settings as exposed externally.
type SecuritySettings struct {
SecretScanningEnabled *bool `json:"secret_scanning_enabled" yaml:"secret_scanning_enabled"`
PrincipalCommitterMatch *bool `json:"principal_committer_match" yaml:"principal_committer_match"`
}
func GetDefaultSecuritySettings() *SecuritySettings {
return &SecuritySettings{
SecretScanningEnabled: ptr.Bool(settings.DefaultSecretScanningEnabled),
PrincipalCommitterMatch: ptr.Bool(settings.DefaultPrincipalCommitterMatch),
}
}
func GetSecuritySettingsMappings(s *SecuritySettings) []settings.SettingHandler {
return []settings.SettingHandler{
settings.Mapping(settings.KeySecretScanningEnabled, s.SecretScanningEnabled),
settings.Mapping(settings.KeyPrincipalCommitterMatch, s.PrincipalCommitterMatch),
}
}
func GetSecuritySettingsAsKeyValues(s *SecuritySettings) []settings.KeyValue {
kvs := make([]settings.KeyValue, 0, 2)
if s.SecretScanningEnabled != nil {
kvs = append(kvs, settings.KeyValue{Key: settings.KeySecretScanningEnabled, Value: *s.SecretScanningEnabled})
}
if s.PrincipalCommitterMatch != nil {
kvs = append(kvs, settings.KeyValue{
Key: settings.KeyPrincipalCommitterMatch,
Value: s.PrincipalCommitterMatch,
})
}
return kvs
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.