repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/pr_list.go | app/api/controller/space/pr_list.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
)
// ListPullReqs returns a list of pull requests from the provided space.
func (c *Controller) ListPullReqs(
ctx context.Context,
session *auth.Session,
spaceRef string,
includeSubspaces bool,
filter *types.PullReqFilter,
) ([]types.PullReqRepo, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("space not found: %w", err)
}
// We deliberately don't check for space permission because the pull request service
// will check for repo-view permission for every returned pull request.
pullReqs, err := c.prListService.ListForSpace(ctx, session, space, includeSubspaces, filter)
if err != nil {
return nil, fmt.Errorf("failed to fetch pull requests from space: %w", err)
}
return pullReqs, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/membership_add.go | app/api/controller/space/membership_add.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/pkg/errors"
)
type MembershipAddInput struct {
UserUID string `json:"user_uid"`
Role enum.MembershipRole `json:"role"`
}
func (in *MembershipAddInput) Validate() error {
if in.UserUID == "" {
return usererror.BadRequest("UserUID must be provided")
}
if in.Role == "" {
return usererror.BadRequest("Role must be provided")
}
role, ok := in.Role.Sanitize()
if !ok {
msg := fmt.Sprintf("Provided role '%s' is not suppored. Valid values are: %v",
in.Role, enum.MembershipRoles)
return usererror.BadRequest(msg)
}
in.Role = role
return nil
}
// MembershipAdd adds a new membership to a space.
func (c *Controller) MembershipAdd(ctx context.Context,
session *auth.Session,
spaceRef string,
in *MembershipAddInput,
) (*types.MembershipUser, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
err = in.Validate()
if err != nil {
return nil, err
}
user, err := c.principalStore.FindUserByUID(ctx, in.UserUID)
if errors.Is(err, store.ErrResourceNotFound) {
return nil, usererror.BadRequestf("User '%s' not found", in.UserUID)
} else if err != nil {
return nil, fmt.Errorf("failed to find the user: %w", err)
}
now := time.Now().UnixMilli()
membership := types.Membership{
MembershipKey: types.MembershipKey{
SpaceID: space.ID,
PrincipalID: user.ID,
},
CreatedBy: session.Principal.ID,
Created: now,
Updated: now,
Role: in.Role,
}
err = c.membershipStore.Create(ctx, &membership)
if err != nil {
return nil, fmt.Errorf("failed to create new membership: %w", err)
}
result := &types.MembershipUser{
Membership: membership,
Principal: *user.ToPrincipalInfo(),
AddedBy: *session.Principal.ToPrincipalInfo(),
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_service_accounts.go | app/api/controller/space/list_service_accounts.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// ListServiceAccounts lists the service accounts of a space.
func (c *Controller) ListServiceAccounts(
ctx context.Context,
session *auth.Session,
spaceRef string,
inherited bool,
opts *types.PrincipalFilter,
) ([]*types.ServiceAccountInfo, int64, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, 0, err
}
if err = apiauth.CheckServiceAccount(
ctx,
c.authorizer,
session,
c.spaceStore,
c.repoStore,
enum.ParentResourceTypeSpace,
space.ID,
"",
enum.PermissionServiceAccountView,
); err != nil {
return nil, 0, err
}
var parentInfos []*types.ServiceAccountParentInfo
if inherited {
ancestorIDs, err := c.spaceStore.GetAncestorIDs(ctx, space.ID)
if err != nil {
return nil, 0, fmt.Errorf("failed to get parent space ids: %w", err)
}
parentInfos = make([]*types.ServiceAccountParentInfo, len(ancestorIDs))
for i := range ancestorIDs {
parentInfos[i] = &types.ServiceAccountParentInfo{
Type: enum.ParentResourceTypeSpace,
ID: ancestorIDs[i],
}
}
} else {
parentInfos = make([]*types.ServiceAccountParentInfo, 1)
parentInfos[0] = &types.ServiceAccountParentInfo{
Type: enum.ParentResourceTypeSpace,
ID: space.ID,
}
}
var accounts []*types.ServiceAccount
var count int64
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
accounts, err = c.principalStore.ListServiceAccounts(ctx, parentInfos, opts)
if err != nil {
return fmt.Errorf("failed to list service accounts: %w", err)
}
if opts.Page == 1 && len(accounts) < opts.Size {
count = int64(len(accounts))
return nil
}
count, err = c.principalStore.CountServiceAccounts(ctx, parentInfos, opts)
if err != nil {
return fmt.Errorf("failed to count pull requests: %w", err)
}
return nil
}, dbtx.TxDefaultReadOnly)
infos := make([]*types.ServiceAccountInfo, len(accounts))
for i := range accounts {
infos[i] = accounts[i].ToServiceAccountInfo()
}
return infos, count, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/membership_delete.go | app/api/controller/space/membership_delete.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// MembershipDelete removes an existing membership from a space.
func (c *Controller) MembershipDelete(ctx context.Context,
session *auth.Session,
spaceRef string,
userUID string,
) error {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return fmt.Errorf("failed to acquire access to space: %w", err)
}
user, err := c.principalStore.FindUserByUID(ctx, userUID)
if err != nil {
return fmt.Errorf("failed to find user by uid: %w", err)
}
err = c.membershipStore.Delete(ctx, types.MembershipKey{
SpaceID: space.ID,
PrincipalID: user.ID,
})
if err != nil {
return fmt.Errorf("failed to delete user membership: %w", err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/update_public_access.go | app/api/controller/space/update_public_access.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types/enum"
)
type UpdatePublicAccessInput struct {
IsPublic bool `json:"is_public"`
}
func (c *Controller) UpdatePublicAccess(
ctx context.Context,
session *auth.Session,
spaceRef string,
in *UpdatePublicAccessInput,
) (*SpaceOutput, error) {
spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
parentPath, _, err := paths.DisectLeaf(space.Path)
if err != nil {
return nil, fmt.Errorf("failed to disect path %q: %w", space.Path, err)
}
isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentPath)
if err != nil {
return nil, fmt.Errorf(
"failed to check if public access is supported for parent space %q: %w",
parentPath,
err,
)
}
if in.IsPublic && !isPublicAccessSupported {
return nil, errPublicSpaceCreationDisabled
}
isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeSpace, space.Path)
if err != nil {
return nil, fmt.Errorf("failed to check current public access status: %w", err)
}
// no op
if isPublic == in.IsPublic {
return &SpaceOutput{
Space: *space,
IsPublic: isPublic,
}, nil
}
if err = c.publicAccess.Set(ctx, enum.PublicResourceTypeSpace, space.Path, in.IsPublic); err != nil {
return nil, fmt.Errorf("failed to update space public access: %w", err)
}
return &SpaceOutput{
Space: *space,
IsPublic: in.IsPublic,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_gitspaces.go | app/api/controller/space/list_gitspaces.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
)
func (c *Controller) ListGitspaces(
ctx context.Context,
session *auth.Session,
spaceRef string,
filter types.GitspaceFilter,
) ([]*types.GitspaceConfig, int64, int64, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, 0, 0, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckGitspace(ctx, c.authorizer, session, space.Path, "", enum.PermissionGitspaceView)
if err != nil {
return nil, 0, 0, fmt.Errorf("failed to authorize gitspace: %w", err)
}
filter.UserIdentifier = session.Principal.UID
filter.SpaceIDs = []int64{space.ID}
filter.Deleted = ptr.Bool(false)
filter.MarkedForDeletion = ptr.Bool(false)
return c.gitspaceSvc.ListGitspacesWithInstance(ctx, filter, true)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/label_define.go | app/api/controller/space/label_define.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// DefineLabel defines a new label for the specified space.
func (c *Controller) DefineLabel(
ctx context.Context,
session *auth.Session,
spaceRef string,
in *types.DefineLabelInput,
) (*types.Label, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
if err := in.Sanitize(); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
label, err := c.labelSvc.Define(
ctx, session.Principal.ID, &space.ID, nil, in)
if err != nil {
return nil, fmt.Errorf("failed to create space label: %w", err)
}
return label, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/events.go | app/api/controller/space/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 space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/sse"
"github.com/harness/gitness/types/enum"
)
func (c *Controller) Events(
ctx context.Context,
session *auth.Session,
spaceRef string,
) (<-chan *sse.Event, <-chan error, func(context.Context) error, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
chEvents, chErr, sseCancel := c.sseStreamer.Stream(ctx, space.ID)
return chEvents, chErr, sseCancel, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/list_spaces.go | app/api/controller/space/list_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 space
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// ListSpaces lists the child spaces of a space.
func (c *Controller) ListSpaces(ctx context.Context,
session *auth.Session,
spaceRef string,
filter *types.SpaceFilter,
) ([]*SpaceOutput, int64, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, 0, err
}
if err = apiauth.CheckSpaceScope(
ctx,
c.authorizer,
session,
space,
enum.ResourceTypeSpace,
enum.PermissionSpaceView,
); err != nil {
return nil, 0, err
}
return c.ListSpacesNoAuth(ctx, space.ID, filter)
}
// ListSpacesNoAuth lists spaces WITHOUT checking PermissionSpaceView.
func (c *Controller) ListSpacesNoAuth(
ctx context.Context,
spaceID int64,
filter *types.SpaceFilter,
) ([]*SpaceOutput, int64, error) {
var spaces []*types.Space
var count int64
err := c.tx.WithTx(ctx, func(ctx context.Context) (err error) {
count, err = c.spaceStore.Count(ctx, spaceID, filter)
if err != nil {
return fmt.Errorf("failed to count child spaces: %w", err)
}
spaces, err = c.spaceStore.List(ctx, spaceID, filter)
if err != nil {
return fmt.Errorf("failed to list child spaces: %w", err)
}
return nil
}, dbtx.TxDefaultReadOnly)
if err != nil {
return nil, 0, err
}
// backfill public access mode
var spacesOut []*SpaceOutput
for _, space := range spaces {
spaceOut, err := GetSpaceOutput(ctx, c.publicAccess, space)
if err != nil {
return nil, 0, fmt.Errorf("failed to get space %q output: %w", space.Path, err)
}
spacesOut = append(spacesOut, spaceOut)
}
return spacesOut, count, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/rule_update.go | app/api/controller/space/rule_update.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/rules"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// RuleUpdate updates an existing protection rule for a space.
func (c *Controller) RuleUpdate(ctx context.Context,
session *auth.Session,
spaceRef string,
identifier string,
in *rules.UpdateInput,
) (*types.Rule, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
rule, err := c.rulesSvc.Update(
ctx,
&session.Principal,
enum.RuleParentSpace,
space.ID,
space.Identifier,
space.Path,
identifier,
in,
)
if err != nil {
return nil, fmt.Errorf("failed to update space-level protection rule by identifier: %w", err)
}
return rule, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/update.go | app/api/controller/space/update.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
import (
"context"
"fmt"
"strings"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
// UpdateInput is used for updating a space.
type UpdateInput struct {
Description *string `json:"description"`
}
func (in *UpdateInput) hasChanges(space *types.Space) bool {
return in.Description != nil && *in.Description != space.Description
}
// Update updates a space.
func (c *Controller) Update(
ctx context.Context,
session *auth.Session,
spaceRef string,
in *UpdateInput,
) (*SpaceOutput, error) {
spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
if !in.hasChanges(space) {
return GetSpaceOutput(ctx, c.publicAccess, space)
}
if err = c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
space, err = c.spaceStore.UpdateOptLock(ctx, space, func(space *types.Space) error {
// update values only if provided
if in.Description != nil {
space.Description = *in.Description
}
return nil
})
if err != nil {
return nil, err
}
return GetSpaceOutput(ctx, c.publicAccess, space)
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
if in.Description != nil {
*in.Description = strings.TrimSpace(*in.Description)
if err := check.Description(*in.Description); err != nil {
return err
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/space/import.go | app/api/controller/space/import.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package space
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/paths"
"github.com/harness/gitness/app/services/importer"
"github.com/harness/gitness/app/services/instrument"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
)
type ProviderInput struct {
Provider importer.Provider `json:"provider"`
ProviderSpace string `json:"provider_space"`
Pipelines importer.PipelineOption `json:"pipelines"`
}
type ImportInput struct {
CreateInput
ProviderInput
}
// Import creates new space and starts import of all repositories from the remote provider's space into it.
//
//nolint:gocognit
func (c *Controller) Import(ctx context.Context, session *auth.Session, in *ImportInput) (*SpaceOutput, error) {
parentSpace, err := c.getSpaceCheckAuthSpaceCreation(ctx, session, in.ParentRef)
if err != nil {
return nil, err
}
if in.Identifier == "" && in.UID == "" {
in.Identifier = in.ProviderSpace
}
err = c.sanitizeImportInput(in)
if err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
remoteRepositories, provider, err :=
importer.LoadRepositoriesFromProviderSpace(ctx, in.Provider, in.ProviderSpace)
if err != nil {
return nil, err
}
if len(remoteRepositories) == 0 {
return nil, usererror.BadRequestf("Found no repositories in %q", in.ProviderSpace)
}
repoIDs := make([]int64, len(remoteRepositories))
repoIsPublicVals := make([]bool, len(remoteRepositories))
cloneURLs := make([]string, len(remoteRepositories))
repos := make([]*types.Repository, 0, len(remoteRepositories))
var space *types.Space
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
if err := c.resourceLimiter.RepoCount(
ctx, parentSpace.ID, len(remoteRepositories)); err != nil {
return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached)
}
space, err = c.createSpaceInnerInTX(ctx, session, parentSpace.ID, &in.CreateInput)
if err != nil {
return err
}
for i, remoteRepository := range remoteRepositories {
repo, isPublic := remoteRepository.ToRepo(
space.ID,
space.Path,
remoteRepository.Identifier,
"",
&session.Principal,
)
err = c.repoStore.Create(ctx, repo)
if err != nil {
return fmt.Errorf("failed to create repository in storage: %w", err)
}
repos = append(repos, repo)
repoIDs[i] = repo.ID
cloneURLs[i] = remoteRepository.CloneURL
repoIsPublicVals[i] = isPublic
}
jobGroupID := fmt.Sprintf("space-import-%d", space.ID)
err = c.importer.RunMany(ctx,
jobGroupID,
provider,
repoIDs,
repoIsPublicVals,
cloneURLs,
in.Pipelines,
)
if err != nil {
return fmt.Errorf("failed to start import repository jobs: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
for _, repo := range repos {
err = c.auditService.Log(ctx,
session.Principal,
audit.NewResource(audit.ResourceTypeRepository, repo.Identifier),
audit.ActionCreated,
paths.Parent(repo.Path),
audit.WithNewObject(audit.RepositoryObject{
Repository: *repo,
IsPublic: false, // in import we configure public access and create a new audit log.
}),
)
if err != nil {
log.Warn().Msgf("failed to insert audit log for import repository operation: %s", err)
}
err = c.instrumentation.Track(ctx, instrument.Event{
Type: instrument.EventTypeRepositoryCreate,
Principal: session.Principal.ToPrincipalInfo(),
Path: space.Path,
Properties: map[instrument.Property]any{
instrument.PropertyRepositoryID: repo.ID,
instrument.PropertyRepositoryName: repo.Identifier,
instrument.PropertyRepositoryCreationType: instrument.CreationTypeImport,
},
})
if err != nil {
log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for import repository operation: %s", err)
}
}
return GetSpaceOutput(ctx, c.publicAccess, space)
}
func (c *Controller) sanitizeImportInput(in *ImportInput) error {
if err := c.sanitizeCreateInput(&in.CreateInput); err != nil {
return err
}
if in.Pipelines == "" {
in.Pipelines = importer.PipelineOptionConvert
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/template/wire.go | app/api/controller/template/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 template
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
templateStore store.TemplateStore,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
) *Controller {
return NewController(authorizer, templateStore, 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/template/create.go | app/api/controller/template/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 template
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 (
// errTemplateRequiresParent if the user tries to create a template without a parent space.
errTemplateRequiresParent = usererror.BadRequest(
"Parent space required - standalone templates 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.Template, 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.CheckTemplate(
ctx,
c.authorizer,
session,
parentSpace.Path,
"",
enum.PermissionTemplateEdit,
)
if err != nil {
return nil, err
}
// Try to parse template data into valid v1 config. Ignore error as it's
// already validated in sanitize function.
resolverType, _ := parseResolverType(in.Data)
var template *types.Template
now := time.Now().UnixMilli()
template = &types.Template{
Description: in.Description,
Data: in.Data,
SpaceID: parentSpace.ID,
Identifier: in.Identifier,
Type: resolverType,
Created: now,
Updated: now,
Version: 0,
}
err = c.templateStore.Create(ctx, template)
if err != nil {
return nil, fmt.Errorf("template creation failed: %w", err)
}
return template, 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 errTemplateRequiresParent
}
if err := check.Identifier(in.Identifier); err != nil {
return err
}
_, err = parseResolverType(in.Data)
if 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/template/validate.go | app/api/controller/template/validate.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package template
import (
"fmt"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
"github.com/drone/spec/dist/go/parse"
)
// parseResolverType parses and validates the input yaml. It returns back the parsed
// template type.
func parseResolverType(data string) (enum.ResolverType, error) {
config, err := parse.ParseString(data)
if err != nil {
return "", check.NewValidationError(fmt.Sprintf("could not parse template data: %s", err))
}
resolverTypeEnum, err := enum.ParseResolverType(config.Type)
if err != nil {
return "", check.NewValidationError(fmt.Sprintf("could not parse template type: %s", config.Type))
}
return resolverTypeEnum, 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/template/delete.go | app/api/controller/template/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 template
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,
resolverType enum.ResolverType,
) error {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckTemplate(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionTemplateDelete)
if err != nil {
return fmt.Errorf("failed to authorize: %w", err)
}
err = c.templateStore.DeleteByIdentifierAndType(ctx, space.ID, identifier, resolverType)
if err != nil {
return fmt.Errorf("could not delete template: %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/template/find.go | app/api/controller/template/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 template
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,
resolverType enum.ResolverType,
) (*types.Template, error) {
space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err)
}
err = apiauth.CheckTemplate(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionTemplateView)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
template, err := c.templateStore.FindByIdentifierAndType(ctx, space.ID, identifier, resolverType)
if err != nil {
return nil, fmt.Errorf("failed to find template: %w", err)
}
return template, 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/template/controller.go | app/api/controller/template/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 template
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
)
type Controller struct {
templateStore store.TemplateStore
authorizer authz.Authorizer
spaceFinder refcache.SpaceFinder
}
func NewController(
authorizer authz.Authorizer,
templateStore store.TemplateStore,
spaceFinder refcache.SpaceFinder,
) *Controller {
return &Controller{
templateStore: templateStore,
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/template/update.go | app/api/controller/template/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 template
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 template.
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,
resolverType enum.ResolverType,
in *UpdateInput,
) (*types.Template, 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.CheckTemplate(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionTemplateEdit)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
template, err := c.templateStore.FindByIdentifierAndType(ctx, space.ID, identifier, resolverType)
if err != nil {
return nil, fmt.Errorf("failed to find template: %w", err)
}
return c.templateStore.UpdateOptLock(ctx, template, func(original *types.Template) error {
if in.Identifier != nil {
original.Identifier = *in.Identifier
}
if in.Description != nil {
original.Description = *in.Description
}
if in.Data != nil {
// ignore error as it's already validated in sanitize function
t, _ := parseResolverType(*in.Data)
original.Data = *in.Data
original.Type = t
}
return nil
})
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
// TODO [CODE-1363]: remove after identifier migration.
if in.Identifier == nil {
in.Identifier = in.UID
}
if in.Identifier != nil {
if err := check.Identifier(*in.Identifier); err != nil {
return err
}
}
if in.Description != nil {
*in.Description = strings.TrimSpace(*in.Description)
if err := check.Description(*in.Description); err != nil {
return err
}
}
if in.Data != nil {
_, err := parseResolverType(*in.Data)
if 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/migrate/wire.go | app/api/controller/migrate/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 migrate
import (
"github.com/harness/gitness/app/api/controller/limiter"
"github.com/harness/gitness/app/auth/authz"
repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/refcache"
"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/store/database/dbtx"
"github.com/harness/gitness/types/check"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
authorizer authz.Authorizer,
publicAccess publicaccess.Service,
rpcClient git.Interface,
urlProvider url.Provider,
pullreqImporter *migrate.PullReq,
ruleImporter *migrate.Rule,
webhookImporter *migrate.Webhook,
labelImporter *migrate.Label,
resourceLimiter limiter.ResourceLimiter,
auditService audit.Service,
identifierCheck check.RepoIdentifier,
tx dbtx.Transactor,
spaceStore store.SpaceStore,
repoStore store.RepoStore,
spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder,
eventReporter *repoevents.Reporter,
) *Controller {
return NewController(
authorizer,
publicAccess,
rpcClient,
urlProvider,
pullreqImporter,
ruleImporter,
webhookImporter,
labelImporter,
resourceLimiter,
auditService,
identifierCheck,
tx,
spaceStore,
repoStore,
spaceFinder,
repoFinder,
eventReporter,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/migrate/webhooks.go | app/api/controller/migrate/webhooks.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 migrate
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type WebhooksInput struct {
Webhooks []*migrate.ExternalWebhook `json:"hooks"`
}
func (c *Controller) Webhooks(
ctx context.Context,
session *auth.Session,
repoRef string,
in *WebhooksInput,
) ([]*types.Webhook, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
if repo.State != enum.RepoStateMigrateDataImport {
return nil, fmt.Errorf("repo state is %s want %s: %w",
repo.State, enum.RepoStateMigrateDataImport, errInvalidRepoState)
}
hookOut, err := c.webhookImporter.Import(ctx, session.Principal, repo, in.Webhooks)
if err != nil {
return nil, fmt.Errorf("failed to import webhooks: %w", err)
}
return hookOut, 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/migrate/rules.go | app/api/controller/migrate/rules.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 migrate
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type RulesInput struct {
Rules []*migrate.ExternalRule `json:"rules"`
Type migrate.ExternalRuleType `json:"type"`
}
func (c *Controller) Rules(
ctx context.Context,
session *auth.Session,
repoRef string,
in *RulesInput,
) ([]*types.Rule, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
if repo.State != enum.RepoStateMigrateDataImport {
return nil, fmt.Errorf("repo state is %s want %s: %w",
repo.State, enum.RepoStateMigrateDataImport, errInvalidRepoState)
}
rulesOut, err := c.ruleImporter.Import(ctx, session.Principal, repo, in.Type, in.Rules)
if err != nil {
return nil, fmt.Errorf("failed to import rules: %w", err)
}
return rulesOut, 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/migrate/error.go | app/api/controller/migrate/error.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 migrate
import "github.com/harness/gitness/errors"
var errInvalidRepoState = errors.PreconditionFailed("Repository data can't be imported at this point")
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/migrate/pullreq.go | app/api/controller/migrate/pullreq.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 migrate
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type PullreqsInput struct {
PullRequestData []*migrate.ExternalPullRequest `json:"pull_request_data"`
}
func (c *Controller) PullRequests(
ctx context.Context,
session *auth.Session,
repoRef string,
in *PullreqsInput,
) ([]*types.PullReq, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
if repo.State != enum.RepoStateMigrateDataImport {
return nil, fmt.Errorf("repo state is %s want %s: %w",
repo.State, enum.RepoStateMigrateDataImport, errInvalidRepoState)
}
pullreqs, err := c.pullreqImporter.Import(ctx, session.Principal, repo, in.PullRequestData)
if err != nil {
return nil, fmt.Errorf("failed to import pull requests and/or comments: %w", err)
}
return pullreqs, 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/migrate/update_state.go | app/api/controller/migrate/update_state.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 migrate
import (
"context"
"fmt"
"slices"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
var validTransitions = map[enum.RepoState][]enum.RepoState{
enum.RepoStateActive: {enum.RepoStateMigrateDataImport},
enum.RepoStateMigrateDataImport: {enum.RepoStateActive},
enum.RepoStateMigrateGitPush: {enum.RepoStateActive, enum.RepoStateMigrateDataImport},
}
type UpdateStateInput struct {
State enum.RepoState `json:"state"`
Force bool `json:"force,omitempty"`
}
func (c *Controller) UpdateRepoState(
ctx context.Context,
session *auth.Session,
repoRef string,
in *UpdateStateInput,
) (*types.Repository, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
repoFull, err := c.repoStore.Find(ctx, repo.ID)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
}
repoFull, err = c.repoStore.UpdateOptLock(ctx, repoFull, func(r *types.Repository) error {
if !stateTransitionValid(ctx, repo.Identifier, r.State, in.State, in.Force) {
return usererror.BadRequestf("Changing repo state from %s to %s is not allowed.", r.State, in.State)
}
r.State = in.State
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to update the repo state: %w", err)
}
c.repoFinder.MarkChanged(ctx, repo)
return repoFull, nil
}
func stateTransitionValid(
ctx context.Context,
repoIdentifier string,
currentState enum.RepoState,
newState enum.RepoState,
force bool,
) bool {
if slices.Contains(validTransitions[currentState], newState) {
return true
}
if force {
log.Ctx(ctx).Warn().Msgf("Forcing state transition for repo %s from %s to %s",
repoIdentifier, currentState, newState)
return true
}
return false
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/migrate/controller.go | app/api/controller/migrate/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 migrate
import (
"context"
"fmt"
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/auth/authz"
repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/refcache"
"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/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
type Controller struct {
authorizer authz.Authorizer
publicAccess publicaccess.Service
git git.Interface
urlProvider url.Provider
pullreqImporter *migrate.PullReq
ruleImporter *migrate.Rule
webhookImporter *migrate.Webhook
labelImporter *migrate.Label
resourceLimiter limiter.ResourceLimiter
auditService audit.Service
identifierCheck check.RepoIdentifier
tx dbtx.Transactor
spaceStore store.SpaceStore
repoStore store.RepoStore
spaceFinder refcache.SpaceFinder
repoFinder refcache.RepoFinder
eventReporter *repoevents.Reporter
}
func NewController(
authorizer authz.Authorizer,
publicAccess publicaccess.Service,
git git.Interface,
urlProvider url.Provider,
pullreqImporter *migrate.PullReq,
ruleImporter *migrate.Rule,
webhookImporter *migrate.Webhook,
labelImporter *migrate.Label,
resourceLimiter limiter.ResourceLimiter,
auditService audit.Service,
identifierCheck check.RepoIdentifier,
tx dbtx.Transactor,
spaceStore store.SpaceStore,
repoStore store.RepoStore,
spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder,
eventReporter *repoevents.Reporter,
) *Controller {
return &Controller{
authorizer: authorizer,
publicAccess: publicAccess,
git: git,
urlProvider: urlProvider,
pullreqImporter: pullreqImporter,
ruleImporter: ruleImporter,
webhookImporter: webhookImporter,
labelImporter: labelImporter,
resourceLimiter: resourceLimiter,
auditService: auditService,
identifierCheck: identifierCheck,
tx: tx,
spaceStore: spaceStore,
repoStore: repoStore,
spaceFinder: spaceFinder,
repoFinder: repoFinder,
eventReporter: eventReporter,
}
}
func (c *Controller) getRepoCheckAccess(
ctx context.Context,
session *auth.Session,
repoRef string,
reqPermission enum.Permission,
) (*types.RepositoryCore, error) {
if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.")
}
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err)
}
// repo state check happens per operation as it varies given the stage of the migration.
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, reqPermission); err != nil {
return nil, fmt.Errorf("failed to verify authorization: %w", err)
}
return repo, nil
}
func (c *Controller) getSpaceCheckAccess(
ctx context.Context,
session *auth.Session,
parentRef string,
reqPermission enum.Permission,
) (*types.SpaceCore, error) {
space, err := c.spaceFinder.FindByRef(ctx, parentRef)
if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err)
}
err = apiauth.CheckSpaceScope(
ctx,
c.authorizer,
session,
space,
enum.ResourceTypeSpace,
reqPermission,
)
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/migrate/create_repo.go | app/api/controller/migrate/create_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 migrate
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/limiter"
repoCtrl "github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/bootstrap"
repoevents "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/githook"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/git"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
type CreateRepoInput struct {
ParentRef string `json:"parent_ref"`
Identifier string `json:"identifier"`
DefaultBranch string `json:"default_branch"`
IsPublic bool `json:"is_public"`
}
func (c *Controller) CreateRepo(
ctx context.Context,
session *auth.Session,
in *CreateRepoInput,
) (*repoCtrl.RepositoryOutput, error) {
if err := c.sanitizeCreateRepoInput(in, session); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
parentSpaceCore, err := c.spaceCheckAuth(ctx, session, in.ParentRef)
if err != nil {
return nil, fmt.Errorf("failed to check auth in parent '%s': %w", in.ParentRef, err)
}
parentSpace, err := c.spaceStore.Find(ctx, parentSpaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
// generate envars (add everything githook CLI needs for execution)
envVars, err := githook.GenerateEnvironmentVariables(
ctx,
c.urlProvider.GetInternalAPIURL(ctx),
0,
session.Principal.ID,
true,
true,
)
if err != nil {
return nil, fmt.Errorf("failed to generate git hook environment variables: %w", err)
}
actor := &git.Identity{
Name: session.Principal.DisplayName,
Email: session.Principal.Email,
}
committer := bootstrap.NewSystemServiceSession().Principal
now := time.Now()
gitResp, err := c.git.CreateRepository(ctx, &git.CreateRepositoryParams{
Actor: *actor,
EnvVars: envVars,
DefaultBranch: in.DefaultBranch,
Files: nil,
Author: actor,
AuthorDate: &now,
Committer: &git.Identity{
Name: committer.DisplayName,
Email: committer.Email,
},
CommitterDate: &now,
})
if err != nil {
return nil, fmt.Errorf("failed to create git repository: %w", err)
}
var repo *types.Repository
err = c.tx.WithTx(ctx, func(ctx context.Context) error {
if err := c.resourceLimiter.RepoCount(ctx, parentSpace.ID, 1); err != nil {
return fmt.Errorf("resource limit exceeded: %w", limiter.ErrMaxNumReposReached)
}
// lock the space for update during repo creation to prevent racing conditions with space soft delete.
parentSpace, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID)
if err != nil {
return fmt.Errorf("failed to find the parent space: %w", err)
}
repo = &types.Repository{
Version: 0,
ParentID: parentSpace.ID,
Identifier: in.Identifier,
GitUID: gitResp.UID,
CreatedBy: session.Principal.ID,
Created: now.UnixMilli(),
Updated: now.UnixMilli(),
LastGITPush: now.UnixMilli(), // even in case of an empty repo, the git repo got created.
DefaultBranch: in.DefaultBranch,
IsEmpty: true,
State: enum.RepoStateMigrateGitPush,
Tags: json.RawMessage(`{}`),
}
return c.repoStore.Create(ctx, repo)
}, sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
// TODO: best effort cleanup
return nil, fmt.Errorf("failed to create a repo on db: %w", err)
}
repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path)
repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path)
isPublicAccessSupported, err := c.publicAccess.
IsPublicAccessSupported(ctx, enum.PublicResourceTypeRepo, parentSpace.Path)
if err != nil {
return nil, fmt.Errorf(
"failed to check if public access is supported for parent space %s: %w",
parentSpace.Path,
err,
)
}
isRepoPublic := in.IsPublic
if !isPublicAccessSupported {
log.Ctx(ctx).Debug().Msgf(
"public access is not supported, create migrating repo %s as private instead",
repo.Identifier)
isRepoPublic = false
}
err = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isRepoPublic)
if err != nil {
return nil, fmt.Errorf("failed to set repo access mode: %w", err)
}
err = c.auditService.Log(ctx,
session.Principal,
audit.NewResource(audit.ResourceTypeRepository, repo.Identifier),
audit.ActionCreated,
paths.Parent(repo.Path),
audit.WithNewObject(audit.RepositoryObject{
Repository: *repo,
IsPublic: isRepoPublic,
}),
)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("failed to insert audit log for import repository operation")
}
c.eventReporter.Created(ctx, &repoevents.CreatedPayload{
Base: repoevents.Base{
RepoID: repo.ID,
PrincipalID: session.Principal.ID,
},
IsPublic: isRepoPublic,
IsMigrated: true,
})
return &repoCtrl.RepositoryOutput{
Repository: *repo,
IsPublic: isRepoPublic,
}, nil
}
func (c *Controller) spaceCheckAuth(
ctx context.Context,
session *auth.Session,
parentRef string,
) (*types.SpaceCore, error) {
space, err := c.spaceFinder.FindByRef(ctx, parentRef)
if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err)
}
// create is a special case - check permission without specific resource
scope := &types.Scope{SpacePath: space.Path}
resource := &types.Resource{
Type: enum.ResourceTypeRepo,
Identifier: "",
}
if err = apiauth.Check(
ctx, c.authorizer, session, scope, resource, enum.PermissionRepoCreate,
); err != nil {
return nil, err
}
return space, nil
}
func (c *Controller) sanitizeCreateRepoInput(in *CreateRepoInput, session *auth.Session) error {
if err := repoCtrl.ValidateParentRef(in.ParentRef); err != nil {
return err
}
if err := c.identifierCheck(in.Identifier, session); 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/migrate/label.go | app/api/controller/migrate/label.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 migrate
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/migrate"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type LabelsInput struct {
Labels []*migrate.ExternalLabel `json:"labels"`
}
func (c *Controller) Labels(
ctx context.Context,
session *auth.Session,
parentRef string,
in *LabelsInput,
) ([]*types.Label, error) {
// TODO update the permission when CODE-2285 is done.
space, err := c.getSpaceCheckAccess(ctx, session, parentRef, enum.PermissionRepoEdit)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err)
}
// TODO have some locking mechanism on space during importing labels
labels, err := c.labelImporter.Import(ctx, session.Principal, space, in.Labels)
if err != nil {
return nil, fmt.Errorf("failed to import labels: %w", err)
}
return labels, 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/lfs/wire.go | app/api/controller/lfs/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 lfs
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/remoteauth"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/blob"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
authorizer authz.Authorizer,
repoFinder refcache.RepoFinder,
repoStore store.RepoStore,
principalStore store.PrincipalStore,
lfsStore store.LFSObjectStore,
blobStore blob.Store,
remoteAuth remoteauth.Service,
urlProvider url.Provider,
settings *settings.Service,
) *Controller {
return NewController(
authorizer,
repoFinder,
repoStore,
principalStore,
lfsStore,
blobStore,
remoteAuth,
urlProvider,
settings,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/lfs/types.go | app/api/controller/lfs/types.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 lfs
import (
"time"
"github.com/harness/gitness/types/enum"
)
type Reference struct {
Name string `json:"name"`
}
// Pointer contains LFS pointer data.
type Pointer struct {
OId string `json:"oid"`
Size int64 `json:"size"`
}
type TransferInput struct {
Operation enum.GitLFSOperationType `json:"operation"`
Transfers []enum.GitLFSTransferType `json:"transfers,omitempty"`
Ref *Reference `json:"ref,omitempty"`
Objects []Pointer `json:"objects"`
HashAlgo string `json:"hash_algo,omitempty"`
}
// ObjectError defines the JSON structure returned to the client in case of an error.
type ObjectError struct {
Code int `json:"code"`
Message string `json:"message"`
}
// Action provides a structure with information about next actions fo the object.
type Action struct {
Href string `json:"href"`
Header map[string]string `json:"header,omitempty"`
ExpiresIn *time.Duration `json:"expires_in,omitempty"`
}
// ObjectResponse is object metadata as seen by clients of the LFS server.
type ObjectResponse struct {
Pointer
Authenticated *bool `json:"authenticated,omitempty"`
Actions map[string]Action `json:"actions"`
Error *ObjectError `json:"error,omitempty"`
}
type TransferOutput struct {
Transfer enum.GitLFSTransferType `json:"transfer"`
Objects []ObjectResponse `json:"objects"`
}
type AuthenticateResponse struct {
Header map[string]string `json:"header"`
HRef string `json:"href"`
ExpiresIn time.Duration `json:"expires_in"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/lfs/errors.go | app/api/controller/lfs/errors.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 lfs
var (
// These are per-object errors when returned status code is 200.
errNotFound = ObjectError{
Code: 404,
Message: "The object does not exist on the server.",
}
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/lfs/transfer.go | app/api/controller/lfs/transfer.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 lfs
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types/enum"
)
func (c *Controller) LFSTransfer(ctx context.Context,
session *auth.Session,
repoRef string,
in *TransferInput,
) (*TransferOutput, error) {
reqPermission := enum.PermissionRepoView
if in.Operation == enum.GitLFSOperationTypeUpload {
reqPermission = enum.PermissionRepoPush
}
var additionalAllowedRepoStates = []enum.RepoState{enum.RepoStateMigrateGitPush}
repo, err := c.getRepoCheckAccessAndSetting(ctx, session, repoRef,
reqPermission, additionalAllowedRepoStates...)
if err != nil {
return nil, err
}
// TODO check if server supports client's transfer adapters
var objResponses []ObjectResponse
switch in.Operation {
case enum.GitLFSOperationTypeDownload:
for _, obj := range in.Objects {
var objResponse = ObjectResponse{
Pointer: Pointer{
OId: obj.OId,
Size: obj.Size,
},
}
object, err := c.lfsStore.Find(ctx, repo.ID, obj.OId)
if errors.Is(err, store.ErrResourceNotFound) {
objResponse.Error = &errNotFound
objResponses = append(objResponses, objResponse)
continue
}
if err != nil {
return nil, fmt.Errorf("failed to find object: %w", err)
}
// size is not a required query param for download hence nil
downloadURL := getRedirectRef(ctx, c.urlProvider, repoRef, obj.OId, nil)
objResponse = ObjectResponse{
Pointer: Pointer{
OId: object.OID,
Size: object.Size,
},
Actions: map[string]Action{
"download": {
Href: downloadURL,
Header: map[string]string{"Content-Type": "application/octet-stream"},
},
},
}
objResponses = append(objResponses, objResponse)
}
case enum.GitLFSOperationTypeUpload:
for _, obj := range in.Objects {
objResponse := ObjectResponse{
Pointer: Pointer{
OId: obj.OId,
Size: obj.Size,
},
}
// we dont create the object in lfs store here as the upload might fail in blob store.
_, err := c.lfsStore.Find(ctx, repo.ID, obj.OId)
if err == nil {
// no need to re-upload existing LFS objects
objResponses = append(objResponses, objResponse)
continue
}
if !errors.Is(err, store.ErrResourceNotFound) {
return nil, fmt.Errorf("failed to find object: %w", err)
}
uploadURL := getRedirectRef(ctx, c.urlProvider, repoRef, obj.OId, &obj.Size)
objResponse.Actions = map[string]Action{
"upload": {
Href: uploadURL,
Header: map[string]string{"Content-Type": "application/octet-stream"},
},
}
objResponses = append(objResponses, objResponse)
}
default:
return nil, usererror.BadRequestf("Git LFS operation %q is not supported", in.Operation)
}
return &TransferOutput{
Transfer: enum.GitLFSTransferTypeBasic,
Objects: objResponses,
}, nil
}
func getRedirectRef(ctx context.Context, urlProvider url.Provider, repoPath, oID string, size *int64) string {
baseGitURL := urlProvider.GenerateGITCloneURL(ctx, repoPath)
queryParams := "oid=" + oID
if size != nil {
queryParams += "&size=" + strconv.FormatInt(*size, 10)
}
return baseGitURL + "/info/lfs/objects/?" + queryParams
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/lfs/authenticate.go | app/api/controller/lfs/authenticate.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 lfs
import (
"context"
"fmt"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/token"
)
func (c *Controller) Authenticate(
ctx context.Context,
session *auth.Session,
repoRef string,
) (*AuthenticateResponse, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repository: %w", err)
}
gitLFSEnabled, err := settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeyGitLFSEnabled,
settings.DefaultGitLFSEnabled,
)
if err != nil {
return nil, fmt.Errorf("failed to check settings for Git LFS enabled: %w", err)
}
if !gitLFSEnabled {
return nil, usererror.ErrGitLFSDisabled
}
jwt, err := c.remoteAuth.GenerateToken(ctx, session.Principal.ID, session.Principal.Type, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to generate auth token: %w", err)
}
return &AuthenticateResponse{
Header: map[string]string{
"Authorization": authn.HeaderTokenPrefixRemoteAuth + jwt,
},
HRef: c.urlProvider.GenerateGITCloneURL(ctx, repoRef) + "/info/lfs",
ExpiresIn: token.RemoteAuthTokenLifeTime,
}, 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/lfs/controller.go | app/api/controller/lfs/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 lfs
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/remoteauth"
"github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/blob"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
const (
lfsObjectsPathFormat = "lfs/%s"
)
type Controller struct {
authorizer authz.Authorizer
repoFinder refcache.RepoFinder
repoStore store.RepoStore
principalStore store.PrincipalStore
lfsStore store.LFSObjectStore
blobStore blob.Store
remoteAuth remoteauth.Service
urlProvider url.Provider
settings *settings.Service
}
func NewController(
authorizer authz.Authorizer,
repoFinder refcache.RepoFinder,
repoStore store.RepoStore,
principalStore store.PrincipalStore,
lfsStore store.LFSObjectStore,
blobStore blob.Store,
remoteAuth remoteauth.Service,
urlProvider url.Provider,
settings *settings.Service,
) *Controller {
return &Controller{
authorizer: authorizer,
repoFinder: repoFinder,
repoStore: repoStore,
principalStore: principalStore,
lfsStore: lfsStore,
blobStore: blobStore,
remoteAuth: remoteAuth,
urlProvider: urlProvider,
settings: settings,
}
}
func (c *Controller) getRepoCheckAccessAndSetting(
ctx context.Context,
session *auth.Session,
repoRef string,
reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState,
) (*types.RepositoryCore, error) {
if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.")
}
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repository: %w", 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)
}
gitLFSEnabled, err := settings.RepoGet(
ctx,
c.settings,
repo.ID,
settings.KeyGitLFSEnabled,
settings.DefaultGitLFSEnabled,
)
if err != nil {
return nil, fmt.Errorf("failed to check settings for Git LFS enabled: %w", err)
}
if !gitLFSEnabled {
return nil, usererror.ErrGitLFSDisabled
}
return repo, nil
}
func getLFSObjectPath(oid string) string {
return fmt.Sprintf(lfsObjectsPathFormat, oid)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/lfs/upload.go | app/api/controller/lfs/upload.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 lfs
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type UploadOut struct {
ObjectPath string `json:"object_path"`
}
func (c *Controller) Upload(ctx context.Context,
session *auth.Session,
repoRef string,
pointer Pointer,
file io.Reader,
) (*UploadOut, error) {
var additionalAllowedRepoStates = []enum.RepoState{enum.RepoStateMigrateGitPush}
repoCore, err := c.getRepoCheckAccessAndSetting(ctx, session, repoRef,
enum.PermissionRepoPush, additionalAllowedRepoStates...)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
if file == nil {
return nil, usererror.BadRequest("No file or content provided")
}
_, err = c.lfsStore.Find(ctx, repoCore.ID, pointer.OId)
if err != nil && !errors.Is(err, store.ErrResourceNotFound) {
return nil, fmt.Errorf("failed to check if object exists: %w", err)
}
if err == nil {
return nil, usererror.Conflict("LFS object already exists and cannot be modified")
}
limitedReader := io.LimitReader(file, pointer.Size)
content, err := io.ReadAll(limitedReader)
if err != nil {
return nil, fmt.Errorf("failed to read uploaded content: %w", err)
}
hasher := sha256.New()
hasher.Write(content)
calculatedHash := hex.EncodeToString(hasher.Sum(nil))
expectedHash := strings.TrimPrefix(pointer.OId, "sha256:")
if calculatedHash != expectedHash {
return nil, usererror.BadRequest("content hash doesn't match provided OID")
}
contentReader := bytes.NewReader(content)
objPath := getLFSObjectPath(pointer.OId)
err = c.blobStore.Upload(ctx, contentReader, objPath)
if err != nil {
return nil, fmt.Errorf("failed to upload file: %w", err)
}
now := time.Now()
object := &types.LFSObject{
OID: pointer.OId,
Size: pointer.Size,
Created: now.UnixMilli(),
CreatedBy: session.Principal.ID,
RepoID: repoCore.ID,
}
// create the object in lfs store after successful upload to the blob store.
err = c.lfsStore.Create(ctx, object)
if err != nil && !errors.Is(err, store.ErrDuplicate) {
return nil, fmt.Errorf("failed to create object: %w", err)
}
return &UploadOut{
ObjectPath: objPath,
}, 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/lfs/download.go | app/api/controller/lfs/download.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 lfs
import (
"context"
"fmt"
"io"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types/enum"
)
type Content struct {
Data io.ReadCloser
Size int64
}
func (c *Content) Read(p []byte) (n int, err error) {
return c.Data.Read(p)
}
func (c *Content) Close() error {
return c.Data.Close()
}
func (c *Controller) Download(ctx context.Context,
session *auth.Session,
repoRef string,
oid string,
) (*Content, error) {
repo, err := c.getRepoCheckAccessAndSetting(ctx, session, repoRef, enum.PermissionRepoView)
if err != nil {
return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
}
return c.DownloadNoAuth(ctx, repo.ID, oid)
}
func (c *Controller) DownloadNoAuth(
ctx context.Context,
repoID int64,
oid string,
) (*Content, error) {
obj, err := c.lfsStore.Find(ctx, repoID, oid)
if err != nil {
return nil, fmt.Errorf("failed to find the oid %q for the repo: %w", oid, err)
}
objPath := getLFSObjectPath(oid)
file, err := c.blobStore.Download(ctx, objPath)
if err != nil {
return nil, fmt.Errorf("failed to download file from blobstore: %w", err)
}
return &Content{
Data: file,
Size: obj.Size,
}, 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/keywordsearch/wire.go | app/api/controller/keywordsearch/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 keywordsearch
import (
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/api/controller/space"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/keywordsearch"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideController,
)
func ProvideController(
authorizer authz.Authorizer,
searcher keywordsearch.Searcher,
repoCtrl *repo.Controller,
spaceCtrl *space.Controller,
) *Controller {
return NewController(authorizer, searcher, repoCtrl, spaceCtrl)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/keywordsearch/search.go | app/api/controller/keywordsearch/search.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 keywordsearch
import (
"context"
"fmt"
"maps"
"math"
"github.com/harness/gitness/app/api/usererror"
"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) Search(
ctx context.Context,
session *auth.Session,
in types.SearchInput,
) (types.SearchResult, error) {
if in.Query == "" {
return types.SearchResult{}, usererror.BadRequest("Query cannot be empty.")
}
if len(in.RepoPaths) == 0 && len(in.SpacePaths) == 0 {
return types.SearchResult{}, usererror.BadRequest(
"either repo paths or space paths need to be set.")
}
repoIDToPathMap, err := c.getReposByPath(ctx, session, in.RepoPaths)
if err != nil {
return types.SearchResult{}, fmt.Errorf("failed to search repos by path: %w", err)
}
spaceRepoIDToPathMap, err := c.getReposBySpacePaths(ctx, session, in.SpacePaths, in.Recursive)
if err != nil {
return types.SearchResult{}, fmt.Errorf("failed to search repos by space path: %w", err)
}
maps.Copy(repoIDToPathMap, spaceRepoIDToPathMap)
if len(repoIDToPathMap) == 0 {
return types.SearchResult{}, usererror.NotFound("No repositories found")
}
repoIDs := make([]int64, 0, len(repoIDToPathMap))
for repoID := range repoIDToPathMap {
repoIDs = append(repoIDs, repoID)
}
result, err := c.searcher.Search(ctx, repoIDs, in.Query, in.EnableRegex, in.MaxResultCount)
if err != nil {
return types.SearchResult{}, fmt.Errorf("failed to search: %w", err)
}
for idx, fileMatch := range result.FileMatches {
repoPath, ok := repoIDToPathMap[fileMatch.RepoID]
if !ok {
log.Ctx(ctx).Warn().Msgf("repo path not found for repo ID %d, repo mapping: %v",
fileMatch.RepoID, repoIDToPathMap)
continue
}
result.FileMatches[idx].RepoPath = repoPath
}
return result, nil
}
// getReposByPath returns a list of repo IDs that the user has access to for input repo paths.
func (c *Controller) getReposByPath(
ctx context.Context,
session *auth.Session,
repoPaths []string,
) (map[int64]string, error) {
repoIDToPathMap := make(map[int64]string)
if len(repoPaths) == 0 {
return repoIDToPathMap, nil
}
for _, repoPath := range repoPaths {
if repoPath == "" {
continue
}
repo, err := c.repoCtrl.Find(ctx, session, repoPath)
if err != nil {
return nil, fmt.Errorf("failed to find repository: %w", err)
}
repoIDToPathMap[repo.ID] = repoPath
}
return repoIDToPathMap, nil
}
func (c *Controller) getReposBySpacePaths(
ctx context.Context,
session *auth.Session,
spacePaths []string,
recursive bool,
) (map[int64]string, error) {
repoIDToPathMap := make(map[int64]string)
for _, spacePath := range spacePaths {
m, err := c.getReposBySpacePath(ctx, session, spacePath, recursive)
if err != nil {
return nil, fmt.Errorf("failed to search repos by space path: %w", err)
}
maps.Copy(repoIDToPathMap, m)
}
return repoIDToPathMap, nil
}
func (c *Controller) getReposBySpacePath(
ctx context.Context,
session *auth.Session,
spacePath string,
recursive bool,
) (map[int64]string, error) {
repoIDToPathMap := make(map[int64]string)
if spacePath == "" {
return repoIDToPathMap, nil
}
filter := &types.RepoFilter{
Page: 1,
Size: int(math.MaxInt),
Query: "",
Order: enum.OrderAsc,
Sort: enum.RepoAttrNone,
Recursive: recursive,
}
repos, _, err := c.spaceCtrl.ListRepositories(ctx, session, spacePath, filter)
if err != nil {
return nil, fmt.Errorf("failed to list space repositories: %w", err)
}
for _, repo := range repos {
repoIDToPathMap[repo.ID] = repo.Path
}
return repoIDToPathMap, 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/keywordsearch/controller.go | app/api/controller/keywordsearch/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 keywordsearch
import (
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/api/controller/space"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/keywordsearch"
)
type Controller struct {
authorizer authz.Authorizer
repoCtrl *repo.Controller
searcher keywordsearch.Searcher
spaceCtrl *space.Controller
}
func NewController(
authorizer authz.Authorizer,
searcher keywordsearch.Searcher,
repoCtrl *repo.Controller,
spaceCtrl *space.Controller,
) *Controller {
return &Controller{
authorizer: authorizer,
searcher: searcher,
repoCtrl: repoCtrl,
spaceCtrl: spaceCtrl,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pipeline/wire.go | app/api/controller/pipeline/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 pipeline
import (
"github.com/harness/gitness/app/auth/authz"
events "github.com/harness/gitness/app/events/pipeline"
"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(
triggerStore store.TriggerStore,
authorizer authz.Authorizer,
pipelineStore store.PipelineStore,
reporter *events.Reporter,
repoFinder refcache.RepoFinder,
) *Controller {
return NewController(
authorizer,
triggerStore,
pipelineStore,
*reporter,
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/pipeline/create.go | app/api/controller/pipeline/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 pipeline
import (
"context"
"fmt"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth"
events "github.com/harness/gitness/app/events/pipeline"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
var (
// errPipelineRequiresConfigPath is returned if the user tries to create a pipeline with an empty config path.
errPipelineRequiresConfigPath = usererror.BadRequest(
"Pipeline requires a config path.")
)
type CreateInput struct {
Description string `json:"description"`
// TODO [CODE-1363]: remove after identifier migration.
UID string `json:"uid" deprecated:"true"`
Identifier string `json:"identifier"`
Disabled bool `json:"disabled"`
DefaultBranch string `json:"default_branch"`
ConfigPath string `json:"config_path"`
}
func (c *Controller) Create(
ctx context.Context,
session *auth.Session,
repoRef string,
in *CreateInput,
) (*types.Pipeline, error) {
if err := c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, "", enum.PermissionPipelineEdit)
if err != nil {
return nil, err
}
var pipeline *types.Pipeline
now := time.Now().UnixMilli()
pipeline = &types.Pipeline{
Description: in.Description,
RepoID: repo.ID,
Identifier: in.Identifier,
Disabled: in.Disabled,
CreatedBy: session.Principal.ID,
Seq: 0,
DefaultBranch: in.DefaultBranch,
ConfigPath: in.ConfigPath,
Created: now,
Updated: now,
Version: 0,
}
err = c.pipelineStore.Create(ctx, pipeline)
if err != nil {
return nil, fmt.Errorf("pipeline creation failed: %w", err)
}
// Try to create a default trigger on pipeline creation.
// Default trigger operations are set on pull request created, reopened or updated.
// We log an error on failure but don't fail the op.
trigger := &types.Trigger{
Description: "auto-created trigger on pipeline creation",
Created: now,
Updated: now,
PipelineID: pipeline.ID,
RepoID: pipeline.RepoID,
CreatedBy: session.Principal.ID,
Identifier: "default",
Actions: []enum.TriggerAction{enum.TriggerActionPullReqCreated,
enum.TriggerActionPullReqReopened, enum.TriggerActionPullReqBranchUpdated},
Disabled: false,
Version: 0,
}
err = c.triggerStore.Create(ctx, trigger)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to create auto trigger on pipeline creation")
}
// send pipeline create event
c.reporter.Created(ctx, &events.CreatedPayload{PipelineID: pipeline.ID, RepoID: pipeline.RepoID})
return pipeline, nil
}
func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
// TODO [CODE-1363]: remove after identifier migration.
if in.Identifier == "" {
in.Identifier = in.UID
}
if err := check.Identifier(in.Identifier); err != nil {
return err
}
in.Description = strings.TrimSpace(in.Description)
if err := check.Description(in.Description); err != nil {
return err
}
if in.DefaultBranch == "" {
in.DefaultBranch = c.defaultBranch
}
if in.ConfigPath == "" {
return errPipelineRequiresConfigPath
}
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/pipeline/delete.go | app/api/controller/pipeline/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 pipeline
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,
identifier string,
) error {
repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, identifier, enum.PermissionPipelineDelete)
if err != nil {
return err
}
err = c.pipelineStore.DeleteByIdentifier(ctx, repo.ID, identifier)
if err != nil {
return fmt.Errorf("could not delete pipeline: %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/pipeline/find.go | app/api/controller/pipeline/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 pipeline
import (
"context"
"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,
identifier string,
) (*types.Pipeline, error) {
repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, identifier, enum.PermissionPipelineView)
if err != nil {
return nil, err
}
return c.pipelineStore.FindByIdentifier(ctx, repo.ID, 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/pipeline/controller.go | app/api/controller/pipeline/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 pipeline
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
events "github.com/harness/gitness/app/events/pipeline"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type Controller struct {
defaultBranch string
triggerStore store.TriggerStore
authorizer authz.Authorizer
pipelineStore store.PipelineStore
reporter events.Reporter
repoFinder refcache.RepoFinder
}
func NewController(
authorizer authz.Authorizer,
triggerStore store.TriggerStore,
pipelineStore store.PipelineStore,
reporter events.Reporter,
repoFinder refcache.RepoFinder,
) *Controller {
return &Controller{
repoFinder: repoFinder,
triggerStore: triggerStore,
authorizer: authorizer,
pipelineStore: pipelineStore,
reporter: reporter,
}
}
// getRepoCheckPipelineAccess fetches a repo, checks if operation is allowed given the repo state
// and checks if the current user has permission to access pipelines of the repo.
//
//nolint:unparam
func (c *Controller) getRepoCheckPipelineAccess(
ctx context.Context,
session *auth.Session,
repoRef string,
pipelineIdentifier string,
reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState,
) (*types.RepositoryCore, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ref: %w", err)
}
if err := apiauth.CheckRepoState(ctx, session, repo, reqPermission, allowedRepoStates...); err != nil {
return nil, err
}
err = apiauth.CheckPipeline(ctx, c.authorizer, session, repo.Path,
pipelineIdentifier, reqPermission)
if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err)
}
return repo, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/controller/pipeline/update.go | app/api/controller/pipeline/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 pipeline
import (
"context"
"fmt"
"strings"
"github.com/harness/gitness/app/auth"
events "github.com/harness/gitness/app/events/pipeline"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/check"
"github.com/harness/gitness/types/enum"
)
type UpdateInput struct {
// TODO [CODE-1363]: remove after identifier migration.
UID *string `json:"uid" deprecated:"true"`
Identifier *string `json:"identifier"`
Description *string `json:"description"`
Disabled *bool `json:"disabled"`
ConfigPath *string `json:"config_path"`
}
func (c *Controller) Update(
ctx context.Context,
session *auth.Session,
repoRef string,
identifier string,
in *UpdateInput,
) (*types.Pipeline, error) {
repo, err := c.getRepoCheckPipelineAccess(ctx, session, repoRef, identifier, enum.PermissionPipelineEdit)
if err != nil {
return nil, err
}
if err = c.sanitizeUpdateInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err)
}
pipeline, err := c.pipelineStore.FindByIdentifier(ctx, repo.ID, identifier)
if err != nil {
return nil, fmt.Errorf("failed to find pipeline: %w", err)
}
updated, err := c.pipelineStore.UpdateOptLock(ctx, pipeline, func(pipeline *types.Pipeline) error {
if in.Identifier != nil {
pipeline.Identifier = *in.Identifier
}
if in.Description != nil {
pipeline.Description = *in.Description
}
if in.ConfigPath != nil {
pipeline.ConfigPath = *in.ConfigPath
}
if in.Disabled != nil {
pipeline.Disabled = *in.Disabled
}
return nil
})
// send pipeline update event
c.reporter.Updated(ctx, &events.UpdatedPayload{PipelineID: pipeline.ID, RepoID: pipeline.RepoID})
return updated, err
}
func (c *Controller) sanitizeUpdateInput(in *UpdateInput) error {
// TODO [CODE-1363]: remove after identifier migration.
if in.Identifier == nil {
in.Identifier = in.UID
}
if in.Identifier != nil {
if err := check.Identifier(*in.Identifier); err != nil {
return err
}
}
if in.Description != nil {
*in.Description = strings.TrimSpace(*in.Description)
if err := check.Description(*in.Description); err != nil {
return err
}
}
if in.ConfigPath != nil {
if *in.ConfigPath == "" {
return errPipelineRequiresConfigPath
}
}
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/auth/registry.go | app/api/auth/registry.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
)
// CheckRegistry checks if a registry specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckRegistry(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
permissionChecks ...types.PermissionCheck,
) error {
return CheckAll(ctx, authorizer, session, permissionChecks...)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/service.go | app/api/auth/service.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckService checks if a service specific permission is granted for the current auth session.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckService(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
svc *types.Service, permission enum.Permission,
) error {
// a service exists outside any scope
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeService,
Identifier: svc.UID,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/space.go | app/api/auth/space.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 auth
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckSpace checks if a space specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if permission is granted, otherwise returns NotAuthenticated, NotAuthorized, or the underlying error.
func CheckSpace(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
space *types.SpaceCore,
permission enum.Permission,
) error {
parentSpace, name, err := paths.DisectLeaf(space.Path)
if err != nil {
return fmt.Errorf("failed to disect path '%s': %w", space.Path, err)
}
scope := &types.Scope{SpacePath: parentSpace}
resource := &types.Resource{
Type: enum.ResourceTypeSpace,
Identifier: name,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
// CheckSpaceScope checks if a specific permission is granted for the current auth session
// in the scope of the provided space.
// Returns nil if permission is granted, otherwise returns NotAuthenticated, NotAuthorized, or the underlying error.
func CheckSpaceScope(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
space *types.SpaceCore,
resourceType enum.ResourceType,
permission enum.Permission,
) error {
scope := &types.Scope{SpacePath: space.Path}
resource := &types.Resource{
Type: resourceType,
Identifier: "",
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/repo.go | app/api/auth/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 auth
import (
"context"
"fmt"
"slices"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckRepo checks if a repo specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckRepo(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
repo *types.RepositoryCore,
permission enum.Permission,
) error {
parentSpace, name, err := paths.DisectLeaf(repo.Path)
if err != nil {
return fmt.Errorf("failed to disect path '%s': %w", repo.Path, err)
}
scope := &types.Scope{SpacePath: parentSpace}
resource := &types.Resource{
Type: enum.ResourceTypeRepo,
Identifier: name,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
func IsRepoOwner(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
repo *types.RepositoryCore,
) (bool, error) {
// for now we use repoedit as permission to verify if someone is a SpaceOwner and hence a RepoOwner.
err := CheckRepo(ctx, authorizer, session, repo, enum.PermissionRepoEdit)
if err != nil && !IsNoAccess(err) {
return false, fmt.Errorf("failed to check access user access: %w", err)
}
return err == nil, nil
}
// CheckRepoState checks if requested permission is allowed given the state of the repository.
func CheckRepoState(
_ context.Context,
_ *auth.Session,
repo *types.RepositoryCore,
reqPermission enum.Permission,
additionalAllowedRepoStates ...enum.RepoState,
) error {
permissionsAllowedPerRepoState := map[enum.RepoState][]enum.Permission{
enum.RepoStateActive: {
enum.PermissionRepoView,
enum.PermissionRepoCreate,
enum.PermissionRepoEdit,
enum.PermissionRepoPush,
enum.PermissionRepoReview,
enum.PermissionRepoDelete,
enum.PermissionRepoReportCommitCheck,
enum.PermissionPipelineView,
enum.PermissionPipelineExecute,
enum.PermissionPipelineEdit,
enum.PermissionPipelineDelete,
enum.PermissionServiceAccountView,
},
enum.RepoStateArchived: {
enum.PermissionRepoView,
enum.PermissionPipelineView,
enum.PermissionServiceAccountView,
},
// allowed permissions for repos on transition states during import/migration are handled by their controller.
enum.RepoStateGitImport: {},
enum.RepoStateMigrateDataImport: {},
enum.RepoStateMigrateGitPush: {},
}
if len(additionalAllowedRepoStates) > 0 && slices.Contains(additionalAllowedRepoStates, repo.State) {
return nil
}
defaultAllowedPermissions := permissionsAllowedPerRepoState[repo.State]
if !slices.Contains(defaultAllowedPermissions, reqPermission) {
return errors.PreconditionFailedf("Operation is not allowed for repository in state %s", repo.State)
}
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/auth/secret.go | app/api/auth/secret.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckSecret checks if a repo specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckSecret(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
parentPath, identifier string, permission enum.Permission) error {
scope := &types.Scope{SpacePath: parentPath}
resource := &types.Resource{
Type: enum.ResourceTypeSecret,
Identifier: identifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/auth.go | app/api/auth/auth.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 auth
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
var (
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
ErrParentResourceTypeUnknown = errors.New("Unknown parent resource type")
ErrPrincipalTypeUnknown = errors.New("Unknown principal type")
)
// Check checks if a resource specific permission is granted for the current auth session in the scope.
// Returns nil if the permission is granted, otherwise returns an error.
func Check(
ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
scope *types.Scope, resource *types.Resource, permission enum.Permission,
) error {
authenticated, err := authorizer.Check(
ctx,
session,
scope,
resource,
permission,
)
if err != nil {
return err
}
return CheckSessionAuth(session, authenticated)
}
// CheckAll checks if multiple resources specific permission is granted for the current auth session in the scope.
// Returns nil if the permission is granted, otherwise returns an error.
func CheckAll(
ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
permissionChecks ...types.PermissionCheck,
) error {
hasPermission, err := authorizer.CheckAll(
ctx,
session,
permissionChecks...,
)
if err != nil {
return err
}
return CheckSessionAuth(session, hasPermission)
}
// CheckSessionAuth returns nil if the user is authenticated.
// Otherwise, ir returns err unauthorized on anonymous or err forbidden on non anonymous session.
func CheckSessionAuth(session *auth.Session, authenticated bool) error {
if !authenticated {
if auth.IsAnonymousSession(session) {
return ErrUnauthorized
}
return ErrForbidden
}
return nil
}
// IsNoAccess returns true if the error is ErrUnauthorized or ErrForbidden.
func IsNoAccess(err error) bool {
return errors.Is(err, ErrForbidden) || errors.Is(err, ErrUnauthorized)
}
// CheckChild checks if a resource specific permission is granted for the current auth session
// in the scope of a parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckChild(
ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
spaceStore store.SpaceStore, repoStore store.RepoStore, parentType enum.ParentResourceType, parentID int64,
resourceType enum.ResourceType, resourceName string, permission enum.Permission,
) error {
scope, err := getScopeForParent(ctx, spaceStore, repoStore, parentType, parentID)
if err != nil {
return err
}
resource := &types.Resource{
Type: resourceType,
Identifier: resourceName,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
// getScopeForParent Returns the scope for a given resource parent (space or repo).
func getScopeForParent(
ctx context.Context, spaceStore store.SpaceStore, repoStore store.RepoStore,
parentType enum.ParentResourceType, parentID int64,
) (*types.Scope, error) {
// TODO: Can this be done cleaner?
switch parentType {
case enum.ParentResourceTypeSpace:
space, err := spaceStore.Find(ctx, parentID)
if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err)
}
return &types.Scope{SpacePath: space.Path}, nil
case enum.ParentResourceTypeRepo:
repo, err := repoStore.Find(ctx, parentID)
if err != nil {
return nil, fmt.Errorf("parent repo not found: %w", err)
}
spacePath, repoName, err := paths.DisectLeaf(repo.Path)
if err != nil {
return nil, fmt.Errorf("failed to disect path '%s': %w", repo.Path, err)
}
return &types.Scope{SpacePath: spacePath, Repo: repoName}, nil
default:
log.Ctx(ctx).Debug().Msgf("Unsupported parent type encountered: '%s'", parentType)
return nil, ErrParentResourceTypeUnknown
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/infraprovider.go | app/api/auth/infraprovider.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckInfraProvider checks if a gitspace specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckInfraProvider(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
parentPath,
identifier string,
permission enum.Permission,
) error {
scope := &types.Scope{SpacePath: parentPath}
resource := &types.Resource{
Type: enum.ResourceTypeInfraProvider,
Identifier: identifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/connector.go | app/api/auth/connector.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckConnector checks if a repo specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckConnector(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
parentPath,
identifier string,
permission enum.Permission,
) error {
scope := &types.Scope{SpacePath: parentPath}
resource := &types.Resource{
Type: enum.ResourceTypeConnector,
Identifier: identifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/gitspace.go | app/api/auth/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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckGitspace checks if a gitspace specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckGitspace(
ctx context.Context,
authorizer authz.Authorizer,
session *auth.Session,
parentPath,
identifier string,
permission enum.Permission,
) error {
scope := &types.Scope{SpacePath: parentPath}
resource := &types.Resource{
Type: enum.ResourceTypeGitspace,
Identifier: identifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/user.go | app/api/auth/user.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckUser checks if a user specific permission is granted for the current auth session.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckUser(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
user *types.User, permission enum.Permission,
) error {
// a user exists outside any scope
scope := &types.Scope{}
resource := &types.Resource{
Type: enum.ResourceTypeUser,
Identifier: user.UID,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/template.go | app/api/auth/template.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckTemplate checks if a repo specific permission is granted for the current auth session
// in the scope of its parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckTemplate(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
parentPath, identifier string, permission enum.Permission) error {
scope := &types.Scope{SpacePath: parentPath}
resource := &types.Resource{
Type: enum.ResourceTypeTemplate,
Identifier: identifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/pipeline.go | app/api/auth/pipeline.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 auth
import (
"context"
"fmt"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// CheckPipeline checks if a pipeline specific permission is granted for the current auth session
// in the scope of the parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckPipeline(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
repoPath string, pipelineIdentifier string, permission enum.Permission) error {
spacePath, repoName, err := paths.DisectLeaf(repoPath)
if err != nil {
return fmt.Errorf("failed to disect path '%s': %w", repoPath, err)
}
scope := &types.Scope{SpacePath: spacePath, Repo: repoName}
resource := &types.Resource{
Type: enum.ResourceTypePipeline,
Identifier: pipelineIdentifier,
}
return Check(ctx, authorizer, session, scope, resource, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/auth/service_account.go | app/api/auth/service_account.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 auth
import (
"context"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types/enum"
)
// CheckServiceAccount checks if a service account specific permission is granted for the current auth session
// in the scope of the parent.
// Returns nil if the permission is granted, otherwise returns an error.
// NotAuthenticated, NotAuthorized, or any underlying error.
func CheckServiceAccount(ctx context.Context, authorizer authz.Authorizer, session *auth.Session,
spaceStore store.SpaceStore, repoStore store.RepoStore, parentType enum.ParentResourceType, parentID int64,
saUID string, permission enum.Permission,
) error {
return CheckChild(ctx, authorizer, session,
spaceStore, repoStore, parentType, parentID,
enum.ResourceTypeServiceAccount, saUID, permission)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/address/address_test.go | app/api/middleware/address/address_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 address
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/address/address.go | app/api/middleware/address/address.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 address
import (
"net/http"
"strings"
)
// Handler returns an http.HandlerFunc middleware that sets
// the http.Request scheme and hostname.
func Handler(scheme, host string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// update the scheme and host for the inbound
// http.Request so they are available to subsequent
// handlers in the chain.
r.URL.Scheme = scheme
r.URL.Host = host
// if the scheme is not configured, attempt to ascertain
// the scheme from the inbound http.Request.
if r.URL.Scheme == "" {
r.URL.Scheme = resolveScheme(r)
}
// if the host is not configured, attempt to ascertain
// the host from the inbound http.Request.
if r.URL.Host == "" {
r.URL.Host = resolveHost(r)
}
// invoke the next handler in the chain.
next.ServeHTTP(w, r)
})
}
}
// resolveScheme is a helper function that evaluates the http.Request
// and returns the scheme, HTTP or HTTPS. It is able to detect,
// using the X-Forwarded-Proto, if the original request was HTTPS
// and routed through a reverse proxy with SSL termination.
func resolveScheme(r *http.Request) string {
const https = "https"
switch {
case r.URL.Scheme == https:
return https
case r.TLS != nil:
return https
case strings.HasPrefix(r.Proto, "HTTPS"):
return https
case r.Header.Get("X-Forwarded-Proto") == https:
return https
default:
return "http"
}
}
// resolveHost is a helper function that evaluates the http.Request
// and returns the hostname. It is able to detect, using the
// X-Forarded-For header, the original hostname when routed
// through a reverse proxy.
func resolveHost(r *http.Request) string {
switch {
case len(r.Host) != 0:
return r.Host
case len(r.URL.Host) != 0:
return r.URL.Host
case len(r.Header.Get("X-Forwarded-For")) != 0:
return r.Header.Get("X-Forwarded-For")
case len(r.Header.Get("X-Host")) != 0:
return r.Header.Get("X-Host")
case len(r.Header.Get("XFF")) != 0:
return r.Header.Get("XFF")
case len(r.Header.Get("X-Real-IP")) != 0:
return r.Header.Get("X-Real-IP")
default:
return "localhost:3000"
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/logging/logging.go | app/api/middleware/logging/logging.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 logging
import (
"net/http"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/git"
"github.com/harness/gitness/logging"
"github.com/rs/xid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
const (
requestIDHeader = "X-Request-Id"
)
// HLogRequestIDHandler provides a middleware that injects request_id into the logging and execution context.
// It prefers the X-Request-Id header, if that doesn't exist it creates a new request id similar to zerolog.
func HLogRequestIDHandler() func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// read requestID from header (or create new one if none exists)
var reqID string
if reqIDs, ok := r.Header[requestIDHeader]; ok && len(reqIDs) > 0 && len(reqIDs[0]) > 0 {
reqID = reqIDs[0]
} else {
// similar to zerolog requestID generation
reqID = xid.New().String()
}
// add requestID to context for internal usage client!
ctx = request.WithRequestID(ctx, reqID)
ctx = git.WithRequestID(ctx, reqID)
// update logging context with request ID
logging.UpdateContext(ctx, logging.WithRequestID(reqID))
// write request ID to response headers
w.Header().Set(requestIDHeader, reqID)
// continue serving request
h.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// HLogAccessLogHandler provides an hlog based middleware that logs access logs.
func HLogAccessLogHandler() func(http.Handler) http.Handler {
return hlog.AccessHandler(
func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).Info().
Int("http.status_code", status).
Int("http.response_size_bytes", size).
Dur("http.elapsed_ms", duration).
Msg("http request completed.")
},
)
}
func URLHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
if r.URL.RawPath != "" {
return c.Str(fieldKey, r.URL.RawPath+"?"+r.URL.RawQuery)
}
return c.Str(fieldKey, r.URL.Path+"?"+r.URL.RawQuery)
})
next.ServeHTTP(w, r)
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/authz/authz.go | app/api/middleware/authz/authz.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 authz
import (
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
// BlockSessionToken blocks any request that uses a session token for authentication.
// NOTE: Major use case as of now is blocking usage of session tokens with git.
func BlockSessionToken(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// only block if auth data was available and it's based on a session token.
if session, oks := request.AuthSessionFrom(ctx); oks {
if tokenMetadata, ok := session.Metadata.(*auth.TokenMetadata); ok &&
tokenMetadata.TokenType == enum.TokenTypeSession {
log.Ctx(ctx).Warn().Msg("blocking git operation - session tokens are not allowed for usage with git")
// NOTE: Git doesn't print the error message, so just return default 401 Unauthorized.
render.Unauthorized(ctx, w)
return
}
}
next.ServeHTTP(w, r)
},
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/goget/goget.go | app/api/middleware/goget/goget.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 goget
import (
"errors"
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/store"
"github.com/rs/zerolog/log"
)
var (
goGetTmpl *template.Template
httpRegex = regexp.MustCompile("https?://")
)
func init() {
var err error
goGetTmpl, err = template.New("goget").Parse(`<!doctype html>
<html>
<head>
<meta name="go-import" content="{{.GoImport}}">
<meta name="go-source" content="{{.GoSource}}">
</head>
<body>
{{.GoCLI}}
</body>
</html>`)
if err != nil {
panic(err)
}
}
// Middleware writes to response with html meta tags go-import and go-source.
//
//nolint:gocognit
func Middleware(
maxRepoPathDepth int,
repoCtrl *repo.Controller,
urlProvider url.Provider,
) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Query().Get("go-get") != "1" {
next.ServeHTTP(w, r)
return
}
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
importPath, err := request.GetRepoRefFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
// go get can also be used with (sub)module suffixes (e.g 127.0.0.1/my-project/my-repo/v2)
// for which go expects us to return the import path corresponding to the repository root
// (e.g. 127.0.0.1/my-project/my-repo).
//
// WARNING: This can lead to ambiguities as we allow matching paths between spaces and repos:
// 1. (space)foo + (repo)bar + (sufix)v2 = 127.0.0.1/my-project/my-repo/v2
// 2. (space)foo/bar + (repo)v2 = 127.0.0.1/my-project/my-repo/v2
//
// We handle ambiguities by always choosing the repo with the longest path (e.g. 2. case above).
// To solve go get related ambiguities users would have to move their repositories.
var repository *repo.RepositoryOutput
var repoRef string
pathSegments := paths.Segments(importPath)
if len(pathSegments) > maxRepoPathDepth {
pathSegments = pathSegments[:maxRepoPathDepth]
}
for l := len(pathSegments); l >= 2; l-- {
repoRef = paths.Concatenate(pathSegments[:l]...)
repository, err = repoCtrl.Find(ctx, session, repoRef)
if err == nil {
break
}
if errors.Is(err, store.ErrResourceNotFound) {
log.Ctx(ctx).Debug().Err(err).
Msgf("repository %q doesn't exist, assume submodule and try again", repoRef)
continue
}
if errors.Is(err, auth.ErrForbidden) {
// To avoid leaking information about repos' existence we continue as if it wasn't found.
// WARNING: This can lead to different import results depending on access (very unlikely)
log.Ctx(ctx).Debug().Err(err).
Msgf("user has no access on repository %q, assume submodule and try again", repoRef)
continue
}
render.TranslatedUserError(ctx, w, fmt.Errorf("failed to find repo for path %q: %w", repoRef, err))
return
}
if repository == nil {
render.NotFound(ctx, w)
return
}
uiRepoURL := urlProvider.GenerateUIRepoURL(ctx, repoRef)
cloneURL := urlProvider.GenerateGITCloneURL(ctx, repoRef)
goImportURL := httpRegex.ReplaceAllString(cloneURL, "")
goImportURL = strings.TrimSuffix(goImportURL, ".git")
prefix := fmt.Sprintf("%s/files/%s/~", uiRepoURL, repository.DefaultBranch)
insecure := ""
if strings.HasPrefix(uiRepoURL, "http:") {
insecure = "--insecure"
}
goImportContent := fmt.Sprintf("%s git %s", goImportURL, cloneURL)
goSourceContent := fmt.Sprintf("%s _ %s %s", goImportURL, prefix+"{/dir}", prefix+"{/dir}/{file}#L{line}")
goGetCliContent := fmt.Sprintf("go get %s %s", insecure, goImportURL)
err = goGetTmpl.Execute(w, struct {
GoImport string
GoSource string
GoCLI string
}{
GoImport: goImportContent,
GoSource: goSourceContent,
GoCLI: goGetCliContent,
})
if err != nil {
render.TranslatedUserError(ctx, w, err)
}
},
)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/principal/principal.go | app/api/middleware/principal/principal.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 principal
import (
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
)
// RestrictTo returns an http.HandlerFunc middleware that ensures the principal
// is of the provided type. In case there is no authenticated principal,
// or the principal type doesn't match, an error is rendered.
func RestrictTo(pType enum.PrincipalType) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
p, ok := request.PrincipalFrom(ctx)
if !ok {
log.Ctx(ctx).Debug().Msg("Failed to get principal from session")
render.Forbidden(ctx, w)
return
}
if p.IsAnonymous() {
log.Ctx(ctx).Debug().Msg("Valid principal is required, received an Anonymous.")
render.Unauthorized(ctx, w)
return
}
if p.Type != pType {
log.Ctx(ctx).Debug().Msgf("Principal of type '%s' required.", pType)
render.Forbidden(ctx, w)
return
}
next.ServeHTTP(w, r)
})
}
}
// RestrictToAdmin returns an http.HandlerFunc middleware that ensures the principal
// is an admin. In case there is no authenticated principal,
// or the principal isn't an admin, an error is rendered.
func RestrictToAdmin() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
p, ok := request.PrincipalFrom(ctx)
if !ok || !p.Admin {
log.Ctx(ctx).Debug().Msg("No principal found or the principal is no admin")
render.Forbidden(ctx, w)
return
}
next.ServeHTTP(w, r)
})
}
}
func GitHookRestrict() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
const userErrorMessage = "Internal error"
p, ok := request.PrincipalFrom(ctx)
if !ok {
log.Ctx(ctx).Error().Msg("Unauthenticated call to git hook")
render.JSON(w, http.StatusOK, &hook.Output{
Error: ptr.String(userErrorMessage),
})
return
}
if p.IsAnonymous() {
log.Ctx(ctx).Error().Msg("Valid principal is required for git hooks, received an Anonymous.")
render.JSON(w, http.StatusOK, &hook.Output{
Error: ptr.String(userErrorMessage),
})
return
}
if p.Type != enum.PrincipalTypeService {
log.Ctx(ctx).Error().
Str("principal.type", string(p.Type)).
Msgf("Principal of type %q required for git hooks.", enum.PrincipalTypeService)
render.JSON(w, http.StatusOK, &hook.Output{
Error: ptr.String(userErrorMessage),
})
return
}
next.ServeHTTP(w, r)
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/authn/authn.go | app/api/middleware/authn/authn.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 authn
import (
"errors"
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/auth/authn"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
// Attempt returns an http.HandlerFunc middleware that authenticates
// the http.Request if authentication payload is available.
// Otherwise, an anonymous user session is used instead.
func Attempt(authenticator authn.Authenticator) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := hlog.FromRequest(r)
session, err := authenticator.Authenticate(r)
if err != nil && !errors.Is(err, authn.ErrNoAuthData) {
log.Warn().Err(err).Msg("authentication failed")
render.Unauthorized(ctx, w)
return
}
if errors.Is(err, authn.ErrNoAuthData) {
log.Info().Msg("No authentication data found, continue as anonymous")
session = &auth.Session{
Principal: auth.AnonymousPrincipal,
}
}
// Update the logging context and inject principal in context
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.
Str("principal_uid", session.Principal.UID).
Str("principal_type", string(session.Principal.Type)).
Bool("principal_admin", session.Principal.Admin)
})
next.ServeHTTP(w, r.WithContext(
request.WithAuthSession(ctx, session),
))
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/nocache/nocache.go | app/api/middleware/nocache/nocache.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 nocache
import (
"net/http"
"time"
)
// Ported from Chi's middleware, source:
// https://github.com/go-chi/chi/blob/v5.0.12/middleware/nocache.go
// Modified the middleware to retain ETags.
var epoch = time.Unix(0, 0).Format(time.RFC1123)
var noCacheHeaders = map[string]string{
"Expires": epoch,
"Cache-Control": "no-cache, no-store, no-transform, must-revalidate, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
// NoCache is same as chi's default NoCache middleware except it doesn't remove etag headers.
func NoCache(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Set our NoCache headers
for k, v := range noCacheHeaders {
w.Header().Set(k, v)
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/nocache/nocache_test.go | app/api/middleware/nocache/nocache_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 nocache
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestNoCache(t *testing.T) {
tests := []struct {
name string
handler http.Handler
expectedStatus int
checkHeaders bool
}{
{
name: "sets no-cache headers",
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("test response"))
}),
expectedStatus: http.StatusOK,
checkHeaders: true,
},
{
name: "preserves handler status code",
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}),
expectedStatus: http.StatusNotFound,
checkHeaders: true,
},
{
name: "works with empty handler",
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Empty handler
}),
expectedStatus: http.StatusOK,
checkHeaders: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a test request
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
// Wrap handler with NoCache middleware
middleware := NoCache(tt.handler)
middleware.ServeHTTP(rec, req)
// Check status code
if rec.Code != tt.expectedStatus {
t.Errorf("expected status %d, got %d", tt.expectedStatus, rec.Code)
}
// Check no-cache headers
if tt.checkHeaders {
expectedHeaders := map[string]string{
"Expires": time.Unix(0, 0).Format(time.RFC1123),
"Cache-Control": "no-cache, no-store, no-transform, must-revalidate, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
for key, expectedValue := range expectedHeaders {
actualValue := rec.Header().Get(key)
if actualValue != expectedValue {
t.Errorf("header %s: expected %q, got %q", key, expectedValue, actualValue)
}
}
}
})
}
}
func TestNoCachePreservesETag(t *testing.T) {
// Create a handler that sets an ETag
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", `"test-etag-123"`)
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
// Wrap with NoCache middleware
middleware := NoCache(handler)
middleware.ServeHTTP(rec, req)
// Verify ETag is preserved
etag := rec.Header().Get("ETag")
if etag != `"test-etag-123"` {
t.Errorf("expected ETag to be preserved, got %q", etag)
}
// Verify no-cache headers are still set
cacheControl := rec.Header().Get("Cache-Control")
if cacheControl != "no-cache, no-store, no-transform, must-revalidate, private, max-age=0" {
t.Errorf("expected Cache-Control header to be set, got %q", cacheControl)
}
}
func TestNoCacheWithMultipleRequests(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("response"))
})
middleware := NoCache(handler)
// Make multiple requests to ensure middleware is reusable
for i := range 3 {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
middleware.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("request %d: expected status 200, got %d", i, rec.Code)
}
expires := rec.Header().Get("Expires")
if expires == "" {
t.Errorf("request %d: Expires header not set", i)
}
}
}
func TestNoCacheHeaderValues(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
middleware := NoCache(handler)
middleware.ServeHTTP(rec, req)
// Verify epoch format
expectedEpoch := time.Unix(0, 0).Format(time.RFC1123)
if rec.Header().Get("Expires") != expectedEpoch {
t.Errorf("Expires header should be epoch time in RFC1123 format")
}
// Verify all required directives in Cache-Control
cacheControl := rec.Header().Get("Cache-Control")
requiredDirectives := []string{"no-cache", "no-store", "no-transform", "must-revalidate", "private", "max-age=0"}
for _, directive := range requiredDirectives {
if !contains(cacheControl, directive) {
t.Errorf("Cache-Control missing directive: %s", directive)
}
}
}
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/web/public_access.go | app/api/middleware/web/public_access.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"errors"
"net/http"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/web"
"github.com/rs/zerolog/hlog"
)
// PublicAccess enables rendering of the UI in public access mode if
// public access is enabled in the configuration and the request contains no logged-in user.
func PublicAccess(
publicAccessEnabled bool,
authenticator authn.Authenticator,
) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
if !publicAccessEnabled {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// slightly more expensive to authenticate the user, but we can't make assumptions about the authenticator.
_, err := authenticator.Authenticate(r)
if errors.Is(err, authn.ErrNoAuthData) {
r = r.WithContext(web.WithRenderPublicAccess(r.Context(), true))
} else if err != nil {
// in case of failure to authenticate the user treat it as attempt to login
hlog.FromRequest(r).Warn().Err(err).Msgf(
"failed to authenticate principal, continue without public access UI",
)
}
next.ServeHTTP(w, r)
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/encode/encode.go | app/api/middleware/encode/encode.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 encode
import (
"net/http"
"regexp"
"strings"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/request"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/hlog"
"golang.org/x/exp/slices"
)
const (
EncodedPathSeparator = "%2F"
)
// GitPathBefore wraps an http.HandlerFunc in a layer that encodes a path coming
// as part of the GIT api (e.g. "space1/repo.git") before executing the provided http.HandlerFunc.
func GitPathBefore(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ok, err := pathTerminatedWithMarker(r, "", ".git", "")
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
if !ok {
if _, err = processGitRequest(r); err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
}
next.ServeHTTP(w, r)
},
)
}
func processGitRequest(r *http.Request) (bool, error) {
const infoRefsPath = "/info/refs"
const uploadPack = "git-upload-pack"
const uploadPackPath = "/" + uploadPack
const receivePack = "git-receive-pack"
const receivePackPath = "/" + receivePack
const serviceParam = "service"
const lfsTransferPath = "/info/lfs/objects"
const lfsTransferBatchPath = lfsTransferPath + "/batch"
const oidParam = "oid"
const sizeParam = "size"
allowedServices := []string{
uploadPack,
receivePack,
}
urlPath := r.URL.Path
if r.URL.RawPath != "" {
urlPath = r.URL.RawPath
}
switch r.Method {
case http.MethodGet:
// check if request is coming from git client
if strings.HasSuffix(urlPath, infoRefsPath) && r.URL.Query().Has(serviceParam) {
service := r.URL.Query().Get(serviceParam)
if !slices.Contains(allowedServices, service) {
return false, errors.InvalidArgumentf("git request allows only %v service, got: %s",
allowedServices, service)
}
return pathTerminatedWithMarkerAndURL(r, "", infoRefsPath, infoRefsPath, urlPath)
}
// check if request is coming from git lfs client
if strings.HasSuffix(urlPath, lfsTransferPath) && r.URL.Query().Has(oidParam) {
return pathTerminatedWithMarkerAndURL(r, "", lfsTransferPath, lfsTransferPath, urlPath)
}
case http.MethodPost:
if strings.HasSuffix(urlPath, uploadPackPath) {
return pathTerminatedWithMarkerAndURL(r, "", uploadPackPath, uploadPackPath, urlPath)
}
if strings.HasSuffix(urlPath, receivePackPath) {
return pathTerminatedWithMarkerAndURL(r, "", receivePackPath, receivePackPath, urlPath)
}
if strings.HasSuffix(urlPath, lfsTransferBatchPath) {
return pathTerminatedWithMarkerAndURL(r, "", lfsTransferBatchPath, lfsTransferBatchPath, urlPath)
}
case http.MethodPut:
if strings.HasSuffix(urlPath, lfsTransferPath) &&
r.URL.Query().Has(oidParam) && r.URL.Query().Has(sizeParam) {
return pathTerminatedWithMarkerAndURL(r, "", lfsTransferPath, lfsTransferPath, urlPath)
}
}
// no other APIs are called by git - just treat it as a full repo path.
return pathTerminatedWithMarkerAndURL(r, "", "", "", urlPath)
}
// TerminatedPathBefore wraps an http.HandlerFunc in a layer that encodes a terminated path (e.g. "/space1/space2/+")
// before executing the provided http.HandlerFunc. The first prefix that matches the URL.Path will
// be used during encoding (prefix is ignored during encoding).
func TerminatedPathBefore(prefixes []string, next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
for _, p := range prefixes {
changed, err := pathTerminatedWithMarker(r, p, "/+", "")
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
// first prefix that leads to success we can stop
if changed {
break
}
}
next.ServeHTTP(w, r)
},
)
}
// TerminatedRegexPathBefore is similar to TerminatedPathBefore but supports regex prefixes.
func TerminatedRegexPathBefore(regexPrefixes []string, next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
for _, p := range regexPrefixes {
changed, err := regexPathTerminatedWithMarker(r, p, "/+", "")
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
// first prefix that leads to success we can stop
if changed {
break
}
}
next.ServeHTTP(w, r)
},
)
}
// pathTerminatedWithMarker function encodes a path followed by a custom marker and returns a request with an
// updated URL.Path.
// A non-empty prefix can be provided to encode only after the prefix.
// It allows our Rest API to handle paths of the form "/spaces/space1/space2/+/authToken"
//
// Examples:
// Prefix: "" Path: "/space1/space2/+" => "/space1%2Fspace2"
// Prefix: "" Path: "/space1/.gitness.git" => "/space1%2F.gitness"
// Prefix: "/spaces" Path: "/spaces/space1/space2/+/authToken" => "/spaces/space1%2Fspace2/authToken".
func pathTerminatedWithMarker(r *http.Request, prefix string, marker string, markerReplacement string) (bool, error) {
// r.URL.Path contains URL-decoded URI path. r.URL.RawPath contains raw URI path. But, if the URI don't contain
// any character that needs encoding, the r.URL.RawPath is empty (otherwise it would be equal to r.URL.Path).
// We work with r.URL.RawPath it is exist, or with r.URL.Path if the r.URL.RawPath is empty.
urlPath := r.URL.Path
if r.URL.RawPath != "" {
urlPath = r.URL.RawPath
}
return pathTerminatedWithMarkerAndURL(r, prefix, marker, markerReplacement, urlPath)
}
func pathTerminatedWithMarkerAndURL(
r *http.Request, prefix string, marker string, markerReplacement string, urlPath string,
) (bool, error) {
// In case path doesn't start with prefix - nothing to encode
if len(urlPath) < len(prefix) || urlPath[0:len(prefix)] != prefix {
return false, nil
}
originalSubPath := urlPath[len(prefix):]
path, found := cutOutTerminatedPath(originalSubPath, marker)
if !found {
// If we don't find a marker - nothing to encode
return false, nil
}
// if marker was found - convert to escaped version (skip first character in case path starts with '/').
escapedPath := path[0:1] + strings.ReplaceAll(path[1:], types.PathSeparatorAsString, EncodedPathSeparator)
prefixWithPath := prefix + path + marker
prefixWithEscapedPath := prefix + escapedPath + markerReplacement
hlog.FromRequest(r).Trace().Msgf(
"[Encode] prefix: '%s', marker: '%s', original: '%s', escaped: '%s'.\n",
prefix,
marker,
prefixWithPath,
prefixWithEscapedPath,
)
err := request.ReplacePrefix(r, prefixWithPath, prefixWithEscapedPath)
if err != nil {
return false, err
}
return true, nil
}
// regexPathTerminatedWithMarker is similar to pathTerminatedWithMarker but with regex prefix support.
//
// Example:
// 1. Path: "/registry/app1%2Fremote2/artifact/foo/bar/+/summary"
// Prefix: => "^/registry/([^/]+)/artifact/" Marker: => "/+" MarkerReplacement: => ""
// ==> "/registry/app1%2Fremote2/artifact/foo%2Fbar/summary"
//
// 2. Path: "/registry/abc/artifact/foo/bar/+/summary"
// Prefix: => "^/registry/([^/]+)/artifact/" Marker: => "/+" MarkerReplacement: => ""
// ==> "/registry/abc/artifact/foo%2Fbar/summary"
func regexPathTerminatedWithMarker(
r *http.Request,
regexPrefix string,
marker string,
markerReplacement string,
) (bool, error) {
prefixPattern := regexp.MustCompile(regexPrefix)
matches := prefixPattern.FindStringSubmatch(r.URL.Path)
// In case path doesn't start with prefix - nothing to encode
if len(matches) == 0 {
return false, nil
}
// We only care about the first match as we provide prefix
prefix := matches[0]
urlPath := r.URL.Path
if r.URL.RawPath != "" {
urlPath = r.URL.RawPath
}
return pathTerminatedWithMarkerAndURL(r, prefix, marker, markerReplacement, urlPath)
}
// cutOutTerminatedPath cuts out the resource path terminated with the provided marker (path segment suffix).
// e.g. subPath: "/space1/space2/+/authToken", marker: "/+" => "/space1/space2"
// e.g. subPath: "/space1/space2.git", marker: ".git" => "/space1/space2"
// e.g. subPath: "/space1/space2.git/", marker: ".git" => "/space1/space2".
// For a subPath, the marker can be at 3 locations:
// case 1: xxxxxxxxxxxxxxxxxxM/xxxxxx (M is the marker and it should have a / after it to terminate)
// case 2: xxxxxxxxxxxxxxxxxxxxxxxxM/ (M is at the end and it should have a / after it)
// case 3: xxxxxxxxxxxxxxxxxxxxxxxxxM (M is at the end).
func cutOutTerminatedPath(subPath string, marker string) (string, bool) {
// base case of marker being empty
if marker == "" {
return subPath, true
}
endsWithSlash := strings.HasSuffix(marker, "/")
if !endsWithSlash {
marker += "/"
}
// case 1 and case 2
if path, _, found := strings.Cut(subPath, marker); found {
return path, true
}
if endsWithSlash {
return "", false
}
trimmedMarker := strings.TrimSuffix(marker, "/")
if strings.HasSuffix(subPath, trimmedMarker) {
subPath = subPath[:len(subPath)-len(trimmedMarker)]
return subPath, true
}
return "", false
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/middleware/encode/encode_test.go | app/api/middleware/encode/encode_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 encode
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTerminatedPathBefore(t *testing.T) {
tests := []struct {
name string
prefixes []string
path string
expectedPath string
expectedStatus int
}{
{
name: "basic terminated path",
prefixes: []string{"/spaces"},
path: "/spaces/space1/space2/+/authToken",
expectedPath: "/spaces/space1%2Fspace2/authToken",
expectedStatus: http.StatusOK,
},
{
name: "no matching prefix",
prefixes: []string{"/other"},
path: "/spaces/space1/space2/+/authToken",
expectedPath: "/spaces/space1/space2/+/authToken",
expectedStatus: http.StatusOK,
},
{
name: "multiple prefixes - first match",
prefixes: []string{"/spaces", "/repos"},
path: "/spaces/space1/space2/+/authToken",
expectedPath: "/spaces/space1%2Fspace2/authToken",
expectedStatus: http.StatusOK,
},
{
name: "encoded paths - no match",
prefixes: []string{"/spaces", "/repos"},
path: "/spaces/space1%2Fspace2/authToken",
expectedPath: "/spaces/space1%2Fspace2/authToken",
expectedStatus: http.StatusOK,
},
{
name: "encoded paths - suffix match 1",
prefixes: []string{"/spaces", "/repos"},
path: "/spaces/space1/space2/+/",
expectedPath: "/spaces/space1%2Fspace2/",
expectedStatus: http.StatusOK,
},
{
name: "encoded paths - suffix match 2",
prefixes: []string{"/spaces", "/repos"},
path: "/spaces/space1/space2/+",
expectedPath: "/spaces/space1%2Fspace2",
expectedStatus: http.StatusOK,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := &http.Request{
Method: http.MethodGet,
URL: &url.URL{
Path: tt.path,
RawPath: tt.path,
},
}
rr := httptest.NewRecorder()
handler := TerminatedPathBefore(tt.prefixes, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
assert.Equal(t, tt.expectedPath, r.URL.RawPath)
}))
handler.ServeHTTP(rr, req)
assert.Equal(t, tt.expectedStatus, rr.Code)
})
}
}
func TestCutOutTerminatedPath(t *testing.T) {
tests := []struct {
name string
subPath string
marker string
expectedPath string
expectedFound bool
}{
{
name: "basic path with marker",
subPath: "/space1/space2/+/authToken",
marker: "/+",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "git suffix",
subPath: "/space1/space2.git",
marker: ".git",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "git suffix with trailing slash",
subPath: "/space1/space2.git/",
marker: ".git",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "multiple markers 1",
subPath: "/foo/bar/+/artifact/myartifact/+",
marker: "/+",
expectedPath: "/foo/bar",
expectedFound: true,
},
{
name: "multiple markers 2",
subPath: "/foo/bar/+/artifact/myartifact/+/",
marker: "/+",
expectedPath: "/foo/bar",
expectedFound: true,
},
{
name: "mixed markers 1",
subPath: "/foo/bar/+artifact/myartifact/+",
marker: "/+",
expectedPath: "/foo/bar/+artifact/myartifact",
expectedFound: true,
},
{
name: "mixed markers 2",
subPath: "/foo/bar/repo.git/myfile1/myfile2/.gitignore",
marker: ".git",
expectedPath: "/foo/bar/repo",
expectedFound: true,
},
{
name: "mixed markers 3",
subPath: "/foo/bar/+artifact/myartifact",
marker: "/+",
expectedPath: "",
expectedFound: false,
},
{
name: "no marker found",
subPath: "/space1/space2",
marker: "/+",
expectedPath: "",
expectedFound: false,
},
{
name: "path with non-slash marker as suffix",
subPath: "/space1/space2/repo.git",
marker: ".git",
expectedPath: "/space1/space2/repo",
expectedFound: true,
},
{
name: "path with non-slash marker as suffix with slash",
subPath: "/space1/space2/repo.git/",
marker: ".git",
expectedPath: "/space1/space2/repo",
expectedFound: true,
},
{
name: "path with non-slash marker in the middle",
subPath: "/space1/space2/repo.git/authToken",
marker: ".git",
expectedPath: "/space1/space2/repo",
expectedFound: true,
},
{
name: "path with multiple non-slash markers",
subPath: "/space1/space2/repo.git/authToken.git",
marker: ".git",
expectedPath: "/space1/space2/repo",
expectedFound: true,
},
{
name: "path with slash marker as suffix",
subPath: "/space1/space2/+",
marker: "/+",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "path with slash marker as suffix with slash",
subPath: "/space1/space2/+/",
marker: "/+",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "path with slash marker as suffix with without slash",
subPath: "/space1/space2/+",
marker: "/+/",
expectedPath: "",
expectedFound: false,
},
{
name: "path with slash marker in the middle",
subPath: "/space1/space2/+/authToken",
marker: "/+",
expectedPath: "/space1/space2",
expectedFound: true,
},
{
name: "path with slash marker in the middle without trailing slash",
subPath: "/space1/space2/+authToken",
marker: "/+",
expectedPath: "",
expectedFound: false,
},
{
name: "encoded path with no marker",
subPath: "/spaces/space1%2Fspace2/authToken",
marker: "/+",
expectedPath: "",
expectedFound: false,
},
{
name: "path with exact length 1",
subPath: "/+/",
marker: "/+",
expectedPath: "",
expectedFound: true,
},
{
name: "path with exact length 2",
subPath: "/+",
marker: "/+",
expectedPath: "",
expectedFound: true,
},
{
name: "empty marker",
subPath: "/foo/bar",
marker: "",
expectedPath: "/foo/bar",
expectedFound: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path, found := cutOutTerminatedPath(tt.subPath, tt.marker)
assert.Equal(t, tt.expectedPath, path)
assert.Equal(t, tt.expectedFound, found)
})
}
}
func TestRegexPathTerminatedWithMarker(t *testing.T) {
tests := []struct {
name string
path string
regexPrefix string
marker string
expectedPath string
expectedStatus int
}{
{
name: "registry artifact path",
path: "/registry/app1%2Fremote2/artifact/foo/bar/+/summary",
regexPrefix: "^/registry/([^/]+)/artifact/",
marker: "/+",
expectedPath: "/registry/app1%2Fremote2/artifact/foo%2Fbar/summary",
expectedStatus: http.StatusOK,
},
{
name: "no regex match",
path: "/other/path/foo/bar/+/summary",
regexPrefix: "^/registry/([^/]+)/artifact/",
marker: "/+",
expectedPath: "/other/path/foo/bar/+/summary",
expectedStatus: http.StatusOK,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := &http.Request{
Method: http.MethodGet,
URL: &url.URL{
Path: tt.path,
RawPath: tt.path,
},
}
rr := httptest.NewRecorder()
handler := TerminatedRegexPathBefore([]string{tt.regexPrefix},
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
assert.Equal(t, tt.expectedPath, r.URL.RawPath)
}))
handler.ServeHTTP(rr, req)
assert.Equal(t, tt.expectedStatus, rr.Code)
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/render_test.go | app/api/render/render_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 render
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/git"
)
func TestWriteErrorf(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
e := usererror.New(500, "abc")
UserError(ctx, w, e)
if got, want := w.Code, 500; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, e.Message; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteErrorCode(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
UserError(ctx, w, usererror.Newf(418, "pc load letter %d", 1))
if got, want := w.Code, 418; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, "pc load letter 1"; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteNotFound(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
NotFound(ctx, w)
if got, want := w.Code, 404; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, usererror.ErrNotFound.Message; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteUnauthorized(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
Unauthorized(ctx, w)
if got, want := w.Code, 401; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, usererror.ErrUnauthorized.Message; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteForbidden(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
Forbidden(ctx, w)
if got, want := w.Code, 403; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, usererror.ErrForbidden.Message; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteBadRequest(t *testing.T) {
ctx := context.TODO()
w := httptest.NewRecorder()
BadRequest(ctx, w)
if got, want := w.Code, 400; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
errjson := &usererror.Error{}
if err := json.NewDecoder(w.Body).Decode(errjson); err != nil {
t.Error(err)
}
if got, want := errjson.Message, usererror.ErrBadRequest.Message; got != want {
t.Errorf("Want error message %s, got %s", want, got)
}
}
func TestWriteJSON(t *testing.T) {
// without indent
{
w := httptest.NewRecorder()
JSON(w, http.StatusTeapot, map[string]string{"hello": "world"})
if got, want := w.Body.String(), "{\"hello\":\"world\"}\n"; got != want {
t.Errorf("Want JSON body %q, got %q", want, got)
}
if got, want := w.Header().Get("Content-Type"), "application/json; charset=utf-8"; got != want {
t.Errorf("Want Content-Type %q, got %q", want, got)
}
if got, want := w.Code, http.StatusTeapot; got != want {
t.Errorf("Want status code %d, got %d", want, got)
}
}
// with indent
{
indent = true
defer func() {
indent = false
}()
w := httptest.NewRecorder()
JSON(w, http.StatusTeapot, map[string]string{"hello": "world"})
if got, want := w.Body.String(), "{\n \"hello\": \"world\"\n}\n"; got != want {
t.Errorf("Want JSON body %q, got %q", want, got)
}
}
}
func TestJSONArrayDynamic(t *testing.T) {
noctx := context.Background()
type mock struct {
ID int `json:"id"`
}
type args[T comparable] struct {
ctx context.Context
f func(ch chan<- *mock, cherr chan<- error)
}
type testCase[T comparable] struct {
name string
args args[T]
len int
wantErr bool
}
tests := []testCase[*mock]{
{
name: "happy path",
args: args[*mock]{
ctx: noctx,
f: func(ch chan<- *mock, _ chan<- error) {
defer close(ch)
ch <- &mock{ID: 1}
},
},
len: 1,
wantErr: false,
},
{
name: "empty array response",
args: args[*mock]{
ctx: noctx,
f: func(ch chan<- *mock, _ chan<- error) {
close(ch)
},
},
len: 0,
wantErr: false,
},
{
name: "error at beginning of the stream",
args: args[*mock]{
ctx: noctx,
f: func(ch chan<- *mock, cherr chan<- error) {
defer close(ch)
defer close(cherr)
cherr <- errors.New("error writing to the response writer")
},
},
len: 0,
wantErr: true,
},
{
name: "error while streaming",
args: args[*mock]{
ctx: noctx,
f: func(ch chan<- *mock, cherr chan<- error) {
defer close(ch)
defer close(cherr)
ch <- &mock{ID: 1}
ch <- &mock{ID: 2}
cherr <- errors.New("error writing to the response writer")
},
},
len: 2,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ch := make(chan *mock)
cherr := make(chan error, 1)
stream := git.NewStreamReader(ch, cherr)
go func() {
tt.args.f(ch, cherr)
}()
w := httptest.NewRecorder()
JSONArrayDynamic[*mock](tt.args.ctx, w, stream)
ct := w.Header().Get("Content-Type")
if ct != "application/json; charset=utf-8" {
t.Errorf("Content type should be application/json, got: %v", ct)
return
}
if tt.wantErr {
if w.Code != 500 {
t.Errorf("stream error code should be 500, got: %v", w.Code)
}
return
}
var m []mock
err := json.NewDecoder(w.Body).Decode(&m)
if err != nil {
t.Errorf("error should be nil, got: %v", err)
return
}
if len(m) != tt.len {
t.Errorf("json array length should be %d, got: %v", tt.len, len(m))
return
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/sse.go | app/api/render/sse.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 render
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/sse"
"github.com/rs/zerolog/log"
)
func StreamSSE(
ctx context.Context,
w http.ResponseWriter,
chStop <-chan struct{},
chEvents <-chan *sse.Event,
chErr <-chan error,
) {
flusher, ok := w.(http.Flusher)
if !ok {
UserError(ctx, w, usererror.ErrResponseNotFlushable)
log.Ctx(ctx).Warn().Err(usererror.ErrResponseNotFlushable).Msg("Failed to build SSE stream")
return
}
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("X-Accel-Buffering", "no")
h.Set("Access-Control-Allow-Origin", "*")
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
stream := sseStream{
enc: enc,
writer: w,
flusher: flusher,
}
const (
pingInterval = 30 * time.Second
tailMaxTime = 2 * time.Hour
)
ctx, ctxCancel := context.WithTimeout(ctx, tailMaxTime)
defer ctxCancel()
if err := stream.ping(); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to send initial ping")
return
}
defer func() {
if err := stream.close(); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to close SSE stream")
}
}()
pingTimer := time.NewTimer(pingInterval)
defer pingTimer.Stop()
for {
select {
case <-ctx.Done():
log.Ctx(ctx).Debug().Err(ctx.Err()).Msg("stream SSE request context done")
return
case <-chStop:
log.Ctx(ctx).Debug().Msg("app shutdown")
return
case err := <-chErr:
log.Ctx(ctx).Debug().Err(err).Msg("received error from SSE stream")
return
case <-pingTimer.C:
if err := stream.ping(); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to send SSE ping")
return
}
case event, canProduce := <-chEvents:
if !canProduce {
log.Ctx(ctx).Debug().Msg("events channel is drained and closed.")
return
}
if err := stream.event(event); err != nil {
log.Ctx(ctx).Err(err).Msgf("failed to send SSE event: %s", event.Type)
return
}
}
pingTimer.Stop() // stop timer
select {
case <-pingTimer.C: // drain channel
default:
}
pingTimer.Reset(pingInterval) // reset timer
}
}
type sseStream struct {
enc *json.Encoder
writer io.Writer
flusher http.Flusher
}
func (r sseStream) event(event *sse.Event) error {
_, err := io.WriteString(r.writer, fmt.Sprintf("event: %s\n", event.Type))
if err != nil {
return fmt.Errorf("failed to send event header: %w", err)
}
_, err = io.WriteString(r.writer, "data: ")
if err != nil {
return fmt.Errorf("failed to send data header: %w", err)
}
err = r.enc.Encode(event.Data)
if err != nil {
return fmt.Errorf("failed to send data: %w", err)
}
// NOTE: enc.Encode is ending the data with a new line, only add one more
// Source: https://cs.opensource.google/go/go/+/refs/tags/go1.21.1:src/encoding/json/stream.go;l=220
_, err = r.writer.Write([]byte{'\n'})
if err != nil {
return fmt.Errorf("failed to send end of message: %w", err)
}
r.flusher.Flush()
return nil
}
func (r sseStream) close() error {
_, err := io.WriteString(r.writer, "event: error\ndata: eof\n\n")
if err != nil {
return fmt.Errorf("failed to send EOF: %w", err)
}
r.flusher.Flush()
return nil
}
func (r sseStream) ping() error {
_, err := io.WriteString(r.writer, ": ping\n\n")
if err != nil {
return fmt.Errorf("failed to send ping: %w", err)
}
r.flusher.Flush()
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/render/render.go | app/api/render/render.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 render
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/url"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
)
// indent the json-encoded API responses.
var indent bool
func init() {
indent, _ = strconv.ParseBool(
os.Getenv("HTTP_JSON_INDENT"),
)
}
// DeleteSuccessful writes the header for a successful delete.
func DeleteSuccessful(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
// JSON writes the json-encoded value to the response
// with the provides status.
func JSON(w http.ResponseWriter, code int, v any) {
setCommonHeaders(w)
w.WriteHeader(code)
writeJSON(w, v)
}
// Reader reads the content from the provided reader and writes it as is to the response body.
// NOTE: If no content-type header is added beforehand, the content-type will be deduced
// automatically by `http.DetectContentType` (https://pkg.go.dev/net/http#DetectContentType).
func Reader(ctx context.Context, w http.ResponseWriter, code int, reader io.Reader) {
w.WriteHeader(code)
_, err := io.Copy(w, reader)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to render data from reader")
}
}
// JSONArrayDynamic outputs an JSON array whose elements are streamed from a channel.
// Due to the dynamic nature (unknown number of elements) the function will use
// chunked transfer encoding for large files.
func JSONArrayDynamic[T comparable](ctx context.Context, w http.ResponseWriter, stream types.Stream[T]) {
count := 0
enc := json.NewEncoder(w)
for {
data, err := stream.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
// based on discussion unrelated histories error should return
// StatusOK on diff.
if uErr := api.AsUnrelatedHistoriesError(err); uErr != nil {
JSON(w, http.StatusOK, &usererror.Error{
Message: uErr.Error(),
Values: uErr.Map(),
})
return
}
// User canceled the request - no need to do anything
if errors.Is(err, context.Canceled) {
return
}
if count == 0 {
// Write the error only if no data has been streamed yet.
TranslatedUserError(ctx, w, err)
return
}
// Array data has been already streamed, it's too late for the output - so just log and quit.
log.Ctx(ctx).Warn().Err(err).Msgf("Failed to write JSON array response body")
// close array
_, _ = w.Write([]byte{']'})
return
}
if count == 0 {
setCommonHeaders(w)
_, _ = w.Write([]byte{'['})
} else {
_, _ = w.Write([]byte{','})
}
count++
_ = enc.Encode(data)
}
if count == 0 {
setCommonHeaders(w)
_, _ = w.Write([]byte{'['})
}
_, _ = w.Write([]byte{']'})
}
func Unprocessable(w http.ResponseWriter, v any) {
JSON(w, http.StatusUnprocessableEntity, v)
}
func Violations(w http.ResponseWriter, violations []types.RuleViolations) {
Unprocessable(w, types.RulesViolations{
Message: protection.GenerateErrorMessageForBlockingViolations(violations),
Violations: violations,
})
}
// GitBasicAuth renders a response that indicates that the client (GIT) requires basic authentication.
// This is required in order to tell git CLI to query user credentials.
func GitBasicAuth(ctx context.Context, w http.ResponseWriter, urlProvider url.Provider) {
// Git doesn't seem to handle "realm" - so it doesn't seem to matter for basic user CLI interactions.
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, urlProvider.GetAPIHostname(ctx)))
w.WriteHeader(http.StatusUnauthorized)
}
func setCommonHeaders(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
}
func writeJSON(w http.ResponseWriter, v any) {
enc := json.NewEncoder(w)
if indent {
enc.SetIndent("", " ")
}
if err := enc.Encode(v); err != nil {
log.Err(err).Msgf("Failed to write json encoding to response body.")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/util.go | app/api/render/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 render
// pagelen calculates to total number of pages given the
// page size and total count of all paginated items.
func pagelen(size, total int) int {
quotient, remainder := total/size, total%size
switch {
case quotient == 0:
return 1
case remainder == 0:
return quotient
default:
return quotient + 1
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/header.go | app/api/render/header.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 render
import (
"fmt"
"net/http"
"net/url"
"strconv"
)
// format string for the link header value.
var linkf = `<%s>; rel="%s"`
// Pagination writes the pagination and link headers to the http.Response.
func Pagination(r *http.Request, w http.ResponseWriter, page, size, total int) {
var (
last = pagelen(size, total)
)
// Add information that doesn't require total
PaginationNoTotal(r, w, page, size, page >= last)
// add information that requires total
uri := getPaginationBaseURL(r, page, size)
params := uri.Query()
// update the page query parameter and re-encode
params.Set("page", strconv.Itoa(last))
uri.RawQuery = params.Encode()
// write the page total to the header.
w.Header().Set("x-total", strconv.Itoa(total))
w.Header().Set("x-total-pages", strconv.Itoa(last))
w.Header().Add("Link", fmt.Sprintf(linkf, uri.String(), "last"))
}
// PaginationNoTotal writes the pagination and link headers to the http.Response when total is unknown.
func PaginationNoTotal(r *http.Request, w http.ResponseWriter, page int, size int, isLastPage bool) {
var (
next = page + 1
prev = max(page-1, 1)
)
// write basic headers
w.Header().Set("x-page", strconv.Itoa(page))
w.Header().Set("x-per-page", strconv.Itoa(size))
// write headers based on relative location of current page
uri := getPaginationBaseURL(r, page, size)
params := uri.Query()
if !isLastPage {
// update the page query parameter and re-encode
params.Set("page", strconv.Itoa(next))
uri.RawQuery = params.Encode()
// write the next page to the header.
w.Header().Set("x-next-page", strconv.Itoa(next))
w.Header().Add("Link", fmt.Sprintf(linkf, uri.String(), "next"))
}
if page > 1 {
// update the page query parameter and re-encode.
params.Set("page", strconv.Itoa(prev))
uri.RawQuery = params.Encode()
// write the previous page to the header.
w.Header().Set("x-prev-page", strconv.Itoa(prev))
w.Header().Add("Link", fmt.Sprintf(linkf, uri.String(), "prev"))
}
}
// PaginationLimit writes the x-total header.
func PaginationLimit(_ *http.Request, w http.ResponseWriter, total int) {
w.Header().Set("x-total", strconv.Itoa(total))
}
func getPaginationBaseURL(r *http.Request, page int, size int) url.URL {
uri := *r.URL
// parse the existing query parameters and
// sanize parameter list.
params := uri.Query()
params.Del("access_token")
params.Del("token")
params.Set("page", strconv.Itoa(page))
params.Set("limit", strconv.Itoa(size))
return uri
}
// NoCache writes the required headers to communicate to the client no caching shall be done.
func NoCache(w http.ResponseWriter) {
w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/header_test.go | app/api/render/header_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 render
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/render_error.go | app/api/render/render_error.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 render
import (
"context"
"net/http"
"github.com/harness/gitness/app/api/usererror"
"github.com/rs/zerolog/log"
)
// TranslatedUserError writes the translated user error of the provided error.
func TranslatedUserError(ctx context.Context, w http.ResponseWriter, err error) {
UserError(ctx, w, usererror.Translate(ctx, err))
}
// NotFound writes the json-encoded message for a not found error.
func NotFound(ctx context.Context, w http.ResponseWriter) {
UserError(ctx, w, usererror.ErrNotFound)
}
// Unauthorized writes the json-encoded message for an unauthorized error.
func Unauthorized(ctx context.Context, w http.ResponseWriter) {
UserError(ctx, w, usererror.ErrUnauthorized)
}
// Forbidden writes the json-encoded message for a forbidden error.
func Forbidden(ctx context.Context, w http.ResponseWriter) {
UserError(ctx, w, usererror.ErrForbidden)
}
// Forbiddenf writes the json-encoded message with a forbidden error.
func Forbiddenf(ctx context.Context, w http.ResponseWriter, format string, args ...any) {
UserError(ctx, w, usererror.Newf(http.StatusForbidden, format, args...))
}
// BadRequest writes the json-encoded message for a bad request error.
func BadRequest(ctx context.Context, w http.ResponseWriter) {
UserError(ctx, w, usererror.ErrBadRequest)
}
// BadRequestf writes the json-encoded message with a bad request status code.
func BadRequestf(ctx context.Context, w http.ResponseWriter, format string, args ...any) {
UserError(ctx, w, usererror.Newf(http.StatusBadRequest, format, args...))
}
// InternalError writes the json-encoded message for an internal error.
func InternalError(ctx context.Context, w http.ResponseWriter) {
UserError(ctx, w, usererror.ErrInternal)
}
// InternalErrorf writes the json-encoded message with internal server error status code.
func InternalErrorf(ctx context.Context, w http.ResponseWriter, format string, args ...any) {
UserError(ctx, w, usererror.Newf(http.StatusInternalServerError, format, args...))
}
// UserError writes the json-encoded user error.
func UserError(ctx context.Context, w http.ResponseWriter, err *usererror.Error) {
log.Ctx(ctx).Debug().Err(err).Msgf("operation resulted in user facing error")
JSON(w, err.Status, err)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/util_test.go | app/api/render/util_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 render
import "testing"
func Test_pagelen(t *testing.T) {
tests := []struct {
size, total, want int
}{
{25, 1, 1},
{25, 24, 1},
{25, 25, 1},
{25, 26, 2},
{25, 49, 2},
{25, 50, 2},
{25, 51, 3},
}
for _, test := range tests {
got, want := pagelen(test.size, test.total), test.want
if got != want {
t.Errorf("got page length %d, want %d", got, want)
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/render/platform/render.go | app/api/render/platform/render.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 platform
import (
"encoding/json"
"net/http"
"github.com/harness/gitness/app/api/render"
)
// RenderResource is a helper function that renders a single
// resource, wrapped in the harness payload envelope.
func RenderResource(w http.ResponseWriter, code int, v any) {
payload := new(wrapper)
payload.Status = "SUCCESS"
payload.Data, _ = json.Marshal(v)
if code >= http.StatusBadRequest {
payload.Status = "ERROR"
} else if code >= http.StatusMultipleChoices {
payload.Status = "FAILURE"
}
render.JSON(w, code, payload)
}
// wrapper defines the payload wrapper.
type wrapper struct {
Status string `json:"status"`
Data json.RawMessage `json:"data"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/usererror/usererror_test.go | app/api/usererror/usererror_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 usererror
import "testing"
func TestError(t *testing.T) {
got, want := ErrNotFound.Message, ErrNotFound.Message
if got != want {
t.Errorf("Want error string %q, got %q", got, want)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/usererror/translate.go | app/api/usererror/translate.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 usererror
import (
"context"
"net/http"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/controller/limiter"
"github.com/harness/gitness/app/services/codeowners"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/webhook"
"github.com/harness/gitness/blob"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/lock"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types/check"
"github.com/rs/zerolog/log"
)
func Translate(ctx context.Context, err error) *Error {
var (
rError *Error
checkError *check.ValidationError
appError *errors.Error
unrelatedHistoriesErr *api.UnrelatedHistoriesError
maxBytesErr *http.MaxBytesError
codeOwnersTooLargeError *codeowners.TooLargeError
codeOwnersFileParseError *codeowners.FileParseError
lockError *lock.Error
)
// print original error for debugging purposes
log.Ctx(ctx).Info().Err(err).Msgf("translating error to user facing error")
// TODO: Improve performance of checking multiple errors with errors.Is
switch {
// api errors
case errors.As(err, &rError):
return rError
// api auth errors
case errors.Is(err, apiauth.ErrForbidden):
return ErrForbidden
case errors.Is(err, apiauth.ErrUnauthorized):
return ErrUnauthorized
// validation errors
case errors.As(err, &checkError):
return New(http.StatusBadRequest, checkError.Error())
// store errors
case errors.Is(err, store.ErrResourceNotFound):
return ErrNotFound
case errors.Is(err, store.ErrDuplicate):
return ErrDuplicate
case errors.Is(err, store.ErrPrimaryPathCantBeDeleted):
return ErrPrimaryPathCantBeDeleted
case errors.Is(err, store.ErrPathTooLong):
return ErrPathTooLong
case errors.Is(err, store.ErrNoChangeInRequestedMove):
return ErrNoChange
case errors.Is(err, store.ErrIllegalMoveCyclicHierarchy):
return ErrCyclicHierarchy
case errors.Is(err, store.ErrSpaceWithChildsCantBeDeleted):
return ErrSpaceWithChildsCantBeDeleted
case errors.Is(err, limiter.ErrMaxNumReposReached):
return Forbidden(err.Error())
// upload errors
case errors.Is(err, blob.ErrNotFound):
return ErrNotFound
case errors.As(err, &maxBytesErr):
return RequestTooLargef("The request is too large. maximum allowed size is %d bytes", maxBytesErr.Limit)
case errors.Is(err, store.ErrLicenseExpired):
return BadRequestf("license expired.")
case errors.Is(err, store.ErrLicenseNotFound):
return BadRequestf("license not found.")
case errors.Is(err, ErrQuarantinedArtifact):
return ErrQuarantinedArtifact
// git errors
case errors.As(err, &appError):
if appError.Err != nil {
log.Ctx(ctx).Warn().Err(appError.Err).Msgf("Application error translation is omitting internal details.")
}
return NewWithPayload(
httpStatusCode(appError.Status),
appError.Message,
appError.Details,
)
case errors.As(err, &unrelatedHistoriesErr):
return NewWithPayload(
http.StatusBadRequest,
err.Error(),
unrelatedHistoriesErr.Map(),
)
// webhook errors
case errors.Is(err, webhook.ErrWebhookNotRetriggerable):
return ErrWebhookNotRetriggerable
// codeowners errors
case errors.Is(err, codeowners.ErrNotFound):
return ErrCodeOwnersNotFound
case errors.As(err, &codeOwnersTooLargeError):
return UnprocessableEntity(codeOwnersTooLargeError.Error())
case errors.As(err, &codeOwnersFileParseError):
return NewWithPayload(
http.StatusUnprocessableEntity,
codeOwnersFileParseError.Error(),
map[string]any{
"line_number": codeOwnersFileParseError.LineNumber,
"line": codeOwnersFileParseError.Line,
"err": codeOwnersFileParseError.Err.Error(),
},
)
// lock errors
case errors.As(err, &lockError):
return errorFromLockError(lockError)
// public access errors
case errors.Is(err, publicaccess.ErrPublicAccessNotAllowed):
return BadRequestf("Public access on resources is not allowed.")
// unknown error
default:
log.Ctx(ctx).Warn().Err(err).Msgf("Unable to translate error - returning Internal Error.")
return ErrInternal
}
}
// errorFromLockError returns the associated error for a given lock error.
func errorFromLockError(err *lock.Error) *Error {
if err.Kind == lock.ErrorKindCannotLock ||
err.Kind == lock.ErrorKindLockHeld ||
err.Kind == lock.ErrorKindMaxRetriesExceeded {
return ErrResourceLocked
}
return ErrInternal
}
// lookup of git error codes to HTTP status codes.
var codes = map[errors.Status]int{
errors.StatusConflict: http.StatusConflict,
errors.StatusInvalidArgument: http.StatusBadRequest,
errors.StatusNotFound: http.StatusNotFound,
errors.StatusNotImplemented: http.StatusNotImplemented,
errors.StatusPreconditionFailed: http.StatusPreconditionFailed,
errors.StatusUnauthorized: http.StatusUnauthorized,
errors.StatusForbidden: http.StatusForbidden,
errors.StatusInternal: http.StatusInternalServerError,
}
// httpStatusCode returns the associated HTTP status code for a git error code.
func httpStatusCode(code errors.Status) int {
if v, ok := codes[code]; ok {
return v
}
return http.StatusInternalServerError
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/usererror/usererror.go | app/api/usererror/usererror.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 usererror
import (
"fmt"
"maps"
"net/http"
)
var (
// ErrInternal is returned when an internal error occurred.
ErrInternal = New(http.StatusInternalServerError, "Internal error occurred")
// ErrInvalidToken is returned when the api request token is invalid.
ErrInvalidToken = New(http.StatusUnauthorized, "Invalid or missing token")
// ErrBadRequest is returned when there was an issue with the input.
ErrBadRequest = New(http.StatusBadRequest, "Bad Request")
// ErrUnauthorized is returned when the acting principal is not authenticated.
ErrUnauthorized = New(http.StatusUnauthorized, "Unauthorized")
// ErrForbidden is returned when the acting principal is not authorized.
ErrForbidden = New(http.StatusForbidden, "Forbidden")
// ErrNotFound is returned when a resource is not found.
ErrNotFound = New(http.StatusNotFound, "Not Found")
// ErrPreconditionFailed is returned when a precondition failed.
ErrPreconditionFailed = New(http.StatusPreconditionFailed, "Precondition failed")
// ErrNotMergeable is returned when a branch can't be merged.
ErrNotMergeable = New(http.StatusPreconditionFailed, "Branch can't be merged")
// ErrNoChange is returned when no change was found based on the request.
ErrNoChange = New(http.StatusBadRequest, "No Change")
// ErrDuplicate is returned when a resource already exits.
ErrDuplicate = New(http.StatusConflict, "Resource already exists")
// ErrPrimaryPathCantBeDeleted is returned when trying to delete a primary path.
ErrPrimaryPathCantBeDeleted = New(http.StatusBadRequest, "The primary path of an object can't be deleted")
// ErrPathTooLong is returned when an action would lead to a path that is too long.
ErrPathTooLong = New(http.StatusBadRequest, "The resource path is too long")
// ErrCyclicHierarchy is returned if the action would create a cyclic dependency between spaces.
ErrCyclicHierarchy = New(http.StatusBadRequest,
"Unable to perform the action as it would lead to a cyclic dependency")
// ErrSpaceWithChildsCantBeDeleted is returned if the principal is trying to delete a space that
// still has child resources.
ErrSpaceWithChildsCantBeDeleted = New(http.StatusBadRequest,
"Space can't be deleted as it still contains child resources")
// ErrDefaultBranchCantBeDeleted is returned if the user tries to delete the default branch of a repository.
ErrDefaultBranchCantBeDeleted = New(http.StatusBadRequest, "The default branch of a repository can't be deleted")
// ErrPullReqRefsCantBeModified is returned if a user tries to tinker with a pull request git ref.
ErrPullReqRefsCantBeModified = New(http.StatusBadRequest, "The pull request git refs can't be modified")
// ErrRequestTooLarge is returned if the request it too large.
ErrRequestTooLarge = New(http.StatusRequestEntityTooLarge, "The request is too large")
// ErrWebhookNotRetriggerable is returned if the webhook can't be retriggered.
ErrWebhookNotRetriggerable = New(http.StatusMethodNotAllowed,
"The webhook execution is incomplete and can't be retriggered")
// ErrCodeOwnersNotFound is returned when codeowners file is not found.
ErrCodeOwnersNotFound = New(http.StatusNotFound, "CODEOWNERS file not found")
// ErrResponseNotFlushable is returned if the response writer doesn't implement http.Flusher.
ErrResponseNotFlushable = New(http.StatusInternalServerError, "Response not streamable")
// ErrResourceLocked is returned if the resource is locked.
ErrResourceLocked = New(
http.StatusLocked,
"The requested resource is temporarily locked, please retry the operation.",
)
// ErrEmptyRepoNeedsBranch is returned if no branch found on the githook post receieve for empty repositories.
ErrEmptyRepoNeedsBranch = New(http.StatusBadRequest,
"Pushing to an empty repository requires at least one branch with commits.")
// ErrGitLFSDisabled is returned if the Git LFS is disabled but LFS endpoint is requested.
ErrGitLFSDisabled = New(http.StatusBadRequest, "Git LFS is disabled")
ErrQuarantinedArtifact = New(http.StatusForbidden, "Artifact is quarantined")
)
// Error represents a json-encoded API error.
type Error struct {
Status int `json:"-"`
Message string `json:"message"`
Values map[string]any `json:"values,omitempty"`
}
func (e *Error) Error() string {
return e.Message
}
// New returns a new user facing error.
func New(status int, message string) *Error {
return &Error{Status: status, Message: message}
}
// Newf returns a new user facing error.
func Newf(status int, format string, args ...any) *Error {
return &Error{Status: status, Message: fmt.Sprintf(format, args...)}
}
// NewWithPayload returns a new user facing error with payload.
func NewWithPayload(status int, message string, valueMaps ...map[string]any) *Error {
var values map[string]any
for _, valueMap := range valueMaps {
if values == nil {
values = valueMap
continue
}
maps.Copy(values, valueMap)
}
return &Error{Status: status, Message: message, Values: values}
}
// BadRequest returns a new user facing bad request error.
func BadRequest(message string) *Error {
return New(http.StatusBadRequest, message)
}
// BadRequestf returns a new user facing bad request error.
func BadRequestf(format string, args ...any) *Error {
return Newf(http.StatusBadRequest, format, args...)
}
// RequestTooLargef returns a new user facing request too large error.
func RequestTooLargef(format string, args ...any) *Error {
return Newf(http.StatusRequestEntityTooLarge, format, args...)
}
// UnprocessableEntity returns a new user facing unprocessable entity error.
func UnprocessableEntity(message string) *Error {
return New(http.StatusUnprocessableEntity, message)
}
// UnprocessableEntityf returns a new user facing unprocessable entity error.
func UnprocessableEntityf(format string, args ...any) *Error {
return Newf(http.StatusUnprocessableEntity, format, args...)
}
// BadRequestWithPayload returns a new user facing bad request error with payload.
func BadRequestWithPayload(message string, values ...map[string]any) *Error {
return NewWithPayload(http.StatusBadRequest, message, values...)
}
// Forbidden returns a new user facing forbidden error.
func Forbidden(message string) *Error {
return New(http.StatusForbidden, message)
}
func MethodNotAllowed(message string) *Error {
return New(http.StatusMethodNotAllowed, message)
}
// NotFound returns a new user facing not found error.
func NotFound(message string) *Error {
return New(http.StatusNotFound, message)
}
// NotFoundf returns a new user facing not found error.
func NotFoundf(format string, args ...any) *Error {
return Newf(http.StatusNotFound, format, args...)
}
// ConflictWithPayload returns a new user facing conflict error with payload.
func ConflictWithPayload(message string, values ...map[string]any) *Error {
return NewWithPayload(http.StatusConflict, message, values...)
}
// Conflict returns a new user facing conflict error.
func Conflict(message string) *Error {
return NewWithPayload(http.StatusConflict, message)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/logs/tail.go | app/api/handler/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.
//nolint:cyclop
package logs
import (
"context"
"encoding/json"
"io"
"net/http"
"time"
"github.com/harness/gitness/app/api/controller/logs"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/rs/zerolog/log"
)
var (
pingInterval = 30 * time.Second
tailMaxTime = 1 * time.Hour
)
// TODO: Move to controller and do error handling (see space events)
//
//nolint:gocognit,errcheck,cyclop // refactor if needed.
func HandleTail(logCtrl *logs.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
pipelineIdentifier, err := request.GetPipelineIdentifierFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
executionNum, err := request.GetExecutionNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
stageNum, err := request.GetStageNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
stepNum, err := request.GetStepNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
repoRef, err := request.GetRepoRefFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
f, ok := w.(http.Flusher)
if !ok {
log.Error().Msg("http writer type assertion failed")
render.InternalError(ctx, w)
return
}
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("X-Accel-Buffering", "no")
h.Set("Access-Control-Allow-Origin", "*")
io.WriteString(w, ": ping\n\n")
f.Flush()
linec, errc, err := logCtrl.Tail(
ctx, session, repoRef, pipelineIdentifier,
executionNum, int(stageNum), int(stepNum))
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
// could not get error channel
if errc == nil {
io.WriteString(w, "event: error\ndata: eof\n\n")
return
}
ctx, cancel := context.WithTimeout(r.Context(), tailMaxTime)
defer cancel()
enc := json.NewEncoder(w)
pingTimer := time.NewTimer(pingInterval)
defer pingTimer.Stop()
L:
for {
// ensure timer is stopped before resetting (see documentation)
if !pingTimer.Stop() {
// in this specific case the timer's channel could be both, empty or full
select {
case <-pingTimer.C:
default:
}
}
pingTimer.Reset(pingInterval)
select {
case <-ctx.Done():
break L
case err := <-errc:
log.Err(err).Msg("received error in the tail channel")
break L
case <-pingTimer.C:
// if time b/w messages takes longer, send a ping
io.WriteString(w, ": ping\n\n")
f.Flush()
case line := <-linec:
io.WriteString(w, "data: ")
enc.Encode(line)
io.WriteString(w, "\n\n")
f.Flush()
}
}
io.WriteString(w, "event: error\ndata: eof\n\n")
f.Flush()
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/logs/find.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/logs"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
//nolint:cyclop // this should move to controller
func HandleFind(logCtrl *logs.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
repoRef, err := request.GetRepoRefFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
pipelineIdentifier, err := request.GetPipelineIdentifierFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
executionNum, err := request.GetExecutionNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
stageNum, err := request.GetStageNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
stepNum, err := request.GetStepNumberFromPath(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
lines, err := logCtrl.Find(
ctx, session, repoRef, pipelineIdentifier,
executionNum, int(stageNum), int(stepNum))
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusOK, lines)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/system/health.go | app/api/handler/system/health.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 "net/http"
// HandleHealth writes a 200 OK status to the http.Response
// if the server is healthy.
func HandleHealth(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/system/health_test.go | app/api/handler/system/health_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 system
import "testing"
func TestHealth(t *testing.T) {
t.Skip()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/system/list_config.go | app/api/handler/system/list_config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package system
import (
"net/http"
"github.com/harness/gitness/app/api/controller/system"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/types"
)
type UI struct {
ShowPlugin bool `json:"show_plugin"`
}
type ConfigOutput struct {
UserSignupAllowed bool `json:"user_signup_allowed"`
PublicResourceCreationEnabled bool `json:"public_resource_creation_enabled"`
SSHEnabled bool `json:"ssh_enabled"`
GitspaceEnabled bool `json:"gitspace_enabled"`
ArtifactRegistryEnabled bool `json:"artifact_registry_enabled"`
UI UI `json:"ui"`
}
// HandleGetConfig returns an http.HandlerFunc that processes an http.Request
// and returns a struct containing all system configs exposed to the users.
func HandleGetConfig(config *types.Config, sysCtrl *system.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userSignupAllowed, err := sysCtrl.IsUserSignupAllowed(ctx)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusOK, ConfigOutput{
SSHEnabled: config.SSH.Enable,
UserSignupAllowed: userSignupAllowed,
PublicResourceCreationEnabled: config.PublicResourceCreationEnabled,
GitspaceEnabled: config.Gitspace.Enable,
ArtifactRegistryEnabled: config.Registry.Enable,
UI: UI{ShowPlugin: config.UI.ShowPlugin},
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/system/version_test.go | app/api/handler/system/version_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 system
import "testing"
func TestVersion(t *testing.T) {
t.Skip()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/system/version.go | app/api/handler/system/version.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 (
"fmt"
"net/http"
"github.com/harness/gitness/version"
)
// HandleVersion writes the server version number
// to the http.Response body in plain text.
func HandleVersion(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "%s", version.Version)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/plugin/list.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/plugin"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
func HandleList(pluginCtrl *plugin.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
filter := request.ParseListQueryFilterFromRequest(r)
ret, totalCount, err := pluginCtrl.List(ctx, filter)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.Pagination(r, w, filter.Page, filter.Size, int(totalCount))
render.JSON(w, http.StatusOK, ret)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/resource/resource.go | app/api/handler/resource/resource.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resource
import (
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/resources"
"github.com/rs/zerolog/log"
)
func HandleGitIgnores() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
files, err := resources.GitIgnores()
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to load gitignore files")
render.InternalError(ctx, w)
return
}
render.JSON(w, http.StatusOK, files)
}
}
func HandleLicences() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
response, err := resources.Licenses()
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to load license files")
render.InternalError(ctx, w)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(response)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/publickey_edit.go | app/api/handler/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 (
"encoding/json"
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
func HandleUpdatePublicKey(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
id, err := request.GetPublicKeyIdentifierFromPath(r)
if err != nil {
render.BadRequest(ctx, w)
return
}
in := new(user.UpdatePublicKeyInput)
err = json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequestf(ctx, w, "Invalid Request Body: %s.", err)
return
}
key, err := userCtrl.UpdatePublicKey(ctx, session, userUID, id, in)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusOK, key)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/publickey_list.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
func HandleListPublicKeys(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
filter, err := request.ParseListPublicKeyQueryFilterFromRequest(r)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
keys, count, err := userCtrl.ListPublicKeys(ctx, session, userUID, &filter)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.Pagination(r, w, filter.Page, filter.Size, count)
render.JSON(w, http.StatusOK, keys)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/find.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
// HandleFind returns an http.HandlerFunc that writes json-encoded
// account information to the http response body.
func HandleFind(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
user, err := userCtrl.Find(ctx, session, userUID)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusOK, user)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/create_favorite.go | app/api/handler/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 (
"encoding/json"
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/types"
)
// HandleCreateFavorite returns a http.HandlerFunc that creates a new favorite.
func HandleCreateFavorite(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
in := new(types.FavoriteResource)
err := json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequestf(ctx, w, "Invalid Request Body: %s.", err)
return
}
favoriteResource, err := userCtrl.CreateFavorite(ctx, session, in)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusCreated, favoriteResource)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/delete_favorite.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/types"
)
// HandleDeleteFavorite returns a http.HandlerFunc that delete a favorite.
func HandleDeleteFavorite(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
resourceID, err := request.GetResourceIDFromPath(r)
if err != nil {
render.BadRequest(ctx, w)
return
}
resourceType, err := request.ParseResourceType(r)
if err != nil {
render.BadRequestf(ctx, w, "Invalid query param: %s.", err)
return
}
err = userCtrl.DeleteFavorite(ctx, session, &types.FavoriteResource{Type: resourceType, ID: resourceID})
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.DeleteSuccessful(w)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/delete_token.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/types/enum"
)
// HandleDeleteToken returns an http.HandlerFunc that
// deletes a token of a user.
func HandleDeleteToken(userCtrl *user.Controller, tokenType enum.TokenType) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
tokenIdentifier, err := request.GetTokenIdentifierFromPath(r)
if err != nil {
render.BadRequest(ctx, w)
return
}
err = userCtrl.DeleteToken(ctx, session, userUID, tokenType, tokenIdentifier)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.DeleteSuccessful(w)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/list_tokens.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/types/enum"
)
// HandleListTokens returns an http.HandlerFunc that
// writes a json-encoded list of Tokens to the http.Response body.
func HandleListTokens(userCtrl *user.Controller, tokenType enum.TokenType) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
res, err := userCtrl.ListTokens(ctx, session, userUID, tokenType)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusOK, res)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/create_access_token.go | app/api/handler/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 (
"encoding/json"
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
// HandleCreateAccessToken returns an http.HandlerFunc that creates a new PAT and
// writes a json-encoded TokenResponse to the http.Response body.
func HandleCreateAccessToken(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
in := new(user.CreateTokenInput)
err := json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequestf(ctx, w, "Invalid request body: %s.", err)
return
}
tokenResponse, err := userCtrl.CreateAccessToken(ctx, session, userUID, in)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.JSON(w, http.StatusCreated, tokenResponse)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/handler/user/membership_spaces.go | app/api/handler/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 (
"net/http"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request"
)
func HandleMembershipSpaces(userCtrl *user.Controller) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
userUID := session.Principal.UID
filter := request.ParseMembershipSpaceFilter(r)
membershipSpaces, membershipSpaceCount, err := userCtrl.MembershipSpaces(ctx, session, userUID, filter)
if err != nil {
render.TranslatedUserError(ctx, w, err)
return
}
render.Pagination(r, w, filter.Page, filter.Size, int(membershipSpaceCount))
render.JSON(w, http.StatusOK, membershipSpaces)
}
}
| 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.