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/registry/app/api/middleware/request_package_access.go | registry/app/api/middleware/request_package_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 middleware
import (
"net/http"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/types/enum"
)
func RequestPackageAccess(
packageHandler packages.Handler,
reqPermissions ...enum.Permission,
) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := packageHandler.GetRegistryCheckAccess(r.Context(), r, reqPermissions...)
if err != nil {
render.TranslatedUserError(r.Context(), w, err)
return
}
next.ServeHTTP(w, r.WithContext(r.Context()))
})
}
}
func RequestNugetPackageAccess(
packageHandler packages.Handler,
reqPermissions ...enum.Permission,
) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := packageHandler.GetRegistryCheckAccess(r.Context(), r, reqPermissions...)
if err != nil {
if errors.Is(err, apiauth.ErrUnauthorized) {
setNugetAuthChallenge(r.Method, w)
render.Unauthorized(r.Context(), w)
return
}
render.TranslatedUserError(r.Context(), w, err)
return
}
next.ServeHTTP(w, r.WithContext(r.Context()))
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/middleware/quarantine_artifact.go | registry/app/api/middleware/quarantine_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package middleware
import (
"context"
"errors"
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/registry/app/api/handler/oci"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/api/router/utils"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/types"
"github.com/opencontainers/go-digest"
"github.com/rs/zerolog/log"
)
func CheckQuarantineStatus(
packageHandler packages.Handler,
) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sw := &StatusWriter{ResponseWriter: w}
err := packageHandler.CheckQuarantineStatus(ctx)
if err != nil {
log.Ctx(ctx).Error().Stack().Str("middleware",
"CheckQuarantineStatus").Err(err).Msgf("error while putting download stat of artifact, %v",
err)
render.TranslatedUserError(r.Context(), w, err)
return
}
next.ServeHTTP(sw, r)
},
)
}
}
func CheckQuarantineStatusOCI(h *oci.Handler) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
methodType := r.Method
requestType := utils.GetRouteTypeV2(path)
sw := &StatusWriter{ResponseWriter: w}
if utils.Manifests != requestType || (http.MethodGet != methodType && http.MethodHead != methodType) {
next.ServeHTTP(sw, r)
return
}
ctx := r.Context()
info, err := h.GetRegistryInfo(r, true)
if err != nil {
log.Ctx(ctx).Error().Stack().Str("middleware",
"CheckQuarantineStatus").Err(err).Msgf("error while fetching the artifact info: %v",
err)
next.ServeHTTP(sw, r)
return
}
err = dbQuarantineStatusOCI(ctx, h.Controller, info)
if err != nil {
if errors.Is(err, errcode.ErrCodeManifestQuarantined) {
render.Forbiddenf(ctx, w, "%s", err.Error())
return
}
log.Ctx(ctx).Error().Stack().Str("middleware",
"CheckQuarantineStatus").Err(err).Msgf("error while checking the quarantine status of artifact, %v",
err)
}
next.ServeHTTP(sw, r)
},
)
}
}
func dbQuarantineStatusOCI(
ctx context.Context,
c *docker.Controller,
info pkg.RegistryInfo,
) error {
registry := info.Registry
var parsedDigest digest.Digest
var err error
if info.Digest == "" {
dbManifest, err := c.DBStore.ManifestDao.FindManifestDigestByTagName(ctx, registry.ID, info.Image, info.Tag)
if err != nil {
return err
}
parsedDigest, err = dbManifest.Parse()
if err != nil {
return err
}
} else {
// Convert raw digest string to proper digest format with prefix
parsedDigest, err = digest.Parse(info.Digest)
if err != nil {
return err
}
}
typesDigest, err := types.NewDigest(parsedDigest)
if err != nil {
return err
}
digestVal := typesDigest.String()
quarantineArtifacts, err := c.DBStore.QuarantineDao.GetByFilePath(ctx, "", registry.ID, info.Image, digestVal, nil)
if err != nil {
return err
}
if len(quarantineArtifacts) > 0 {
return errcode.ErrCodeManifestQuarantined
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/interfaces/package_wrapper.go | registry/app/api/interfaces/package_wrapper.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfaces
import (
"context"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
)
type PackageWrapper interface {
IsValidPackageType(packageType string) bool
IsValidPackageTypes(packageTypes []string) bool
IsValidRepoType(repoType string) bool
IsValidRepoTypes(repoTypes []string) bool
ValidateRepoType(packageType string, repoType string) bool
IsValidUpstreamSource(upstreamSource string) bool
IsValidUpstreamSources(upstreamSources []string) bool
ValidateUpstreamSource(packageType string, upstreamSource string) bool
IsURLRequiredForUpstreamSource(packageType string, upstreamSource string) bool
GetPackageTypeFromPathPackageType(pathPackageType string) (string, error)
DeleteArtifactVersion(
ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
) error
DeleteArtifact(
ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string,
) error
GetFilePath(
packageType string,
artifactName string,
versionName string,
) (string, error)
GetPackageURL(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageType string,
) (string, error)
GetArtifactMetadata(
artifact types.ArtifactMetadata,
) *artifact.ArtifactMetadata
GetArtifactVersionMetadata(
packageType string,
image string,
tag types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata
GetFileMetadata(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageType string,
artifactName string,
version string,
file types.FileNodeMetadata,
) *artifact.FileDetail
GetArtifactDetail(
packageType string,
img *types.Image,
art *types.Artifact,
downloadCount int64,
) (*artifact.ArtifactDetail, error)
GetClientSetupDetails(
ctx context.Context,
regRef string,
image *artifact.ArtifactParam,
tag *artifact.VersionParam,
registryType artifact.RegistryType,
packageType string,
) (*artifact.ClientSetupDetails, error)
BuildRegistryIndexAsync(
ctx context.Context,
payload types.BuildRegistryIndexTaskPayload,
) error
BuildPackageIndexAsync(
ctx context.Context,
payload types.BuildPackageIndexTaskPayload,
) error
BuildPackageMetadataAsync(
ctx context.Context,
payload types.BuildPackageMetadataTaskPayload,
) error
ReportDeleteVersionEvent(
ctx context.Context,
registryID int64,
artifactName string,
versionName string,
) error
ReportBuildPackageIndexEvent(
ctx context.Context,
registryID int64,
artifactName string,
) error
ReportBuildRegistryIndexEvent(
ctx context.Context,
registryID int64,
sourceRefs []types.SourceRef,
) error
GetNodePathsForImage(
packageType string,
artifactType *string,
packageName string,
) ([]string, error)
GetNodePathsForArtifact(
packageType string,
artifactType *string,
packageName string,
version string,
) ([]string, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/interfaces/registry_helper.go | registry/app/api/interfaces/registry_helper.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfaces
import (
"context"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/types"
)
type RegistryHelper interface {
GetAuthHeaderPrefix() string
DeleteFileNode(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
filePath string,
) error
// DeleteVersion deletes the version
DeleteVersion(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
filePath string,
) error
// DeleteArtifact deletes the artifact
DeleteGenericImage(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string, filePath string,
) error
// ReportDeleteVersionEvent reports the delete version event
ReportDeleteVersionEvent(
ctx context.Context,
payload *registryevents.ArtifactDeletedPayload,
)
// ReportBuildPackageIndexEvent reports the build package index event
ReportBuildPackageIndexEvent(ctx context.Context, registryID int64, artifactName string)
// ReportBuildRegistryIndexEvent reports the build registry index event
ReportBuildRegistryIndexEvent(ctx context.Context, registryID int64, sources []types.SourceRef)
// GetPackageURL returns the package URL
GetPackageURL(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageTypePathParam string,
) string
GetHostName(
ctx context.Context,
rootSpace string,
) string
GetArtifactMetadata(
artifact types.ArtifactMetadata,
pullCommand string,
) *artifact.ArtifactMetadata
GetArtifactVersionMetadata(
tag types.NonOCIArtifactMetadata,
pullCommand string,
packageType string,
) *artifact.ArtifactVersionMetadata
GetFileMetadata(
file types.FileNodeMetadata,
filename string,
downloadCommand string,
) *artifact.FileDetail
GetArtifactDetail(
img *types.Image,
art *types.Artifact,
metadata map[string]any,
downloadCount int64,
) *artifact.ArtifactDetail
ReplacePlaceholders(
ctx context.Context,
clientSetupSections *[]artifact.ClientSetupSection,
username string,
regRef string,
image *artifact.ArtifactParam,
version *artifact.VersionParam,
registryURL string,
groupID string,
uploadURL string,
hostname string,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/interfaces/package_type_factory.go | registry/app/api/interfaces/package_type_factory.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfaces
import (
"context"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
)
type PackageHelper interface {
GetPackageType() string
GetPathPackageType() string
GetPackageURL(ctx context.Context,
rootIdentifier string,
registryIdentifier string,
) string
GetFilePath(artifactName string, versionName string) string
DeleteArtifact(
ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string,
) error
DeleteVersion(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
) error
ReportDeleteVersionEvent(ctx context.Context,
principalID int64,
registryID int64,
artifact string,
version string,
)
ReportBuildPackageIndexEvent(ctx context.Context, registryID int64, artifactName string)
ReportBuildRegistryIndexEvent(ctx context.Context, registryID int64, sources []types.SourceRef)
IsValidRepoType(repoType string) bool
IsValidUpstreamSource(upstreamSource string) bool
IsURLRequiredForUpstreamSource(upstreamSource string) bool
GetArtifactMetadata(
artifact types.ArtifactMetadata,
) *artifact.ArtifactMetadata
GetArtifactVersionMetadata(
image string,
tag types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata
GetFileMetadata(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
artifactName string,
version string,
file types.FileNodeMetadata,
) *artifact.FileDetail
GetArtifactDetail(
img *types.Image,
art *types.Artifact,
downloadCount int64,
) (*artifact.ArtifactDetail, error)
GetClientSetupDetails(
ctx context.Context,
regRef string,
image *artifact.ArtifactParam,
tag *artifact.VersionParam,
registryType artifact.RegistryType,
) (*artifact.ClientSetupDetails, error)
BuildRegistryIndexAsync(
ctx context.Context,
registry *types.Registry,
payload types.BuildRegistryIndexTaskPayload,
) error
BuildPackageIndexAsync(
ctx context.Context,
registry *types.Registry,
payload types.BuildPackageIndexTaskPayload,
) error
BuildPackageMetadataAsync(
ctx context.Context,
registry *types.Registry,
payload types.BuildPackageMetadataTaskPayload,
) error
GetNodePathsForImage(
artifactType *string,
packageName string,
) ([]string, error)
GetNodePathsForArtifact(
artifactType *string,
packageName string,
version string,
) ([]string, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/interfaces/space_finder.go | registry/app/api/interfaces/space_finder.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfaces
import (
"context"
"github.com/harness/gitness/types"
)
// SpaceFinder defines the interface for finding spaces.
type SpaceFinder interface {
// FindByID finds the space by id.
FindByID(ctx context.Context, id int64) (*types.SpaceCore, error)
// FindByRef finds the space using the spaceRef as either the id or the space path.
FindByRef(ctx context.Context, spaceRef string) (*types.SpaceCore, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/interfaces/registry_metadata.go | registry/app/api/interfaces/registry_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfaces
import (
"context"
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// RegistryMetadataHelper provides helper methods for registry metadata operations.
type RegistryMetadataHelper interface {
// GetRegistryRequestBaseInfo retrieves base info for registry request.
GetRegistryRequestBaseInfo(
ctx context.Context,
parentPath string,
identifier string,
) (*registrytypes.RegistryRequestBaseInfo, error)
// GetPermissionChecks returns permission checks for registry operations.
GetPermissionChecks(
space *types.SpaceCore,
registryIdentifier string,
permission enum.Permission,
) []types.PermissionCheck
// MapToWebhookCore maps webhook request to core webhook type.
MapToWebhookCore(
ctx context.Context,
webhookRequest api.WebhookRequest,
regInfo *registrytypes.RegistryRequestBaseInfo,
) (*types.WebhookCore, error)
// MapToWebhookResponseEntity maps webhook core to response entity.
MapToWebhookResponseEntity(
ctx context.Context,
webhook *types.WebhookCore,
) (*api.Webhook, error)
// MapToInternalWebhookTriggers maps webhook triggers to internal type.
MapToInternalWebhookTriggers(
triggers []api.Trigger,
) ([]enum.WebhookTrigger, error)
// MapToAPIWebhookTriggers maps webhook triggers to API type.
MapToAPIWebhookTriggers(
triggers []enum.WebhookTrigger,
) []api.Trigger
// GetSecretSpaceID retrieves secret space ID from secret space path.
GetSecretSpaceID(
ctx context.Context,
secretSpacePath *string,
) (int64, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/utils/path_utils.go | registry/app/api/utils/path_utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"fmt"
"strings"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
func GetMavenFilePath(imageName string, version string) string {
parts := strings.SplitN(imageName, ":", 2)
filePathPrefix := "/"
if len(parts) == 2 {
groupID := strings.ReplaceAll(parts[0], ".", "/")
filePathPrefix += groupID + "/" + parts[1]
}
if version != "" {
filePathPrefix += "/" + version
}
return filePathPrefix
}
func GetGenericFilePath(imageName string, version string) string {
filePathPrefix := "/" + imageName
if version != "" {
filePathPrefix += "/" + version
}
return filePathPrefix
}
func GetRpmFilePath(imageName string, version string) string {
lastDotIndex := strings.LastIndex(version, ".")
rpmVersion := version[:lastDotIndex]
epochIndex := strings.LastIndex(version, ":")
var epoch string
if epochIndex > -1 {
parts := strings.Split(rpmVersion, ":")
epoch = parts[0]
rpmVersion = parts[1]
}
rpmArch := version[lastDotIndex+1:]
path := "/" + imageName + "/" + rpmVersion + "/" + rpmArch
if epochIndex > -1 {
path = path + "/" + epoch
}
return path
}
func GetCargoFilePath(imageName string, version string) string {
filePathPrefix := "/crates/" + imageName
if version != "" {
filePathPrefix += "/" + version
}
return filePathPrefix
}
func GetGoFilePath(imageName string, version string) string {
filePathPrefix := "/" + imageName + "/@v"
if version != "" {
filePathPrefix += "/" + version
}
return filePathPrefix
}
func GetHuggingFaceFilePath(imageName string, artifactType *artifact.ArtifactType, version string) string {
filePathPrefix := "/"
if artifactType != nil {
filePathPrefix += string(*artifactType) + "/"
}
return filePathPrefix + imageName + "/" + version
}
func GetFilePath(packageType artifact.PackageType, imageName string, version string) (string, error) {
switch packageType { //nolint:exhaustive
case artifact.PackageTypeDOCKER:
return "", fmt.Errorf("docker package type not supported")
case artifact.PackageTypeHELM:
return "", fmt.Errorf("helm package type not supported")
case artifact.PackageTypeNPM:
return GetGenericFilePath(imageName, version), nil
case artifact.PackageTypeMAVEN:
return GetMavenFilePath(imageName, version), nil
case artifact.PackageTypePYTHON:
return GetGenericFilePath(imageName, version), nil
case artifact.PackageTypeGENERIC:
return GetGenericFilePath(imageName, version), nil
case artifact.PackageTypeNUGET:
return GetGenericFilePath(imageName, version), nil
case artifact.PackageTypeRPM:
return GetRpmFilePath(imageName, version), nil
case artifact.PackageTypeCARGO:
return GetCargoFilePath(imageName, version), nil
case artifact.PackageTypeGO:
return GetGoFilePath(imageName, version), nil
default:
return "", fmt.Errorf("unsupported package type: %s", packageType)
}
}
func GetFilePathWithArtifactType(
packageType artifact.PackageType, imageName string, version string,
artifactType *artifact.ArtifactType,
) (string, error) {
switch packageType { //nolint:exhaustive
case artifact.PackageTypeHUGGINGFACE:
return GetHuggingFaceFilePath(imageName, artifactType, version), nil
default:
return "", fmt.Errorf("unsupported package type: %s", packageType)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/wire.go | registry/app/api/router/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 router
import (
spacecontroller "github.com/harness/gitness/app/api/controller/space"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/config"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/registry/app/api/handler/cargo"
"github.com/harness/gitness/registry/app/api/handler/generic"
"github.com/harness/gitness/registry/app/api/handler/gopackage"
"github.com/harness/gitness/registry/app/api/handler/huggingface"
"github.com/harness/gitness/registry/app/api/handler/maven"
"github.com/harness/gitness/registry/app/api/handler/npm"
"github.com/harness/gitness/registry/app/api/handler/nuget"
hoci "github.com/harness/gitness/registry/app/api/handler/oci"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/api/handler/python"
"github.com/harness/gitness/registry/app/api/handler/rpm"
"github.com/harness/gitness/registry/app/api/interfaces"
generic2 "github.com/harness/gitness/registry/app/api/router/generic"
"github.com/harness/gitness/registry/app/api/router/harness"
mavenRouter "github.com/harness/gitness/registry/app/api/router/maven"
"github.com/harness/gitness/registry/app/api/router/oci"
packagerrouter "github.com/harness/gitness/registry/app/api/router/packages"
storagedriver "github.com/harness/gitness/registry/app/driver"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/quarantine"
"github.com/harness/gitness/registry/app/services/publicaccess"
refcache2 "github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/app/store"
cargoutils "github.com/harness/gitness/registry/app/utils/cargo"
registrywebhook "github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/google/wire"
)
func AppRouterProvider(
ocir oci.RegistryOCIHandler,
appHandler harness.APIHandler,
mavenHandler mavenRouter.Handler,
genericHandler generic2.Handler,
handler packagerrouter.Handler,
) AppRouter {
return GetAppRouter(ocir, appHandler, config.APIURL, mavenHandler, genericHandler, handler)
}
func APIHandlerProvider(
repoDao store.RegistryRepository,
upstreamproxyDao store.UpstreamProxyConfigRepository,
fileManager filemanager.FileManager,
tagDao store.TagRepository,
manifestDao store.ManifestRepository,
cleanupPolicyDao store.CleanupPolicyRepository,
imageDao store.ImageRepository,
driver storagedriver.StorageDriver,
spaceFinder refcache.SpaceFinder,
tx dbtx.Transactor,
authenticator authn.Authenticator,
urlProvider urlprovider.Provider,
authorizer authz.Authorizer,
auditService audit.Service,
artifactStore store.ArtifactRepository,
webhooksRepository store.WebhooksRepository,
webhooksExecutionRepository store.WebhooksExecutionRepository,
webhookService *registrywebhook.Service,
spacePathStore corestore.SpacePathStore,
artifactEventReporter *registryevents.Reporter,
downloadStatRepository store.DownloadStatRepository,
gitnessConfig *types.Config,
registryBlobsDao store.RegistryBlobRepository,
regFinder refcache2.RegistryFinder,
postProcessingReporter *registrypostprocessingevents.Reporter,
cargoRegistryHelper cargoutils.RegistryHelper,
spaceController *spacecontroller.Controller,
quarantineArtifactRepository store.QuarantineArtifactRepository,
spaceStore corestore.SpaceStore,
packageWrapper interfaces.PackageWrapper,
publicAccess publicaccess.CacheService,
quarantineFinder quarantine.Finder,
) harness.APIHandler {
return harness.NewAPIHandler(
repoDao,
fileManager,
upstreamproxyDao,
tagDao,
manifestDao,
cleanupPolicyDao,
imageDao,
driver,
config.APIURL,
spaceFinder,
tx,
authenticator,
urlProvider,
authorizer,
auditService,
artifactStore,
webhooksRepository,
webhooksExecutionRepository,
*webhookService,
spacePathStore,
*artifactEventReporter,
downloadStatRepository,
gitnessConfig,
registryBlobsDao,
regFinder,
postProcessingReporter,
cargoRegistryHelper,
spaceController,
quarantineArtifactRepository,
spaceStore,
packageWrapper,
publicAccess,
quarantineFinder,
)
}
func OCIHandlerProvider(handlerV2 *hoci.Handler) oci.RegistryOCIHandler {
return oci.NewOCIHandler(handlerV2)
}
func MavenHandlerProvider(handler *maven.Handler) mavenRouter.Handler {
return mavenRouter.NewMavenHandler(handler)
}
func GenericHandlerProvider(handler *generic.Handler) generic2.Handler {
return generic2.NewGenericArtifactHandler(handler)
}
func PackageHandlerProvider(
handler packages.Handler,
mavenHandler *maven.Handler,
genericHandler *generic.Handler,
pypiHandler python.Handler,
nugetHandler nuget.Handler,
npmHandler npm.Handler,
rpmHandler rpm.Handler,
cargoHandler cargo.Handler,
gopackageHandler gopackage.Handler,
huggingfaceHandler huggingface.Handler,
spaceFinder refcache.SpaceFinder,
publicAccessService publicaccess.CacheService,
) packagerrouter.Handler {
return packagerrouter.NewRouter(
handler,
mavenHandler,
genericHandler,
pypiHandler,
nugetHandler,
npmHandler,
rpmHandler,
cargoHandler,
gopackageHandler,
huggingfaceHandler,
spaceFinder,
publicAccessService,
)
}
var WireSet = wire.NewSet(APIHandlerProvider, OCIHandlerProvider, AppRouterProvider,
MavenHandlerProvider, GenericHandlerProvider, PackageHandlerProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/router.go | registry/app/api/router/router.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package router
import (
"fmt"
"net/http"
"github.com/harness/gitness/app/api/middleware/address"
"github.com/harness/gitness/app/api/middleware/logging"
"github.com/harness/gitness/registry/app/api/handler/swagger"
generic2 "github.com/harness/gitness/registry/app/api/router/generic"
"github.com/harness/gitness/registry/app/api/router/harness"
"github.com/harness/gitness/registry/app/api/router/maven"
"github.com/harness/gitness/registry/app/api/router/oci"
"github.com/harness/gitness/registry/app/api/router/packages"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/hlog"
)
type AppRouter interface {
http.Handler
}
func GetAppRouter(
ociHandler oci.RegistryOCIHandler,
appHandler harness.APIHandler,
baseURL string,
mavenHandler maven.Handler,
genericHandler generic2.Handler,
packageHandler packages.Handler,
) AppRouter {
r := chi.NewRouter()
r.Use(hlog.URLHandler("http.url"))
r.Use(hlog.MethodHandler("http.method"))
r.Use(logging.HLogRequestIDHandler())
r.Use(logging.HLogAccessLogHandler())
r.Use(address.Handler("", ""))
r.Group(func(r chi.Router) {
r.Handle(fmt.Sprintf("%s/*", baseURL), appHandler)
r.Handle("/v2/*", ociHandler)
// deprecated
r.Handle("/maven/*", mavenHandler)
// deprecated
r.Handle("/generic/*", genericHandler)
r.Mount("/pkg/", packageHandler)
r.Handle("/registry/swagger*", swagger.GetSwaggerHandler("/registry"))
})
return r
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/registry_router.go | registry/app/api/router/registry_router.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package router
import (
"net/http"
"strings"
"github.com/harness/gitness/registry/utils"
)
const RegistryMount = "/api/v1/registry"
const APIMount = "/api"
type RegistryRouter struct {
handler http.Handler
}
func NewRegistryRouter(handler http.Handler) *RegistryRouter {
return &RegistryRouter{handler: handler}
}
func (r *RegistryRouter) Handle(w http.ResponseWriter, req *http.Request) {
r.handler.ServeHTTP(w, req)
}
func (r *RegistryRouter) IsEligibleTraffic(req *http.Request) bool {
urlPath := req.URL.Path
if req.URL.RawPath != "" {
urlPath = req.URL.RawPath
}
if utils.HasAnyPrefix(urlPath, []string{RegistryMount, "/v2/", "/registry/",
"/maven/", "/generic/", "/pkg/"}) ||
(strings.HasPrefix(urlPath, APIMount+"/v1/spaces/") &&
utils.HasAnySuffix(urlPath, []string{"/artifacts", "/registries"})) {
return true
}
return false
}
func (r *RegistryRouter) Name() string {
return "registry"
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/generic/route.go | registry/app/api/router/generic/route.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"net/http"
middlewareauthn "github.com/harness/gitness/app/api/middleware/authn"
"github.com/harness/gitness/registry/app/api/handler/generic"
"github.com/harness/gitness/registry/app/api/middleware"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
type Handler interface {
http.Handler
}
// NewGenericArtifactHandler
// Deprecated: This function is deprecated and will be removed in a future release.
// Use router.NewRouter instead.
func NewGenericArtifactHandler(handler *generic.Handler) Handler {
r := chi.NewRouter()
var routeHandlers = map[string]http.HandlerFunc{
http.MethodPut: handler.PushArtifact,
http.MethodGet: handler.PullArtifact,
}
r.Route("/generic", func(r chi.Router) {
r.Use(middleware.StoreOriginalPath)
r.Use(middlewareauthn.Attempt(handler.Authenticator))
r.Use(middleware.TrackDownloadStatForGenericArtifact(handler))
r.Use(middleware.TrackBandwidthStatForGenericArtifacts(handler))
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
methodType := req.Method
if h, ok := routeHandlers[methodType]; ok {
h(w, req)
return
}
w.WriteHeader(http.StatusNotFound)
_, err := w.Write([]byte("Invalid route"))
if err != nil {
log.Error().Err(err).Msg("Failed to write response")
return
}
}))
})
return r
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/utils/route_utils.go | registry/app/api/router/utils/route_utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import "strings"
type RouteType string
const (
Manifests RouteType = "manifests" // /v2/:registry/:image/manifests/:reference.
Blobs RouteType = "blobs" // /v2/:registry/:image/blobs/:digest.
BlobsUploadsSession RouteType = "blob-uploads-session" // /v2/:registry/:image/blobs/uploads/:session_id.
Tags RouteType = "tags" // /v2/:registry/:image/tags/list.
Referrers RouteType = "referrers" // /v2/:registry/:image/referrers/:digest.
Invalid RouteType = "invalid" // Invalid route.
// Add other route types here.
)
func GetRouteTypeV2(url string) RouteType {
url = strings.Trim(url, "/")
segments := strings.Split(url, "/")
if len(segments) < 4 {
return Invalid
}
typ := segments[len(segments)-2]
switch typ {
case "manifests":
return Manifests
case "blobs":
if segments[len(segments)-1] == "uploads" {
return BlobsUploadsSession
}
return Blobs
case "uploads":
return BlobsUploadsSession
case "tags":
return Tags
case "referrers":
return Referrers
}
return Invalid
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/harness/route.go | registry/app/api/router/harness/route.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package harness
import (
"context"
"net/http"
spacecontroller "github.com/harness/gitness/app/api/controller/space"
middlewareauthn "github.com/harness/gitness/app/api/middleware/authn"
"github.com/harness/gitness/app/api/middleware/encode"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
corestore "github.com/harness/gitness/app/store"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/audit"
"github.com/harness/gitness/registry/app/api/controller/metadata"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
storagedriver "github.com/harness/gitness/registry/app/driver"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/quarantine"
"github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/utils/cargo"
registrywebhook "github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/go-chi/chi/v5"
)
var (
// terminatedPathPrefixesAPI is the list of prefixes that will require resolving terminated paths.
terminatedPathPrefixesAPI = []string{
"/api/v1/spaces/", "/api/v1/registry/",
}
// terminatedPathRegexPrefixesAPI is the list of regex prefixes that will require resolving terminated paths.
terminatedPathRegexPrefixesAPI = []string{
"^/api/v1/registry/([^/]+)/artifact/",
}
)
type APIHandler interface {
http.Handler
}
func NewAPIHandler(
repoDao store.RegistryRepository,
fileManager filemanager.FileManager,
upstreamproxyDao store.UpstreamProxyConfigRepository,
tagDao store.TagRepository,
manifestDao store.ManifestRepository,
cleanupPolicyDao store.CleanupPolicyRepository,
imageDao store.ImageRepository,
driver storagedriver.StorageDriver,
baseURL string,
spaceFinder interfaces.SpaceFinder,
tx dbtx.Transactor,
authenticator authn.Authenticator,
urlProvider urlprovider.Provider,
authorizer authz.Authorizer,
auditService audit.Service,
artifactStore store.ArtifactRepository,
webhooksRepository store.WebhooksRepository,
webhooksExecutionRepository store.WebhooksExecutionRepository,
webhookService registrywebhook.Service,
spacePathStore corestore.SpacePathStore,
artifactEventReporter registryevents.Reporter,
downloadStatRepository store.DownloadStatRepository,
gitnessConfig *types.Config,
registryBlobsDao store.RegistryBlobRepository,
regFinder refcache.RegistryFinder,
postProcessingReporter *registrypostprocessingevents.Reporter,
cargoRegistryHelper cargo.RegistryHelper,
spaceController *spacecontroller.Controller,
quarantineArtifactRepository store.QuarantineArtifactRepository,
spaceStore corestore.SpaceStore,
packageWrapper interfaces.PackageWrapper,
publicAccess publicaccess.Service,
quarantineFinder quarantine.Finder,
) APIHandler {
r := chi.NewRouter()
r.Use(audit.Middleware())
r.Use(middlewareauthn.Attempt(authenticator))
registryMetadataHelper := metadata.NewRegistryMetadataHelper(spacePathStore, spaceFinder, repoDao)
apiController := metadata.NewAPIController(
repoDao,
fileManager,
nil,
nil,
upstreamproxyDao,
tagDao,
manifestDao,
cleanupPolicyDao,
imageDao,
driver,
spaceFinder,
tx,
urlProvider,
authorizer,
auditService,
artifactStore,
webhooksRepository,
webhooksExecutionRepository,
registryMetadataHelper,
&webhookService,
artifactEventReporter,
downloadStatRepository,
gitnessConfig.Registry.SetupDetailsAuthHeaderPrefix,
registryBlobsDao,
regFinder,
postProcessingReporter,
cargoRegistryHelper,
spaceController,
quarantineArtifactRepository,
quarantineFinder,
spaceStore,
func(_ context.Context) bool {
return true
},
packageWrapper,
publicAccess,
)
handler := artifact.NewStrictHandler(apiController, []artifact.StrictMiddlewareFunc{})
muxHandler := artifact.HandlerFromMuxWithBaseURL(handler, r, baseURL)
return encode.TerminatedPathBefore(
terminatedPathPrefixesAPI,
encode.TerminatedRegexPathBefore(terminatedPathRegexPrefixesAPI, muxHandler),
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/maven/route.go | registry/app/api/router/maven/route.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"net/http"
middlewareauthn "github.com/harness/gitness/app/api/middleware/authn"
"github.com/harness/gitness/registry/app/api/handler/maven"
"github.com/harness/gitness/registry/app/api/middleware"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
type Handler interface {
http.Handler
}
func NewMavenHandler(handler *maven.Handler) Handler {
r := chi.NewRouter()
var routeHandlers = map[string]http.HandlerFunc{
http.MethodHead: handler.HeadArtifact,
http.MethodGet: handler.GetArtifact,
http.MethodPut: handler.PutArtifact,
}
r.Route("/maven", func(r chi.Router) {
r.Use(middleware.StoreOriginalPath)
r.Use(middleware.CheckAuthHeader())
r.Use(middlewareauthn.Attempt(handler.Authenticator))
r.Use(middleware.CheckAuthWithChallenge(handler, handler.SpaceFinder, handler.PublicAccessService))
r.Use(middleware.TrackDownloadStatForMavenArtifact(handler))
r.Use(middleware.TrackBandwidthStatForMavenArtifacts(handler))
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
methodType := req.Method
if h, ok := routeHandlers[methodType]; ok {
h(w, req)
return
}
w.WriteHeader(http.StatusNotFound)
_, err := w.Write([]byte("Invalid route"))
if err != nil {
log.Error().Err(err).Msg("Failed to write response")
return
}
}))
})
return r
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/oci/route.go | registry/app/api/router/oci/route.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
middlewareauthn "github.com/harness/gitness/app/api/middleware/authn"
"github.com/harness/gitness/registry/app/api/handler/oci"
"github.com/harness/gitness/registry/app/api/middleware"
"github.com/harness/gitness/registry/app/api/router/utils"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
type HandlerBlock struct {
Handler2 http.HandlerFunc
RemoteSupport bool
}
func NewHandlerBlock2(h2 http.HandlerFunc, remoteSupport bool) HandlerBlock {
return HandlerBlock{
Handler2: h2,
RemoteSupport: remoteSupport,
}
}
type RegistryOCIHandler interface {
http.Handler
}
func NewOCIHandler(handlerV2 *oci.Handler) RegistryOCIHandler {
r := chi.NewRouter()
var routeHandlers = map[utils.RouteType]map[string]HandlerBlock{
utils.Manifests: {
http.MethodGet: NewHandlerBlock2(handlerV2.GetManifest, true),
http.MethodHead: NewHandlerBlock2(handlerV2.HeadManifest, true),
http.MethodPut: NewHandlerBlock2(handlerV2.PutManifest, false),
http.MethodDelete: NewHandlerBlock2(handlerV2.DeleteManifest, false),
},
utils.Blobs: {
http.MethodGet: NewHandlerBlock2(handlerV2.GetBlob, true),
http.MethodHead: NewHandlerBlock2(handlerV2.HeadBlob, false),
http.MethodDelete: NewHandlerBlock2(handlerV2.DeleteBlob, false),
},
utils.BlobsUploadsSession: {
http.MethodGet: NewHandlerBlock2(handlerV2.GetUploadBlobStatus, false),
http.MethodPatch: NewHandlerBlock2(handlerV2.PatchBlobUpload, false),
http.MethodPut: NewHandlerBlock2(handlerV2.CompleteBlobUpload, false),
http.MethodDelete: NewHandlerBlock2(handlerV2.CancelBlobUpload, false),
http.MethodPost: NewHandlerBlock2(handlerV2.InitiateUploadBlob, false),
},
utils.Tags: {
http.MethodGet: NewHandlerBlock2(handlerV2.GetTags, false),
},
utils.Referrers: {
http.MethodGet: NewHandlerBlock2(handlerV2.GetReferrers, false),
},
}
r.Route("/v2", func(r chi.Router) {
r.Use(middleware.StoreOriginalPath)
r.Use(middlewareauthn.Attempt(handlerV2.Authenticator))
r.Get("/token", func(w http.ResponseWriter, req *http.Request) {
handlerV2.GetToken(w, req)
})
r.With(middleware.OciCheckAuth(handlerV2)).
Get("/", func(w http.ResponseWriter, req *http.Request) {
handlerV2.APIBase(w, req)
})
r.Route("/{registryIdentifier}", func(r chi.Router) {
r.Use(middleware.OciCheckAuth(handlerV2))
r.Use(middleware.BlockNonOciSourceToken(handlerV2.URLProvider))
r.Use(middleware.TrackDownloadStat(handlerV2))
r.Use(middleware.TrackBandwidthStat(handlerV2))
r.Use(middleware.CheckQuarantineStatusOCI(handlerV2))
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
methodType := req.Method
requestType := utils.GetRouteTypeV2(path)
if _, ok := routeHandlers[requestType]; ok {
if h, ok2 := routeHandlers[requestType][methodType]; ok2 {
h.Handler2(w, req)
return
}
}
w.WriteHeader(http.StatusNotFound)
_, err := w.Write([]byte("Invalid route"))
if err != nil {
log.Error().Err(err).Msg("Failed to write response")
return
}
}))
})
})
return r
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/router/packages/route.go | registry/app/api/router/packages/route.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package packages
import (
"fmt"
"net/http"
middlewareauthn "github.com/harness/gitness/app/api/middleware/authn"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/handler/cargo"
"github.com/harness/gitness/registry/app/api/handler/generic"
"github.com/harness/gitness/registry/app/api/handler/gopackage"
"github.com/harness/gitness/registry/app/api/handler/huggingface"
"github.com/harness/gitness/registry/app/api/handler/maven"
"github.com/harness/gitness/registry/app/api/handler/npm"
"github.com/harness/gitness/registry/app/api/handler/nuget"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/api/handler/python"
"github.com/harness/gitness/registry/app/api/handler/rpm"
"github.com/harness/gitness/registry/app/api/middleware"
"github.com/harness/gitness/types/enum"
"github.com/go-chi/chi/v5"
)
type Handler interface {
http.Handler
}
/**
* NewRouter creates a new router for the package API.
* It sets up the routes and middleware for handling package-related requests.
* Paths look like:
* For all packages: /{rootIdentifier}/{registryName}/<package_type>/<package specific routes> .
*/
func NewRouter(
packageHandler packages.Handler,
mavenHandler *maven.Handler,
genericHandler *generic.Handler,
pythonHandler python.Handler,
nugetHandler nuget.Handler,
npmHandler npm.Handler,
rpmHandler rpm.Handler,
cargoHandler cargo.Handler,
gopackageHandler gopackage.Handler,
huggingfaceHandler huggingface.Handler,
spaceFinder refcache.SpaceFinder,
publicAccessService publicaccess.Service,
) Handler {
r := chi.NewRouter()
r.Route("/{rootIdentifier}/{registryIdentifier}", func(r chi.Router) {
r.Use(middleware.StoreOriginalPath)
r.Route("/maven", func(r chi.Router) {
r.Use(middleware.CheckAuthHeader())
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.Use(middleware.CheckAuthWithChallenge(mavenHandler, spaceFinder, publicAccessService))
r.Use(middleware.TrackDownloadStatForMavenArtifact(mavenHandler))
r.Use(middleware.TrackBandwidthStatForMavenArtifacts(mavenHandler))
r.Get("/*", mavenHandler.GetArtifact)
r.Head("/*", mavenHandler.HeadArtifact)
r.Put("/*", mavenHandler.PutArtifact)
})
r.Route("/generic", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.Route("/{package}/{version}", func(r chi.Router) {
r.Use(middleware.StoreArtifactInfo(genericHandler))
r.Use(middleware.TrackDownloadStatForGenericArtifact(genericHandler))
r.Use(middleware.TrackBandwidthStatForGenericArtifacts(genericHandler))
r.With(middleware.CheckQuarantineStatus(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", genericHandler.PullArtifact)
r.With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/", genericHandler.PushArtifact)
})
})
// Files uses Generic Engine to serve and manage files
r.Route("/files", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
// We currently support managing files for a given package and a version. If requirements change in the future,
// this line will need to be removed
r.Route("/{package}/{version}", func(r chi.Router) {
r.Use(middleware.StoreArtifactInfo(genericHandler))
r.Route("/", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.With(middleware.CheckQuarantineStatus(packageHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/*", genericHandler.GetFile)
r.With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDelete)).
Delete("/*", genericHandler.DeleteFile)
r.With(middleware.CheckQuarantineStatus(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Head("/*", genericHandler.HeadFile)
r.With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/*", genericHandler.PutFile)
})
})
})
})
r.Route("/python", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
// TODO (Arvind): Move this to top layer with total abstraction
r.With(middleware.StoreArtifactInfo(pythonHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Post("/*", pythonHandler.UploadPackageFile)
r.With(middleware.StoreArtifactInfo(pythonHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/files/{image}/{version}/{filename}", pythonHandler.DownloadPackageFile)
r.With(middleware.StoreArtifactInfo(pythonHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/simple/{image}/", pythonHandler.PackageMetadata)
r.Get("/simple/{image}", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
})
})
r.Route("/{packageType}", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.HandleFunc("/*", func(w http.ResponseWriter, r *http.Request) {
packageType := chi.URLParam(r, "packageType")
http.Error(w, fmt.Sprintf("Package type '%s' is not supported", packageType), http.StatusNotFound)
})
})
r.Route("/download", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", packageHandler.DownloadFile)
})
r.Route("/nuget", func(r chi.Router) {
r.Use(middleware.CheckNugetAPIKey())
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/*", nugetHandler.UploadPackage)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/symbolpackage/*", nugetHandler.UploadSymbolPackage)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/package/{id}/{version}/{filename}", nugetHandler.DownloadPackage)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDelete)).
Delete("/{id}/{version}", nugetHandler.DeletePackage)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/index.json", nugetHandler.GetServiceEndpoint)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", nugetHandler.GetServiceEndpointV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/$metadata", nugetHandler.GetServiceMetadataV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/package/{id}/index.json", nugetHandler.ListPackageVersion)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/FindPackagesById()", nugetHandler.ListPackageVersionV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/query", nugetHandler.SearchPackage)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/Packages()", nugetHandler.SearchPackageV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/Packages()/$count", nugetHandler.CountPackageV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/Search()", nugetHandler.SearchPackageV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/Search()/$count", nugetHandler.CountPackageV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/FindPackagesById()", nugetHandler.ListPackageVersionV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/FindPackagesById()/$count", nugetHandler.GetPackageVersionCountV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/registration/{id}/index.json", nugetHandler.GetPackageMetadata)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/Packages(Id='{id:[^']+}',Version='{version:[^']+}')", nugetHandler.GetPackageVersionMetadataV2)
r.With(middleware.StoreArtifactInfo(nugetHandler)).
With(middleware.RequestNugetPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/registration/{id}/{version}", nugetHandler.GetPackageVersionMetadata)
})
r.Route("/npm", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.Route("/@{scope}/{id}", func(r chi.Router) {
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/", npmHandler.UploadPackage)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/-/{version}/@{scope}/{filename}", npmHandler.DownloadPackageFile)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/-/@{scope}/{filename}", npmHandler.DownloadPackageFileByName)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Head("/-/@{scope}/{filename}", npmHandler.HeadPackageFileByName)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", npmHandler.GetPackageMetadata)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDelete)).
Delete("/-/{version}/@{scope}/{filename}/-rev/{revision}", npmHandler.DeleteVersion)
})
r.Route("/{id}", func(r chi.Router) {
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/", npmHandler.UploadPackage)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/-/{version}/{filename}", npmHandler.DownloadPackageFile)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/-/{filename}", npmHandler.DownloadPackageFileByName)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Head("/-/{filename}", npmHandler.HeadPackageFileByName)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", npmHandler.GetPackageMetadata)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDelete)).
Delete("/-/{version}/{filename}/-rev/{revision}", npmHandler.DeleteVersion)
})
r.Route("/-/package/@{scope}/{id}/dist-tags", func(r chi.Router) {
registerDistTagRoutes(r, npmHandler, packageHandler)
})
r.Route("/-/package/{id}/dist-tags", func(r chi.Router) {
registerDistTagRoutes(r, npmHandler, packageHandler)
})
r.Route("/@{scope}/-rev/{revision}", func(r chi.Router) {
registerRevisionRoutes(r, npmHandler, packageHandler)
})
r.Route("/{id}/-rev/{revision}", func(r chi.Router) {
registerRevisionRoutes(r, npmHandler, packageHandler)
})
r.Route("/-/v1/search", func(r chi.Router) {
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/", npmHandler.SearchPackage)
})
})
r.Route("/rpm", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(rpmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/*", rpmHandler.UploadPackageFile)
r.With(middleware.StoreArtifactInfo(rpmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/repodata/{file}", rpmHandler.GetRepoData)
r.With(middleware.StoreArtifactInfo(rpmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/package/{name}/{version}/{architecture}/{file}", rpmHandler.DownloadPackageFile)
r.With(middleware.StoreArtifactInfo(rpmHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/package/{name}/{version}/{architecture}/{file}/*", rpmHandler.DownloadPackageFile)
})
r.Route("/cargo", func(r chi.Router) {
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionRegistryView)).
Get("/index/config.json", cargoHandler.GetRegistryConfig)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionRegistryView)).
Put("/index/{name}/regenerate", cargoHandler.RegeneratePackageIndex)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionRegistryView)).
Get("/index/*", cargoHandler.DownloadPackageIndex)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionRegistryView)).
Get("/api/v1/crates", cargoHandler.SearchPackage)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/api/v1/crates/new", cargoHandler.UploadPackage)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.TrackDownloadStats(packageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/api/v1/crates/{name}/{version}/download", cargoHandler.DownloadPackage)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Delete("/api/v1/crates/{name}/{version}/yank", cargoHandler.YankVersion)
r.With(middleware.StoreArtifactInfo(cargoHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/api/v1/crates/{name}/{version}/unyank", cargoHandler.UnYankVersion)
})
// GO Package uses Basic Authorization
r.Route("/go", func(r chi.Router) {
r.Use(middleware.CheckAuthHeader())
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(gopackageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/upload", gopackageHandler.UploadPackage)
r.With(middleware.StoreArtifactInfo(gopackageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/regenerate-index", gopackageHandler.RegeneratePackageIndex)
r.With(middleware.StoreArtifactInfo(gopackageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/regenerate-metadata", gopackageHandler.RegeneratePackageMetadata)
r.With(middleware.StoreArtifactInfo(gopackageHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
With(middleware.TrackDownloadStatsForGoPackage(packageHandler)).
Get("/*", gopackageHandler.DownloadPackageFile)
// TODO: Add api for regenerate package index and download latest package info file
})
// Huggingface routes
r.Route("/huggingface", func(r chi.Router) {
r.Use(middleware.CheckSig())
r.Use(middlewareauthn.Attempt(packageHandler.GetAuthenticator()))
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Post("/api/validate-yaml", huggingfaceHandler.ValidateYAML)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Post("/api/{repoType}/{repo}/preupload/{rev}", huggingfaceHandler.PreUpload)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Get("/api/{repoType}/{repo}/revision/{rev}", huggingfaceHandler.RevisionInfo)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Post("/{repo}.git/info/lfs/objects/batch", huggingfaceHandler.LfsInfo)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Post("/{repoType}/{repo}.git/info/lfs/objects/batch", huggingfaceHandler.LfsInfo)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Put("/api/{repoType}/{repo}/{rev}/multipart/upload/{sha256}", huggingfaceHandler.LfsUpload)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Post("/api/{repoType}/{repo}/{rev}/multipart/verify/{sha256}", huggingfaceHandler.LfsVerify)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Post("/api/{repoType}/{repo}/commit/{rev}", huggingfaceHandler.CommitRevision)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Head("/{repo}/resolve/{rev}/*", huggingfaceHandler.HeadFile)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
Head("/{repoType}/{repo}/resolve/{rev}/*", huggingfaceHandler.HeadFile)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
With(middleware.TrackDownloadStats(packageHandler)).
Get("/{repo}/resolve/{rev}/*", huggingfaceHandler.DownloadFile)
r.With(middleware.StoreArtifactInfo(huggingfaceHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDownload)).
With(middleware.TrackDownloadStats(packageHandler)).
Get("/{repoType}/{repo}/resolve/{rev}/*", huggingfaceHandler.DownloadFile)
})
})
return r
}
func registerDistTagRoutes(r chi.Router, npmHandler npm.Handler, packageHandler packages.Handler) {
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Get("/", npmHandler.ListPackageTag)
r.With(middleware.StoreArtifactInfo(npmHandler)).
With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsUpload)).
Route("/{tag}", func(r chi.Router) {
r.Put("/", npmHandler.AddPackageTag)
r.Delete("/", npmHandler.DeletePackageTag)
})
}
func registerRevisionRoutes(r chi.Router, npmHandler npm.Handler, packageHandler packages.Handler) {
r.Use(middleware.StoreArtifactInfo(npmHandler))
r.With(middleware.RequestPackageAccess(packageHandler, enum.PermissionArtifactsDelete)).
Route("/", func(r chi.Router) {
r.Delete("/", npmHandler.DeletePackage)
r.Put("/", npmHandler.DeletePreview)
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/python/list.go | registry/app/api/handler/python/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 python
import (
"fmt"
"html/template"
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/registry/app/common/lib/errors"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/request"
)
const HTMLTemplate = `
<!DOCTYPE html>
<html>
<head>
<meta name="pypi:repository-version" content="1.3">
<title>Links for {{.Name}}</title>
</head>
<body>
{{- /* PEP 503 – Simple Repository API: https://peps.python.org/pep-0503/ */ -}}
<h1>Links for {{.Name}}</h1>
{{range .Files}}
<a href="{{.FileURL}}"{{if .RequiresPython}} data-requires-python="{{.RequiresPython}}"{{end}}>{{.Name}}</a><br>
{{end}}
</body>
</html>
`
func (h *handler) PackageMetadata(w http.ResponseWriter, r *http.Request) {
contextInfo := request.ArtifactInfoFrom(r.Context())
info, ok := contextInfo.(*pythontype.ArtifactInfo)
if !ok {
render.TranslatedUserError(r.Context(), w, fmt.Errorf("invalid request context"))
return
}
packageData := h.controller.GetPackageMetadata(r.Context(), *info)
if packageData.GetError() != nil {
notFound := errors.IsErr(packageData.GetError(), errors.NotFoundCode)
if notFound {
render.NotFound(r.Context(), w)
return
}
render.TranslatedUserError(r.Context(), w, packageData.GetError())
return
}
// Parse and execute the template
tmpl, err := template.New("simple").Parse(HTMLTemplate)
if err != nil {
render.TranslatedUserError(r.Context(), w, fmt.Errorf("template error: %w", err))
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.Execute(w, packageData.PackageMetadata); err != nil {
render.TranslatedUserError(r.Context(), w, fmt.Errorf("template rendering error: %w", err))
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/python/upload.go | registry/app/api/handler/python/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 python
import (
"fmt"
"net/http"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/request"
)
func (h *handler) UploadPackageFile(w http.ResponseWriter, r *http.Request) {
file, fileHeader, err := r.FormFile("content")
if err != nil {
h.HandleError(r.Context(), w, err)
return
}
defer file.Close()
contextInfo := request.ArtifactInfoFrom(r.Context())
info, ok := contextInfo.(*pythontype.ArtifactInfo)
if !ok {
h.HandleError(r.Context(), w, fmt.Errorf("failed to fetch info from context"))
return
}
// TODO: Can we extract this out to ArtifactInfoProvider
if info.Filename == "" {
info.Filename = fileHeader.Filename
request.WithArtifactInfo(r.Context(), info)
}
response := h.controller.UploadPackageFile(r.Context(), *info, file, fileHeader)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
_, err = fmt.Fprintf(w, "Pushed.\nSha256: %s", response.Sha256)
if err != nil {
h.HandleError(r.Context(), w, err)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/python/handler.go | registry/app/api/handler/python/handler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package python
import (
"fmt"
"net/http"
"regexp"
"strings"
"unicode"
"github.com/harness/gitness/registry/app/api/controller/pkg/python"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/api/handler/utils"
python2 "github.com/harness/gitness/registry/app/metadata/python"
"github.com/harness/gitness/registry/app/pkg"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/validation"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
// https://peps.python.org/pep-0426/#name
var (
normalizer = strings.NewReplacer(".", "-", "_", "-")
nameMatcher = regexp.MustCompile(`\A(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\.\-_]*[a-zA-Z0-9])\z`)
)
// https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions
var versionMatcher = regexp.MustCompile(`\Av?` +
`(?:[0-9]+!)?` + // epoch
`[0-9]+(?:\.[0-9]+)*` + // release segment
`(?:[-_\.]?(?:a|b|c|rc|alpha|beta|pre|preview)[-_\.]?[0-9]*)?` + // pre-release
`(?:-[0-9]+|[-_\.]?(?:post|rev|r)[-_\.]?[0-9]*)?` + // post release
`(?:[-_\.]?dev[-_\.]?[0-9]*)?` + // dev release
`(?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)?` + // local version
`\z`)
type Handler interface {
pkg.ArtifactInfoProvider
UploadPackageFile(writer http.ResponseWriter, request *http.Request)
DownloadPackageFile(http.ResponseWriter, *http.Request)
PackageMetadata(writer http.ResponseWriter, request *http.Request)
}
type handler struct {
packages.Handler
controller python.Controller
}
func NewHandler(
controller python.Controller,
packageHandler packages.Handler,
) Handler {
return &handler{
Handler: packageHandler,
controller: controller,
}
}
var _ Handler = (*handler)(nil)
func (h *handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, err := h.Handler.GetArtifactInfo(r)
if err != nil {
return nil, err
}
image := chi.URLParam(r, "image")
filename := chi.URLParam(r, "filename")
version := chi.URLParam(r, "version")
var md python2.Metadata
err2 := utils.FillFromForm(r, &md)
if err2 == nil {
if image == "" {
image = md.Name
}
if version == "" {
version = md.Version
}
}
image = normalizer.Replace(image)
if image != "" && version != "" && !isValidNameAndVersion(image, version) {
log.Info().Msgf("Invalid image name/version: %s/%s", info.Image, version)
return nil, fmt.Errorf("invalid name or version")
}
md.HomePage = getHomePage(md)
info.Image = image
return &pythontype.ArtifactInfo{
ArtifactInfo: info,
Metadata: md,
Filename: filename,
Version: version,
}, nil
}
func getHomePage(md python2.Metadata) string {
var homepageURL string
if len(md.ProjectURLs) > 0 {
for k, v := range md.ProjectURLs {
if normalizeLabel(k) != "homepage" {
continue
}
homepageURL = strings.TrimSpace(v)
break
}
}
if len(homepageURL) == 0 {
homepageURL = md.HomePage
}
if !validation.IsValidURL(homepageURL) {
homepageURL = ""
}
return homepageURL
}
func isValidNameAndVersion(image, version string) bool {
return nameMatcher.MatchString(image) && versionMatcher.MatchString(version)
}
// Normalizes a Project-URL label.
// See https://packaging.python.org/en/latest/specifications/well-known-project-urls/#label-normalization.
func normalizeLabel(label string) string {
var builder strings.Builder
// "A label is normalized by deleting all ASCII punctuation and whitespace, and then converting the result
// to lowercase."
for _, r := range label {
if unicode.IsPunct(r) || unicode.IsSpace(r) {
continue
}
builder.WriteRune(unicode.ToLower(r))
}
return builder.String()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/python/download.go | registry/app/api/handler/python/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 python
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadPackageFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*pythontype.ArtifactInfo)
if !ok {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.DownloadPackageFile(ctx, *info)
if response == nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to get response from controller")}, w)
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close read closer: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(ctx, w, response.GetError())
return
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
w.WriteHeader(http.StatusOK)
err := commons.ServeContent(w, r, response.Body, info.Filename, response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/get_file.go | registry/app/api/handler/generic/get_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
// GetFile handles file download and metadata retrieval requests.
func (h *Handler) GetFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info := request.ArtifactInfoFrom(ctx)
artifactInfo, ok := info.(generic.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get generic artifact info from context")
h.HandleError(ctx, w, fmt.Errorf("failed to fetch info from context"))
return
}
response := h.Controller.DownloadFile(ctx, artifactInfo,
artifactInfo.FilePath)
if response == nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to get response from controller")}, w)
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to close read closer body: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(ctx, w, response.GetError())
return
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
// Set content disposition for download
if info.GetFileName() != "" {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", info.GetFileName()))
}
err := commons.ServeContent(w, r, response.Body, info.GetFileName(), response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/pull_artifact.go | registry/app/api/handler/generic/pull_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"net/http"
"time"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
func (h *Handler) PullArtifact(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetGenericArtifactInfo(r)
if !commons.IsEmptyError(err) {
handleErrors(r.Context(), err, w)
return
}
if info.FileName == "" {
info.FileName = r.FormValue("filename")
}
headers, fileReader, redirectURL, err := h.Controller.PullArtifact(ctx, info)
if commons.IsEmptyError(err) {
w.Header().Set("Content-Disposition", "attachment; filename="+info.FileName)
if redirectURL != "" {
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
return
}
h.serveContent(w, r, fileReader, info)
headers.WriteToResponse(w)
return
}
handleErrors(r.Context(), err, w)
}
func (h *Handler) serveContent(
w http.ResponseWriter, r *http.Request, fileReader *storage.FileReader, info pkg.GenericArtifactInfo,
) {
if fileReader != nil {
http.ServeContent(w, r, info.FileName, time.Time{}, fileReader)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/base.go | registry/app/api/handler/generic/base.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"context"
"fmt"
"net/http"
"path"
"path/filepath"
"regexp"
"strings"
usercontroller "github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/controller/metadata"
"github.com/harness/gitness/registry/app/api/controller/pkg/generic"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/api/handler/utils"
artifact2 "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
generic2 "github.com/harness/gitness/registry/app/pkg/types/generic"
refcache2 "github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/request"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
const (
packageNameRegex = `^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$`
versionRegex = `^[a-z0-9][a-z0-9.-]*[a-z0-9]$`
versionRegexV2 = `^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$`
filePathRegex = `^(?:[A-Za-z0-9._~@-]+/)*[A-Za-z0-9._~@-]+$`
maxFilePathLength = 4000
)
var (
packageNameRe = regexp.MustCompile(packageNameRegex)
versionRe = regexp.MustCompile(versionRegex)
versionV2Re = regexp.MustCompile(versionRegexV2)
filePathRe = regexp.MustCompile(filePathRegex)
)
func NewGenericArtifactHandler(
spaceStore corestore.SpaceStore, controller *generic.Controller, tokenStore corestore.TokenStore,
userCtrl *usercontroller.Controller, authenticator authn.Authenticator, urlProvider urlprovider.Provider,
authorizer authz.Authorizer, packageHandler packages.Handler, spaceFinder refcache.SpaceFinder,
registryFinder refcache2.RegistryFinder,
) *Handler {
return &Handler{
Handler: packageHandler,
Controller: controller,
SpaceStore: spaceStore,
TokenStore: tokenStore,
UserCtrl: userCtrl,
Authenticator: authenticator,
URLProvider: urlProvider,
Authorizer: authorizer,
SpaceFinder: spaceFinder,
RegistryFinder: registryFinder,
}
}
type Handler struct {
packages.Handler
Controller *generic.Controller
SpaceStore corestore.SpaceStore
TokenStore corestore.TokenStore
UserCtrl *usercontroller.Controller
Authenticator authn.Authenticator
URLProvider urlprovider.Provider
Authorizer authz.Authorizer
SpaceFinder refcache.SpaceFinder
RegistryFinder refcache2.RegistryFinder
}
//nolint:staticcheck
func (h *Handler) GetGenericArtifactInfo(r *http.Request) (
pkg.GenericArtifactInfo,
errcode.Error,
) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(pkg.GenericArtifactInfo)
if ok {
return info, errcode.Error{}
}
path := r.URL.Path
rootIdentifier, registryIdentifier, artifact, tag, fileName, description, err := ExtractPathVars(r)
if err != nil {
return pkg.GenericArtifactInfo{}, errcode.ErrCodeInvalidRequest.WithDetail(err)
}
if err := metadata.ValidateIdentifier(registryIdentifier); err != nil {
return pkg.GenericArtifactInfo{}, errcode.ErrCodeInvalidRequest.WithDetail(err)
}
if err := validatePackageVersion(artifact, tag); err != nil {
return pkg.GenericArtifactInfo{}, errcode.ErrCodeInvalidRequest.WithDetail(err)
}
rootSpaceID, err := h.SpaceStore.FindByRefCaseInsensitive(ctx, rootIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root spaceID not found: %s", rootIdentifier)
return pkg.GenericArtifactInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
rootSpace, err := h.SpaceFinder.FindByID(ctx, rootSpaceID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root space not found: %d", rootSpaceID)
return pkg.GenericArtifactInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
registry, err := h.Controller.DBStore.RegistryDao.GetByRootParentIDAndName(ctx, rootSpace.ID, registryIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf(
"registry %s not found for root: %s. Reason: %s", registryIdentifier, rootSpace.Identifier, err,
)
return pkg.GenericArtifactInfo{}, errcode.ErrCodeRegNotFound.WithDetail(err)
}
if registry.PackageType != artifact2.PackageTypeGENERIC {
log.Ctx(ctx).Error().Msgf(
"registry %s is not a generic artifact registry for root: %s", registryIdentifier, rootSpace.Identifier,
)
return pkg.GenericArtifactInfo{}, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("registry %s is"+
" not a generic artifact registry", registryIdentifier))
}
_, err = h.SpaceFinder.FindByID(r.Context(), registry.ParentID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Parent space not found: %d", registry.ParentID)
return pkg.GenericArtifactInfo{}, errcode.ErrCodeParentNotFound.WithDetail(err)
}
info = pkg.GenericArtifactInfo{
ArtifactInfo: &pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootIdentifier: rootIdentifier,
RootParentID: rootSpace.ID,
ParentID: registry.ParentID,
},
RegIdentifier: registryIdentifier,
Image: artifact,
},
RegistryID: registry.ID,
Version: tag,
FileName: fileName,
Description: description,
}
log.Ctx(ctx).Info().Msgf("Dispatch: URI: %s", path)
if commons.IsEmpty(rootSpace.Identifier) {
log.Ctx(ctx).Error().Msgf("ParentRef not found in context")
return pkg.GenericArtifactInfo{}, errcode.ErrCodeParentNotFound.WithDetail(err)
}
if commons.IsEmpty(registryIdentifier) {
log.Ctx(ctx).Warn().Msgf("registry not found in context")
return pkg.GenericArtifactInfo{}, errcode.ErrCodeRegNotFound.WithDetail(err)
}
if info.Image != "" && info.Version != "" && info.FileName != "" {
err2 := utils.PatternAllowed(registry.AllowedPattern, registry.BlockedPattern,
info.Image+":"+info.Version+":"+info.FileName)
if err2 != nil {
return pkg.GenericArtifactInfo{}, errcode.ErrCodeInvalidRequest.WithDetail(err2)
}
}
return info, errcode.Error{}
}
func (h *Handler) GetGenericArtifactInfoV2(r *http.Request) (generic2.ArtifactInfo, error) {
ctx := r.Context()
path := r.URL.Path
path = strings.TrimPrefix(path, "/")
splits := strings.Split(path, "/")
filePath := strings.Join(splits[6:], "/")
fileName := splits[len(splits)-1]
rootIdentifier, registryIdentifier, packageName, version :=
chi.URLParam(r, "rootIdentifier"),
chi.URLParam(r, "registryIdentifier"),
chi.URLParam(r, "package"),
chi.URLParam(r, "version")
if err := validatePackageVersionV2(packageName, version); err != nil {
return generic2.ArtifactInfo{}, fmt.Errorf("invalid image name/version/fileName: %q/%q %w", packageName,
version, err)
}
if err := validateFilePath(filePath); err != nil {
return generic2.ArtifactInfo{}, usererror.BadRequestf("%v", err)
}
rootSpaceID, err := h.SpaceStore.FindByRefCaseInsensitive(ctx, rootIdentifier)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Root spaceID not found: %q", rootIdentifier)
return generic2.ArtifactInfo{}, usererror.NotFoundf("Root %q not found", rootIdentifier)
}
rootSpace, err := h.SpaceFinder.FindByID(ctx, rootSpaceID)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Root space not found: %d", rootSpaceID)
return generic2.ArtifactInfo{}, usererror.New(http.StatusInternalServerError,
"Root ID not found "+rootIdentifier)
}
registry, err := h.RegistryFinder.FindByRootRef(ctx, rootSpace.Identifier, registryIdentifier)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf(
"registry %q not found for root: %q. Reason: %q", registryIdentifier, rootSpace.Identifier, err,
)
return generic2.ArtifactInfo{}, usererror.NotFoundf("Registry %q not found for root: %q", registryIdentifier,
rootSpace.Identifier)
}
info := generic2.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
PathPackageType: registry.PackageType,
ParentID: registry.ParentID,
RootIdentifier: rootIdentifier,
RootParentID: rootSpace.ID,
},
RegIdentifier: registryIdentifier,
RegistryID: registry.ID,
Registry: *registry,
Image: packageName,
ArtifactType: nil,
},
FileName: fileName,
FilePath: filePath,
Version: version,
Description: "",
}
log.Ctx(ctx).Info().Msgf("Dispatch: URI: %s", path)
if info.Image == "" || info.Version == "" || info.FileName == "" || info.FilePath == "" {
log.Ctx(ctx).Warn().Msgf("Invalid request")
return generic2.ArtifactInfo{}, usererror.BadRequestf("Invalid request Image: %q, Version: %q, FileName: %q",
info.Image, info.Version,
info.FileName)
}
if info.Image != "" && info.Version != "" && info.FilePath != "" {
artifact := info.Image + ":" + info.Version + ":" + info.FilePath
err2 := utils.PatternAllowed(registry.AllowedPattern, registry.BlockedPattern,
artifact)
if err2 != nil {
return generic2.ArtifactInfo{}, usererror.BadRequestf("Invalid request: File path %q not "+
"allowed due to allowed / blocked patterns",
artifact)
}
}
return info, nil
}
func (h *Handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
path := r.URL.Path
path = strings.TrimPrefix(path, "/")
splits := strings.Split(path, "/")
if len(splits) >= 7 && splits[0] == "pkg" && splits[3] == "files" {
artifactInfo, err := h.GetGenericArtifactInfoV2(r)
if err != nil {
return nil, fmt.Errorf("failed to get generic artifact info: %w", err)
}
return artifactInfo, nil
}
info, e := h.GetArtifactInfo(r)
if e != nil {
log.Ctx(r.Context()).Error().Msgf("failed to get artifact info: %q", e)
return nil, fmt.Errorf("failed to get artifact info: %w", e)
}
info.Image = r.PathValue("package")
version := r.PathValue("version")
if err := validatePackageVersion(info.Image, version); err != nil {
log.Error().Msgf("Invalid image name/version/fileName: %s/%s", info.Image, version)
return nil, err
}
return pkg.GenericArtifactInfo{
ArtifactInfo: &info,
Version: version,
RegistryID: info.RegistryID,
}, nil
}
// ExtractPathVars extracts registry,image, reference, digest and tag from the path
// Path format: /generic/:rootSpace/:registry/:image/:tag (for ex:
// /generic/myRootSpace/reg1/alpine/v1).
func ExtractPathVars(r *http.Request) (
rootIdentifier, registry, artifact,
tag, fileName string, description string, err error,
) {
path := r.URL.Path
// Ensure the path starts with "/generic/"
if !strings.HasPrefix(path, "/generic/") {
return "", "", "", "", "", "", fmt.Errorf("invalid path: must start with /generic/")
}
trimmedPath := strings.TrimPrefix(path, "/generic/")
firstSlashIndex := strings.Index(trimmedPath, "/")
if firstSlashIndex == -1 {
return "", "", "", "", "", "", fmt.Errorf("invalid path format: missing rootIdentifier or registry")
}
rootIdentifier = trimmedPath[:firstSlashIndex]
remainingPath := trimmedPath[firstSlashIndex+1:]
secondSlashIndex := strings.Index(remainingPath, "/")
if secondSlashIndex == -1 {
return "", "", "", "", "", "", fmt.Errorf("invalid path format: missing registry")
}
registry = remainingPath[:secondSlashIndex]
// Extract the artifact and tag from the remaining path
artifactPath := remainingPath[secondSlashIndex+1:]
// Check if the artifactPath contains a ":" for tag and filename
if strings.Contains(artifactPath, ":") {
segments := strings.SplitN(artifactPath, ":", 3)
if len(segments) < 3 {
return "", "", "", "", "", "", fmt.Errorf("invalid artifact format: %s", artifactPath)
}
artifact = segments[0]
tag = segments[1]
fileName = segments[2]
} else {
segments := strings.SplitN(artifactPath, "/", 2)
if len(segments) < 2 {
return "", "", "", "", "", "", fmt.Errorf("invalid artifact format: %s", artifactPath)
}
artifact = segments[0]
tag = segments[1]
}
return rootIdentifier, registry, artifact, tag, fileName, description, nil
}
func handleErrors(ctx context.Context, err errcode.Error, w http.ResponseWriter) {
if !commons.IsEmptyError(err) {
w.WriteHeader(err.Code.Descriptor().HTTPStatusCode)
_ = errcode.ServeJSON(w, err)
log.Ctx(ctx).Error().Msgf("Error occurred while performing generic artifact action: %s", err.Message)
}
}
func validatePackageVersionV2(packageName, version string) error {
// Compile the regular expressions
// Validate package name
if !packageNameRe.MatchString(packageName) {
return usererror.BadRequestf("Invalid package name: %q. Should follow pattern: %q", packageName,
packageNameRegex)
}
// Validate version
if !versionV2Re.MatchString(version) {
return usererror.BadRequestf("Invalid version: %q. Should follow pattern: %q", version, versionRegexV2)
}
return nil
}
func validatePackageVersion(packageName, version string) error {
// Compile the regular expressions
// Validate package name
if !packageNameRe.MatchString(packageName) {
return usererror.BadRequestf("Invalid package name: %q. Should follow pattern: %q", packageName,
packageNameRegex)
}
// Validate version
if !versionRe.MatchString(version) {
return usererror.BadRequestf("Invalid version: %q. Should follow pattern: %q", version, versionRegex)
}
return nil
}
func validateFilePath(filePath string) error {
if !filePathRe.MatchString(filePath) {
return fmt.Errorf("invalid file path: %q, should follow pattern: %q", filePath, filePathRegex)
}
if path.Clean(filePath) != filePath {
return fmt.Errorf("relative segments not allowed in file path: %q", filePath)
}
parts := strings.SplitSeq(filePath, "/")
for e := range parts {
if e == "" || e == "." || e == ".." || filepath.IsAbs(e) {
return fmt.Errorf("unsafe path element: %q", e)
}
if strings.HasPrefix(e, "...") {
return fmt.Errorf("invalid path component detected: %q", e)
}
}
if filePath == "" || strings.HasPrefix(filePath, "/") {
return fmt.Errorf("invalid file path: [%s]", filePath)
}
if len(filePath) > maxFilePathLength {
return fmt.Errorf("file path too long: %s", filePath)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/base_test.go | registry/app/api/handler/generic/base_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 generic
import (
"strings"
"testing"
)
func TestValidateFilePath(t *testing.T) {
tests := []struct {
name string
filePath string
wantErr bool
errMsg string
}{
// Valid file paths
{
name: "simple filename",
filePath: "file.txt",
wantErr: false,
},
{
name: "filename with allowed characters",
filePath: "my-file_name.test@version.txt",
wantErr: false,
},
{
name: "nested path with allowed characters",
filePath: "folder/subfolder/file.txt",
wantErr: false,
},
{
name: "deep nested path",
filePath: "a/b/c/d/e/file.txt",
wantErr: false,
},
{
name: "filename with tilde",
filePath: "file~backup.txt",
wantErr: false,
},
{
name: "filename with at symbol",
filePath: "file@version.txt",
wantErr: false,
},
{
name: "filename with dash and underscore",
filePath: "my-file_name.txt",
wantErr: false,
},
{
name: "alphanumeric path",
filePath: "folder123/file456.txt",
wantErr: false,
},
// Invalid file paths - regex pattern violations
{
name: "empty string",
filePath: "",
wantErr: true,
},
{
name: "whitespace only",
filePath: " ",
wantErr: true,
},
{
name: "starts with slash",
filePath: "/file.txt",
wantErr: true,
},
{
name: "contains spaces",
filePath: "file name.txt",
wantErr: true,
errMsg: "invalid file path: \"file name.txt\", should follow pattern:",
},
{
name: "contains special characters",
filePath: "file!.txt",
wantErr: true,
errMsg: "invalid file path: \"file!.txt\", should follow pattern:",
},
{
name: "contains hash",
filePath: "file#.txt",
wantErr: true,
errMsg: "invalid file path: \"file#.txt\", should follow pattern:",
},
{
name: "contains percent",
filePath: "file%.txt",
wantErr: true,
errMsg: "invalid file path: \"file%.txt\", should follow pattern:",
},
{
name: "contains ampersand",
filePath: "file&.txt",
wantErr: true,
errMsg: "invalid file path: \"file&.txt\", should follow pattern:",
},
{
name: "contains asterisk",
filePath: "file*.txt",
wantErr: true,
errMsg: "invalid file path: \"file*.txt\", should follow pattern:",
},
{
name: "contains question mark",
filePath: "file?.txt",
wantErr: true,
errMsg: "invalid file path: \"file?.txt\", should follow pattern:",
},
{
name: "contains pipe",
filePath: "file|.txt",
wantErr: true,
errMsg: "invalid file path: \"file|.txt\", should follow pattern:",
},
{
name: "contains backslash",
filePath: "file\\.txt",
wantErr: true,
},
{
name: "contains colon",
filePath: "file:.txt",
wantErr: true,
errMsg: "invalid file path: \"file:.txt\", should follow pattern:",
},
{
name: "contains semicolon",
filePath: "file;.txt",
wantErr: true,
},
{
name: "contains quotes",
filePath: "file\".txt",
wantErr: true,
},
{
name: "contains single quote",
filePath: "file'.txt",
wantErr: true,
},
{
name: "contains less than",
filePath: "file<.txt",
wantErr: true,
},
{
name: "contains greater than",
filePath: "file>.txt",
wantErr: true,
errMsg: "invalid file path: \"file>.txt\", should follow pattern:",
},
// Invalid file paths - relative path segments
{
name: "current directory reference",
filePath: "./file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:",
},
{
name: "parent directory reference",
filePath: "../file.txt",
wantErr: true,
},
{
name: "current directory in middle",
filePath: "folder/./file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:",
},
{
name: "parent directory in middle",
filePath: "folder/../file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:",
},
{
name: "multiple relative segments",
filePath: "folder/../../file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:",
},
// Invalid file paths - unsafe path elements
{
name: "empty path segment",
filePath: "folder//file.txt",
wantErr: true,
},
{
name: "dot segment",
filePath: "folder/./file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:", // This will be caught by path.Clean first
},
{
name: "double dot segment",
filePath: "folder/../file.txt",
wantErr: true,
errMsg: "relative segments not allowed in file path:", // This will be caught by path.Clean first
},
// Invalid file paths - length validation
{
name: "path too long",
filePath: strings.Repeat("a", maxFilePathLength+1),
wantErr: true,
errMsg: "file path too long:",
},
{
name: "path at max length",
filePath: strings.Repeat("a", maxFilePathLength),
wantErr: false,
},
// Edge cases
{
name: "single character",
filePath: "a",
wantErr: false,
},
{
name: "single dot",
filePath: ".",
wantErr: true,
errMsg: "unsafe path element",
},
{
name: "double dots",
filePath: "..",
wantErr: true,
errMsg: "unsafe path element",
},
{
name: "trailing slash",
filePath: "folder/",
wantErr: true,
},
{
name: "multiple slashes",
filePath: "folder///file.txt",
wantErr: true,
},
// Valid edge cases with whitespace
{
name: "path with leading whitespace gets trimmed",
filePath: " file.txt",
wantErr: true,
},
{
name: "path with trailing whitespace gets trimmed",
filePath: "file.txt ",
wantErr: true,
},
{
name: "path with leading and trailing whitespace gets trimmed",
filePath: " file.txt ",
wantErr: true,
},
// Additional regex pattern tests
{
name: "starts with number",
filePath: "123file.txt",
wantErr: false,
},
{
name: "starts with letter",
filePath: "afile.txt",
wantErr: false,
},
{
name: "ends with number",
filePath: "file123",
wantErr: false,
},
{
name: "ends with letter",
filePath: "filea",
wantErr: false,
},
{
name: "mixed case",
filePath: "MyFile.TXT",
wantErr: false,
},
{
name: "exactly max length",
filePath: strings.Repeat("a", maxFilePathLength),
wantErr: false,
},
{
name: "one character over max length",
filePath: strings.Repeat("a", maxFilePathLength+1),
wantErr: true,
},
{
name: "long period",
filePath: ".........abc",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateFilePath(tt.filePath)
if tt.wantErr {
if err == nil {
t.Errorf("validateFilePath() expected error but got nil for input: %q", tt.filePath)
return
}
if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
t.Errorf("validateFilePath() error = %v, expected to contain %q", err, tt.errMsg)
}
} else if err != nil {
t.Errorf("validateFilePath() unexpected error = %v for input: %q", err, tt.filePath)
}
})
}
}
// TestValidateFilePathRegexPattern tests the regex pattern specifically.
func TestValidateFilePathRegexPattern(t *testing.T) {
validPaths := []string{
"file.txt",
"folder/file.txt",
"a/b/c/file.txt",
"my-file_name.test@version~backup.txt",
"123",
"a",
"file123",
"MyFile.TXT",
}
invalidPaths := []string{
"file name.txt", // space
"file!.txt", // exclamation
"file#.txt", // hash
"file$.txt", // dollar
"file%.txt", // percent
"file&.txt", // ampersand
"file*.txt", // asterisk
"file+.txt", // plus
"file=.txt", // equals
"file?.txt", // question mark
"file^.txt", // caret
"file|.txt", // pipe
"file\\.txt", // backslash
"file:.txt", // colon
"file;.txt", // semicolon
"file\".txt", // quote
"file'.txt", // single quote
"file<.txt", // less than
"file>.txt", // greater than
"file[.txt", // left bracket
"file].txt", // right bracket
"file{.txt", // left brace
"file}.txt", // right brace
"file(.txt", // left paren
"file).txt", // right paren
"file,.txt", // comma
}
for _, path := range validPaths {
t.Run("valid_regex_"+path, func(t *testing.T) {
if !filePathRe.MatchString(path) {
t.Errorf("filePathRe should match valid path: %q", path)
}
})
}
for _, path := range invalidPaths {
t.Run("invalid_regex_"+path, func(t *testing.T) {
if filePathRe.MatchString(path) {
t.Errorf("filePathRe should not match invalid path: %q", path)
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/delete_file_metadata.go | registry/app/api/handler/generic/delete_file_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
// DeleteFile handles file and metadata deletion requests.
func (h *Handler) DeleteFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Extract artifact info
info := request.ArtifactInfoFrom(ctx)
artifactInfo, ok := info.(generic.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get generic artifact info from context")
h.HandleError(ctx, w, fmt.Errorf("failed to fetch info from context"))
return
}
response := h.Controller.DeleteFile(ctx, artifactInfo)
if response.ResponseHeaders == nil || response.GetError() != nil {
log.Ctx(ctx).Error().Err(response.GetError()).Msg("failed to delete file")
h.HandleError(ctx, w, response.Error)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/put_file.go | registry/app/api/handler/generic/put_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
// PutFile handles file upload requests.
func (h *Handler) PutFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
artifactInfo := request.ArtifactInfoFrom(ctx)
info, ok := artifactInfo.(generic.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get generic artifact info from context")
h.HandleError(ctx, w, fmt.Errorf("failed to fetch info from context"))
return
}
contentType := r.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/octet-stream"
}
// Upload file
response := h.Controller.PutFile(ctx, info, r.Body, contentType)
if response.GetError() != nil {
log.Ctx(ctx).Error().Err(response.GetError()).Msg("failed to upload file")
h.HandleError(ctx, w, response.GetError())
return
}
// Set response headers
if response.ResponseHeaders != nil {
response.ResponseHeaders.WriteToResponse(w)
}
w.WriteHeader(http.StatusCreated)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/push_artifact.go | registry/app/api/handler/generic/push_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) PushArtifact(w http.ResponseWriter, r *http.Request) {
info, err := h.GetGenericArtifactInfo(r)
if !commons.IsEmptyError(err) {
handleErrors(r.Context(), err, w)
return
}
// Process the upload
ctx := r.Context()
headers, sha256, err := h.Controller.UploadArtifact(ctx, info, r)
if commons.IsEmptyError(err) {
headers.WriteToResponse(w)
_, err := fmt.Fprintf(w, "Pushed.\nSha256: %s", sha256)
if err != nil {
handleErrors(r.Context(), errcode.ErrCodeUnknown.WithDetail(err), w)
return
}
} else {
handleErrors(r.Context(), err, w)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/push_artifact_test.go | registry/app/api/handler/generic/push_artifact_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 generic
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
// Helper to create multipart request.
func createMultipartRequest(t *testing.T, filename, content string) *http.Request {
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
t.Fatal(err)
}
_, err = part.Write([]byte(content))
if err != nil {
t.Fatal(err)
}
err = writer.WriteField("filename", filename)
if err != nil {
t.Fatal(err)
}
err = writer.WriteField("description", "Test description")
if err != nil {
t.Fatal(err)
}
_ = writer.Close()
req := httptest.NewRequest(http.MethodPost, "/test", &buf)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req
}
func TestCreateMultipartRequest(t *testing.T) {
req := createMultipartRequest(t, "test.txt", "content")
assert.Equal(t, http.MethodPost, req.Method)
assert.Contains(t, req.Header.Get("Content-Type"), "multipart/form-data")
assert.NotNil(t, req.Body)
}
func TestHandler_Struct(t *testing.T) {
handler := &Handler{}
assert.NotNil(t, handler)
assert.Nil(t, handler.Controller)
assert.Nil(t, handler.SpaceStore)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/head_file.go | registry/app/api/handler/generic/head_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
// HeadFile handles HEAD requests for file metadata.
func (h *Handler) HeadFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info := request.ArtifactInfoFrom(ctx)
artifactInfo, ok := info.(generic.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get generic artifact info from context")
h.HandleError(ctx, w, fmt.Errorf("failed to fetch info from context"))
return
}
// Get file headers
response := h.Controller.HeadFile(ctx, artifactInfo, artifactInfo.FilePath)
if response.ResponseHeaders == nil || response.ResponseHeaders.Code == 0 {
log.Ctx(ctx).Error().Err(response.Error).Msg("failed to get file headers")
h.HandleError(ctx, w, response.Error)
return
}
// Set response headers
if response.ResponseHeaders != nil {
response.ResponseHeaders.WriteToResponse(w)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/generic/pull_artifact_test.go | registry/app/api/handler/generic/pull_artifact_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 generic
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/harness/gitness/registry/app/pkg"
"github.com/stretchr/testify/assert"
)
func TestPullArtifact_InvalidPath(t *testing.T) {
handler := &Handler{}
req := httptest.NewRequest(http.MethodGet, "/invalid", nil)
w := httptest.NewRecorder()
handler.PullArtifact(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
func TestServeContent_NilReader(t *testing.T) {
handler := &Handler{}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
info := pkg.GenericArtifactInfo{FileName: "test.txt"} //nolint:staticcheck // deprecated type
handler.serveContent(w, req, nil, info)
// Should not crash with nil reader
assert.Equal(t, http.StatusOK, w.Code)
}
func TestServeContent_ValidFilename(t *testing.T) {
handler := &Handler{}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
info := pkg.GenericArtifactInfo{FileName: "test.txt"} //nolint:staticcheck // deprecated type
handler.serveContent(w, req, nil, info)
// Should handle the call without crashing
assert.Equal(t, http.StatusOK, w.Code)
}
func TestServeContent_EmptyFilename(t *testing.T) {
handler := &Handler{}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
info := pkg.GenericArtifactInfo{FileName: ""} //nolint:staticcheck // deprecated type
handler.serveContent(w, req, nil, info)
// Should handle empty filename
assert.Equal(t, http.StatusOK, w.Code)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/pre_upload.go | registry/app/api/handler/huggingface/pre_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 huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) PreUpload(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.PreUpload(r.Context(), *info, r.Body)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/lfs_upload.go | registry/app/api/handler/huggingface/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 huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) LfsUpload(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.LfsUpload(ctx, *info, r.Body)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/wire.go | registry/app/api/handler/huggingface/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 huggingface
import (
"github.com/harness/gitness/registry/app/api/controller/pkg/huggingface"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/google/wire"
)
// WireSet provides a wire set for the huggingface package.
var WireSet = wire.NewSet(
ProvideHandler,
)
// ProvideHandler provides a huggingface handler.
func ProvideHandler(
controller huggingface.Controller,
packageHandler packages.Handler,
) Handler {
return NewHandler(
controller,
packageHandler,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/commit_revision.go | registry/app/api/handler/huggingface/commit_revision.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) CommitRevision(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.CommitRevision(ctx, *info, r.Body)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/validate_yaml.go | registry/app/api/handler/huggingface/validate_yaml.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) ValidateYAML(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.ValidateYaml(r.Context(), *info, r.Body)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/revision_info.go | registry/app/api/handler/huggingface/revision_info.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) RevisionInfo(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.RevisionInfo(r.Context(), *info, r.URL.Query())
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/download_file.go | registry/app/api/handler/huggingface/download_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"fmt"
"net/http"
"net/url"
"github.com/harness/gitness/registry/app/pkg/commons"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
filePath := r.PathValue("*")
decodedFilePath, err := url.PathUnescape(filePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to decode file path: %v", err)
h.HandleError(r.Context(), w, err)
return
}
response := h.controller.DownloadFile(ctx, *info, decodedFilePath)
defer func() {
if response != nil && response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
err = commons.ServeContent(w, r, response.Body, decodedFilePath, nil)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/head_file.go | registry/app/api/handler/huggingface/head_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"fmt"
"net/http"
"net/url"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) HeadFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
filePath := r.PathValue("*")
decodedFilePath, err := url.PathUnescape(filePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to decode file path: %v", err)
h.HandleError(r.Context(), w, err)
return
}
response := h.controller.HeadFile(r.Context(), *info, decodedFilePath)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/handler.go | registry/app/api/handler/huggingface/handler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/harness/gitness/registry/app/api/controller/metadata"
"github.com/harness/gitness/registry/app/api/controller/pkg/huggingface"
"github.com/harness/gitness/registry/app/api/handler/packages"
apicontract "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg"
hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
// Repo validation regex.
var (
repoIDMatcher = regexp.MustCompile(`^[a-zA-Z0-9](?:[a-zA-Z0-9_\-/]{0,126}[a-zA-Z0-9])?$`)
allowedTypes = map[string]bool{"model": true, "dataset": true}
)
// Handler defines the interface for Huggingface package operations.
type Handler interface {
pkg.ArtifactInfoProvider
ValidateYAML(writer http.ResponseWriter, request *http.Request)
LfsInfo(writer http.ResponseWriter, request *http.Request)
LfsUpload(writer http.ResponseWriter, request *http.Request)
LfsVerify(writer http.ResponseWriter, request *http.Request)
PreUpload(writer http.ResponseWriter, request *http.Request)
RevisionInfo(w http.ResponseWriter, r *http.Request)
CommitRevision(writer http.ResponseWriter, request *http.Request)
HeadFile(w http.ResponseWriter, r *http.Request)
DownloadFile(w http.ResponseWriter, r *http.Request)
}
// handler implements the Handler interface.
type handler struct {
packages.Handler
controller huggingface.Controller
}
// NewHandler creates a new Huggingface handler.
func NewHandler(
controller huggingface.Controller,
packageHandler packages.Handler,
) Handler {
return &handler{
Handler: packageHandler,
controller: controller,
}
}
var _ Handler = (*handler)(nil)
// GetPackageArtifactInfo retrieves artifact information from the request.
func (h *handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, err := h.Handler.GetArtifactInfo(r)
if err != nil {
return nil, err
}
repoType := chi.URLParam(r, "repoType")
repo := chi.URLParam(r, "repo")
rev := chi.URLParam(r, "rev")
sha256 := chi.URLParam(r, "sha256")
if repoType != "" {
repoType = strings.TrimSuffix(repoType, "s")
} else {
repoType = "model"
}
// Validate repoType
artifactType, err := metadata.ValidateAndGetArtifactType(apicontract.PackageTypeHUGGINGFACE, repoType)
if err != nil {
log.Ctx(r.Context()).Error().Msgf("unsupported repoType: %s with error: %v", repoType, err)
return nil, fmt.Errorf("unsupported repoType")
}
if !allowedTypes[repoType] {
log.Ctx(r.Context()).Error().Msgf("unsupported repoType: %s", repoType)
return nil, fmt.Errorf("unsupported repoType")
}
// Validate repoID
if repo != "" && !isValidRepoID(repo) {
log.Ctx(r.Context()).Error().Msgf("Invalid repo ID: %s", repo)
return nil, fmt.Errorf("invalid repo ID format")
}
// Set default revision if not provided
if rev == "" {
rev = "main"
}
info.Image = repo
return &hftype.ArtifactInfo{
ArtifactInfo: info,
Repo: repo,
Revision: rev,
RepoType: *artifactType,
SHA256: sha256,
}, nil
}
// isValidRepoID validates the format of a repo ID.
func isValidRepoID(repoID string) bool {
return repoIDMatcher.MatchString(repoID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/lfs_verify.go | registry/app/api/handler/huggingface/lfs_verify.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) LfsVerify(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.LfsVerify(r.Context(), *info, r.Body)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/huggingface/lfs_info.go | registry/app/api/handler/huggingface/lfs_info.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"encoding/json"
"fmt"
"net/http"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) LfsInfo(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*huggingfacetype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
token := r.Header.Get("Authorization")
response := h.controller.LfsInfo(ctx, *info, r.Body, token)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response.Response)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/swagger/swagger.go | registry/app/api/handler/swagger/swagger.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swagger
import (
"encoding/json"
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
httpswagger "github.com/swaggo/http-swagger"
)
type Handler interface {
http.Handler
}
func GetSwaggerHandler(base string) Handler {
r := chi.NewRouter()
// Generate OpenAPI specification
swagger, err := artifact.GetSwagger()
if err != nil {
panic(err)
}
// Serve the OpenAPI specification JSON
r.Get(
fmt.Sprintf("%s/swagger.json", base), http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
jsonResponse, _ := json.Marshal(swagger)
_, err2 := w.Write(jsonResponse)
if err2 != nil {
log.Error().Err(err2).Msg("Failed to write response")
}
},
),
)
r.Get(
fmt.Sprintf("%s/swagger/*", base), httpswagger.Handler(
httpswagger.URL(fmt.Sprintf("%s/swagger.json", base)), // The url pointing to API definition
),
)
return r
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/utils/request.go | registry/app/api/handler/utils/request.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
)
func GetFileReader(r *http.Request, formKey string) (*multipart.Part, string, error) {
reader, err := r.MultipartReader()
if err != nil {
return nil, "", err
}
for {
part, err := reader.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, "", err
}
if part.FormName() == formKey {
filename := part.FileName()
return part, filename, nil
}
}
return nil, "", fmt.Errorf("file not found in request")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/utils/jsonform.go | registry/app/api/handler/utils/jsonform.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/rs/zerolog/log"
)
// fillFromForm uses reflection to fill fields of 'data' from r.FormValue.
// It looks for a 'json' struct tag and uses that as the key in FormValue.
func FillFromForm(r *http.Request, data any) error {
// Make sure form data is parsed
if err := r.ParseForm(); err != nil {
return err
}
if err := r.ParseMultipartForm(32 << 22); err != nil {
return err
}
v := reflect.ValueOf(data).Elem()
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
jsonTag := field.Tag.Get("json")
if jsonTag == "" {
// Skip fields with no json tag
continue
}
// The tag might be `json:"author,omitempty"`, so split on comma to isolate the key
tagParts := strings.Split(jsonTag, ",")
key := tagParts[0]
// Single-value retrieval:
formVal := r.FormValue(key)
// Now decide how to set based on the field type
fieldVal := v.Field(i)
switch fieldVal.Kind() { // nolint:exhaustive
case reflect.String:
// Just set the string
fieldVal.SetString(formVal)
case reflect.Slice:
// Check if it's a slice of strings
if fieldVal.Type().Elem().Kind() == reflect.String {
// For slices, let's fetch all form values under that key
// e.g. name=foo&name=bar => r.Form["name"] = []string{"foo","bar"}
values := r.Form[key]
fieldVal.Set(reflect.ValueOf(values))
}
case reflect.Map:
// Check if it's a map[string]string
if fieldVal.Type().Key().Kind() == reflect.String && // nolint:nestif
fieldVal.Type().Elem().Kind() == reflect.String {
// We'll assume the form value is a JSON string. For example:
// extra={"foo":"bar","something":"else"}
if formVal == "" {
// If nothing is provided, just set an empty map
fieldVal.Set(reflect.ValueOf(map[string]string{}))
} else {
m := make(map[string]string)
if err := json.Unmarshal([]byte(formVal), &m); err != nil {
splitVal := strings.Split(formVal, ", ")
if len(splitVal) > 1 {
m[splitVal[0]] = splitVal[1]
} else {
return fmt.Errorf("cannot unmarshal map from key %q: %w", key, err)
}
}
fieldVal.Set(reflect.ValueOf(m))
}
}
default:
log.Warn().Ctx(r.Context()).Msgf("Unsupported field type %v", fieldVal.Kind())
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/utils/artifactfilter.go | registry/app/api/handler/utils/artifactfilter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"errors"
"fmt"
"regexp"
"github.com/lib/pq"
"github.com/rs/zerolog/log"
)
func PatternAllowed(allowedPattern pq.StringArray, blockedPattern pq.StringArray, artifact string) error {
allowedPatterns := []string(allowedPattern)
blockedPatterns := []string(blockedPattern)
if len(blockedPatterns) > 0 {
flag, err := matchPatterns(blockedPatterns, artifact)
if err != nil {
return fmt.Errorf(
"failed to match blocked patterns for artifact %s: %w",
artifact, err,
)
}
if flag {
return errors.New(
"failed because artifact matches blocked patterns configured on repository",
)
}
}
if len(allowedPatterns) > 0 {
flag, err := matchPatterns(allowedPatterns, artifact)
if err != nil {
return fmt.Errorf(
"failed to match allowed patterns for artifact %s: %w",
artifact, err,
)
}
if !flag {
return errors.New(
"failed because artifact doesn't match with allowed patterns configured on repository",
)
}
}
return nil
}
func matchPatterns(
patterns []string,
val string,
) (bool, error) {
for _, pattern := range patterns {
flag, err := regexp.MatchString(pattern, val)
if err != nil {
log.Error().Err(err).Msgf(
"failed to match pattern %s for val %s",
pattern,
val,
)
return flag, fmt.Errorf(
"failed to match pattern %s for val %s: %w",
pattern,
val,
err,
)
}
if flag {
return true, nil
}
}
return false, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/rpm/upload.go | registry/app/api/handler/rpm/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 rpm
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/api/handler/utils"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/request"
)
func (h *handler) UploadPackageFile(w http.ResponseWriter, r *http.Request) {
file, fileName, err := utils.GetFileReader(r, "file")
if err != nil {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage(fmt.Sprintf("failed to parse file: %s, "+
"please provide correct file path ", err.Error())), w)
return
}
defer file.Close()
contextInfo := request.ArtifactInfoFrom(r.Context())
info, ok := contextInfo.(*rpmtype.ArtifactInfo)
if !ok {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage("failed to fetch info from context"), w)
return
}
response := h.controller.UploadPackageFile(r.Context(), *info, *file, fileName)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
_, err = fmt.Fprintf(w, "Pushed.\nSha256: %s", response.Sha256)
if err != nil {
h.HandleError(r.Context(), w, err)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/rpm/handler.go | registry/app/api/handler/rpm/handler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpm
import (
"net/http"
"net/url"
"github.com/harness/gitness/registry/app/api/controller/pkg/rpm"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/pkg"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
)
type Handler interface {
pkg.ArtifactInfoProvider
UploadPackageFile(writer http.ResponseWriter, request *http.Request)
GetRepoData(writer http.ResponseWriter, request *http.Request)
DownloadPackageFile(http.ResponseWriter, *http.Request)
}
type handler struct {
packages.Handler
controller rpm.Controller
}
func NewHandler(
controller rpm.Controller,
packageHandler packages.Handler,
) Handler {
return &handler{
Handler: packageHandler,
controller: controller,
}
}
var _ Handler = (*handler)(nil)
func (h *handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, err := h.Handler.GetArtifactInfo(r)
if err != nil {
return nil, err
}
image, err := url.PathUnescape(r.PathValue("name"))
if err != nil {
return nil, err
}
info.Image = image
var version string
if r.PathValue("version") != "" && r.PathValue("architecture") != "" {
v, err := url.PathUnescape(r.PathValue("version"))
if err != nil {
return nil, err
}
version = v + "." + r.PathValue("architecture")
}
return &rpmtype.ArtifactInfo{
ArtifactInfo: info,
Version: version,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/rpm/repodata.go | registry/app/api/handler/rpm/repodata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpm
import (
"fmt"
"net/http"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/registry/app/pkg/commons"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetRepoData(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
contextInfo := request.ArtifactInfoFrom(ctx)
info, ok := contextInfo.(*rpmtype.ArtifactInfo)
if !ok {
render.TranslatedUserError(r.Context(), w, fmt.Errorf("invalid request context"))
return
}
fileName := r.PathValue("file")
packageData := h.controller.GetRepoData(r.Context(), *info, fileName)
if packageData == nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to get response from controller")}, w)
return
}
defer func() {
if packageData.Body != nil {
err := packageData.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if packageData.ReadCloser != nil {
err := packageData.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close read closer: %v", err)
}
}
}()
if packageData.GetError() != nil {
h.HandleError(ctx, w, packageData.GetError())
return
}
if packageData.RedirectURL != "" {
http.Redirect(w, r, packageData.RedirectURL, http.StatusTemporaryRedirect)
return
}
err := commons.ServeContent(w, r, packageData.Body, info.FileName, packageData.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
packageData.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/rpm/download.go | registry/app/api/handler/rpm/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 rpm
import (
"fmt"
"net/http"
"net/url"
"github.com/harness/gitness/registry/app/pkg/commons"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadPackageFile(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*rpmtype.ArtifactInfo)
if !ok {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
image, err := url.PathUnescape(r.PathValue("name"))
if err != nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to decode package name: %s", r.PathValue("name"))}, w)
return
}
info.Image = image
info.Arch = r.PathValue("architecture")
version, err := url.PathUnescape(r.PathValue("version"))
if err != nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to decode version: %s", r.PathValue("version"))}, w)
return
}
info.Version = version + "." + info.Arch
file, err := url.PathUnescape(r.PathValue("file"))
if err != nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to decode file name: %s", r.PathValue("file"))}, w)
return
}
info.FileName = file
packagePath, err := url.PathUnescape(r.PathValue("*"))
if err != nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to decode package path: %s", r.PathValue("*"))}, w)
return
}
info.PackagePath = packagePath
response := h.controller.DownloadPackageFile(ctx, *info)
if response == nil {
h.HandleErrors(ctx, []error{fmt.Errorf("failed to get response from controller")}, w)
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close read closer: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(ctx, w, response.GetError())
return
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
err = commons.ServeContent(w, r, response.Body, info.FileName, response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/gopackage/regenerate_package_metadata.go | registry/app/api/handler/gopackage/regenerate_package_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"encoding/json"
"fmt"
"net/http"
"strings"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/request"
)
func (h *handler) RegeneratePackageMetadata(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*gopackagetype.ArtifactInfo)
if !ok {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to fetch info from context"))
return
}
info.Image = strings.Trim(r.URL.Query().Get("image"), "'")
info.Version = strings.Trim(r.URL.Query().Get("version"), "'")
if info.Image == "" || info.Version == "" {
h.handleGoPackageAPIError(w, r, fmt.Errorf("image and version are required"))
return
}
// regenerate package metadata
response := h.controller.RegeneratePackageMetadata(ctx, info)
if response.GetError() != nil {
h.handleGoPackageAPIError(
w, r, fmt.Errorf("failed to regenerate package metadata: %w", response.GetError()),
)
return
}
// Final response
w.Header().Set("Content-Type", "application/json")
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response)
if err != nil {
h.handleGoPackageAPIError(w, r,
fmt.Errorf(
"error occurred during sending response for regenerate package metadata for go package: %w", err,
),
)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/gopackage/download_package_file.go | registry/app/api/handler/gopackage/download_package_file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadPackageFile(
w http.ResponseWriter, r *http.Request,
) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*gopackagetype.ArtifactInfo)
if !ok {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to fetch info from context"))
return
}
response := h.controller.DownloadPackageFile(ctx, info)
if response == nil {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to get response from controller"))
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close read closer: %v", err)
}
}
}()
if response.GetError() != nil {
h.handleGoPackageAPIError(w, r, response.GetError())
return
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
err := commons.ServeContent(w, r, response.Body, info.FileName, response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to serve content: %w", err))
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/gopackage/regenerate_package_index.go | registry/app/api/handler/gopackage/regenerate_package_index.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"encoding/json"
"fmt"
"net/http"
"strings"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/request"
)
func (h *handler) RegeneratePackageIndex(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*gopackagetype.ArtifactInfo)
if !ok {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to fetch info from context"))
return
}
info.Image = strings.Trim(r.URL.Query().Get("image"), "'")
if info.Image == "" {
h.handleGoPackageAPIError(w, r, fmt.Errorf("image is required"))
return
}
// regenerate package index
response := h.controller.RegeneratePackageIndex(ctx, info)
if response.GetError() != nil {
h.handleGoPackageAPIError(
w, r, fmt.Errorf("failed to regenerate package index: %w", response.GetError()),
)
return
}
// Final response
w.Header().Set("Content-Type", "application/json")
response.ResponseHeaders.WriteToResponse(w)
err := json.NewEncoder(w).Encode(response)
if err != nil {
h.handleGoPackageAPIError(w, r,
fmt.Errorf("error occurred during sending response for regenerate package index for go package: %w", err),
)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/gopackage/handler.go | registry/app/api/handler/gopackage/handler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"strings"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/registry/app/api/controller/pkg/gopackage"
"github.com/harness/gitness/registry/app/api/handler/packages"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/gopackage/utils"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
)
var ValidDownloadPaths = []string{
"/@latest",
"/@v/",
}
type Handler interface {
pkg.ArtifactInfoProvider
UploadPackage(writer http.ResponseWriter, request *http.Request)
DownloadPackageFile(writer http.ResponseWriter, request *http.Request)
RegeneratePackageIndex(writer http.ResponseWriter, request *http.Request)
RegeneratePackageMetadata(writer http.ResponseWriter, request *http.Request)
}
type handler struct {
packages.Handler
controller gopackage.Controller
}
func NewHandler(
controller gopackage.Controller,
packageHandler packages.Handler,
) Handler {
return &handler{
Handler: packageHandler,
controller: controller,
}
}
var _ Handler = (*handler)(nil)
func (h *handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, err := h.Handler.GetArtifactInfo(r)
if err != nil {
return nil, err
}
var version, filename string
image := r.PathValue("name")
path := r.PathValue("*")
if path != "" {
isValidPath := h.validatePathForDownload(path)
if !isValidPath {
return nil, usererror.NotFoundf("path not found: %s", path)
}
image, version, filename, err = utils.GetArtifactInfoFromURL(path)
if err != nil {
return nil, usererror.BadRequest(fmt.Sprintf("image and version not found in path %s: %s", path, err.Error()))
}
}
info.Image = image
return &gopackagetype.ArtifactInfo{
ArtifactInfo: info,
Version: version,
FileName: filename,
}, nil
}
func (h *handler) validatePathForDownload(path string) bool {
for _, validPath := range ValidDownloadPaths {
if strings.Contains(path, validPath) {
return true
}
}
return false
}
func (h *handler) handleGoPackageAPIError(writer http.ResponseWriter, request *http.Request, err error) {
h.HandleError(request.Context(), writer, err)
}
func (h *handler) parseDataFromPayload(r *http.Request) (*bytes.Buffer, *bytes.Buffer, io.ReadCloser, error) {
var (
infoBytes = &bytes.Buffer{}
modBytes = &bytes.Buffer{}
zipRC *multipart.Part
)
reader, err := r.MultipartReader()
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading multipart: %w", err)
}
for infoBytes.Len() <= 0 || modBytes.Len() <= 0 || zipRC == nil {
part, err := reader.NextPart()
if err == io.EOF {
break
}
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading multipart: %w", err)
}
switch part.FormName() {
case "info":
if _, err := io.Copy(infoBytes, part); err != nil {
return nil, nil, nil, fmt.Errorf("error reading 'info': %w", err)
}
part.Close()
case "mod":
if _, err := io.Copy(modBytes, part); err != nil {
return nil, nil, nil, fmt.Errorf("error reading 'mod': %w", err)
}
part.Close()
case "zip":
zipRC = part
default:
part.Close()
}
}
if infoBytes.Len() == 0 {
return nil, nil, nil, fmt.Errorf("'info' part not found")
}
if modBytes.Len() == 0 {
return nil, nil, nil, fmt.Errorf("'mod' part not found")
}
if zipRC == nil {
return nil, nil, nil, fmt.Errorf("'zip' part not found")
}
return infoBytes, modBytes, zipRC, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/gopackage/upload_package.go | registry/app/api/handler/gopackage/upload_package.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/registry/app/pkg/gopackage/utils"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/request"
)
func (h *handler) UploadPackage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*gopackagetype.ArtifactInfo)
if !ok {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to fetch info from context"))
return
}
// parse metadata, info, mod and zip files
infoBytes, modBytes, zipRC, err := h.parseDataFromPayload(r)
if err != nil {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to parse data from payload: %w", err))
return
}
// get package metadata from info file
metadata, err := utils.GetPackageMetadataFromInfoFile(infoBytes)
if err != nil {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to get package metadata from info file: %w", err))
return
}
// get module name from mod file
moduleName, err := utils.GetModuleNameFromModFile(bytes.NewReader(modBytes.Bytes()))
if err != nil {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to get module name from mod file: %w", err))
return
}
metadata.Name = moduleName
// update artifact info with required data
info.Metadata = metadata
info.Version = metadata.Version
info.Image = metadata.Name
modRC := io.NopCloser(bytes.NewReader(modBytes.Bytes()))
defer modRC.Close()
defer zipRC.Close()
// upload package
response := h.controller.UploadPackage(ctx, info, modRC, zipRC)
if response.GetError() != nil {
h.handleGoPackageAPIError(w, r, fmt.Errorf("failed to upload package: %w", response.GetError()))
return
}
// Final response
w.Header().Set("Content-Type", "application/json")
response.ResponseHeaders.WriteToResponse(w)
err = json.NewEncoder(w).Encode(response)
if err != nil {
h.handleGoPackageAPIError(w, r,
fmt.Errorf("error occurred during sending response for upload package for go package: %w", err),
)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/maven/base.go | registry/app/api/handler/maven/base.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
usercontroller "github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/registry/app/api/controller/metadata"
"github.com/harness/gitness/registry/app/api/handler/utils"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/maven"
mavenutils "github.com/harness/gitness/registry/app/pkg/maven/utils"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
type Handler struct {
Controller *maven.Controller
SpaceStore corestore.SpaceStore
TokenStore corestore.TokenStore
UserCtrl *usercontroller.Controller
Authenticator authn.Authenticator
Authorizer authz.Authorizer
SpaceFinder refcache.SpaceFinder
PublicAccessService publicaccess.Service
}
func NewHandler(
controller *maven.Controller, spaceStore corestore.SpaceStore, tokenStore corestore.TokenStore,
userCtrl *usercontroller.Controller, authenticator authn.Authenticator, authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder, publicAccessService publicaccess.Service,
) *Handler {
return &Handler{
Controller: controller,
SpaceStore: spaceStore,
TokenStore: tokenStore,
UserCtrl: userCtrl,
Authenticator: authenticator,
Authorizer: authorizer,
SpaceFinder: spaceFinder,
PublicAccessService: publicAccessService,
}
}
var (
illegalCharacters = regexp.MustCompile(`[\\/:"<>|?\*]`)
invalidPathFormat = "invalid path format: %s"
)
func (h *Handler) GetArtifactInfo(r *http.Request, remoteSupport bool) (pkg.MavenArtifactInfo, error) {
ctx := r.Context()
path := r.URL.Path
rootIdentifier, registryIdentifier, groupID, artifactID, version, fileName, err := ExtractPathVars(path)
if err != nil {
return pkg.MavenArtifactInfo{}, err
}
if err = metadata.ValidateIdentifier(registryIdentifier); err != nil {
return pkg.MavenArtifactInfo{}, err
}
rootSpaceID, err := h.SpaceStore.FindByRefCaseInsensitive(ctx, rootIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root spaceID not found: %s", rootIdentifier)
return pkg.MavenArtifactInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
rootSpace, err := h.SpaceFinder.FindByID(ctx, rootSpaceID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root space not found: %d", rootSpaceID)
return pkg.MavenArtifactInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
registry, err := h.Controller.DBStore.RegistryDao.GetByRootParentIDAndName(ctx, rootSpace.ID, registryIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf(
"registry %s not found for root: %s. Reason: %s", registryIdentifier, rootSpace.Identifier, err,
)
return pkg.MavenArtifactInfo{}, errcode.ErrCodeRegNotFound
}
_, err = h.SpaceFinder.FindByID(r.Context(), registry.ParentID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Parent space not found: %d", registry.ParentID)
return pkg.MavenArtifactInfo{}, errcode.ErrCodeParentNotFound
}
pathRoot := getPathRoot(r.Context())
info := &pkg.MavenArtifactInfo{
ArtifactInfo: &pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
PathRoot: pathRoot,
RootIdentifier: rootIdentifier,
RootParentID: rootSpace.ID,
ParentID: registry.ParentID,
},
Registry: *registry,
RegIdentifier: registryIdentifier,
RegistryID: registry.ID,
Image: groupID + ":" + artifactID,
},
GroupID: groupID,
ArtifactID: artifactID,
Version: version,
FileName: fileName,
Path: r.URL.Path,
}
log.Ctx(ctx).Info().Msgf("Dispatch: URI: %s", path)
if commons.IsEmpty(rootSpace.Identifier) {
log.Ctx(ctx).Error().Msgf("ParentRef not found in context")
return pkg.MavenArtifactInfo{}, errcode.ErrCodeParentNotFound
}
if commons.IsEmpty(registryIdentifier) {
log.Ctx(ctx).Warn().Msgf("registry not found in context")
return pkg.MavenArtifactInfo{}, errcode.ErrCodeRegNotFound
}
if !commons.IsEmpty(info.GroupID) && !commons.IsEmpty(info.ArtifactID) && !commons.IsEmpty(info.Version) {
err2 := utils.PatternAllowed(registry.AllowedPattern, registry.BlockedPattern,
info.GroupID+":"+info.ArtifactID+":"+info.Version)
if err2 != nil {
return pkg.MavenArtifactInfo{}, errcode.ErrCodeDenied
}
}
if registry.Type == artifact.RegistryTypeUPSTREAM && !remoteSupport {
log.Ctx(ctx).Warn().Msgf("Remote registryIdentifier %s not supported", registryIdentifier)
return pkg.MavenArtifactInfo{}, errcode.ErrCodeDenied
}
return *info, nil
}
// ExtractPathVars extracts registry, groupId, artifactId, version and tag from the path
// Path format: /maven/:rootSpace/:registry/:groupId/artifactId/:version/:filename (for ex:
// /maven/myRootSpace/reg1/io/example/my-app/1.0/my-app-1.0.jar.
func ExtractPathVars(path string) (rootIdentifier, registry, groupID, artifactID, version, fileName string, err error) {
path = strings.Trim(path, "/")
segments := strings.Split(path, "/")
if len(segments) < 6 {
err = fmt.Errorf(invalidPathFormat, path)
return "", "", "", "", "", "", err
}
rootIdentifier = segments[1]
registry = segments[2]
fileName = segments[len(segments)-1]
if segments[0] == "pkg" {
segments = segments[4 : len(segments)-1]
} else {
segments = segments[3 : len(segments)-1]
}
version = segments[len(segments)-1]
if mavenutils.IsMetadataFile(fileName) && !strings.HasSuffix(version, "-SNAPSHOT") {
version = ""
} else {
segments = segments[:len(segments)-1]
if len(segments) < 2 {
err = fmt.Errorf(invalidPathFormat, path)
return rootIdentifier, registry, groupID, artifactID, version, fileName, err
}
}
artifactID = segments[len(segments)-1]
groupID = strings.Join(segments[:len(segments)-1], ".")
if illegalCharacters.MatchString(groupID) || illegalCharacters.MatchString(artifactID) ||
illegalCharacters.MatchString(version) {
err = fmt.Errorf(invalidPathFormat, path)
return rootIdentifier, registry, groupID, artifactID, version, fileName, err
}
return rootIdentifier, registry, groupID, artifactID, version, fileName, nil
}
func getPathRoot(ctx context.Context) string {
originalURL := request.OriginalPathFrom(ctx)
pathRoot := ""
if originalURL != "" {
originalURL = strings.Trim(originalURL, "/")
segments := strings.Split(originalURL, "/")
if len(segments) > 1 {
pathRoot = segments[1]
}
}
return pathRoot
}
func handleErrors(ctx context.Context, errs errcode.Errors, w http.ResponseWriter, headers *commons.ResponseHeaders) {
if !commons.IsEmpty(errs) {
LogError(errs)
log.Ctx(ctx).Error().Errs("errs occurred during maven operation: ", errs).Msgf("Error occurred")
err := errs[0]
var e *commons.Error
switch {
case headers != nil:
headers.WriteToResponse(w)
case errors.As(err, &e):
code := e.Status
w.WriteHeader(code)
default:
render.TranslatedUserError(ctx, w, err)
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(errs)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Error occurred during maven error encoding")
}
}
}
func LogError(errList errcode.Errors) {
for _, e1 := range errList {
log.Error().Err(e1).Msgf("error: %v", e1)
}
}
func (h *Handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, e := h.GetArtifactInfo(r, true)
if e != nil {
return pkg.MavenArtifactInfo{}, e
}
artifactInfo := info.ArtifactInfo
artifactInfo.PathPackageType = artifact.PackageTypeMAVEN
return pkg.MavenArtifactInfo{
ArtifactInfo: artifactInfo,
Version: info.Version,
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/maven/put_artifact.go | registry/app/api/handler/maven/put_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"bytes"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) PutArtifact(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetArtifactInfo(r, true)
if err != nil {
handleErrors(ctx, []error{err}, w, nil)
return
}
result := h.Controller.PutArtifact(ctx, info, r.Body)
if !commons.IsEmpty(result.GetErrors()) {
handleErrors(ctx, result.GetErrors(), w, result.ResponseHeaders)
return
}
result.ResponseHeaders.WriteToResponse(w)
}
type ReaderFile struct {
*bytes.Buffer
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/maven/get_artifact.go | registry/app/api/handler/maven/get_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"errors"
"io"
"net/http"
"time"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/maven"
"github.com/rs/zerolog/log"
)
func (h *Handler) GetArtifact(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetArtifactInfo(r, true)
if err != nil {
handleErrors(ctx, []error{err}, w, nil)
return
}
response := h.Controller.GetArtifact(
ctx,
info,
)
if !commons.IsEmpty(response.GetErrors()) {
handleErrors(ctx, response.GetErrors(), w, response.ResponseHeaders)
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close readCloser: %v", err)
}
}
}()
if !commons.IsEmpty(response.RedirectURL) {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
response.ResponseHeaders.WriteHeadersToResponse(w)
h.serveContent(w, r, response, info)
response.ResponseHeaders.WriteToResponse(w)
}
func (h *Handler) serveContent(
w http.ResponseWriter, r *http.Request, response *maven.GetArtifactResponse, info pkg.MavenArtifactInfo,
) {
if response.Body != nil {
http.ServeContent(w, r, info.FileName, time.Time{}, response.Body)
} else {
w.Header().Set("Transfer-Encoding", "chunked")
_, err2 := io.Copy(w, response.ReadCloser)
if err2 != nil {
response.Errors = append(response.Errors, errors.New("error copying file to response"))
log.Ctx(r.Context()).Error().Msg("error copying file to response:")
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/maven/head_artifact.go | registry/app/api/handler/maven/head_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) HeadArtifact(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetArtifactInfo(r, true)
if err != nil {
handleErrors(ctx, []error{err}, w, nil)
return
}
result := h.Controller.HeadArtifact(
ctx,
info,
)
if !commons.IsEmpty(result.GetErrors()) {
handleErrors(ctx, result.GetErrors(), w, result.ResponseHeaders)
return
}
result.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/delete_blob.go | registry/app/api/handler/oci/delete_blob.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) DeleteBlob(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
headers, errs := h.Controller.DeleteBlob(r.Context(), info)
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_base.go | registry/app/api/handler/oci/get_base.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
)
func (h *Handler) APIBase(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/registry/app/api/handler/oci/delete_manifest.go | registry/app/api/handler/oci/delete_manifest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/rs/zerolog/log"
)
// DeleteManifest a manifest from the registry.
func (h *Handler) DeleteManifest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
length := r.ContentLength
if length > 0 {
r.Body = http.MaxBytesReader(w, r.Body, length)
}
errs, headers := h.Controller.DeleteManifest(r.Context(), info)
if !commons.IsEmpty(errs) {
log.Ctx(ctx).Error().Msgf("DeleteManifest: %v", errs)
}
if headers != nil {
headers.WriteToResponse(w)
}
handleErrors(ctx, errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/base.go | registry/app/api/handler/oci/base.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"context"
"net/http"
"strings"
usercontroller "github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/auth/authn"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/publicaccess"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/handler/utils"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/common"
"github.com/harness/gitness/registry/app/dist_temp/dcontext"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/docker"
refcache2 "github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/request"
v2 "github.com/distribution/distribution/v3/registry/api/v2"
"github.com/opencontainers/go-digest"
"github.com/rs/zerolog/log"
)
func NewHandler(
controller *docker.Controller,
spaceFinder refcache.SpaceFinder,
spaceStore corestore.SpaceStore,
tokenStore corestore.TokenStore,
userCtrl *usercontroller.Controller,
authenticator authn.Authenticator,
urlProvider urlprovider.Provider,
authorizer authz.Authorizer,
ociRelativeURL bool,
registryFinder refcache2.RegistryFinder,
publicAccessService publicaccess.Service,
anonymousUserSecret string,
) *Handler {
return &Handler{
Controller: controller,
SpaceFinder: spaceFinder,
SpaceStore: spaceStore,
TokenStore: tokenStore,
UserCtrl: userCtrl,
Authenticator: authenticator,
URLProvider: urlProvider,
Authorizer: authorizer,
registryFinder: registryFinder,
OCIRelativeURL: ociRelativeURL,
PublicAccessService: publicAccessService,
AnonymousUserSecret: anonymousUserSecret,
}
}
type Handler struct {
Controller *docker.Controller
SpaceFinder refcache.SpaceFinder
SpaceStore corestore.SpaceStore
TokenStore corestore.TokenStore
UserCtrl *usercontroller.Controller
Authenticator authn.Authenticator
URLProvider urlprovider.Provider
Authorizer authz.Authorizer
registryFinder refcache2.RegistryFinder
OCIRelativeURL bool
PublicAccessService publicaccess.Service
AnonymousUserSecret string
}
type routeType string
const (
Manifests routeType = "manifests" // /v2/:registry/:image/manifests/:reference.
Blobs routeType = "blobs" // /v2/:registry/:image/blobs/:digest.
BlobsUploadsSession routeType = "blob-uploads-session" // /v2/:registry/:image/blobs/uploads/:session_id.
Tags routeType = "tags" // /v2/:registry/:image/tags/list.
Referrers routeType = "referrers" // /v2/:registry/:image/referrers/:digest.
Invalid routeType = "invalid" // Invalid route.
MinSizeOfURLSegments = 5
APIPartManifest = "manifests"
APIPartBlobs = "blobs"
APIPartUpload = "uploads"
APIPartTag = "tags"
APIPartReferrer = "referrers"
// Add other route types here.
)
func getRouteType(url string) routeType {
url = strings.Trim(url, "/")
segments := strings.Split(url, "/")
if len(segments) < MinSizeOfURLSegments {
return Invalid
}
typ := segments[len(segments)-2]
switch typ {
case APIPartManifest:
return Manifests
case APIPartBlobs:
if segments[len(segments)-1] == APIPartUpload {
return BlobsUploadsSession
}
return Blobs
case APIPartUpload:
return BlobsUploadsSession
case APIPartTag:
return Tags
case APIPartReferrer:
return Referrers
}
return Invalid
}
// ExtractPathVars extracts registry, image, reference, digest and tag from the path
// Path format: /v2/:rootSpace/:registry/:image/manifests/:reference (for ex:
// /v2/myRootSpace/reg1/alpine/blobs/sha256:a258b2a6b59a7aa244d8ceab095c7f8df726f27075a69fca7ad8490f3f63148a).
func ExtractPathVars(
ctx context.Context,
path string,
paramMap map[string]string,
) (rootIdentifier, registry, image, ref, dgst, tag string) {
path = strings.Trim(path, "/")
segments := strings.Split(path, "/")
if len(segments) < MinSizeOfURLSegments {
log.Ctx(ctx).Error().Msgf("Invalid route: %s", path)
return "", "", "", "", "", ""
}
rootIdentifier = segments[1]
registry = segments[2]
image = strings.Join(segments[3:len(segments)-2], "/")
typ := getRouteType(path)
switch typ {
case Manifests:
ref = segments[len(segments)-1]
_, err := digest.Parse(ref)
if err != nil {
tag = ref
} else {
dgst = ref
}
case Blobs:
dgst = segments[len(segments)-1]
case BlobsUploadsSession:
if segments[len(segments)-1] != APIPartUpload && segments[len(segments)-2] == APIPartUpload {
image = strings.Join(segments[3:len(segments)-3], "/")
ref = segments[len(segments)-1]
}
if _, ok := paramMap["digest"]; ok {
dgst = paramMap["digest"]
}
case Tags:
// do nothing.
case Referrers:
dgst = segments[len(segments)-1]
case Invalid:
log.Ctx(ctx).Warn().Msgf("Invalid route: %s", path)
default:
log.Ctx(ctx).Warn().Msgf("Unknown route type: %s", typ)
}
log.Ctx(ctx).Debug().Msgf(
"For path: %s, rootIdentifier: %s, registry: %s, image: %s, ref: %s, dgst: %s, tag: %s",
path, rootIdentifier, registry, image, ref, dgst, tag,
)
return rootIdentifier, registry, image, ref, dgst, tag
}
func handleErrors(ctx context.Context, errors errcode.Errors, w http.ResponseWriter) {
if !commons.IsEmpty(errors) {
_ = errcode.ServeJSON(w, errors)
docker.LogError(errors)
log.Ctx(ctx).Error().Errs("OCI errors", errors).Msgf("Error occurred")
} else if status, ok := ctx.Value("http.response.status").(int); ok && status >= 200 && status <= 399 {
dcontext.GetResponseLogger(ctx, log.Info()).Msg("response completed")
}
}
func getPathRoot(ctx context.Context) string {
originalURL := request.OriginalPathFrom(ctx)
pathRoot := ""
if originalURL != "" {
originalURL = strings.Trim(originalURL, "/")
segments := strings.Split(originalURL, "/")
if len(segments) > 1 {
pathRoot = segments[1]
}
}
return pathRoot
}
func (h *Handler) GetRegistryInfo(r *http.Request, remoteSupport bool) (pkg.RegistryInfo, error) {
ctx := r.Context()
queryParams := r.URL.Query()
path := r.URL.Path
paramMap := common.ExtractFirstQueryParams(queryParams)
rootIdentifier, registryIdentifier, image, ref, dgst, tag := ExtractPathVars(r.Context(), path, paramMap)
// Skip rootIdentifier validation since it may not be OCI compliant. We do modifications on it before it reaches here.
rootSpaceID, err := h.SpaceStore.FindByRefCaseInsensitive(ctx, rootIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root spaceID not found: %s", rootIdentifier)
return pkg.RegistryInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
rootSpace, err := h.SpaceFinder.FindByID(ctx, rootSpaceID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Root space not found: %d", rootSpaceID)
return pkg.RegistryInfo{}, errcode.ErrCodeRootNotFound.WithDetail(err)
}
registry, err := h.registryFinder.FindByRootParentID(ctx, rootSpaceID, registryIdentifier)
if err != nil {
log.Ctx(ctx).Error().Msgf(
"registry %s not found for root: %s. Reason: %s", registryIdentifier, rootSpace.Identifier, err,
)
return pkg.RegistryInfo{}, errcode.ErrCodeRegNotFound
}
_, err = h.SpaceFinder.FindByID(r.Context(), registry.ParentID)
if err != nil {
log.Ctx(ctx).Error().Msgf("Parent space not found: %d", registry.ParentID)
return pkg.RegistryInfo{}, errcode.ErrCodeParentNotFound
}
pathRoot := getPathRoot(r.Context())
info := &pkg.RegistryInfo{
ArtifactInfo: &pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
PathRoot: pathRoot,
RootIdentifier: rootIdentifier,
RootParentID: rootSpace.ID,
ParentID: registry.ParentID,
},
RegIdentifier: registryIdentifier,
Image: image,
Registry: *registry,
},
Reference: ref,
Digest: dgst,
Tag: tag,
URLBuilder: v2.NewURLBuilderFromRequest(r, h.OCIRelativeURL),
Path: r.URL.Path,
PackageType: registry.PackageType,
}
log.Ctx(ctx).Info().Msgf("Dispatch: URI: %s", path)
if commons.IsEmpty(rootSpace.Identifier) {
log.Ctx(ctx).Error().Msgf("ParentRef not found in context")
return pkg.RegistryInfo{}, errcode.ErrCodeParentNotFound
}
if commons.IsEmpty(registryIdentifier) {
log.Ctx(ctx).Warn().Msgf("registry not found in context")
return pkg.RegistryInfo{}, errcode.ErrCodeRegNotFound
}
if !commons.IsEmpty(info.Image) && !commons.IsEmpty(info.Tag) {
err2 := utils.PatternAllowed(registry.AllowedPattern, registry.BlockedPattern, info.Image+":"+info.Tag)
if err2 != nil {
return pkg.RegistryInfo{}, errcode.ErrCodeDenied
}
}
if registry.Type == artifact.RegistryTypeUPSTREAM && !remoteSupport {
log.Ctx(ctx).Warn().Msgf("Remote registryIdentifier %s not supported", registryIdentifier)
return pkg.RegistryInfo{}, errcode.ErrCodeDenied
}
return *info, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_manifest.go | registry/app/api/handler/oci/get_manifest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/app/storage"
"github.com/rs/zerolog/log"
)
// GetManifest fetches the image manifest from the storage backend, if it exists.
func (h *Handler) GetManifest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetRegistryInfo(r, true)
if err != nil {
handleErrors(ctx, errcode.Errors{err}, w)
return
}
result := h.Controller.PullManifest(
ctx,
info,
r.Header[storage.HeaderAccept],
r.Header[storage.HeaderIfNoneMatch],
)
if commons.IsEmpty(result.GetErrors()) {
response, ok := result.(*docker.GetManifestResponse)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to cast result to GetManifestResponse")
return
}
response.ResponseHeaders.WriteToResponse(w)
if response.ResponseHeaders.Code == http.StatusMovedPermanently {
return
}
_, bytes, _ := response.Manifest.Payload()
if _, err := w.Write(bytes); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to write response")
response.ResponseHeaders.Code = http.StatusInternalServerError
}
return
}
handleErrors(ctx, result.GetErrors(), w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/put_manifest.go | registry/app/api/handler/oci/put_manifest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/rs/zerolog/log"
)
const (
maxManifestBodySize = 4 * 1024 * 1024
)
// PutManifest validates and stores a manifest in the registry.
func (h *Handler) PutManifest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
mediaType := r.Header.Get("Content-Type")
length := r.ContentLength
r.Body = http.MaxBytesReader(w, r.Body, maxManifestBodySize)
headers, errs := h.Controller.PutManifest(r.Context(), info, mediaType, r.Body, length)
if !commons.IsEmpty(errs) {
log.Ctx(ctx).Error().Errs("Failed to Put manifest", errs).Msg("Failed to Put manifest")
}
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(ctx, errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/delete_blob_upload.go | registry/app/api/handler/oci/delete_blob_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 oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) CancelBlobUpload(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
headers, errs := h.Controller.CancelBlobUpload(r.Context(), info, r.FormValue("_state"))
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_referrers.go | registry/app/api/handler/oci/get_referrers.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"encoding/json"
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
)
func (h *Handler) GetReferrers(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
defer r.Body.Close()
errorsList := make(errcode.Errors, 0)
index, responseHeaders, err := h.Controller.GetReferrers(r.Context(), info, r.URL.Query().Get("artifactType"))
if err != nil {
errorsList = append(errorsList, err)
}
if index != nil {
responseHeaders.WriteHeadersToResponse(w)
if err := json.NewEncoder(w).Encode(index); err != nil {
errorsList = append(errorsList, errcode.ErrCodeUnknown.WithDetail(err))
}
}
handleErrors(r.Context(), errorsList, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_blob.go | registry/app/api/handler/oci/get_blob.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/rs/zerolog/log"
)
func (h *Handler) GetBlob(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetRegistryInfo(r, true)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
result := h.Controller.GetBlob(ctx, info)
response, ok := result.(*docker.GetBlobResponse)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to cast result to GetBlobResponse")
handleErrors(ctx, []error{errors.New("failed to cast result to GetBlobResponse")}, w)
return
}
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close readCloser: %v", err)
}
}
}()
if commons.IsEmpty(response.GetErrors()) {
if !commons.IsEmpty(response.RedirectURL) {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
if response.ResponseHeaders != nil && response.ResponseHeaders.Code == http.StatusMovedPermanently {
response.ResponseHeaders.WriteToResponse(w)
return
}
response.ResponseHeaders.WriteHeadersToResponse(w)
if r.Method == http.MethodHead {
return
}
h.serveContent(w, r, response, info)
response.ResponseHeaders.WriteToResponse(w)
}
handleErrors(r.Context(), response.GetErrors(), w)
}
func (h *Handler) serveContent(
w http.ResponseWriter, r *http.Request, response *docker.GetBlobResponse, info pkg.RegistryInfo,
) {
if response.Body != nil {
http.ServeContent(w, r, info.Digest, time.Time{}, response.Body)
} else {
// Use io.CopyN to avoid out of memory when pulling big blob
written, err2 := io.CopyN(w, response.ReadCloser, response.Size)
if err2 != nil {
response.Errors = append(response.Errors, errors.New("error copying blob to response"))
log.Ctx(r.Context()).Error().Msg("error copying blob to response:")
}
if written != response.Size {
response.Errors = append(
response.Errors,
//nolint:staticcheck
fmt.Errorf("The size mismatch, actual:%d, expected: %d", written, response.Size),
)
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/head_blob.go | registry/app/api/handler/oci/head_blob.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) HeadBlob(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
headers, errs := h.Controller.HeadBlob(r.Context(), info)
if commons.IsEmpty(errs) {
headers.WriteHeadersToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/head_manifest.go | registry/app/api/handler/oci/head_manifest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/app/storage"
)
// HeadManifest fetches the image manifest from the storage backend, if it exists.
func (h *Handler) HeadManifest(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, true)
if err != nil {
handleErrors(r.Context(), errcode.Errors{err}, w)
return
}
result := h.Controller.HeadManifest(
r.Context(),
info,
r.Header[storage.HeaderAccept],
r.Header[storage.HeaderIfNoneMatch],
)
if commons.IsEmpty(result.GetErrors()) {
response, ok := result.(*docker.GetManifestResponse)
if !ok {
handleErrors(r.Context(), errcode.Errors{errcode.ErrCodeManifestUnknown}, w)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
handleErrors(r.Context(), result.GetErrors(), w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/post_blob_upload.go | registry/app/api/handler/oci/post_blob_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 oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) InitiateUploadBlob(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
fromParam := r.FormValue("from")
mountDigest := r.FormValue("mount")
headers, errs := h.Controller.InitiateUploadBlob(r.Context(), info, fromParam, mountDigest)
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_catalog.go | registry/app/api/handler/oci/get_catalog.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import "net/http"
func (h *Handler) GetCatalog(w http.ResponseWriter, r *http.Request) {
h.Controller.GetCatalog(w, r)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/patch_blob_upload.go | registry/app/api/handler/oci/patch_blob_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 oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
func (h *Handler) PatchBlobUpload(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
ct := r.Header.Get(storage.HeaderContentType)
cr := r.Header.Get(storage.HeaderContentRange)
cl := r.Header.Get(storage.HeaderContentLength)
length := r.ContentLength
if length > 0 {
r.Body = http.MaxBytesReader(w, r.Body, length)
}
stateToken := r.FormValue("_state")
headers, errs := h.Controller.PatchBlobUpload(r.Context(), info, ct, cr, cl, length, stateToken, r.Body)
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_blob_upload.go | registry/app/api/handler/oci/get_blob_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 oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) GetUploadBlobStatus(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
stateToken := r.FormValue("_state")
headers, errs := h.Controller.GetUploadBlobStatus(r.Context(), info, stateToken)
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
return
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_tags.go | registry/app/api/handler/oci/get_tags.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oci
import (
"encoding/json"
"net/http"
"strconv"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *Handler) GetTags(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(ctx, []error{err}, w)
return
}
errorsList := make(errcode.Errors, 0)
q := r.URL.Query()
lastEntry := q.Get("last")
var maxEntries int
n := q.Get("n")
if n == "" {
maxEntries = docker.DefaultMaximumReturnedEntries
} else {
maxEntries, err = strconv.Atoi(n)
if err != nil {
log.Ctx(ctx).Info().Err(err).Msgf("Failed to parse max entries %s", n)
maxEntries = docker.DefaultMaximumReturnedEntries
}
}
if maxEntries <= 0 {
maxEntries = docker.DefaultMaximumReturnedEntries
}
// Use original full URL from context if available, fallback to current URL
origURL := request.OriginalURLFrom(ctx)
if origURL == "" {
origURL = r.URL.String()
}
rs, tags, err := h.Controller.GetTags(ctx, lastEntry, maxEntries, origURL, info)
log.Ctx(ctx).Debug().Msgf("GetTags: %v %s", rs, tags)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to list tags")
handleErrors(ctx, errorsList, w)
return
}
rs.WriteHeadersToResponse(w)
enc := json.NewEncoder(w)
if err := enc.Encode(
docker.TagsAPIResponse{
Name: info.RegIdentifier,
Tags: tags,
},
); err != nil {
errorsList = append(errorsList, errcode.ErrCodeUnknown.WithDetail(err))
}
handleErrors(ctx, errorsList, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/get_token.go | registry/app/api/handler/oci/get_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 oci
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
apiauth "github.com/harness/gitness/app/api/auth"
"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/jwt"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/app/token"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
type TokenResponseOCI struct {
Token string `json:"token"`
}
func (h *Handler) GetToken(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
if tokenMetadata, okt := session.Metadata.(*auth.TokenMetadata); okt &&
tokenMetadata.TokenType != enum.TokenTypePAT {
returnForbiddenResponse(ctx, w, fmt.Errorf("only personal access token allowed"))
return
}
var user *types.User
if auth.IsAnonymousSession(session) {
user = &types.User{
ID: session.Principal.ID,
UID: session.Principal.UID,
Salt: h.AnonymousUserSecret,
}
} else {
var err error
user, err = h.UserCtrl.FindNoAuth(ctx, session.Principal.UID)
if err != nil {
returnForbiddenResponse(ctx, w, err)
return
}
}
requestedOciAccess := GetRequestedResourceActions(getScopes(r.URL))
var accessPermissionsList = []jwt.AccessPermissions{}
for _, ra := range requestedOciAccess {
space, err := h.getSpace(ctx, ra.Name)
if err != nil {
render.TranslatedUserError(ctx, w, err)
log.Ctx(ctx).Warn().Msgf("failed to find space by ref: %v", err)
continue
}
accessPermissionsList = h.getAccessPermissionList(ctx, space, ra, session, accessPermissionsList)
}
subClaimsAccessPermissions := &jwt.SubClaimsAccessPermissions{
Source: jwt.OciSource,
Permissions: accessPermissionsList,
}
jwtToken, err := h.getTokenDetails(user, subClaimsAccessPermissions)
if err != nil {
returnForbiddenResponse(ctx, w, err)
return
}
if jwtToken != "" {
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
if err := enc.Encode(
TokenResponseOCI{
Token: jwtToken,
},
); err != nil {
log.Ctx(ctx).Error().Msgf("failed to write token response: %v", err)
}
return
}
}
func (h *Handler) getSpace(ctx context.Context, name string) (*types.SpaceCore, error) {
spaceRef, _, _ := paths.DisectRoot(name)
space, err := h.SpaceFinder.FindByRef(ctx, spaceRef)
return space, err
}
func (h *Handler) getAccessPermissionList(
ctx context.Context, space *types.SpaceCore, ra *ResourceActions, session *auth.Session,
accessPermissionsList []jwt.AccessPermissions,
) []jwt.AccessPermissions {
accessPermissions := &jwt.AccessPermissions{SpaceID: space.ID, Permissions: []enum.Permission{}}
for _, a := range ra.Actions {
permission, err := getPermissionFromAction(ctx, a)
if err != nil {
log.Ctx(ctx).Warn().Msgf("failed to get permission from action: %v", err)
continue
}
scopeErr := apiauth.CheckSpaceScope(
ctx,
h.Authorizer,
session,
space,
enum.ResourceTypeRegistry,
permission,
)
if scopeErr != nil {
log.Ctx(ctx).Warn().Msgf("failed to check space scope: %v", scopeErr)
continue
}
accessPermissions.Permissions = append(accessPermissions.Permissions, permission)
}
accessPermissionsList = append(accessPermissionsList, *accessPermissions)
return accessPermissionsList
}
func getPermissionFromAction(ctx context.Context, action string) (enum.Permission, error) {
switch action {
case "pull":
return enum.PermissionArtifactsDownload, nil
case "push":
return enum.PermissionArtifactsUpload, nil
case "delete":
return enum.PermissionArtifactsDelete, nil
default:
err := fmt.Errorf("unknown action: %s", action)
log.Ctx(ctx).Err(err).Msgf("Failed to get permission from action: %v", err)
return "", err
}
}
func returnForbiddenResponse(ctx context.Context, w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusForbidden)
_, err2 := fmt.Fprintf(w, "requested access to the resource is denied: %v", err)
if err2 != nil {
log.Ctx(ctx).Error().Msgf("failed to write token response: %v", err2)
}
}
/*
* getTokenDetails attempts to get token details.
*/
func (h *Handler) getTokenDetails(
user *types.User,
accessPermissions *jwt.SubClaimsAccessPermissions,
) (string, error) {
return token.CreateUserWithAccessPermissions(user, accessPermissions)
}
// GetRequestedResourceActions ...
func GetRequestedResourceActions(scopes []string) []*ResourceActions {
var res []*ResourceActions
for _, s := range scopes {
if s == "" {
continue
}
items := strings.Split(s, ":")
length := len(items)
var resourceType string
var resourceName string
actions := make([]string, 0)
switch length {
case 1:
resourceType = items[0]
case 2:
resourceType = items[0]
resourceName = items[1]
default:
resourceType = items[0]
resourceName = strings.Join(items[1:length-1], ":")
if len(items[length-1]) > 0 {
actions = strings.Split(items[length-1], ",")
}
}
res = append(
res, &ResourceActions{
Type: resourceType,
Name: resourceName,
Actions: actions,
},
)
}
return res
}
func getScopes(u *url.URL) []string {
var sector string
var result []string
for _, sector = range u.Query()["scope"] {
result = append(result, strings.Split(sector, " ")...)
}
return result
}
// ResourceActions stores allowed actions on a resource.
type ResourceActions struct {
Type string `json:"type"`
Name string `json:"name"`
Actions []string `json:"actions"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/oci/put_blob_upload.go | registry/app/api/handler/oci/put_blob_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 oci
import (
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
)
func (h *Handler) CompleteBlobUpload(w http.ResponseWriter, r *http.Request) {
info, err := h.GetRegistryInfo(r, false)
if err != nil {
handleErrors(r.Context(), []error{err}, w)
return
}
stateToken := r.FormValue("_state")
length := r.ContentLength
if length > 0 {
r.Body = http.MaxBytesReader(w, r.Body, length)
}
headers, errs := h.Controller.CompleteBlobUpload(r.Context(), info, r.Body, r.ContentLength, stateToken)
if commons.IsEmpty(errs) {
headers.WriteToResponse(w)
}
handleErrors(r.Context(), errs, w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/search_count_v2.go | registry/app/api/handler/nuget/search_count_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) CountPackageV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.CountPackageV2(r.Context(), *info, nugettype.GetSearchTerm(r))
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
_, err := w.Write([]byte(xml.Header))
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
err = xml.NewEncoder(w).Encode(response.Count)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/list_package_version_v2.go | registry/app/api/handler/nuget/list_package_version_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) ListPackageVersionV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.ListPackageVersionV2(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
_, err := w.Write([]byte(xml.Header))
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
err = xml.NewEncoder(w).Encode(response.FeedResponse)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/package_version_count_v2.go | registry/app/api/handler/nuget/package_version_count_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetPackageVersionCountV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.CountPackageVersionV2(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
_, err := w.Write([]byte(xml.Header))
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
err = xml.NewEncoder(w).Encode(response.Count)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/download_symbol_package_v2.go | registry/app/api/handler/nuget/download_symbol_package_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadSymbolPackageV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.DownloadPackage(ctx, *info)
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close readcloser: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
err := commons.ServeContent(w, r, response.Body, info.Filename, response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/upload_symbol_package.go | registry/app/api/handler/nuget/upload_symbol_package.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/api/handler/utils"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/nuget"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) UploadSymbolPackage(w http.ResponseWriter, r *http.Request) {
fileReader, _, err := utils.GetFileReader(r, "package")
if err != nil {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage(fmt.Sprintf("failed to parse file: %s, "+
"please provide correct file path ", err.Error())), w)
return
}
defer fileReader.Close()
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.UploadPackage(r.Context(), *info, fileReader, nuget.SymbolsFile)
if response.GetError() != nil {
h.HandleError(ctx, w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/service_endpoint.go | registry/app/api/handler/nuget/service_endpoint.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/json"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetServiceEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetServiceEndpoint(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := json.NewEncoder(w).Encode(response.ServiceEndpoint)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/service_metadata_v2.go | registry/app/api/handler/nuget/service_metadata_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetServiceMetadataV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetServiceMetadataV2(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := xml.NewEncoder(w).Encode(response.ServiceMetadata)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/search.go | registry/app/api/handler/nuget/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 nuget
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) SearchPackage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
searchTerm := r.URL.Query().Get("q")
offset, err := strconv.Atoi(r.URL.Query().Get("skip"))
if err != nil {
offset = 0
}
limit, err2 := strconv.Atoi(r.URL.Query().Get("take"))
if err2 != nil {
limit = 20
}
response := h.controller.SearchPackage(r.Context(), *info, searchTerm, limit, offset)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err3 := json.NewEncoder(w).Encode(response.SearchResponse)
if err3 != nil {
h.HandleErrors(r.Context(), []error{err3}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/delete_package.go | registry/app/api/handler/nuget/delete_package.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DeletePackage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.DeletePackage(ctx, *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/list_package_version.go | registry/app/api/handler/nuget/list_package_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 nuget
import (
"encoding/json"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) ListPackageVersion(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.ListPackageVersion(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := json.NewEncoder(w).Encode(response.PackageVersion)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/service_endpoint_v2.go | registry/app/api/handler/nuget/service_endpoint_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetServiceEndpointV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetServiceEndpointV2(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := xml.NewEncoder(w).Encode(response.ServiceEndpoint)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/package_metadata.go | registry/app/api/handler/nuget/package_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/json"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetPackageMetadata(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetPackageMetadata(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := json.NewEncoder(w).Encode(response.RegistrationResponse)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/package_version_metadata.go | registry/app/api/handler/nuget/package_version_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/json"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetPackageVersionMetadata(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetPackageVersionMetadata(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
err := json.NewEncoder(w).Encode(response.RegistrationLeafResponse)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/handler.go | registry/app/api/handler/nuget/handler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"net/http"
"strings"
"github.com/harness/gitness/registry/app/api/controller/pkg/nuget"
"github.com/harness/gitness/registry/app/api/handler/packages"
nugetmetadata "github.com/harness/gitness/registry/app/metadata/nuget"
"github.com/harness/gitness/registry/app/pkg"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/go-chi/chi/v5"
)
type Handler interface {
pkg.ArtifactInfoProvider
UploadPackage(writer http.ResponseWriter, request *http.Request)
UploadSymbolPackage(writer http.ResponseWriter, request *http.Request)
DownloadPackage(http.ResponseWriter, *http.Request)
DeletePackage(writer http.ResponseWriter, request *http.Request)
GetServiceEndpoint(http.ResponseWriter, *http.Request)
GetServiceEndpointV2(http.ResponseWriter, *http.Request)
ListPackageVersion(http.ResponseWriter, *http.Request)
ListPackageVersionV2(http.ResponseWriter, *http.Request)
GetPackageMetadata(http.ResponseWriter, *http.Request)
GetPackageVersionMetadataV2(http.ResponseWriter, *http.Request)
GetPackageVersionMetadata(http.ResponseWriter, *http.Request)
SearchPackage(http.ResponseWriter, *http.Request)
SearchPackageV2(http.ResponseWriter, *http.Request)
CountPackageV2(http.ResponseWriter, *http.Request)
GetPackageVersionCountV2(http.ResponseWriter, *http.Request)
GetServiceMetadataV2(http.ResponseWriter, *http.Request)
}
type handler struct {
packages.Handler
controller nuget.Controller
}
func NewHandler(
controller nuget.Controller,
packageHandler packages.Handler,
) Handler {
return &handler{
Handler: packageHandler,
controller: controller,
}
}
var _ Handler = (*handler)(nil)
func (h *handler) GetPackageArtifactInfo(r *http.Request) (pkg.PackageArtifactInfo, error) {
info, err := h.Handler.GetArtifactInfo(r)
if err != nil {
return nil, err
}
image := chi.URLParam(r, "id")
filename := chi.URLParam(r, "filename")
version := chi.URLParam(r, "version")
proxyEndpoint := r.URL.Query().Get("proxy_endpoint")
if image == "" {
image = r.URL.Query().Get("id")
image = strings.TrimPrefix(image, "'")
image = strings.TrimSuffix(image, "'")
}
var md nugetmetadata.Metadata
info.Image = image
return &nugettype.ArtifactInfo{
ArtifactInfo: info,
Metadata: md,
Filename: filename,
Version: version,
ProxyEndpoint: proxyEndpoint,
NestedPath: strings.TrimSuffix(r.PathValue("*"), "/"),
}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/package_version_metadata_v2.go | registry/app/api/handler/nuget/package_version_metadata_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetPackageVersionMetadataV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.GetPackageVersionMetadataV2(r.Context(), *info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
_, err := w.Write([]byte(xml.Header))
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
err = xml.NewEncoder(w).Encode(response.FeedEntryResponse)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/upload_package.go | registry/app/api/handler/nuget/upload_package.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/api/handler/utils"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/nuget"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) UploadPackage(w http.ResponseWriter, r *http.Request) {
fileReader, _, err := utils.GetFileReader(r, "package")
if err != nil {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage(fmt.Sprintf("failed to parse file: %s, "+
"please provide correct file path ", err.Error())), w)
return
}
defer fileReader.Close()
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.UploadPackage(r.Context(), *info, fileReader, nuget.DependencyFile)
if response.GetError() != nil {
h.HandleError(ctx, w, response.GetError())
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/search_v2.go | registry/app/api/handler/nuget/search_v2.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"fmt"
"net/http"
"strconv"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) SearchPackageV2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
offset, err := strconv.Atoi(r.URL.Query().Get("$skip"))
if err != nil {
offset = 0
}
limit, err := strconv.Atoi(r.URL.Query().Get("$top"))
if err != nil {
limit = 20
}
response := h.controller.SearchPackageV2(r.Context(), *info, nugettype.GetSearchTerm(r), limit, offset)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
_, err = w.Write([]byte(xml.Header))
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
err = xml.NewEncoder(w).Encode(response.FeedResponse)
if err != nil {
h.HandleErrors(r.Context(), []error{err}, w)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/nuget/download_package.go | registry/app/api/handler/nuget/download_package.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) DownloadPackage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*nugettype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch info from context")}, w)
return
}
response := h.controller.DownloadPackage(ctx, *info)
defer func() {
if response.Body != nil {
err := response.Body.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close body: %v", err)
}
}
if response.ReadCloser != nil {
err := response.ReadCloser.Close()
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to close readcloser: %v", err)
}
}
}()
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
}
if response.RedirectURL != "" {
http.Redirect(w, r, response.RedirectURL, http.StatusTemporaryRedirect)
return
}
err := commons.ServeContent(w, r, response.Body, info.Filename, response.ReadCloser)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to serve content: %v", err)
h.HandleError(ctx, w, err)
return
}
response.ResponseHeaders.WriteToResponse(w)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/npm/list_tag.go | registry/app/api/handler/npm/list_tag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"encoding/json"
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
npm2 "github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/request"
)
func (h *handler) ListPackageTag(w http.ResponseWriter, r *http.Request) {
contextInfo := request.ArtifactInfoFrom(r.Context())
info, ok := contextInfo.(*npm2.ArtifactInfo)
if !ok {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage("failed to fetch info from context"), w)
return
}
response := h.controller.ListTags(r.Context(), info)
if response.GetError() != nil {
h.HandleError(r.Context(), w, response.GetError())
return
}
jsonResponse, err := json.Marshal(response.Tags)
if err != nil {
http.Error(w, "Error encoding response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(jsonResponse)
if err != nil {
http.Error(w, "Failed to write response", http.StatusInternalServerError)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/npm/get_metadata.go | registry/app/api/handler/npm/get_metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"encoding/json"
"fmt"
"net/http"
"github.com/harness/gitness/registry/app/pkg/commons"
npm2 "github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) GetPackageMetadata(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*npm2.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get npm artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch npm artifact info from context")}, w)
return
}
response := h.controller.GetPackageMetadata(ctx, info)
if !commons.IsEmpty(response.GetError()) {
h.HandleError(ctx, w, response.GetError())
return
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(response.PackageMetadata)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/npm/utils.go | registry/app/api/handler/npm/utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"fmt"
"net/http"
"net/url"
"regexp"
)
func PackageNameFromParams(r *http.Request) string {
scope, _ := url.PathUnescape(r.PathValue("scope")) // Decode encoded scope
id, _ := url.PathUnescape(r.PathValue("id"))
if scope != "" {
if id != "" {
return fmt.Sprintf("@%s/%s", scope, id)
}
return fmt.Sprintf("@%s", scope)
}
return id
}
func GetVersionFromParams(r *http.Request) string {
version := r.PathValue("version")
if version == "" {
var err error
version, err = VersionNameFromFileName(GetFileName(r))
if err != nil {
return ""
}
return version
}
return version
}
func VersionNameFromFileName(filename string) (string, error) {
// Define regex pattern: package-name-version.tgz
re := regexp.MustCompile(`-(\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?)\.tgz$`)
// Find match
matches := re.FindStringSubmatch(filename)
if len(matches) > 1 {
return matches[1], nil
}
return "", fmt.Errorf("version not found in filename: %s", filename)
}
func GetFileName(r *http.Request) string {
scope := r.PathValue("scope")
file := r.PathValue("filename")
if scope != "" {
return fmt.Sprintf("@%s/%s", scope, file)
}
return file
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/npm/add_tag.go | registry/app/api/handler/npm/add_tag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"encoding/json"
"net/http"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/pkg/commons"
npm2 "github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/request"
)
func (h *handler) AddPackageTag(w http.ResponseWriter, r *http.Request) {
contextInfo := request.ArtifactInfoFrom(r.Context())
info, ok := contextInfo.(*npm2.ArtifactInfo)
if !ok {
h.HandleErrors2(r.Context(), errcode.ErrCodeInvalidRequest.WithMessage("failed to fetch info from context"), w)
return
}
response := h.controller.AddTag(r.Context(), info)
if commons.IsEmpty(response.GetError()) {
jsonResponse, err := json.Marshal(response.Tags)
if err != nil {
http.Error(w, "Error encoding response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(jsonResponse)
if err != nil {
http.Error(w, "Failed to write response", http.StatusInternalServerError)
}
}
h.HandleError(r.Context(), w, response.GetError())
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/handler/npm/search.go | registry/app/api/handler/npm/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 npm
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
errors2 "github.com/harness/gitness/errors"
"github.com/harness/gitness/registry/app/pkg/commons"
npm2 "github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/request"
"github.com/rs/zerolog/log"
)
func (h *handler) SearchPackage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
info, ok := request.ArtifactInfoFrom(ctx).(*npm2.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msg("Failed to get npm artifact info from context")
h.HandleErrors(r.Context(), []error{fmt.Errorf("failed to fetch npm artifact info from context")}, w)
return
}
info.Image = r.FormValue("text")
limit, err := strconv.Atoi(r.FormValue("size"))
if err != nil {
limit = 20
}
offset, err := strconv.Atoi(r.FormValue("from"))
if err != nil {
offset = 0
}
response := h.controller.SearchPackage(ctx, info, limit, offset)
if !commons.IsEmpty(response.GetError()) {
if errors2.IsNotFound(response.GetError()) {
http.Error(w, response.GetError().Error(), http.StatusNotFound)
return
}
http.Error(w, response.GetError().Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(response.Artifacts)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
| 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.