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/pkg/artifact_info.go | registry/app/pkg/artifact_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 pkg
import (
"net/http"
)
// PackageArtifactInfo is an interface that must be implemented by all package-specific
// artifact info types. It ensures that all package artifact infos can be converted to
// the base ArtifactInfo type.
type PackageArtifactInfo interface {
BaseArtifactInfo() ArtifactInfo
GetImageVersion() (bool, string)
GetVersion() string
GetRegistryID() int64
GetImage() string
GetFileName() string
}
// ArtifactInfoProvider is an interface that must be implemented by package handlers
// to provide artifact information from HTTP requests.
type ArtifactInfoProvider interface {
// GetPackageArtifactInfo returns package-specific artifact info that implements
// the PackageArtifactInfo interface
GetPackageArtifactInfo(r *http.Request) (PackageArtifactInfo, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/utils.go | registry/app/pkg/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 pkg
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
var (
numberRegex = regexp.MustCompile(`\d+`)
)
func IsEmpty(slice any) bool {
if slice == nil {
return true
}
return reflect.ValueOf(slice).Len() == 0
}
func JoinWithSeparator(sep string, args ...string) string {
return strings.Join(args, sep)
}
func ExtractFirstNumber(input string) (int, error) {
match := numberRegex.FindString(input)
if match == "" {
return 0, fmt.Errorf("no number found in input: %s", input)
}
result, err := strconv.Atoi(match)
if err != nil {
return 0, fmt.Errorf("failed to convert string '%s' to number: %w", match, err)
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/utils_test.go | registry/app/pkg/utils_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 pkg
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsEmpty(t *testing.T) {
tests := []struct {
name string
input any
expected bool
}{
{
name: "nil slice",
input: nil,
expected: true,
},
{
name: "empty string slice",
input: []string{},
expected: true,
},
{
name: "non-empty string slice",
input: []string{"a", "b"},
expected: false,
},
{
name: "empty int slice",
input: []int{},
expected: true,
},
{
name: "non-empty int slice",
input: []int{1, 2, 3},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := IsEmpty(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
func TestJoinWithSeparator(t *testing.T) {
tests := []struct {
name string
sep string
args []string
expected string
}{
{
name: "join with comma",
sep: ",",
args: []string{"a", "b", "c"},
expected: "a,b,c",
},
{
name: "join with space",
sep: " ",
args: []string{"hello", "world"},
expected: "hello world",
},
{
name: "empty strings",
sep: "-",
args: []string{"", "", ""},
expected: "--",
},
{
name: "single string",
sep: ".",
args: []string{"single"},
expected: "single",
},
{
name: "no strings",
sep: "+",
args: []string{},
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := JoinWithSeparator(tt.sep, tt.args...)
assert.Equal(t, tt.expected, result)
})
}
}
func TestExtractFirstNumber(t *testing.T) {
tests := []struct {
name string
input string
expected int
expectError bool
}{
{
name: "simple number",
input: "123",
expected: 123,
expectError: false,
},
{
name: "number with text",
input: "abc123def",
expected: 123,
expectError: false,
},
{
name: "multiple numbers",
input: "123abc456",
expected: 123,
expectError: false,
},
{
name: "no numbers",
input: "abc",
expected: 0,
expectError: true,
},
{
name: "empty string",
input: "",
expected: 0,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := ExtractFirstNumber(tt.input)
if tt.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expected, result)
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/context.go | registry/app/pkg/context.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pkg
import (
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
v2 "github.com/distribution/distribution/v3/registry/api/v2"
)
type BaseInfo struct {
PathPackageType artifact.PackageType
PathRoot string
ParentID int64
RootIdentifier string
RootParentID int64
}
type ArtifactInfo struct {
*BaseInfo
RegIdentifier string
RegistryID int64
// Currently used only for Python packages
// TODO: extend to all package types
Registry types.Registry
ArtifactType *artifact.ArtifactType
Image string
}
func (a ArtifactInfo) GetImage() string {
return a.Image
}
func (a ArtifactInfo) GetRegistryID() int64 {
return a.RegistryID
}
func (a *ArtifactInfo) UpdateRegistryInfo(r types.Registry) {
a.RegistryID = r.ID
a.RegIdentifier = r.Name
a.Registry = r
a.ParentID = r.ParentID
}
type RegistryInfo struct {
*ArtifactInfo
Reference string
Digest string
Tag string
URLBuilder *v2.URLBuilder
Path string
PackageType artifact.PackageType
}
func (r *RegistryInfo) SetReference(ref string) {
r.Reference = ref
}
func (a *ArtifactInfo) SetRepoKey(key string) {
a.RegIdentifier = key
}
type MavenArtifactInfo struct {
*ArtifactInfo
GroupID string
ArtifactID string
Version string
FileName string
Path string
}
// Deprecated: use generic.ArtifactInfo instead.
type GenericArtifactInfo struct {
*ArtifactInfo
FileName string
RegistryID int64
Version string
Description string
}
func (a *MavenArtifactInfo) SetMavenRepoKey(key string) {
a.RegIdentifier = key
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a GenericArtifactInfo) BaseArtifactInfo() ArtifactInfo {
return *a.ArtifactInfo
}
func (a GenericArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a GenericArtifactInfo) GetVersion() string {
return a.Version
}
func (a GenericArtifactInfo) GetFileName() string {
return a.FileName
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a MavenArtifactInfo) BaseArtifactInfo() ArtifactInfo {
return *a.ArtifactInfo
}
func (a MavenArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, JoinWithSeparator(":", a.GroupID, a.ArtifactID, a.Version)
}
return false, ""
}
func (a MavenArtifactInfo) GetVersion() string {
return a.Version
}
func (a MavenArtifactInfo) GetFileName() string {
return a.FileName
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/helpers.go | registry/app/pkg/helpers.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pkg
import (
"context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
// GetRegistryCheckAccess fetches an active registry
// and checks if the current user has permission to access it.
func GetRegistryCheckAccess(
ctx context.Context,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
parentID int64,
art ArtifactInfo,
reqPermissions ...enum.Permission,
) error {
registry := art.Registry
space, err := spaceFinder.FindByID(ctx, parentID)
if err != nil {
return fmt.Errorf("failed to find parent by ref: %w", err)
}
session, _ := request.AuthSessionFrom(ctx)
var permissionChecks []types.PermissionCheck
for i := range reqPermissions {
permissionCheck := types.PermissionCheck{
Permission: reqPermissions[i],
Scope: types.Scope{SpacePath: space.Path},
Resource: types.Resource{
Type: enum.ResourceTypeRegistry,
Identifier: registry.Name,
},
}
permissionChecks = append(permissionChecks, permissionCheck)
}
if err = apiauth.CheckRegistry(ctx, authorizer, session, permissionChecks...); err != nil {
err = fmt.Errorf("registry access check failed: %w", err)
log.Ctx(ctx).Error().Msgf("Error: %v", err)
return err
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/core_controller.go | registry/app/pkg/core_controller.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pkg
import (
"context"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg/quarantine"
store2 "github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type ArtifactType int
const (
LocalRegistry ArtifactType = 1 << iota
RemoteRegistry
)
var TypeRegistry = map[ArtifactType]Artifact{}
type CoreController struct {
RegistryDao store2.RegistryRepository
QuarantineFinder quarantine.Finder
}
func NewCoreController(registryDao store2.RegistryRepository, quarantineFinder quarantine.Finder) *CoreController {
return &CoreController{
RegistryDao: registryDao,
QuarantineFinder: quarantineFinder,
}
}
func (c *CoreController) factory(ctx context.Context, t ArtifactType) Artifact {
switch t {
case LocalRegistry:
return TypeRegistry[t]
case RemoteRegistry:
return TypeRegistry[t]
default:
log.Ctx(ctx).Error().Stack().Msgf("Invalid artifact type %v", t)
return nil
}
}
func (c *CoreController) GetArtifact(ctx context.Context, registry types.Registry) Artifact {
if string(registry.Type) == string(artifact.RegistryTypeVIRTUAL) {
return c.factory(ctx, LocalRegistry)
}
return c.factory(ctx, RemoteRegistry)
}
func (c *CoreController) GetOrderedRepos(ctx context.Context, artInfo RegistryInfo) ([]types.Registry, error) {
var result []types.Registry
registry := artInfo.Registry
result = append(result, registry)
proxies := registry.UpstreamProxies
if len(proxies) > 0 {
upstreamRepos, err2 := c.RegistryDao.GetByIDIn(ctx, proxies)
if err2 != nil {
log.Ctx(ctx).Error().Msgf("Failed to get upstream proxies for %s: %v", registry.Name, err2)
return result, err2
}
repoMap := make(map[int64]types.Registry)
for _, repo := range *upstreamRepos {
repoMap[repo.ID] = repo
}
for _, proxyID := range proxies {
if repo, ok := repoMap[proxyID]; ok {
result = append(result, repo)
}
}
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/artifact.go | registry/app/pkg/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 pkg
import "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
// Artifact Fixme: Name change to Registry as it provides Registry Type.
type Artifact interface {
GetArtifactType() artifact.RegistryType
GetPackageTypes() []artifact.PackageType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/local.go | registry/app/pkg/python/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"sort"
"strings"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
pythonmetadata "github.com/harness/gitness/registry/app/metadata/python"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/app/remote/adapter/commons/pypi"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypePYTHON}
}
func (c *localRegistry) DownloadPackageFile(
ctx context.Context,
info pythontype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
headers, fileReader, redirectURL, err := c.localBase.Download(ctx, info.ArtifactInfo, info.Version,
info.Filename)
if err != nil {
return nil, nil, nil, "", err
}
return headers, fileReader, nil, redirectURL, nil
}
// GetPackageMetadata Metadata represents the metadata of a Python package.
func (c *localRegistry) GetPackageMetadata(
ctx context.Context,
info pythontype.ArtifactInfo,
) (pythontype.PackageMetadata, error) {
registry, err := c.registryDao.GetByRootParentIDAndName(ctx, info.RootParentID, info.RegIdentifier)
packageMetadata := pythontype.PackageMetadata{}
packageMetadata.Name = info.Image
packageMetadata.Files = []pythontype.File{}
if err != nil {
return packageMetadata, err
}
artifacts, err := c.artifactDao.GetByRegistryIDAndImage(ctx, registry.ID, info.Image)
if err != nil {
return packageMetadata, err
}
if len(*artifacts) == 0 {
return packageMetadata, errors.NotFoundf("no artifacts found for registry %s and image %s", info.RegIdentifier,
info.Image)
}
for _, artifact := range *artifacts {
metadata := &pythonmetadata.PythonMetadata{}
err = json.Unmarshal(artifact.Metadata, metadata)
if err != nil {
return packageMetadata, err
}
for _, file := range metadata.Files {
pkgURL := c.urlProvider.PackageURL(
ctx,
info.RootIdentifier+"/"+info.RegIdentifier,
"python",
)
fileInfo := pythontype.File{
Name: file.Filename,
FileURL: fmt.Sprintf(
"%s/files/%s/%s/%s",
pkgURL,
info.Image,
artifact.Version,
file.Filename,
),
RequiresPython: metadata.RequiresPython,
}
packageMetadata.Files = append(packageMetadata.Files, fileInfo)
}
}
sortPackageMetadata(ctx, packageMetadata)
return packageMetadata, nil
}
func sortPackageMetadata(ctx context.Context, metadata pythontype.PackageMetadata) {
sort.Slice(metadata.Files, func(i, j int) bool {
version1 := pypi.GetPyPIVersion(metadata.Files[i].Name)
version2 := pypi.GetPyPIVersion(metadata.Files[j].Name)
if version1 == "" || version2 == "" || version1 == version2 {
return metadata.Files[i].Name < metadata.Files[j].Name
}
vi := parseVersion(ctx, version1)
vj := parseVersion(ctx, version2)
for k := 0; k < len(vi) && k < len(vj); k++ {
if vi[k] != vj[k] {
return vi[k] < vj[k]
}
}
return len(vi) < len(vj)
})
}
func parseVersion(ctx context.Context, version string) []int {
parts := strings.Split(version, ".")
result := make([]int, len(parts))
for i, part := range parts {
num, err := pkg.ExtractFirstNumber(part)
if err != nil {
log.Debug().Ctx(ctx).Msgf("failed to parse version %s, part %s: %v", version, part, err)
continue
}
result[i] = num
}
return result
}
func (c *localRegistry) UploadPackageFile(
ctx context.Context,
info pythontype.ArtifactInfo,
file multipart.File,
filename string,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
path := pkg.JoinWithSeparator("/", info.Image, info.Metadata.Version, filename)
return c.localBase.UploadFile(ctx, info.ArtifactInfo, filename, info.Metadata.Version, path, file,
&pythonmetadata.PythonMetadata{
Metadata: info.Metadata,
})
}
func (c *localRegistry) UploadPackageFileReader(
ctx context.Context,
info pythontype.ArtifactInfo,
file io.ReadCloser,
filename string,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
path := pkg.JoinWithSeparator("/", info.Image, info.Metadata.Version, filename)
return c.localBase.Upload(ctx, info.ArtifactInfo, filename, info.Metadata.Version, path, file,
&pythonmetadata.PythonMetadata{
Metadata: info.Metadata,
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/wire.go | registry/app/pkg/python/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 python
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider)
base.Register(registry)
return registry
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
proxy := NewProxy(fileManager, proxyStore, tx, registryDao, imageDao, artifactDao, urlProvider,
spaceFinder, service, localRegistryHelper)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/proxy.go | registry/app/pkg/python/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"fmt"
"io"
"mime/multipart"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"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/metadata/python"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
pythontype "github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/app/remote/adapter/commons/pypi"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
request2 "github.com/harness/gitness/registry/request"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/remote/adapter/pypi" // This is required to init pypi adapter
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
localRegistryHelper LocalRegistryHelper
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
return &proxy{
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
localRegistryHelper: localRegistryHelper,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypePYTHON}
}
func (r *proxy) DownloadPackageFile(ctx context.Context, info pythontype.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, nil, nil, "", err
}
// TODO: Extract out to Path Utils for all package types
exists := r.localRegistryHelper.FileExists(ctx, info)
if exists {
headers, fileReader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, nil, redirectURL, nil
}
// If file exists in local registry, but download failed, we should try to download from remote
log.Warn().Ctx(ctx).Msgf("failed to pull from local, attempting streaming from remote, %v", err)
}
remote, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, nil, nil, "", err
}
file, err := remote.GetFile(ctx, info.Image, info.Filename)
if err != nil {
return nil, nil, nil, "", errcode.ErrCodeUnknown.WithDetail(err)
}
go func(info pythontype.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = r.putFileToLocal(ctx2, info.Image, info.Filename, remote)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf("error while putting file to localRegistry, %v", err)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated file: %s, registry: %s", info.Filename, info.RegIdentifier)
}(info)
return nil, nil, file, "", nil
}
// GetPackageMetadata Returns metadata from remote.
func (r *proxy) GetPackageMetadata(
ctx context.Context,
info pythontype.ArtifactInfo,
) (pythontype.PackageMetadata, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return pythontype.PackageMetadata{}, err
}
helper, _ := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
result, err := helper.GetMetadata(ctx, info.Image)
if err != nil {
return pythontype.PackageMetadata{}, err
}
var files []pythontype.File
for _, file := range result.Packages {
pkgURL := r.urlProvider.PackageURL(
ctx,
info.RootIdentifier+"/"+info.RegIdentifier,
"python",
)
files = append(files, pythontype.File{
Name: file.Name,
FileURL: fmt.Sprintf(
"%s/files/%s/%s/%s",
pkgURL,
info.Image,
file.Version(),
file.Name),
RequiresPython: file.RequiresPython(),
})
}
metadata := pythontype.PackageMetadata{
Name: info.Image,
Files: files,
}
sortPackageMetadata(ctx, metadata)
return metadata, nil
}
func (r *proxy) putFileToLocal(ctx context.Context, pkg string, filename string, remote RemoteRegistryHelper) error {
version := pypi.GetPyPIVersion(filename)
metadata, err := remote.GetJSON(ctx, pkg, version)
if err != nil {
log.Ctx(ctx).Warn().Stack().Err(err).Msgf("fetching metadata for %s failed, %v", filename, err)
}
file, err := remote.GetFile(ctx, pkg, filename)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("fetching file %s failed, %v", filename, err)
return err
}
defer file.Close()
info, ok := request2.ArtifactInfoFrom(ctx).(*pythontype.ArtifactInfo)
if !ok {
log.Ctx(ctx).Error().Msgf("failed to cast artifact info to python artifact info")
return errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("failed to cast artifact info to python artifact info"))
}
if metadata == nil {
metadata = &python.Metadata{
Version: version,
}
}
info.Metadata = *metadata
info.Filename = filename
_, sha256, err2 := r.localRegistryHelper.UploadPackageFile(ctx, *info, file, filename)
if err2 != nil {
log.Ctx(ctx).Error().Stack().Err(err2).Msgf("uploading file %s failed, %v", filename, err)
return err2
}
log.Ctx(ctx).Info().Msgf("Successfully uploaded %s with SHA256: %s", filename, sha256)
return nil
}
// UploadPackageFile TODO: Extract this upload function for all types of packageTypes
// uploads the package file to the storage.
func (r *proxy) UploadPackageFile(
ctx context.Context,
_ pythontype.ArtifactInfo,
_ multipart.File,
_ string,
) (*commons.ResponseHeaders, string, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
// UploadPackageFile TODO: Extract this upload function for all types of packageTypes
// uploads the package file to the storage.
func (r *proxy) UploadPackageFileReader(
ctx context.Context,
_ pythontype.ArtifactInfo,
_ io.ReadCloser,
_ string,
) (*commons.ResponseHeaders, string, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/registry.go | registry/app/pkg/python/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package python
import (
"context"
"io"
"mime/multipart"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
pkg.Artifact
GetPackageMetadata(ctx context.Context, info python.ArtifactInfo) (python.PackageMetadata, error)
UploadPackageFile(
ctx context.Context,
info python.ArtifactInfo,
file multipart.File,
filename string,
) (*commons.ResponseHeaders, string, error)
UploadPackageFileReader(
ctx context.Context,
info python.ArtifactInfo,
file io.ReadCloser,
filename string,
) (*commons.ResponseHeaders, string, error)
DownloadPackageFile(ctx context.Context, info python.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
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/pkg/python/local_helper_test.go | registry/app/pkg/python/local_helper_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 python
import (
"context"
"errors"
"io"
"mime/multipart"
"testing"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/metadata"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type MockLocalRegistry struct {
mock.Mock
}
func (m *MockLocalRegistry) GetArtifactType() artifact.RegistryType {
args := m.Called()
return args.Get(0).(artifact.RegistryType) //nolint:errcheck
}
func (m *MockLocalRegistry) GetPackageTypes() []artifact.PackageType {
args := m.Called()
return args.Get(0).([]artifact.PackageType) //nolint:errcheck
}
func (m *MockLocalRegistry) DownloadPackageFile(ctx context.Context, info python.ArtifactInfo) (
*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error,
) {
args := m.Called(ctx, info)
//nolint:errcheck
return args.Get(0).(*commons.ResponseHeaders), args.Get(1).(*storage.FileReader),
args.Get(2).(io.ReadCloser), args.String(3), args.Error(4)
}
func (m *MockLocalRegistry) GetPackageMetadata(ctx context.Context, info python.ArtifactInfo) (
python.PackageMetadata,
error,
) {
args := m.Called(ctx, info)
return args.Get(0).(python.PackageMetadata), args.Error(1) //nolint:errcheck
}
func (m *MockLocalRegistry) UploadPackageFile(
ctx context.Context,
info python.ArtifactInfo,
file multipart.File,
filename string,
) (*commons.ResponseHeaders, string, error) {
args := m.Called(ctx, info, file, filename)
return args.Get(0).(*commons.ResponseHeaders), args.String(1), args.Error(2) //nolint:errcheck
}
func (m *MockLocalRegistry) UploadPackageFileReader(
ctx context.Context,
info python.ArtifactInfo,
file io.ReadCloser,
filename string,
) (*commons.ResponseHeaders, string, error) {
args := m.Called(ctx, info, file, filename)
return args.Get(0).(*commons.ResponseHeaders), args.String(1), args.Error(2) //nolint:errcheck
}
type MockLocalBase struct {
mock.Mock
}
func (m *MockLocalBase) ExistsE(
ctx context.Context,
info pkg.PackageArtifactInfo,
path string,
) (headers *commons.ResponseHeaders, err error) {
args := m.Called(ctx, info, path)
//nolint:errcheck
return args.Get(0).(*commons.ResponseHeaders), args.Error(1)
}
func (m *MockLocalBase) DeleteFile(
ctx context.Context,
info pkg.PackageArtifactInfo,
filePath string,
) (headers *commons.ResponseHeaders, err error) {
args := m.Called(ctx, info, filePath)
//nolint:errcheck
return args.Get(0).(*commons.ResponseHeaders), args.Error(1)
}
func (m *MockLocalBase) MoveTempFileAndCreateArtifact(
_ context.Context,
_ pkg.ArtifactInfo,
_, _, _ string,
_ metadata.Metadata,
_ types.FileInfo,
_ bool,
) (*commons.ResponseHeaders, string, int64, bool, error) {
// TODO implement me
panic("implement me")
}
func (m *MockLocalBase) CheckIfVersionExists(_ context.Context, _ pkg.PackageArtifactInfo) (bool, error) {
// TODO implement me
panic("implement me")
}
func (m *MockLocalBase) DeletePackage(_ context.Context, _ pkg.PackageArtifactInfo) error {
// TODO implement me
panic("implement me")
}
func (m *MockLocalBase) DeleteVersion(_ context.Context, _ pkg.PackageArtifactInfo) error {
// TODO implement me
panic("implement me")
}
func (m *MockLocalBase) Exists(ctx context.Context, info pkg.ArtifactInfo, path string) bool {
args := m.Called(ctx, info, path)
return args.Bool(0)
}
func (m *MockLocalBase) ExistsByFilePath(ctx context.Context, registryID int64, filePath string) (bool, error) {
args := m.Called(ctx, registryID, filePath)
return args.Bool(0), args.Error(1)
}
func (m *MockLocalBase) Download(ctx context.Context, info pkg.ArtifactInfo, version, filename string) (
*commons.ResponseHeaders, *storage.FileReader, string, error,
) {
args := m.Called(ctx, info, version, filename)
//nolint:errcheck
return args.Get(0).(*commons.ResponseHeaders), args.Get(1).(*storage.FileReader),
args.String(2), args.Error(3)
}
func (m *MockLocalBase) Upload(
ctx context.Context, info pkg.ArtifactInfo, filename, version, path string,
reader io.ReadCloser, metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
args := m.Called(ctx, info, filename, version, path, reader, metadata)
return args.Get(0).(*commons.ResponseHeaders), args.String(1), args.Error(2) //nolint:errcheck
}
func (m *MockLocalBase) Move(
ctx context.Context,
info pkg.ArtifactInfo,
filename, version, path string,
metadata metadata.Metadata,
fileInfo types.FileInfo,
) (*commons.ResponseHeaders, string, error) {
args := m.Called(ctx, info, filename, version, path, metadata, fileInfo)
return args.Get(0).(*commons.ResponseHeaders), args.String(1), args.Error(2) //nolint:errcheck
}
func (m *MockLocalBase) UploadFile(
ctx context.Context, info pkg.ArtifactInfo, filename, version, path string,
file multipart.File,
metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
args := m.Called(ctx, info, filename, version, path, file, metadata)
return args.Get(0).(*commons.ResponseHeaders), args.String(1), args.Error(2) //nolint:errcheck
}
func (m *MockLocalBase) MoveMultipleTempFilesAndCreateArtifact(
ctx context.Context,
info *pkg.ArtifactInfo,
pathPrefix string,
metadata metadata.Metadata,
filesInfo *[]types.FileInfo,
getTempFilePath func(info *pkg.ArtifactInfo, fileInfo *types.FileInfo) string,
version string,
) error {
args := m.Called(ctx, info, pathPrefix, metadata, filesInfo, getTempFilePath, version)
return args.Error(0)
}
type MockReadCloser struct {
mock.Mock
}
func (m *MockReadCloser) Read(p []byte) (n int, err error) {
args := m.Called(p)
return args.Int(0), args.Error(1)
}
func (m *MockReadCloser) Close() error {
args := m.Called()
return args.Error(0)
}
func TestNewLocalRegistryHelper(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
assert.NotNil(t, helper, "Helper should not be nil")
}
// Test for FileExists method.
func TestLocalRegistryHelper_FileExists(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
ctx := context.Background()
artifactInfo := python.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootParentID: 1,
RootIdentifier: "root",
//RegParentID: 2,
},
RegIdentifier: "registry",
Image: "package",
},
Version: "1.0.0",
Filename: "package-1.0.0.whl",
}
mockLocalBase.On("Exists", ctx, artifactInfo.ArtifactInfo,
artifactInfo.Image+"/"+artifactInfo.Version+"/"+artifactInfo.Filename).Return(true)
exists := helper.FileExists(ctx, artifactInfo)
assert.True(t, exists, "File should exist")
mockLocalBase.AssertExpectations(t)
}
// Test for DownloadFile method.
func TestLocalRegistryHelper_DownloadFile(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
ctx := context.Background()
artifactInfo := python.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootParentID: 1,
RootIdentifier: "root",
//RegParentID: 2,
},
RegIdentifier: "registry",
Image: "package",
},
Version: "1.0.0",
Filename: "package-1.0.0.whl",
}
expectedHeaders := &commons.ResponseHeaders{}
expectedFileReader := &storage.FileReader{}
expectedRedirectURL := "http://example.com/download"
var expectedError error
mockLocalBase.On("Download", ctx, artifactInfo.ArtifactInfo, artifactInfo.Version,
artifactInfo.Filename).
Return(expectedHeaders, expectedFileReader, expectedRedirectURL, expectedError)
headers, fileReader, redirectURL, err := helper.DownloadFile(ctx, artifactInfo)
assert.Equal(t, expectedHeaders, headers, "Headers should match")
assert.Equal(t, expectedFileReader, fileReader, "FileReader should match")
assert.Equal(t, expectedRedirectURL, redirectURL, "RedirectURL should match")
assert.Nil(t, err, "Error should be nil")
mockLocalBase.AssertExpectations(t)
}
// Test for DownloadFile method with error.
func TestLocalRegistryHelper_DownloadFile_Error(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
ctx := context.Background()
artifactInfo := python.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootParentID: 1,
RootIdentifier: "root",
//RegParentID: 2,
},
RegIdentifier: "registry",
Image: "package",
},
Version: "1.0.0",
Filename: "package-1.0.0.whl",
}
expectedError := errors.New("download error")
mockLocalBase.On("Download", ctx, artifactInfo.ArtifactInfo, artifactInfo.Version,
artifactInfo.Filename).
Return((*commons.ResponseHeaders)(nil), (*storage.FileReader)(nil), "", expectedError)
headers, fileReader, redirectURL, err := helper.DownloadFile(ctx, artifactInfo)
assert.Nil(t, headers, "Headers should be nil")
assert.Nil(t, fileReader, "FileReader should be nil")
assert.Equal(t, "", redirectURL, "RedirectURL should be empty")
assert.Equal(t, expectedError, err, "Error should match expected error")
mockLocalBase.AssertExpectations(t)
}
// Test for PutFile method.
func TestLocalRegistryHelper_UploadPackageFile(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
ctx := context.Background()
artifactInfo := python.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootParentID: 1,
RootIdentifier: "root",
//RegParentID: 2,
},
RegIdentifier: "registry",
Image: "package",
},
Version: "1.0.0",
Filename: "package-1.0.0.whl",
}
mockReader := new(MockReadCloser)
mockReader.On("Close").Return(nil)
expectedHeaders := &commons.ResponseHeaders{}
expectedSHA256 := "abc123"
var expectedError error
mockLocalRegistry.On("UploadPackageFileReader", ctx, artifactInfo,
mock.AnythingOfType("*python.MockReadCloser"),
"package-1.0.0.whl").
Return(expectedHeaders, expectedSHA256, expectedError)
headers, sha256, err := helper.UploadPackageFile(ctx, artifactInfo, mockReader, "package-1.0.0.whl")
assert.Equal(t, expectedHeaders, headers, "Headers should match")
assert.Equal(t, expectedSHA256, sha256, "SHA256 should match")
assert.Nil(t, err, "Error should be nil")
mockLocalRegistry.AssertExpectations(t)
}
// Test for PutFile method with error.
func TestLocalRegistryHelper_UploadPackageFile_Error(t *testing.T) {
mockLocalRegistry := new(MockLocalRegistry)
mockLocalBase := new(MockLocalBase)
helper := NewLocalRegistryHelper(mockLocalRegistry, mockLocalBase)
ctx := context.Background()
artifactInfo := python.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{
RootParentID: 1,
RootIdentifier: "root",
//RegParentID: 2,
},
RegIdentifier: "registry",
Image: "package",
},
Version: "1.0.0",
Filename: "package-1.0.0.whl",
}
mockReader := new(MockReadCloser)
mockReader.On("Close").Return(nil)
expectedError := errors.New("upload error")
mockLocalRegistry.On("UploadPackageFileReader", ctx, artifactInfo,
mock.AnythingOfType("*python.MockReadCloser"),
"package-1.0.0.whl").
Return((*commons.ResponseHeaders)(nil), "", expectedError)
headers, sha256, err := helper.UploadPackageFile(ctx, artifactInfo, mockReader, "package-1.0.0.whl")
assert.Nil(t, headers, "Headers should be nil")
assert.Equal(t, "", sha256, "SHA256 should be empty")
assert.Equal(t, expectedError, err, "Error should match expected error")
mockLocalRegistry.AssertExpectations(t)
}
func TestMockLocalBase_MoveMultipleTempFilesAndCreateArtifact(t *testing.T) {
mockLocalBase := new(MockLocalBase)
ctx := context.Background()
info := &pkg.ArtifactInfo{}
pathPrefix := "test/path"
var meta metadata.Metadata
filesInfo := &[]types.FileInfo{}
version := "1.0.0"
// Use mock.AnythingOfType for the func argument
mockLocalBase.On(
"MoveMultipleTempFilesAndCreateArtifact",
ctx, info, pathPrefix, meta, filesInfo, mock.AnythingOfType("func(*pkg.ArtifactInfo,"+
" *types.FileInfo) string"), version,
).Return(nil)
err := mockLocalBase.MoveMultipleTempFilesAndCreateArtifact(ctx, info, pathPrefix, meta, filesInfo,
func(_ *pkg.ArtifactInfo, _ *types.FileInfo) string { return "temp/path" }, version)
assert.Nil(t, err, "Expected no error from mock implementation")
mockLocalBase.AssertExpectations(t)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/remote_helper.go | registry/app/pkg/python/remote_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 python
import (
"context"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/metadata/python"
"github.com/harness/gitness/registry/app/remote/adapter"
pypi2 "github.com/harness/gitness/registry/app/remote/adapter/commons/pypi"
"github.com/harness/gitness/registry/app/remote/adapter/pypi"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
// GetFile Downloads the file for the given package and filename
GetFile(ctx context.Context, pkg string, filename string) (io.ReadCloser, error)
// GetMetadata Fetches the metadata for the given package for all versions
GetMetadata(ctx context.Context, pkg string) (*pypi2.SimpleMetadata, error)
// GetJSON Fetches the metadata for the given package and specific version
GetJSON(ctx context.Context, pkg string, version string) (*python.Metadata, error)
}
type remoteRegistryHelper struct {
adapter registry.PythonRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, err
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypePYTHON)
if r.registry.Source == string(artifact.UpstreamConfigSourcePyPi) {
r.registry.RepoURL = pypi.PyPiURL
}
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
pythonReg, ok := adpt.(registry.PythonRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to python registry")
return err
}
r.adapter = pythonReg
return nil
}
func (r *remoteRegistryHelper) GetFile(ctx context.Context, pkg string, filename string) (io.ReadCloser, error) {
v2, err := r.adapter.GetPackage(ctx, pkg, filename)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get pkg: %s, file: %s", pkg, filename)
}
return v2, err
}
func (r *remoteRegistryHelper) GetMetadata(ctx context.Context, pkg string) (*pypi2.SimpleMetadata, error) {
packages, err := r.adapter.GetMetadata(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
return packages, nil
}
func (r *remoteRegistryHelper) GetJSON(ctx context.Context, pkg string, version string) (*python.Metadata, error) {
metadata, err := r.adapter.GetJSON(ctx, pkg, version)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get JSON for pkg: %s, version: %s", pkg, version)
return nil, err
}
return metadata, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/python/local_helper.go | registry/app/pkg/python/local_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 python
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/python"
"github.com/harness/gitness/registry/app/storage"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info python.ArtifactInfo) bool
DownloadFile(ctx context.Context, info python.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
)
UploadPackageFile(
ctx context.Context,
info python.ArtifactInfo,
fileReader io.ReadCloser,
filename string,
) (*commons.ResponseHeaders, string, error)
}
type localRegistryHelper struct {
localRegistry LocalRegistry
localBase base.LocalBase
}
func NewLocalRegistryHelper(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return &localRegistryHelper{
localRegistry: localRegistry,
localBase: localBase,
}
}
func (h *localRegistryHelper) FileExists(ctx context.Context, info python.ArtifactInfo) bool {
return h.localBase.Exists(ctx, info.ArtifactInfo, pkg.JoinWithSeparator("/", info.Image, info.Version, info.Filename))
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info python.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
) {
return h.localBase.Download(ctx, info.ArtifactInfo, info.Version, info.Filename)
}
func (h *localRegistryHelper) UploadPackageFile(
ctx context.Context,
info python.ArtifactInfo,
fileReader io.ReadCloser,
filename string,
) (*commons.ResponseHeaders, string, error) {
return h.localRegistry.UploadPackageFileReader(ctx, info, fileReader, filename)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/request.go | registry/app/pkg/commons/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 commons
import (
"errors"
"fmt"
"io"
"net/http"
"reflect"
"time"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/storage"
)
type ResponseHeaders struct {
Headers map[string]string
Code int
}
func IsEmpty(slice any) bool {
if slice == nil {
return true
}
val := reflect.ValueOf(slice)
// Check if the input is a pointer
if val.Kind() == reflect.Ptr {
// Dereference the pointer
val = val.Elem()
}
// Check if the dereferenced value is nil
if !val.IsValid() {
return true
}
kind := val.Kind()
if kind == reflect.Slice || kind == reflect.Array || kind == reflect.Map || kind == reflect.String ||
kind == reflect.Chan || kind == reflect.Ptr {
return val.Len() == 0
}
return false
}
func IsEmptyError(err errcode.Error) bool {
return err.Code == 0
}
func (r *ResponseHeaders) WriteToResponse(w http.ResponseWriter) {
if w == nil || r == nil {
return
}
if r.Headers != nil {
for key, value := range r.Headers {
w.Header().Set(key, value)
}
}
if r.Code != 0 {
w.WriteHeader(r.Code)
}
}
func (r *ResponseHeaders) WriteHeadersToResponse(w http.ResponseWriter) {
if w == nil || r == nil {
return
}
if r.Headers != nil {
for key, value := range r.Headers {
w.Header().Set(key, value)
}
}
}
func ServeContent(
w http.ResponseWriter,
r *http.Request,
body *storage.FileReader,
fileName string,
readCloser io.ReadCloser,
) error {
if body != nil {
http.ServeContent(w, r, fileName, time.Time{}, body)
return nil
}
if readCloser != nil {
_, err := io.Copy(w, readCloser)
if err != nil {
return fmt.Errorf("failed to copy content: %w", err)
}
return nil
}
return errors.New("no content to serve")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/usererror.go | registry/app/pkg/commons/usererror.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commons
import "net/http"
var (
// ErrBadRequest is returned when there was an issue with the input.
ErrBadRequest = New(http.StatusNotFound, "Bad Request", nil)
ErrNotSupported = New(http.StatusMethodNotAllowed, "not supported", nil)
)
// Error represents a json-encoded API error.
type Error struct {
Status int `json:"-"`
Message string `json:"message"`
Detail any `json:"detail,omitempty"`
}
func (e *Error) Error() string {
return e.Message
}
// New returns a new user facing error.
func New(status int, message string, detail any) *Error {
return &Error{Status: status, Message: message, Detail: detail}
}
// NotFoundError returns a new user facing not found error.
func NotFoundError(message string, detail any) *Error {
return New(http.StatusNotFound, message, detail)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/zipreader/descriptor.go | registry/app/pkg/commons/zipreader/descriptor.go | // Major portions copied from the GO std lib, copyright below:
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Code enabling ZipStreaming, copyright below:
// Copyright (c) 2015 Richard Warburton. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * The name Richard Warburton may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package zipreader
import (
"archive/zip"
"bufio"
"bytes"
"encoding/binary"
"io"
)
type descriptorReader struct {
br *bufio.Reader
size uint64
eof bool
fileHeader *zip.FileHeader
}
var (
sigBytes = []byte{0x50, 0x4b}
)
func (r *descriptorReader) Read(p []byte) (n int, err error) {
if r.eof {
return 0, io.EOF
}
if n = len(p); n > maxRead {
n = maxRead
}
z, err := r.br.Peek(n + readAhead)
if err != nil {
if err == io.EOF && len(z) < 46+22 { // Min length of Central directory + End of central directory
return 0, err
}
n = len(z)
}
// Look for header of next file or central directory
discard := n
s := 16
for !r.eof && s < n {
i := bytes.Index(z[s:len(z)-4], sigBytes) + s
if i == -1 {
break
}
// If directoryHeaderSignature or fileHeaderSignature file could be finished
//nolint: nestif
if sig := binary.LittleEndian.Uint32(z[i : i+4]); sig == fileHeaderSignature ||
sig == directoryHeaderSignature {
// Now check for compressed file sizes to ensure not false positive and if zip64.
if i < len(z)-8 { // Zip32
// Zip32 optional dataDescriptorSignature
offset := 0
if binary.LittleEndian.Uint32(z[i-16:i-12]) == dataDescriptorSignature {
offset = 4
}
// Zip32 compressed file size
//nolint: gosec
if binary.LittleEndian.Uint32(z[i-8:i-4]) == uint32(r.size)+uint32(i-12-offset) {
n, discard = i-12-offset, i
r.eof = true
r.fileHeader.CRC32 = binary.LittleEndian.Uint32(z[i-12 : i-8])
break
}
}
if i > 24 {
// Zip64 optional dataDescriptorSignature
offset := 0
if binary.LittleEndian.Uint32(z[i-24:i-20]) == dataDescriptorSignature {
offset = 4
}
// Zip64 compressed file size
//nolint: gosec
if i >= 8 && binary.LittleEndian.Uint64(z[i-16:i-8]) == r.size+uint64(i-20-offset) {
n, discard = i-20-offset, i
r.eof = true
break
}
}
}
s = i + 2
}
copy(p, z[:n])
//nolint: errcheck
r.br.Discard(discard)
//nolint: gosec
r.size += uint64(n)
return n, err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/zipreader/reader.go | registry/app/pkg/commons/zipreader/reader.go | // Major portions copied from the GO std lib, copyright below:
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Code enabling ZipStreaming, copyright below:
// Copyright (c) 2015 Richard Warburton. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * The name Richard Warburton may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package zipreader
import (
"archive/zip"
"bufio"
"bytes"
"encoding/binary"
"hash/crc32"
"io"
)
const (
readAhead = 28
maxRead = 4096
bufferSize = maxRead + readAhead
)
// A Reader provides sequential access to the contents of a zip archive.
// A zip archive consists of a sequence of files,
// The Next method advances to the next file in the archive (including the first),
// and then it can be treated as an io.Reader to access the file's data.
// The Buffered method recovers any bytes read beyond the end of the zip file,
// necessary if you plan to process anything after it that is not another zip file.
type Reader struct {
io.Reader
br *bufio.Reader
}
// NewReader creates a new Reader reading from r.
func NewReader(r io.Reader) *Reader {
return &Reader{br: bufio.NewReaderSize(r, bufferSize)}
}
// Next advances to the next entry in the zip archive.
//
// io.EOF is returned when the end of the zip file has been reached.
// If Next is called again, it will presume another zip file immediately follows
// and it will advance into it.
func (r *Reader) Next() (*zip.FileHeader, error) {
if r.Reader != nil {
if _, err := io.Copy(io.Discard, r.Reader); err != nil {
return nil, err
}
}
for {
sigData, err := r.br.Peek(4096)
if err != nil {
if err == io.EOF && len(sigData) < 46+22 { // Min length of Central directory + End of central directory
return nil, err
}
}
switch sig := binary.LittleEndian.Uint32(sigData); sig {
case fileHeaderSignature:
break
case directoryHeaderSignature: // Directory appears at end of file so we are finished
return nil, discardCentralDirectory(r.br)
default:
index := bytes.Index(sigData[1:], sigBytes)
if index == -1 {
//nolint: errcheck
r.br.Discard(len(sigData) - len(sigBytes) + 1)
continue
}
//nolint: errcheck
r.br.Discard(index + 1)
}
break
}
headBuf := make([]byte, fileHeaderLen)
if _, err := io.ReadFull(r.br, headBuf); err != nil {
return nil, err
}
b := readBuf(headBuf[4:])
f := &zip.FileHeader{
ReaderVersion: b.uint16(),
Flags: b.uint16(),
Method: b.uint16(),
ModifiedTime: b.uint16(),
ModifiedDate: b.uint16(),
CRC32: b.uint32(),
CompressedSize: b.uint32(), // TODO handle zip64
UncompressedSize: b.uint32(), // TODO handle zip64
}
filenameLen := b.uint16()
extraLen := b.uint16()
d := make([]byte, filenameLen+extraLen)
if _, err := io.ReadFull(r.br, d); err != nil {
return nil, err
}
f.Name = string(d[:filenameLen])
f.Extra = d[filenameLen : filenameLen+extraLen]
dcomp := decompressor(f.Method)
if dcomp == nil {
return nil, zip.ErrAlgorithm
}
// TODO handle encryption here
crc := &crcReader{
hash: crc32.NewIEEE(),
crc: &f.CRC32,
}
if f.Flags&0x8 != 0 { // If has dataDescriptor
crc.Reader = dcomp(&descriptorReader{br: r.br, fileHeader: f})
} else {
//nolint: gosec,staticcheck
crc.Reader = dcomp(io.LimitReader(r.br, int64(f.CompressedSize)))
crc.crc = &f.CRC32
}
r.Reader = crc
return f, nil
}
// Buffered returns any bytes beyond the end of the zip file that it may have
// read. These are necessary if you plan to process anything after it,
// that isn't another zip file.
func (r *Reader) Buffered() io.Reader { return r.br }
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/zipreader/crc_reader.go | registry/app/pkg/commons/zipreader/crc_reader.go | // Major portions copied from the GO std lib, copyright below:
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Code enabling ZipStreaming, copyright below:
// Copyright (c) 2015 Richard Warburton. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * The name Richard Warburton may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package zipreader
import (
"archive/zip"
"hash"
"io"
)
type crcReader struct {
io.Reader
hash hash.Hash32
crc *uint32
}
func (r *crcReader) Read(b []byte) (n int, err error) {
n, err = r.Reader.Read(b)
r.hash.Write(b[:n])
if err == nil {
return n, nil
}
if err == io.EOF {
if r.crc != nil && *r.crc != 0 && r.hash.Sum32() != *r.crc {
err = zip.ErrChecksum
}
}
return n, err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/zipreader/central_directory.go | registry/app/pkg/commons/zipreader/central_directory.go | // Major portions copied from the GO std lib, copyright below:
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Code enabling ZipStreaming, copyright below:
// Copyright (c) 2015 Richard Warburton. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * The name Richard Warburton may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package zipreader
import (
"archive/zip"
"bufio"
"encoding/binary"
"errors"
"io"
)
// We're not interested in the central directory's data, we just want to skip over it,
// clearing the stream of the current zip, in case anything else needs to be sent over
// the same stream.
func discardCentralDirectory(br *bufio.Reader) error {
for {
sigBytes, err := br.Peek(4)
if err != nil {
return err
}
switch sig := binary.LittleEndian.Uint32(sigBytes); sig {
case directoryHeaderSignature:
if err := discardDirectoryHeaderRecord(br); err != nil {
return err
}
case directoryEndSignature:
if err := discardDirectoryEndRecord(br); err != nil {
return err
}
return io.EOF
case directory64EndSignature:
return errors.New("Zip64 not yet supported")
case directory64LocSignature: // Not sure what this is yet
return errors.New("Zip64 not yet supported")
default:
return zip.ErrFormat
}
}
}
func discardDirectoryHeaderRecord(br *bufio.Reader) error {
if _, err := br.Discard(28); err != nil {
return err
}
lb, err := br.Peek(6)
if err != nil {
return err
}
lengths := int(binary.LittleEndian.Uint16(lb[:2])) + // File name length
int(binary.LittleEndian.Uint16(lb[2:4])) + // Extra field length
int(binary.LittleEndian.Uint16(lb[4:])) // File comment length
_, err = br.Discard(18 + lengths)
return err
}
func discardDirectoryEndRecord(br *bufio.Reader) error {
if _, err := br.Discard(20); err != nil {
return err
}
commentLength, err := br.Peek(2)
if err != nil {
return err
}
_, err = br.Discard(2 + int(binary.LittleEndian.Uint16(commentLength)))
return err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/commons/zipreader/stolen.go | registry/app/pkg/commons/zipreader/stolen.go | // Major portions copied from the GO std lib, copyright below:
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Code enabling ZipStreaming, copyright below:
// Copyright (c) 2015 Richard Warburton. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * The name Richard Warburton may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package zipreader
import (
"compress/flate"
"encoding/binary"
"io"
"sync"
)
// #### struct.go
// Compression methods.
const (
Store uint16 = 0
Deflate uint16 = 8
)
const (
fileHeaderSignature = 0x04034b50
directoryHeaderSignature = 0x02014b50
directoryEndSignature = 0x06054b50
directory64LocSignature = 0x07064b50
directory64EndSignature = 0x06064b50
dataDescriptorSignature = 0x08074b50 // de-facto standard; required by OS X Finder
fileHeaderLen = 30 // + filename + extra
)
// #### register.go
// Decompressor is a function that wraps a Reader with a decompressing Reader.
// The decompressed ReadCloser is returned to callers who open files from
// within the archive. These callers are responsible for closing this reader
// when they're finished reading.
type Decompressor func(io.Reader) io.ReadCloser
var (
mu sync.RWMutex // guards compressor and decompressor maps
decompressors = map[uint16]Decompressor{
Store: io.NopCloser,
Deflate: flate.NewReader,
}
)
// RegisterDecompressor allows custom decompressors for a specified method ID.
func RegisterDecompressor(method uint16, d Decompressor) {
mu.Lock()
defer mu.Unlock()
if _, ok := decompressors[method]; ok {
panic("decompressor already registered")
}
decompressors[method] = d
}
func decompressor(method uint16) Decompressor {
mu.RLock()
defer mu.RUnlock()
return decompressors[method]
}
// #### reader.go
type readBuf []byte
func (b *readBuf) uint16() uint16 {
v := binary.LittleEndian.Uint16(*b)
*b = (*b)[2:]
return v
}
func (b *readBuf) uint32() uint32 {
v := binary.LittleEndian.Uint32(*b)
*b = (*b)[4:]
return v
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/local.go | registry/app/pkg/generic/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"io"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
generic2 "github.com/harness/gitness/registry/app/metadata/generic"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeGENERIC}
}
func (c *localRegistry) PutFile(
ctx context.Context,
info generic.ArtifactInfo,
reader io.ReadCloser,
contentType string,
) (*commons.ResponseHeaders, string, error) {
completePath := pkg.JoinWithSeparator("/", info.Image, info.Version, info.FilePath)
headers, sha256, err := c.localBase.Upload(ctx, info.ArtifactInfo, info.FileName, info.Version, completePath,
reader, &generic2.GenericMetadata{})
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to upload file: %q, %q, %q", info.FileName, info.Version,
completePath)
return nil, "", fmt.Errorf("failed to upload file: %w", err)
}
log.Ctx(ctx).Info().Str("sha256", sha256).Msg("Successfully uploaded file. content type: " + contentType)
return headers, sha256, nil
}
func (c *localRegistry) DownloadFile(
ctx context.Context,
info generic.ArtifactInfo,
filePath string,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
download, reader, url, err := c.localBase.Download(ctx, info.ArtifactInfo, info.Version, filePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to download file: %q, %q, %q", info.FileName, info.Version, filePath)
return nil, nil, nil, "", fmt.Errorf("failed to download file: %w", err)
}
return download, reader, nil, url, err
}
func (c *localRegistry) DeleteFile(ctx context.Context, info generic.ArtifactInfo) (*commons.ResponseHeaders, error) {
return c.localBase.DeleteFile(ctx, info, info.FilePath)
}
func (c *localRegistry) HeadFile(
ctx context.Context,
info generic.ArtifactInfo,
filePath string,
) (headers *commons.ResponseHeaders, err error) {
return c.localBase.ExistsE(ctx, info, filePath)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/wire.go | registry/app/pkg/generic/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 generic
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider)
base.Register(registry)
return registry
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
proxy := NewProxy(fileManager, proxyStore, tx, registryDao, imageDao, artifactDao, urlProvider,
spaceFinder, service, localRegistryHelper)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/proxy.go | registry/app/pkg/generic/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"io"
"net/http"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/remote/adapter/generic" // This is required to init generic adapter
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
localRegistryHelper LocalRegistryHelper
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
return &proxy{
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
localRegistryHelper: localRegistryHelper,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeGENERIC}
}
func (r *proxy) PutFile(
_ context.Context,
_ generic.ArtifactInfo,
_ io.ReadCloser,
_ string,
) (*commons.ResponseHeaders, string, error) {
return nil, "", usererror.MethodNotAllowed("generic upload to upstream is not allowed")
}
func (r *proxy) DownloadFile(ctx context.Context, info generic.ArtifactInfo, filePath string) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, nil, nil, "", err
}
_, err = r.localRegistryHelper.FileExists(ctx, info)
if err == nil {
headers, fileReader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, nil, redirectURL, nil
}
// If file exists in local registry, but download failed, we should try to download from remote
log.Error().Ctx(ctx).Msgf("failed to pull from local, attempting to stream from remote, %v", err)
}
remote, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, nil, nil, "", err
}
readCloser, err := remote.GetFile(ctx, filePath)
if err != nil {
return nil, nil, nil, "", usererror.NotFoundf("filepath not found %q, %v", filePath, err)
}
go func(info generic.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
log.Ctx(ctx2).Info().Msgf("Downloading generic artifact %q:%q, filepath: %q for registry: %d",
info.ArtifactInfo.Image, info.Version, filePath, info.RegistryID)
remote2, err2 := NewRemoteRegistryHelper(ctx2, r.spaceFinder, *upstreamProxy, r.service)
if err2 != nil {
log.Ctx(ctx2).Error().Msgf("failed to create remote in goroutine: %v", err2)
return
}
err2 = r.putFileToLocal(ctx2, info, filePath, remote2)
if err2 != nil {
log.Ctx(ctx2).Error().Stack().Err(err2).Msgf("error while putting file to localRegistry %q, %v",
info.RegIdentifier, err2)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated file: %s, registry: %s", filePath, info.RegIdentifier)
}(info)
return &commons.ResponseHeaders{
Headers: map[string]string{},
Code: http.StatusOK,
}, nil, readCloser, "", nil
}
func (r *proxy) putFileToLocal(
ctx context.Context,
info generic.ArtifactInfo,
filePath string,
remote RemoteRegistryHelper,
) error {
readCloser, err := remote.GetFile(ctx, filePath)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("fetching file %s failed, %v", filePath, err)
return err
}
defer readCloser.Close()
_, sha256, err2 := r.localRegistryHelper.PutFile(ctx, info, readCloser, "")
if err2 != nil {
log.Ctx(ctx).Error().Stack().Err(err2).Msgf("uploading file %s failed", filePath)
return err2
}
log.Ctx(ctx).Info().Msgf("Successfully uploaded %s with SHA256: %s", filePath, sha256)
return nil
}
func (r *proxy) DeleteFile(ctx context.Context, info generic.ArtifactInfo) (*commons.ResponseHeaders, error) {
return r.localRegistryHelper.DeleteFile(ctx, info)
}
func (r *proxy) HeadFile(
ctx context.Context,
info generic.ArtifactInfo,
filePath string,
) (headers *commons.ResponseHeaders, err error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, err
}
headers, err = r.localRegistryHelper.FileExists(ctx, info)
if err == nil {
return headers, nil
}
remote, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, err
}
headers, err = remote.HeadFile(ctx, filePath)
if err != nil {
return nil, fmt.Errorf("HeadFile Failure: %w", err)
}
return headers, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/registry.go | registry/app/pkg/generic/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
pkg.Artifact
PutFile(
ctx context.Context,
info generic.ArtifactInfo,
reader io.ReadCloser,
contentType string,
) (
headers *commons.ResponseHeaders,
sha256 string,
err error,
)
DownloadFile(ctx context.Context, info generic.ArtifactInfo, filePath string) (
headers *commons.ResponseHeaders,
fileReader *storage.FileReader,
readCloser io.ReadCloser,
redirectURL string,
err error,
)
DeleteFile(ctx context.Context, info generic.ArtifactInfo) (headers *commons.ResponseHeaders, err error)
HeadFile(ctx context.Context, info generic.ArtifactInfo, filePath string) (
headers *commons.ResponseHeaders,
err error,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/remote_helper.go | registry/app/pkg/generic/remote_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 generic
import (
"context"
"fmt"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
// GetFile Downloads the file for the given package and filename
GetFile(ctx context.Context, filePath string) (io.ReadCloser, error)
HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error)
}
type remoteRegistryHelper struct {
adapter registry.GenericRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, fmt.Errorf("failed to init remote registry: %w", err)
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypeGENERIC)
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
genericReg, ok := adpt.(registry.GenericRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to generic registry")
return fmt.Errorf("adapter not a GenericRegistry (got %T)", adpt)
}
r.adapter = genericReg
return nil
}
func (r *remoteRegistryHelper) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
headers, readCloser, err := r.adapter.GetFile(ctx, filePath)
if err != nil {
evt := log.Ctx(ctx).Error().Err(err).Str("file", filePath)
if headers != nil {
evt = evt.Int("code", headers.Code).Interface("headers", headers.Headers)
} else {
evt = evt.Str("headers", "<nil>")
}
evt.Msgf("GetFile failed")
return nil, fmt.Errorf("GetFile Failure: %w", err)
}
return readCloser, nil
}
func (r *remoteRegistryHelper) HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error) {
headers, err := r.adapter.HeadFile(ctx, filePath)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to head file: %s", filePath)
return nil, fmt.Errorf("HeadFile Failure: %w", err)
}
return headers, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/generic/local_helper.go | registry/app/pkg/generic/local_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 generic
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/generic"
"github.com/harness/gitness/registry/app/storage"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info generic.ArtifactInfo) (*commons.ResponseHeaders, error)
DownloadFile(ctx context.Context, info generic.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
)
PutFile(
ctx context.Context,
info generic.ArtifactInfo,
fileReader io.ReadCloser,
contentType string,
) (headers *commons.ResponseHeaders, sha256 string, err error)
DeleteFile(ctx context.Context, info generic.ArtifactInfo) (*commons.ResponseHeaders, error)
}
type localRegistryHelper struct {
localRegistry LocalRegistry
localBase base.LocalBase
}
func NewLocalRegistryHelper(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return &localRegistryHelper{
localRegistry: localRegistry,
localBase: localBase,
}
}
func (h *localRegistryHelper) FileExists(ctx context.Context, info generic.ArtifactInfo) (
*commons.ResponseHeaders,
error,
) {
headers, err := h.localBase.ExistsE(ctx, info, info.FilePath)
return headers, err
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info generic.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
) {
return h.localBase.Download(ctx, info.ArtifactInfo, info.Version, info.FilePath)
}
func (h *localRegistryHelper) PutFile(
ctx context.Context,
info generic.ArtifactInfo,
fileReader io.ReadCloser,
contentType string,
) (*commons.ResponseHeaders, string, error) {
responseHeaders, sha256, err := h.localRegistry.PutFile(ctx, info, fileReader, contentType)
return responseHeaders, sha256, err
}
func (h *localRegistryHelper) DeleteFile(ctx context.Context, info generic.ArtifactInfo) (
*commons.ResponseHeaders,
error,
) {
return h.localRegistry.DeleteFile(ctx, info)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/base/wire.go | registry/app/pkg/base/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 base
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalBaseProvider(
registryDao store.RegistryRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
nodesDao store.NodesRepository,
tagsDao store.PackageTagRepository,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
) LocalBase {
return NewLocalBase(registryDao, fileManager, tx, imageDao, artifactDao, nodesDao, tagsDao, authorizer, spaceFinder)
}
var WireSet = wire.NewSet(LocalBaseProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/base/base.go | registry/app/pkg/base/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 base
import (
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"path"
"strconv"
"strings"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/metadata"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
var _ LocalBase = (*localBase)(nil)
type LocalBase interface {
// UploadFile uploads the file to the storage.
// FIXME: Validate upload by given sha256 or any other checksums provided
UploadFile(
ctx context.Context,
info pkg.ArtifactInfo,
fileName string,
version string,
path string,
file multipart.File,
metadata metadata.Metadata,
) (headers *commons.ResponseHeaders, sha256 string, err error)
Upload(
ctx context.Context,
info pkg.ArtifactInfo,
fileName,
version,
path string,
file io.ReadCloser,
metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error)
MoveTempFileAndCreateArtifact(
ctx context.Context,
info pkg.ArtifactInfo,
tempFileName,
version,
path string,
metadata metadata.Metadata,
fileInfo types.FileInfo,
failOnConflict bool,
) (*commons.ResponseHeaders, string, int64, bool, error)
Download(ctx context.Context, info pkg.ArtifactInfo, version string, fileName string) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
)
Exists(ctx context.Context, info pkg.ArtifactInfo, path string) bool
ExistsE(ctx context.Context, info pkg.PackageArtifactInfo, path string) (
headers *commons.ResponseHeaders,
err error,
)
DeleteFile(ctx context.Context, info pkg.PackageArtifactInfo, filePath string) (
headers *commons.ResponseHeaders,
err error,
)
ExistsByFilePath(ctx context.Context, registryID int64, filePath string) (bool, error)
CheckIfVersionExists(ctx context.Context, info pkg.PackageArtifactInfo) (bool, error)
DeletePackage(ctx context.Context, info pkg.PackageArtifactInfo) error
DeleteVersion(ctx context.Context, info pkg.PackageArtifactInfo) error
MoveMultipleTempFilesAndCreateArtifact(
ctx context.Context, info *pkg.ArtifactInfo, pathPrefix string,
metadata metadata.Metadata, filesInfo *[]types.FileInfo,
getTempFilePath func(info *pkg.ArtifactInfo, fileInfo *types.FileInfo) string, version string,
) error
}
type localBase struct {
registryDao store.RegistryRepository
fileManager filemanager.FileManager
tx dbtx.Transactor
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
nodesDao store.NodesRepository
tagsDao store.PackageTagRepository
authorizer authz.Authorizer
spaceFinder refcache.SpaceFinder
}
func NewLocalBase(
registryDao store.RegistryRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
nodesDao store.NodesRepository,
tagsDao store.PackageTagRepository,
authorizer authz.Authorizer,
spaceFinder refcache.SpaceFinder,
) LocalBase {
return &localBase{
registryDao: registryDao,
fileManager: fileManager,
tx: tx,
imageDao: imageDao,
artifactDao: artifactDao,
nodesDao: nodesDao,
tagsDao: tagsDao,
authorizer: authorizer,
spaceFinder: spaceFinder,
}
}
func (l *localBase) UploadFile(
ctx context.Context,
info pkg.ArtifactInfo,
fileName string,
version string,
path string,
file multipart.File,
metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
return l.uploadInternal(ctx, info, fileName, version, path, file, nil, metadata)
}
func (l *localBase) Upload(
ctx context.Context,
info pkg.ArtifactInfo,
fileName,
version,
path string,
file io.ReadCloser,
metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
return l.uploadInternal(ctx, info, fileName, version, path, nil, file, metadata)
}
func (l *localBase) MoveTempFileAndCreateArtifact(
ctx context.Context,
info pkg.ArtifactInfo,
tempFileName,
version,
path string,
metadata metadata.Metadata,
fileInfo types.FileInfo,
failOnConflict bool,
) (response *commons.ResponseHeaders, sha256 string, artifactID int64, isExistent bool, err error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
err = l.CheckIfFileAlreadyExist(ctx, info, version, metadata, fileInfo.Filename, path)
if err != nil {
if !errors.IsConflict(err) {
return nil, "", 0, false, err
}
if failOnConflict {
responseHeaders.Code = http.StatusConflict
return responseHeaders, "", 0, true,
usererror.Conflict(fmt.Sprintf("File with name:[%s],"+
" package:[%s], version:[%s] already exist", fileInfo.Filename, info.Image, version))
}
_, fileSha256, err2 := l.GetSHA256ByPath(ctx, info.RegistryID, path)
if err2 != nil {
return responseHeaders, "", 0, true, err2
}
responseHeaders.Code = http.StatusCreated
return responseHeaders, fileSha256, 0, true, nil
}
registry, err := l.registryDao.GetByRootParentIDAndName(ctx, info.RootParentID, info.RegIdentifier)
if err != nil {
return responseHeaders, "", 0, false, errcode.ErrCodeUnknown.WithDetail(err)
}
session, _ := request.AuthSessionFrom(ctx)
err = l.fileManager.MoveTempFile(ctx, path, registry.ID,
info.RootParentID, info.RootIdentifier, fileInfo, tempFileName, session.Principal.ID)
if err != nil {
return responseHeaders, "", 0, false, errcode.ErrCodeUnknown.WithDetail(err)
}
artifactID, err = l.postUploadArtifact(ctx, info, registry, version, metadata, fileInfo)
if err != nil {
return responseHeaders, "", 0, false, err
}
responseHeaders.Code = http.StatusCreated
return responseHeaders, fileInfo.Sha256, artifactID, false, nil
}
func (l *localBase) MoveMultipleTempFilesAndCreateArtifact(
ctx context.Context, info *pkg.ArtifactInfo,
pathPrefix string, metadata metadata.Metadata, filesInfo *[]types.FileInfo,
getTempFilePath func(info *pkg.ArtifactInfo, fileInfo *types.FileInfo) string, version string,
) error {
session, _ := request.AuthSessionFrom(ctx)
for _, fileInfo := range *filesInfo {
filePath := path.Join(pathPrefix, fileInfo.Filename)
_, err := l.fileManager.HeadSHA256(ctx, fileInfo.Sha256, info.RegistryID, info.RootParentID)
if err == nil {
// It means file already exist, or it was moved in some iteration, no need to move it, just save nodes
err = l.fileManager.SaveNodes(ctx, fileInfo.Sha256, info.RegistryID, info.RootParentID,
session.Principal.ID,
fileInfo.Sha256)
if err != nil {
log.Ctx(ctx).Info().Msgf("Failed to move filesInfo with sha %s to %s", fileInfo.Sha256,
fileInfo.Filename)
return err
}
continue
}
// Otherwise, move the file to permanent location and save nodes
err = l.fileManager.MoveTempFile(ctx, filePath, info.RegistryID, info.RootParentID, info.RootIdentifier,
fileInfo, getTempFilePath(info, &fileInfo), session.Principal.ID)
if err != nil {
log.Ctx(ctx).Info().Msgf("Failed to move filesInfo with sha %s to %s", fileInfo.Sha256,
fileInfo.Filename)
return err
}
}
err := l.tx.WithTx(
ctx, func(ctx context.Context) error {
image := &types.Image{
Name: info.Image,
RegistryID: info.RegistryID,
ArtifactType: info.ArtifactType,
Enabled: true,
}
// Create or update image
err := l.imageDao.CreateOrUpdate(ctx, image)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to create image for artifact: [%s] with error: %v",
info.Image, err)
return fmt.Errorf("failed to create image for artifact: [%s], error: %w",
info.Image, err)
}
dbArtifact, err := l.artifactDao.GetByName(ctx, image.ID, version)
if err != nil && !strings.Contains(err.Error(), "resource not found") {
log.Ctx(ctx).Error().Msgf("Failed to fetch artifact : [%s] with error: %v", version, err)
return fmt.Errorf("failed to fetch artifact : [%s] with error: %w", info.Image, err)
}
// Update metadata
err2 := l.updateFilesMetadata(ctx, dbArtifact, metadata, info, filesInfo)
if err2 != nil {
log.Ctx(ctx).Error().Msgf("Failed to update metadata for artifact: [%s] with error: %v",
info.Image, err2)
return fmt.Errorf("failed to update metadata for artifact: [%s] with error: %w", info.Image, err2)
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to parse metadata for artifact: [%s] with error: %v",
info.Image, err)
return fmt.Errorf("failed to parse metadata for artifact: [%s] with error: %w", info.Image, err)
}
// Create or update artifact
_, err = l.artifactDao.CreateOrUpdate(ctx, &types.Artifact{
ImageID: image.ID,
Version: version,
Metadata: metadataJSON,
})
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to create artifact : [%s] with error: %v", info.Image, err)
return fmt.Errorf("failed to create artifact : [%s] with error: %w", info.Image, err)
}
return nil
})
return err
}
func (l *localBase) updateFilesMetadata(
ctx context.Context,
dbArtifact *types.Artifact,
inputMetadata metadata.Metadata,
info *pkg.ArtifactInfo,
filesInfo *[]types.FileInfo,
) error {
var files []metadata.File
if dbArtifact != nil {
err := json.Unmarshal(dbArtifact.Metadata, inputMetadata)
if err != nil {
log.Ctx(ctx).Error().Msgf("Failed to get metadata for artifact: [%s] with registry: [%s] and"+
" error: %v", info.Image, info.RegIdentifier, err)
return fmt.Errorf("failed to get metadata for artifact: [%s] with registry: [%s] and error: %w",
info.Image, info.RegIdentifier, err)
}
}
for _, fileInfo := range *filesInfo {
fileExist := false
files = inputMetadata.GetFiles()
for _, file := range files {
if file.Filename == fileInfo.Filename {
fileExist = true
}
}
if !fileExist {
files = append(files, metadata.File{
Size: fileInfo.Size, Filename: fileInfo.Filename,
CreatedAt: time.Now().UnixMilli(),
Sha256: fileInfo.Sha256,
})
inputMetadata.SetFiles(files)
inputMetadata.UpdateSize(fileInfo.Size)
}
}
return nil
}
func (l *localBase) uploadInternal(
ctx context.Context,
info pkg.ArtifactInfo,
fileName string,
version string,
path string,
file multipart.File,
fileReadCloser io.ReadCloser,
metadata metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
err := l.CheckIfFileAlreadyExist(ctx, info, version, metadata, fileName, path)
if err != nil {
if !errors.IsConflict(err) {
return nil, "", err
}
err = pkg.GetRegistryCheckAccess(ctx, l.authorizer, l.spaceFinder,
info.ParentID, info, enum.PermissionArtifactsDelete)
if err != nil {
return nil, "", usererror.Forbidden(fmt.Sprintf("Not enough permissions to overwrite file %s "+
"(needs DELETE permission).",
fileName))
}
}
registry, err := l.registryDao.GetByRootParentIDAndName(ctx, info.RootParentID, info.RegIdentifier)
if err != nil {
return responseHeaders, "", errcode.ErrCodeUnknown.WithDetail(err)
}
session, _ := request.AuthSessionFrom(ctx)
fileInfo, err := l.fileManager.UploadFile(ctx, path, registry.ID,
info.RootParentID, info.RootIdentifier, file, fileReadCloser, fileName, session.Principal.ID)
if err != nil {
return responseHeaders, "", errcode.ErrCodeUnknown.WithDetail(err)
}
_, err = l.postUploadArtifact(ctx, info, registry, version, metadata, fileInfo)
if err != nil {
return responseHeaders, "", err
}
responseHeaders.Code = http.StatusCreated
return responseHeaders, fileInfo.Sha256, nil
}
func (l *localBase) postUploadArtifact(
ctx context.Context,
info pkg.ArtifactInfo,
registry *types.Registry,
version string,
metadata metadata.Metadata,
fileInfo types.FileInfo,
) (int64, error) {
var artifactID int64
err := l.tx.WithTx(
ctx, func(ctx context.Context) error {
image := &types.Image{
Name: info.Image,
RegistryID: registry.ID,
Enabled: true,
}
err := l.imageDao.CreateOrUpdate(ctx, image)
if err != nil {
return fmt.Errorf("failed to create image for artifact: [%s], error: %w", info.Image, err)
}
dbArtifact, err := l.artifactDao.GetByName(ctx, image.ID, version)
if err != nil && !strings.Contains(err.Error(), "resource not found") {
return fmt.Errorf("failed to fetch artifact : [%s] with error: %w", info.Image, err)
}
metadataJSON := []byte("{}")
if metadata != nil {
err2 := l.updateMetadata(dbArtifact, metadata, info, fileInfo)
if err2 != nil {
return fmt.Errorf("failed to update metadata for artifact: [%s] with error: %w", info.Image, err2)
}
metadataJSON, err = json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to parse metadata for artifact: [%s] with error: %w", info.Image, err)
}
}
artifactID, err = l.artifactDao.CreateOrUpdate(ctx, &types.Artifact{
ImageID: image.ID,
Version: version,
Metadata: metadataJSON,
})
if err != nil {
return fmt.Errorf("failed to create artifact : [%s] with error: %w", info.Image, err)
}
return nil
})
return artifactID, err
}
func (l *localBase) Download(
ctx context.Context,
info pkg.ArtifactInfo,
version string,
fileName string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
path := "/" + info.Image + "/" + version + "/" + fileName
reg, _ := l.registryDao.GetByRootParentIDAndName(ctx, info.RootParentID, info.RegIdentifier)
fileReader, _, redirectURL, err := l.fileManager.DownloadFile(ctx, path, reg.ID,
info.RegIdentifier, info.RootIdentifier, true)
if err != nil {
return responseHeaders, nil, "", err
}
responseHeaders.Code = http.StatusOK
return responseHeaders, fileReader, redirectURL, nil
}
func (l *localBase) Exists(ctx context.Context, info pkg.ArtifactInfo, path string) bool {
exists, _, _, err := l.getSHA256(ctx, info.RegistryID, path)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to check if file: [%s] exists", path)
}
return exists
}
func (l *localBase) ExistsE(
ctx context.Context,
info pkg.PackageArtifactInfo,
filePath string,
) (headers *commons.ResponseHeaders, err error) {
exists, sha256, size, err := l.getSHA256(ctx, info.GetRegistryID(), GetCompletePath(info, filePath))
headers = &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
// TODO: Need better error handling
if exists {
headers.Code = http.StatusOK
headers.Headers[storage.HeaderContentDigest] = sha256
headers.Headers[storage.HeaderContentLength] = strconv.FormatInt(size, 10)
headers.Headers[storage.HeaderEtag] = "sha256:" + sha256
} else {
headers.Code = http.StatusNotFound
}
return headers, err
}
func (l *localBase) DeleteFile(ctx context.Context, info pkg.PackageArtifactInfo, filePath string) (
headers *commons.ResponseHeaders,
err error,
) {
completePath := GetCompletePath(info, filePath)
exists, _, _, _ := l.getSHA256(ctx, info.GetRegistryID(), completePath)
if exists {
err = l.fileManager.DeleteLeafNode(ctx, info.GetRegistryID(), completePath)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("Failed to delete file: %q, registry: %d", completePath,
info.GetRegistryID())
return nil, err
}
return &commons.ResponseHeaders{
Code: 204,
Headers: map[string]string{},
}, nil
}
return &commons.ResponseHeaders{
Code: http.StatusNotFound,
Headers: map[string]string{},
}, nil
}
func (l *localBase) ExistsByFilePath(ctx context.Context, registryID int64, filePath string) (bool, error) {
exists, _, err := l.GetSHA256ByPath(ctx, registryID, filePath)
if err != nil && strings.Contains(err.Error(), "resource not found") {
return false, nil
}
return exists, err
}
func (l *localBase) CheckIfVersionExists(ctx context.Context, info pkg.PackageArtifactInfo) (bool, error) {
_, err := l.artifactDao.GetByRegistryImageAndVersion(ctx,
info.BaseArtifactInfo().RegistryID, info.BaseArtifactInfo().Image, info.GetVersion())
if err != nil {
return false, err
}
return true, nil
}
func (l *localBase) getSHA256(ctx context.Context, registryID int64, path string) (
exists bool,
sha256 string,
size int64,
err error,
) {
filePath := "/" + path
sha256, size, err = l.fileManager.HeadFile(ctx, filePath, registryID)
if err != nil {
return false, "", 0, err
}
//FIXME: err should be checked on if the record doesn't exist or there was DB call issue
return true, sha256, size, nil
}
func (l *localBase) GetSHA256ByPath(ctx context.Context, registryID int64, filePath string) (
exists bool,
sha256 string,
err error,
) {
sha256, _, err = l.fileManager.HeadFile(ctx, "/"+filePath, registryID)
if err != nil {
return false, "", err
}
//FIXME: err should be checked on if the record doesn't exist or there was DB call issue
return true, sha256, err
}
func (l *localBase) updateMetadata(
dbArtifact *types.Artifact,
inputMetadata metadata.Metadata,
info pkg.ArtifactInfo,
fileInfo types.FileInfo,
) error {
var files []metadata.File
if dbArtifact != nil {
err := json.Unmarshal(dbArtifact.Metadata, inputMetadata)
if err != nil {
return fmt.Errorf("failed to get metadata for artifact: [%s] with registry: [%s] and error: %w", info.Image,
info.RegIdentifier, err)
}
fileExist := false
files = inputMetadata.GetFiles()
for _, file := range files {
if file.Filename == fileInfo.Filename {
fileExist = true
}
}
if !fileExist {
files = append(files, metadata.File{
Size: fileInfo.Size, Filename: fileInfo.Filename,
CreatedAt: time.Now().UnixMilli(),
Sha256: fileInfo.Sha256,
})
inputMetadata.SetFiles(files)
inputMetadata.UpdateSize(fileInfo.Size)
}
} else {
files = append(files, metadata.File{
Size: fileInfo.Size, Filename: fileInfo.Filename,
Sha256: fileInfo.Sha256, CreatedAt: time.Now().UnixMilli(),
})
inputMetadata.SetFiles(files)
inputMetadata.UpdateSize(fileInfo.Size)
}
return nil
}
func (l *localBase) CheckIfFileAlreadyExist(
ctx context.Context,
info pkg.ArtifactInfo,
version string,
metadata metadata.Metadata,
fileName string,
path string,
) error {
image, err := l.imageDao.GetByName(ctx, info.RegistryID, info.Image)
if err != nil && !strings.Contains(err.Error(), "resource not found") {
return fmt.Errorf("failed to fetch the image for artifact : [%s] with registry : [%s]", info.Image,
info.RegIdentifier)
}
if image == nil {
return nil
}
dbArtifact, err := l.artifactDao.GetByName(ctx, image.ID, version)
if err != nil && !strings.Contains(err.Error(), "resource not found") {
return fmt.Errorf("failed to fetch artifact : [%s] with registry : [%s]", info.Image, info.RegIdentifier)
}
if dbArtifact == nil {
return nil
}
err = json.Unmarshal(dbArtifact.Metadata, metadata)
if err != nil {
return fmt.Errorf("failed to get metadata for artifact: [%s] with registry: [%s] and error: %w", info.Image,
info.RegIdentifier, err)
}
for _, file := range metadata.GetFiles() {
if file.Filename == fileName && l.Exists(ctx, info, path) {
return errors.Conflictf("file: [%s] for Artifact: [%s], Version: [%s] and registry: [%s] already exist",
fileName, info.Image, version, info.RegIdentifier)
}
}
return nil
}
func (l *localBase) DeletePackage(ctx context.Context, info pkg.PackageArtifactInfo) error {
err := l.tx.WithTx(
ctx, func(ctx context.Context) error {
path := "/" + info.BaseArtifactInfo().Image
err := l.nodesDao.DeleteByNodePathAndRegistryID(ctx, path, info.BaseArtifactInfo().RegistryID)
if err != nil {
return err
}
err = l.artifactDao.DeleteByImageNameAndRegistryID(ctx,
info.BaseArtifactInfo().RegistryID, info.BaseArtifactInfo().Image)
if err != nil {
return err
}
err = l.imageDao.DeleteByImageNameAndRegID(ctx, info.BaseArtifactInfo().RegistryID,
info.BaseArtifactInfo().Image)
if err != nil {
return err
}
return nil
})
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to delete the package %v", info.BaseArtifactInfo().Image)
return err
}
return nil
}
func (l *localBase) DeleteVersion(ctx context.Context, info pkg.PackageArtifactInfo) error {
err := l.tx.WithTx(
ctx, func(ctx context.Context) error {
path := "/" + info.BaseArtifactInfo().Image + "/" + info.GetVersion()
err := l.nodesDao.DeleteByNodePathAndRegistryID(ctx,
path, info.BaseArtifactInfo().RegistryID)
if err != nil {
return err
}
err = l.artifactDao.DeleteByVersionAndImageName(ctx,
info.BaseArtifactInfo().Image, info.GetVersion(), info.BaseArtifactInfo().RegistryID)
if err != nil {
return err
}
return nil
})
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to delete the version for artifact %v:%v", info.BaseArtifactInfo().Image,
info.GetVersion())
return err
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/base/wrapper.go | registry/app/pkg/base/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 base
import (
"context"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/errors"
"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/pkg"
"github.com/harness/gitness/registry/app/pkg/quarantine"
"github.com/harness/gitness/registry/app/pkg/response"
huggingfacetypes "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/app/store"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
var TypeRegistry = map[string]pkg.Artifact{}
func Register(registries ...pkg.Artifact) {
for _, r := range registries {
for _, packageType := range r.GetPackageTypes() {
log.Info().Msgf("Registering package type %s with artifact type %s", packageType, r.GetArtifactType())
key := getFactoryKey(packageType, r.GetArtifactType())
TypeRegistry[key] = r
}
}
}
func NoProxyWrapper(
ctx context.Context,
registryDao store.RegistryRepository,
f func(registry registrytypes.Registry, a pkg.Artifact) response.Response,
info pkg.PackageArtifactInfo,
) (response.Response, error) {
return proxyInternal(ctx, registryDao, nil, f, info, false, false)
}
func ProxyWrapper(
ctx context.Context,
registryDao store.RegistryRepository,
quarantineFinder quarantine.Finder,
f func(registry registrytypes.Registry, a pkg.Artifact) response.Response,
info pkg.PackageArtifactInfo,
checkQuarantine bool,
) (response.Response, error) {
return proxyInternal(ctx, registryDao, quarantineFinder, f, info, true, checkQuarantine)
}
func proxyInternal(
ctx context.Context,
registryDao store.RegistryRepository,
quarantineFinder quarantine.Finder,
f func(registry registrytypes.Registry, a pkg.Artifact) response.Response,
info pkg.PackageArtifactInfo,
useUpstream bool,
checkQuarantine bool,
) (response.Response, error) {
var r response.Response
requestRepoKey := info.BaseArtifactInfo().RegIdentifier
registries, skipped, err := filterRegs(ctx, registryDao, requestRepoKey, info, useUpstream)
if err != nil {
return r, err
}
var lastError error
for _, registry := range registries {
log.Ctx(ctx).Info().Msgf("Using Registry: %s, Type: %s", registry.Name, registry.Type)
art := GetArtifactRegistry(registry)
if art != nil { //nolint:nestif
// Check quarantine status if enabled
if checkQuarantine && quarantineFinder != nil {
version := info.GetVersion()
image := info.BaseArtifactInfo().Image
var artifactType *artifact.ArtifactType
// Extract artifact type from package-specific info (valid for only HuggingFace RepoType)
if hfInfo, ok := info.(huggingfacetypes.ArtifactInfo); ok {
artifactType = &hfInfo.RepoType
}
err := quarantineFinder.CheckArtifactQuarantineStatus(ctx, registry.ID, image, version, artifactType)
if err != nil {
if errors.Is(err, usererror.ErrQuarantinedArtifact) {
return r, usererror.ErrQuarantinedArtifact
}
log.Ctx(ctx).Error().Stack().Err(err).Msgf("error"+
" while checking the quarantine status of artifact: [%s], version: [%s]",
image, version)
return r, err
}
}
r = f(registry, art)
if r.GetError() == nil {
return r, nil
}
lastError = r.GetError()
log.Ctx(ctx).Warn().Msgf("Repository: %s, Type: %s, error: %v", registry.Name, registry.Type,
r.GetError())
}
}
if !pkg.IsEmpty(skipped) {
var skippedRegNames []string
for _, registry := range skipped {
skippedRegNames = append(skippedRegNames, registry.Name)
}
return r, errors.InvalidArgumentf("no matching artifacts found in registry %s, skipped registries: [%s] "+
"due to allowed/blocked policies",
requestRepoKey, pkg.JoinWithSeparator(", ", skippedRegNames...))
}
if lastError != nil {
return r, lastError
}
return r, errors.NotFoundf("no matching artifacts found in registry %s", requestRepoKey)
}
func factory(key string) pkg.Artifact {
return TypeRegistry[key]
}
func getFactoryKey(packageType artifact.PackageType, registryType artifact.RegistryType) string {
return string(packageType) + ":" + string(registryType)
}
func GetArtifactRegistry(registry registrytypes.Registry) pkg.Artifact {
key := getFactoryKey(registry.PackageType, registry.Type)
return factory(key)
}
func filterRegs(
ctx context.Context,
registryDao store.RegistryRepository,
repoKey string,
info pkg.PackageArtifactInfo,
upstream bool,
) (included []registrytypes.Registry, skipped []registrytypes.Registry, err error) {
registries, err := GetOrderedRepos(ctx, registryDao, repoKey, info.BaseArtifactInfo().ParentID, upstream)
if err != nil {
return nil, nil, err
}
exists, imageVersion := info.GetImageVersion()
if !exists {
log.Ctx(ctx).Debug().Msgf("image version not ready for %s, skipping filter", repoKey)
return registries, nil, nil
}
for _, repo := range registries {
allowedPatterns := repo.AllowedPattern
blockedPatterns := repo.BlockedPattern
err2 := utils.PatternAllowed(allowedPatterns, blockedPatterns, imageVersion)
if err2 != nil {
log.Ctx(ctx).Debug().Msgf("Skipping repository %s", repo.Name)
skipped = append(skipped, repo)
continue
}
included = append(included, repo)
}
return included, skipped, nil
}
func GetOrderedRepos(
ctx context.Context,
registryDao store.RegistryRepository,
repoKey string,
parentID int64,
upstream bool,
) ([]registrytypes.Registry, error) {
var result []registrytypes.Registry
registry, err := registryDao.GetByParentIDAndName(ctx, parentID, repoKey)
if err != nil {
return result, errors.NotFoundf("registry %s not found", repoKey)
}
result = append(result, *registry)
if !upstream {
return result, nil
}
proxies := registry.UpstreamProxies
if len(proxies) > 0 {
upstreamRepos, err2 := registryDao.GetByIDIn(ctx, proxies)
if err2 != nil {
log.Ctx(ctx).Error().Msgf("Failed to get upstream proxies for %s: %v", repoKey, err2)
return result, err2
}
repoMap := make(map[int64]registrytypes.Registry)
for _, repo := range *upstreamRepos {
repoMap[repo.ID] = repo
}
for _, proxyID := range proxies {
if repo, ok := repoMap[proxyID]; ok {
result = append(result, repo)
}
}
}
return result, nil
}
func SearchPackagesProxyWrapper(
ctx context.Context,
registryDao store.RegistryRepository,
f func(registry registrytypes.Registry, a pkg.Artifact, limit, offset int) response.Response,
extractResponseDataFunc func(searchResponse response.Response) ([]any, int64),
info pkg.PackageArtifactInfo,
limit int,
offset int,
) ([]any, int64, error) {
requestRepoKey := info.BaseArtifactInfo().RegIdentifier
// Get all registries (local + proxies) - Z = [x, p1, p2, p3...]
registries, skipped, err := filterRegs(ctx, registryDao, requestRepoKey, info, true)
if err != nil {
return nil, 0, err
}
// Pre-allocate slice for aggregated results (generic interface{})
var aggregatedResults []any
var totalCount int64
currentOffset := offset
remainingLimit := limit
// Loop through each registry R in Z
for _, registry := range registries {
if remainingLimit <= 0 {
break
}
log.Ctx(ctx).Info().Msgf("Searching in Registry: %s, Type: %s", registry.Name, registry.Type)
art := GetArtifactRegistry(registry)
if art == nil {
log.Ctx(ctx).Warn().Msgf("No artifact registry found for: %s", registry.Name)
continue
}
// 1. Call f with remainingLimit and currentOffset
searchResponse := f(registry, art, remainingLimit, currentOffset)
if searchResponse.GetError() != nil {
log.Ctx(ctx).Warn().Msgf("Search failed for registry %s: %v", registry.Name, searchResponse.GetError())
continue
}
// Extract response data using the provided function
nativeResults, totalHits := extractResponseDataFunc(searchResponse)
resultsSize := len(nativeResults)
totalCount += totalHits
if resultsSize == 0 {
continue
}
// 2. Append search results (preserve native types)
aggregatedResults = append(aggregatedResults, nativeResults...)
// 3. Update currentOffset = max(0, currentOffset - registryResults.size)
currentOffset = max(0, currentOffset-resultsSize)
// 4. Update remainingLimit = remainingLimit - registryResults.size
remainingLimit -= resultsSize
// Early exit if we have enough results
if remainingLimit <= 0 {
break
}
}
// Log skipped registries if any
if !pkg.IsEmpty(skipped) {
skippedRegNames := make([]string, 0, len(skipped))
for _, registry := range skipped {
skippedRegNames = append(skippedRegNames, registry.Name)
}
log.Ctx(ctx).Warn().Msgf("Skipped registries due to policies: [%s]",
pkg.JoinWithSeparator(", ", skippedRegNames...))
}
return aggregatedResults, totalCount, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/base/utils.go | registry/app/pkg/base/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 base
import "github.com/harness/gitness/registry/app/pkg"
func GetCompletePath(info pkg.PackageArtifactInfo, filePath string) string {
return info.GetImage() + "/" + info.GetVersion() + "/" + filePath
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/huggingface/local.go | registry/app/pkg/huggingface/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
"regexp"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
urlprovider "github.com/harness/gitness/app/url"
apicontract "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
huggingfacemetadata "github.com/harness/gitness/registry/app/metadata/huggingface"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
)
var (
frontMatterRE = regexp.MustCompile(`(?s)^---\s*\n(.*?)\n---`)
allowedTypes = map[string]bool{"model": true, "dataset": true}
)
const (
rootPathString = "/"
tmp = "tmp"
maxCommitEntries = 50000 // Add reasonable limit
contentTypeJSON = "application/json"
)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
}
func (c *localRegistry) ValidateYaml(_ context.Context, _ huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.ValidateYamlResponse, err error,
) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
req := &huggingfacetype.ValidateYamlRequest{}
if err = json.NewDecoder(body).Decode(&req); err != nil {
err = usererror.BadRequest("Invalid request json body")
headers.Code = http.StatusBadRequest
return headers, nil, err
}
if req.RepoType == nil || !allowedTypes[*req.RepoType] {
err = usererror.BadRequest("Unsupported repoType")
headers.Code = http.StatusBadRequest
return headers, nil, err
}
if req.Content == nil || frontMatterRE.FindStringSubmatch(*req.Content) == nil {
return headers, &huggingfacetype.ValidateYamlResponse{
Errors: &[]huggingfacetype.Debug{},
Warnings: &[]huggingfacetype.Debug{},
}, nil
}
// Parse YAML
var meta map[string]any
if err = yaml.Unmarshal([]byte(frontMatterRE.FindStringSubmatch(*req.Content)[1]), &meta); err != nil {
errMsg := stringPtr(fmt.Sprintf("Invalid YAML: %v", err))
errors := &[]huggingfacetype.Debug{
{Message: errMsg},
}
response = &huggingfacetype.ValidateYamlResponse{
Errors: errors,
Warnings: &[]huggingfacetype.Debug{},
}
headers.Code = http.StatusBadRequest
return headers, response, nil
}
// Validate fields
// Create a slice of validations to perform
validations := []struct {
field string
validate func(map[string]any, string) (*huggingfacetype.ValidateYamlResponse, bool)
}{
{"pipeline_tag", validateString},
{"tags", validateSlice},
{"widget", validateSlice},
}
// Run all validations
for _, v := range validations {
if res, ok := v.validate(meta, v.field); !ok {
headers.Code = http.StatusBadRequest
return headers, res, nil
}
}
headers.Code = http.StatusOK
return headers,
&huggingfacetype.ValidateYamlResponse{
Errors: &[]huggingfacetype.Debug{},
Warnings: &[]huggingfacetype.Debug{},
}, nil
}
func (c *localRegistry) PreUpload(_ context.Context, _ huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.PreUploadResponse, err error,
) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
req := &huggingfacetype.PreUploadRequest{}
if err = json.NewDecoder(body).Decode(&req); err != nil {
err = usererror.BadRequest("Invalid request json body")
headers.Code = http.StatusBadRequest
return headers, nil, err
}
if req.Files == nil || len(*req.Files) == 0 {
err = usererror.BadRequest("Invalid request json body")
headers.Code = http.StatusBadRequest
return
}
// Create the response file slice
files := make([]huggingfacetype.PreUploadResponseFile, 0, len(*req.Files))
for _, f := range *req.Files {
files = append(files, huggingfacetype.NewPreUploadResponseFile(f.Path))
}
resp := &huggingfacetype.PreUploadResponse{
Files: &files,
}
headers.Code = http.StatusOK
return headers, resp, nil
}
func (c *localRegistry) RevisionInfo(
ctx context.Context, info huggingfacetype.ArtifactInfo,
queryParams map[string][]string,
) (
headers *commons.ResponseHeaders, response *huggingfacetype.RevisionInfoResponse, err error,
) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
expand := queryParams["expand"]
if len(expand) > 0 && expand[0] == "xetEnabled" {
headers.Code = http.StatusOK
return headers, &huggingfacetype.RevisionInfoResponse{
XetEnabled: false,
Metadata: huggingfacemetadata.Metadata{
ID: info.Repo,
},
}, nil
}
//todo: add logs
image, err := c.imageDao.GetByNameAndType(ctx, info.RegistryID, info.Repo, &info.RepoType)
if err != nil {
return headers, nil, err
}
artifact, err := c.artifactDao.GetByName(ctx, image.ID, info.Revision)
if err != nil {
return headers, nil, err
}
metadata := &huggingfacemetadata.HuggingFaceMetadata{}
err = json.Unmarshal(artifact.Metadata, metadata)
if err != nil {
return headers, nil, err
}
metadata.SHA = info.Revision
if metadata.ID == "" {
err = usererror.BadRequest("Repo ID not found")
headers.Code = http.StatusNotFound
return headers, nil, err
}
headers.Code = http.StatusOK
return headers, &huggingfacetype.RevisionInfoResponse{
XetEnabled: false,
Metadata: metadata.Metadata,
}, nil
}
func (c *localRegistry) LfsInfo(
ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser,
token string,
) (headers *commons.ResponseHeaders, response *huggingfacetype.LfsInfoResponse, err error) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": "application/vnd.git-lfs+json"},
}
resp := &huggingfacetype.LfsInfoResponse{
Objects: &[]huggingfacetype.LfsObjectResponse{},
}
pkgURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "huggingface")
req := &huggingfacetype.LfsInfoRequest{}
if err = json.NewDecoder(body).Decode(req); err != nil {
err = usererror.BadRequest("Invalid LFS info body")
headers.Code = http.StatusBadRequest
return headers, nil, err
}
if req.Objects == nil || len(*req.Objects) == 0 {
headers.Code = http.StatusOK
return headers, resp, nil
}
for _, obj := range *req.Objects {
objResp := huggingfacetype.LfsObjectResponse{
Oid: obj.Oid,
Size: obj.Size,
}
filePath, _ := c.fileManager.HeadSHA256(ctx, obj.Oid, info.RegistryID, info.RootParentID)
exists := filePath != ""
switch req.Operation {
case "upload":
if exists {
continue
}
objResp.Actions = &map[string]huggingfacetype.LfsAction{
req.Operation: lfsAction(getBlobURL(pkgURL, req.Operation, obj.Oid, token, info), obj.Oid, token),
"verify": lfsAction(getBlobURL(pkgURL, "verify", obj.Oid, token, info), obj.Oid, token),
}
case "download":
if exists {
objResp.Actions = &map[string]huggingfacetype.LfsAction{
req.Operation: lfsAction(getBlobURL(pkgURL, req.Operation, obj.Oid, token, info), obj.Oid, token),
}
} else {
objResp.Error = &huggingfacetype.LfsError{
Code: http.StatusNotFound,
Message: "object not found",
}
}
default:
objResp.Error = &huggingfacetype.LfsError{
Code: http.StatusBadRequest,
Message: "unsupported operation: " + req.Operation,
}
}
*resp.Objects = append(*resp.Objects, objResp)
}
headers.Code = http.StatusOK
return headers, resp, nil
}
func (c *localRegistry) LfsUpload(
ctx context.Context, info huggingfacetype.ArtifactInfo,
body io.ReadCloser,
) (headers *commons.ResponseHeaders, response *huggingfacetype.LfsUploadResponse, err error) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
resp := &huggingfacetype.LfsUploadResponse{}
file := types.FileInfo{Sha256: info.SHA256}
info.Image = info.Repo
tmpFilePath := getTmpFilePath(&info.ArtifactInfo, &file)
fileInfo, tmpFileName, err := c.fileManager.UploadTempFileToPath(ctx, info.RootIdentifier, nil,
tmpFilePath, tmpFilePath, body)
if err != nil {
log.Ctx(ctx).Info().Msgf("Upload failed for file %s, %v", tmpFileName, err)
headers.Code = http.StatusInternalServerError
return headers, resp, err
}
log.Ctx(ctx).Info().Msgf("Uploaded file %s to %s", tmpFileName, fileInfo.Filename)
resp.Success = true
headers.Code = http.StatusCreated
return headers, resp, nil
}
func (c *localRegistry) LfsVerify(
ctx context.Context, info huggingfacetype.ArtifactInfo,
_ io.ReadCloser,
) (headers *commons.ResponseHeaders, response *huggingfacetype.LfsVerifyResponse, err error) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
resp := &huggingfacetype.LfsVerifyResponse{}
filePath, _ := c.fileManager.HeadSHA256(ctx, info.SHA256, info.RegistryID, info.RootParentID)
exists := c.FileExists(ctx, info)
if filePath == "" && !exists {
log.Ctx(ctx).Info().Msgf("File %s does not exist", info.SHA256)
return headers, nil, fmt.Errorf("file %s does not exist", info.SHA256)
}
resp.Success = true
headers.Code = http.StatusOK
return headers, resp, nil
}
func (c *localRegistry) CommitRevision(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.CommitRevisionResponse, err error,
) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{"Content-Type": contentTypeJSON},
}
headerInfo := &huggingfacetype.HeaderInfo{}
lfsFiles := &[]huggingfacetype.LfsFileInfo{}
siblings := &[]huggingfacemetadata.Sibling{}
commitBytes, _ := io.ReadAll(body)
commits := string(commitBytes)
scanner := bufio.NewScanner(strings.NewReader(commits))
processedEntries := 0
for scanner.Scan() {
if processedEntries >= maxCommitEntries {
log.Ctx(ctx).Warn().Msgf("Reached maximum commit entries limit: %d", maxCommitEntries)
break
}
processedEntries++
line := scanner.Text()
var entry huggingfacetype.CommitEntry
if err = json.Unmarshal([]byte(line), &entry); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to unmarshal commit entry: %s", line)
continue
}
data, err2 := json.Marshal(entry.Value)
if err2 != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to marshal header info")
return headers, nil, err2
}
switch entry.Key {
case "header":
if err = json.Unmarshal(data, &headerInfo); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to unmarshal header info")
return headers, nil, err
}
case "lfsFile":
var lfsFile huggingfacetype.LfsFileInfo
if err = json.Unmarshal(data, &lfsFile); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to unmarshal LFS file info")
continue
}
*lfsFiles = append(*lfsFiles, lfsFile)
*siblings = append(*siblings, huggingfacemetadata.Sibling{RFilename: lfsFile.Path})
}
}
if err = scanner.Err(); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Error reading commits string")
return headers, nil, err
}
var readme string
var filesInfo []types.FileInfo
for _, lfsFile := range *lfsFiles {
fileInfo := types.FileInfo{
Size: lfsFile.Size,
Sha256: lfsFile.Oid,
Filename: lfsFile.Path,
}
filesInfo = append(filesInfo, fileInfo)
}
readme = c.readme(ctx, info, lfsFiles)
modelMetadata := huggingfacemetadata.Metadata{
ID: info.Repo,
ModelID: info.Repo,
Siblings: *siblings,
LastModified: time.Now().UTC().Format(time.RFC3339),
Private: true,
Readme: readme,
CardData: &huggingfacemetadata.CardData{},
}
if headerInfo.Summary != "" {
modelMetadata.CardData.Tags = append(modelMetadata.CardData.Tags, "summary:"+headerInfo.Summary)
}
hfMetadata := huggingfacemetadata.HuggingFaceMetadata{
Metadata: modelMetadata,
}
info.ArtifactType = &info.RepoType
info.Image = info.Repo
filePathPrefix := fmt.Sprintf("/%s/%s/%s", info.RepoType, info.Repo, info.Revision)
err = c.localBase.MoveMultipleTempFilesAndCreateArtifact(ctx, &info.ArtifactInfo, filePathPrefix, &hfMetadata,
&filesInfo, getTmpFilePath, info.Revision)
if err != nil {
return headers, nil, err
}
commitURL := fmt.Sprintf("%s/%s/commit/%s", info.RepoType, info.Repo, info.Revision)
headers.Code = http.StatusOK
headers.Headers["X-Harness-Commit-Processed"] = "true"
resp := &huggingfacetype.CommitRevisionResponse{
CommitURL: commitURL,
CommitMessage: headerInfo.Summary,
CommitDescription: headerInfo.Description,
OID: info.Revision,
Success: true,
}
return headers, resp, nil
}
func (c *localRegistry) HeadFile(ctx context.Context, info huggingfacetype.ArtifactInfo, fileName string) (
headers *commons.ResponseHeaders, err error,
) {
headers = &commons.ResponseHeaders{
Headers: map[string]string{},
}
dbImage, err := c.imageDao.GetByNameAndType(ctx, info.RegistryID, info.Repo, &info.RepoType)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get image: %s", string(info.RepoType)+"/"+info.Repo)
headers.Headers["Content-Type"] = contentTypeJSON
headers.Code = http.StatusNotFound
return headers, err
}
_, err = c.artifactDao.GetByName(ctx, dbImage.ID, info.Revision)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get artifact: %s", info.Revision)
headers.Headers["Content-Type"] = contentTypeJSON
headers.Code = http.StatusNotFound
return headers, err
}
sha256, size, err := c.fileManager.HeadFile(ctx,
"/"+string(info.RepoType)+"/"+info.Repo+"/"+info.Revision+"/"+fileName,
info.RegistryID)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file: %s", fileName)
headers.Headers["Content-Type"] = contentTypeJSON
headers.Code = http.StatusNotFound
return headers, err
}
headers.Code = http.StatusOK
headers.Headers["Content-Type"] = "application/octet-stream"
headers.Headers["Content-Length"] = fmt.Sprintf("%d", size)
headers.Headers["X-Repo-Commit"] = info.Revision
headers.Headers["ETag"] = sha256
return headers, nil
}
func (c *localRegistry) DownloadFile(ctx context.Context, info huggingfacetype.ArtifactInfo, fileName string) (
headers *commons.ResponseHeaders, body *storage.FileReader, redirectURL string, err error,
) {
headers, err = c.HeadFile(ctx, info, fileName)
if err != nil {
return headers, nil, "", err
}
body, _, redirectURL, err = c.fileManager.DownloadFile(ctx,
"/"+string(info.RepoType)+"/"+info.Repo+"/"+info.Revision+"/"+fileName, info.RegistryID,
info.RegIdentifier, info.RootIdentifier, true)
return headers, body, redirectURL, err
}
func (c *localRegistry) FileExists(ctx context.Context, info huggingfacetype.ArtifactInfo) bool {
file := types.FileInfo{Sha256: info.SHA256}
info.Image = info.Repo
tmpFilePath := getTmpFilePath(&info.ArtifactInfo, &file)
tmpPath := path.Join(rootPathString, info.RootIdentifier, tmp, tmpFilePath)
exists, _, err := c.fileManager.FileExists(ctx, info.RootIdentifier, tmpPath)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to check if file exists: %s", tmpPath)
}
return exists
}
func getBlobURL(pkgURL, operation, sha256, token string, info huggingfacetype.ArtifactInfo) string {
return fmt.Sprintf(pkgURL+"/api/%ss/%s/%s/multipart/%s/%s?sig=%s",
info.RepoType, info.Repo, info.Revision, operation, sha256, strings.TrimPrefix(token, "Bearer "))
}
func (c *localRegistry) readme(
ctx context.Context, info huggingfacetype.ArtifactInfo,
lfsFiles *[]huggingfacetype.LfsFileInfo,
) string {
for _, lfsFile := range *lfsFiles {
file := types.FileInfo{Sha256: lfsFile.Oid}
tmpFileName := getTmpFilePath(&info.ArtifactInfo, &file)
if strings.ToLower(lfsFile.Path) == "readme.md" {
reader, _, err := c.fileManager.DownloadTempFile(ctx, lfsFile.Size, tmpFileName, info.RootIdentifier)
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to download readme file %s", tmpFileName)
return ""
}
defer reader.Close()
readmeBytes, err2 := io.ReadAll(reader)
if err2 != nil {
log.Ctx(ctx).Warn().Msgf("Failed to read readme file %s", tmpFileName)
return ""
}
return string(readmeBytes)
}
}
return ""
}
func lfsAction(blobURL, oid, token string) huggingfacetype.LfsAction {
return huggingfacetype.LfsAction{
Href: blobURL,
Header: map[string]string{
"X-Checksum-Sha256": oid,
"Authorization": token,
},
}
}
func validateSlice(meta map[string]any, metaKey string) (*huggingfacetype.ValidateYamlResponse, bool) {
if v, ok := meta[metaKey]; ok && !isSlice(v) {
msg := stringPtr(fmt.Sprintf(`"%s" must be an array`, metaKey))
warnings := &[]huggingfacetype.Debug{
{Message: msg},
}
return &huggingfacetype.ValidateYamlResponse{
Errors: &[]huggingfacetype.Debug{},
Warnings: warnings,
}, false
}
return nil, true
}
func getTmpFilePath(info *pkg.ArtifactInfo, fileInfo *types.FileInfo) string {
return info.RootIdentifier + "/" + info.RegIdentifier + "/" + info.Image + "/" + "/upload/" + fileInfo.Sha256
}
func validateString(meta map[string]any, metaKey string) (*huggingfacetype.ValidateYamlResponse, bool) {
if v, ok := meta[metaKey]; ok && !isString(v) {
msg := stringPtr(fmt.Sprintf(`"%s" must be a string`, metaKey))
warnings := &[]huggingfacetype.Debug{
{Message: msg},
}
return &huggingfacetype.ValidateYamlResponse{
Errors: &[]huggingfacetype.Debug{},
Warnings: warnings,
}, false
}
return nil, true
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
}
}
func (c *localRegistry) GetArtifactType() apicontract.RegistryType {
return apicontract.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []apicontract.PackageType {
return []apicontract.PackageType{apicontract.PackageTypeHUGGINGFACE}
}
func isSlice(v any) bool { _, ok := v.([]any); return ok }
func isString(v any) bool { _, ok := v.(string); return ok }
// stringPtr returns a pointer to the given string.
func stringPtr(s string) *string {
return &s
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/huggingface/wire.go | registry/app/pkg/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 (
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
// WireSet provides a wire set for the huggingface package.
var WireSet = wire.NewSet(
LocalRegistryProvider,
)
// ProvideLocalRegistry provides a huggingface local registry.
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider)
base.Register(registry)
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/pkg/huggingface/registry.go | registry/app/pkg/huggingface/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface"
"github.com/harness/gitness/registry/app/storage"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type Registry interface {
pkg.Artifact
ValidateYaml(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.ValidateYamlResponse, err error)
PreUpload(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.PreUploadResponse, err error)
RevisionInfo(ctx context.Context, info huggingfacetype.ArtifactInfo, queryParams map[string][]string) (
headers *commons.ResponseHeaders, response *huggingfacetype.RevisionInfoResponse, err error)
LfsInfo(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser, token string) (
headers *commons.ResponseHeaders, response *huggingfacetype.LfsInfoResponse, err error)
LfsUpload(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.LfsUploadResponse, err error)
LfsVerify(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.LfsVerifyResponse, err error)
CommitRevision(ctx context.Context, info huggingfacetype.ArtifactInfo, body io.ReadCloser) (
headers *commons.ResponseHeaders, response *huggingfacetype.CommitRevisionResponse, err error)
HeadFile(ctx context.Context, info huggingfacetype.ArtifactInfo, fileName string) (
responseHeaders *commons.ResponseHeaders, err error)
DownloadFile(ctx context.Context, info huggingfacetype.ArtifactInfo, fileName string) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, redirectURL string, err error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/compat.go | registry/app/pkg/docker/compat.go | // Source: https://gitlab.com/gitlab-org/container-registry
// Copyright 2019 Gitlab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"errors"
"fmt"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/manifest/manifestlist"
"github.com/harness/gitness/registry/app/manifest/ocischema"
"github.com/harness/gitness/registry/app/manifest/schema2"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
const (
// MediaTypeManifest specifies the mediaType for the current version. Note
// that for schema version 1, the media is optionally "application/json".
MediaTypeManifest = "application/vnd.docker.distribution.manifest.v1+json"
// MediaTypeSignedManifest specifies the mediatype for current SignedManifest version.
MediaTypeSignedManifest = "application/vnd.docker.distribution.manifest.v1+prettyjws"
)
// MediaTypeBuildxCacheConfig is the mediatype associated with buildx
// cache config blobs. This should be unique to buildx.
var MediaTypeBuildxCacheConfig = "application/vnd.buildkit.cacheconfig.v0"
// SplitReferences contains two lists of manifest list references broken down
// into either blobs or manifests. The result of appending these two lists
// together should include all of the descriptors returned by
// ManifestList.References with no duplicates, additions, or omissions.
type SplitReferences struct {
Manifests []manifest.Descriptor
Blobs []manifest.Descriptor
}
// References returns the references of the DeserializedManifestList split into
// manifests and layers based on the mediatype of the standard list of
// descriptors. Only known manifest mediatypes will be sorted into the manifests
// array while everything else will be sorted into blobs. Helm chart manifests
// do not include a mediatype at the time of this commit, but they are unlikely
// to be included within a manifest list.
func References(ml *manifestlist.DeserializedManifestList) SplitReferences {
var (
manifests = make([]manifest.Descriptor, 0)
blobs = make([]manifest.Descriptor, 0)
)
for _, r := range ml.References() {
switch r.MediaType {
case schema2.MediaTypeManifest,
manifestlist.MediaTypeManifestList,
v1.MediaTypeImageManifest,
MediaTypeSignedManifest,
MediaTypeManifest:
manifests = append(manifests, r)
default:
blobs = append(blobs, r)
}
}
return SplitReferences{Manifests: manifests, Blobs: blobs}
}
// LikelyBuildxCache returns true if the manifest list is likely a buildx cache
// manifest based on the unique buildx config mediatype.
func LikelyBuildxCache(ml *manifestlist.DeserializedManifestList) bool {
blobs := References(ml).Blobs
for _, desc := range blobs {
if desc.MediaType == MediaTypeBuildxCacheConfig {
return true
}
}
return false
}
// ContainsBlobs returns true if the manifest list contains any blobs.
func ContainsBlobs(ml *manifestlist.DeserializedManifestList) bool {
return len(References(ml).Blobs) > 0
}
func OCIManifestFromBuildkitIndex(ml *manifestlist.DeserializedManifestList) (*ocischema.DeserializedManifest, error) {
refs := References(ml)
if len(refs.Manifests) > 0 {
return nil, errors.New("buildkit index has unexpected manifest references")
}
// set "config" and "layer" references apart.
var cfg *manifest.Descriptor
var layers []manifest.Descriptor
for _, ref := range refs.Blobs {
refCopy := ref
if refCopy.MediaType == MediaTypeBuildxCacheConfig {
cfg = &refCopy
} else {
layers = append(layers, refCopy)
}
}
// make sure they were found.
if cfg == nil {
return nil, errors.New("buildkit index has no config reference")
}
m, err := ocischema.FromStruct(
ocischema.Manifest{
Versioned: ocischema.SchemaVersion,
Config: *cfg,
Layers: layers,
},
)
if err != nil {
return nil, fmt.Errorf("building manifest from buildkit index: %w", err)
}
return m, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/local.go | registry/app/pkg/docker/local.go | // Source: https://gitlab.com/gitlab-org/container-registry
// Copyright 2019 Gitlab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/dist_temp/dcontext"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/events/replication"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/manifest/manifestlist"
"github.com/harness/gitness/registry/app/manifest/ocischema"
"github.com/harness/gitness/registry/app/manifest/schema2"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/gc"
"github.com/harness/gitness/registry/types"
store2 "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database/dbtx"
gitnesstypes "github.com/harness/gitness/types"
"github.com/distribution/distribution/v3"
"github.com/distribution/reference"
"github.com/opencontainers/go-digest"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog/log"
)
const (
defaultArch = "amd64"
defaultOS = "linux"
imageClass = "image"
)
type storageType int
const (
manifestSchema2 storageType = iota // 0
manifestlistSchema // 1
ociSchema // 2
ociImageIndexSchema // 3
numStorageTypes // 4
)
const (
manifestListCreateGCReviewWindow = 1 * time.Hour
manifestListCreateGCLockTimeout = 10 * time.Second
manifestTagGCLockTimeout = 30 * time.Second
tagDeleteGCLockTimeout = 10 * time.Second
manifestTagGCReviewWindow = 1 * time.Hour
manifestDeleteGCReviewWindow = 1 * time.Hour
manifestDeleteGCLockTimeout = 10 * time.Second
blobExistsGCLockTimeout = 10 * time.Second
blobExistsGCReviewWindow = 1 * time.Hour
DefaultMaximumReturnedEntries = 100
)
const (
ReferrersSchemaVersion = 2
ReferrersMediaType = "application/vnd.oci.image.index.v1+json"
HeaderCacheControl = "Cache-Control"
HeaderContentLength = "Content-Length"
HeaderContentType = "Content-Type"
HeaderDockerContentDigest = "Docker-Content-Digest"
HeaderEtag = "Etag"
blobCacheControlMaxAge = 365 * 24 * time.Hour
)
type CatalogAPIResponse struct {
Repositories []string `json:"repositories"`
}
type S3Store any
var errInvalidSecret = fmt.Errorf("invalid secret")
type hmacKey string
func NewLocalRegistry(
app *App, ms ManifestService, manifestDao store.ManifestRepository,
registryDao store.RegistryRepository, registryBlobDao store.RegistryBlobRepository,
blobRepo store.BlobRepository, mtRepository store.MediaTypesRepository,
tagDao store.TagRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository,
bandwidthStatDao store.BandwidthStatRepository, downloadStatDao store.DownloadStatRepository,
gcService gc.Service, tx dbtx.Transactor, quarantineArtifactDao store.QuarantineArtifactRepository,
bucketService BucketService, replicationReporter replication.Reporter,
) Registry {
return &LocalRegistry{
App: app,
ms: ms,
registryDao: registryDao,
manifestDao: manifestDao,
registryBlobDao: registryBlobDao,
blobRepo: blobRepo,
mtRepository: mtRepository,
tagDao: tagDao,
imageDao: imageDao,
artifactDao: artifactDao,
bandwidthStatDao: bandwidthStatDao,
downloadStatDao: downloadStatDao,
gcService: gcService,
tx: tx,
quarantineArtifactDao: quarantineArtifactDao,
bucketService: bucketService,
replicationReporter: replicationReporter,
}
}
type LocalRegistry struct {
App *App
ms ManifestService
registryDao store.RegistryRepository
manifestDao store.ManifestRepository
registryBlobDao store.RegistryBlobRepository
blobRepo store.BlobRepository
mtRepository store.MediaTypesRepository
tagDao store.TagRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
bandwidthStatDao store.BandwidthStatRepository
downloadStatDao store.DownloadStatRepository
gcService gc.Service
tx dbtx.Transactor
quarantineArtifactDao store.QuarantineArtifactRepository
bucketService BucketService
replicationReporter replication.Reporter
}
func (r *LocalRegistry) Base() error {
return nil
}
func (r *LocalRegistry) CanBeMount() (mount bool, repository string, err error) {
// TODO implement me
panic("implement me")
}
func (r *LocalRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (r *LocalRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeDOCKER, artifact.PackageTypeHELM}
}
func (r *LocalRegistry) getManifest(
ctx context.Context,
manifestDigest digest.Digest,
imageName string,
info pkg.RegistryInfo,
) (manifest.Manifest, error) {
dbRepo := info.Registry
log.Ctx(ctx).Debug().Msgf("getting manifest by digest from database")
dig, _ := types.NewDigest(manifestDigest)
// Find manifest by its digest
dbManifest, err := r.manifestDao.FindManifestByDigest(ctx, dbRepo.ID, imageName, dig)
if err != nil {
if errors.Is(err, store2.ErrResourceNotFound) {
return nil, manifest.UnknownRevisionError{
Name: info.RegIdentifier,
Revision: manifestDigest,
}
}
return nil, err
}
return DBManifestToManifest(dbManifest)
}
func DBManifestToManifest(dbm *types.Manifest) (manifest.Manifest, error) {
if dbm.SchemaVersion == 1 {
return nil, manifest.ErrSchemaV1Unsupported
}
if dbm.SchemaVersion != 2 {
return nil, fmt.Errorf("unrecognized manifest schema version %d", dbm.SchemaVersion)
}
mediaType := dbm.MediaType
if dbm.NonConformant {
// parse payload and get real media type
var versioned manifest.Versioned
if err := json.Unmarshal(dbm.Payload, &versioned); err != nil {
return nil, fmt.Errorf("failed to unmarshal manifest payload: %w", err)
}
mediaType = versioned.MediaType
}
// This can be an image manifest or a manifest list
switch mediaType {
case schema2.MediaTypeManifest:
m := &schema2.DeserializedManifest{}
if err := m.UnmarshalJSON(dbm.Payload); err != nil {
return nil, err
}
return m, nil
case v1.MediaTypeImageManifest:
m := &ocischema.DeserializedManifest{}
if err := m.UnmarshalJSON(dbm.Payload); err != nil {
return nil, err
}
return m, nil
case manifestlist.MediaTypeManifestList, v1.MediaTypeImageIndex:
m := &manifestlist.DeserializedManifestList{}
if err := m.UnmarshalJSON(dbm.Payload); err != nil {
return nil, err
}
return m, nil
case "":
// OCI image or image index - no media type in the content
// First see if it looks like an image index
resIndex := &manifestlist.DeserializedManifestList{}
if err := resIndex.UnmarshalJSON(dbm.Payload); err != nil {
return nil, err
}
if resIndex.Manifests != nil {
return resIndex, nil
}
// Otherwise, assume it must be an image manifest
m := &ocischema.DeserializedManifest{}
if err := m.UnmarshalJSON(dbm.Payload); err != nil {
return nil, err
}
return m, nil
default:
return nil,
manifest.VerificationErrors{
fmt.Errorf("unrecognized manifest content type %s", dbm.MediaType),
}
}
}
func (r *LocalRegistry) getTag(ctx context.Context, info pkg.RegistryInfo) (*manifest.Descriptor, error) {
dbRepo := info.Registry
log.Ctx(ctx).Info().Msgf("getting manifest by tag from database")
dbManifest, err := r.manifestDao.FindManifestByTagName(ctx, dbRepo.ID, info.Image, info.Tag)
if err != nil {
// at the DB level a tag has a FK to manifests, so a tag cannot exist
// unless it points to an existing manifest
if errors.Is(err, store2.ErrResourceNotFound) {
return nil, manifest.TagUnknownError{Tag: info.Tag}
}
return nil, err
}
return &manifest.Descriptor{Digest: dbManifest.Digest}, nil
}
func etagMatch(headers []string, etag string) bool {
for _, headerVal := range headers {
if headerVal == etag || headerVal == fmt.Sprintf(`"%s"`, etag) {
// allow quoted or unquoted
return true
}
}
return false
}
// copyFullPayload copies the payload of an HTTP request to destWriter. If it
// receives less content than expected, and the client disconnected during the
// upload, it avoids sending a 400 error to keep the logs cleaner.
//
// The copy will be limited to `limit` bytes, if limit is greater than zero.
func copyFullPayload(
ctx context.Context, length int64, body io.ReadCloser,
destWriter io.Writer, action string,
) error {
// Get a channel that tells us if the client disconnects
clientClosed := ctx.Done()
// Read in the data, if any.
copied, err := io.Copy(destWriter, body)
if clientClosed != nil && (err != nil || (length > 0 && copied < length)) {
// Didn't receive as much content as expected. Did the client
// disconnect during the request? If so, avoid returning a 400
// error to keep the logs cleaner.
select {
case <-clientClosed:
// Set the response Code to "499 Client Closed Request"
// Even though the connection has already been closed,
// this causes the logger to pick up a 499 error
// instead of showing 0 for the HTTP status.
// responseWriter.WriteHeader(499)
dcontext.GetLoggerWithFields(
ctx, log.Error(), map[any]any{
"error": err,
"copied": copied,
"contentLength": length,
}, "error", "copied", "contentLength",
).Msg("client disconnected during " + action)
return errors.New("client disconnected")
default:
}
}
if err != nil {
dcontext.GetLogger(ctx, log.Error()).Msgf("unknown error reading request payload: %v", err)
return err
}
return nil
}
func (r *LocalRegistry) HeadBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
return r.headBlobInternal(ctx2, artInfo)
}
func (r *LocalRegistry) GetBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, fr *storage.FileReader, size int64,
readCloser io.ReadCloser, redirectURL string, errs []error,
) {
return r.fetchBlobInternal(ctx2, http.MethodGet, artInfo)
}
func (r *LocalRegistry) fetchBlobInternal(
ctx2 context.Context,
method string,
info pkg.RegistryInfo,
) (*commons.ResponseHeaders, *storage.FileReader, int64, io.ReadCloser, string, []error) {
responseHeaders := &commons.ResponseHeaders{
Code: 0,
Headers: make(map[string]string),
}
errs := make([]error, 0)
var dgst digest.Digest
blobID, err := r.dbBlobLinkExists(ctx2, digest.Digest(info.Digest), info)
if err != nil { //nolint:contextcheck
errs = append(errs, errcode.FromUnknownError(err))
return responseHeaders, nil, -1, nil, "", errs
}
ctx := r.App.GetBlobsContext(ctx2, info, blobID)
blobs := ctx.OciBlobStore
dgst = ctx.Digest
headers := make(map[string]string)
// Use the blob store to serve the blob
var fileReader *storage.FileReader
var redirectURL string
var size int64
//nolint:contextcheck
fileReader, redirectURL, size, err = blobs.ServeBlobInternal(
ctx.Context,
info.RootIdentifier,
dgst,
headers,
method,
)
if err != nil {
if fileReader != nil {
fileReader.Close()
}
if errors.Is(err, storage.ErrBlobUnknown) {
errs = append(errs, errcode.ErrCodeBlobUnknown.WithDetail(ctx.Digest))
} else {
errs = append(errs, errcode.FromUnknownError(err))
}
return responseHeaders, nil, -1, nil, "", errs
}
if redirectURL != "" {
return responseHeaders, nil, -1, nil, redirectURL, errs
}
maps.Copy(responseHeaders.Headers, headers)
return responseHeaders, fileReader, size, nil, "", errs
}
func (r *LocalRegistry) headBlobInternal(
ctx context.Context,
info pkg.RegistryInfo,
) (*commons.ResponseHeaders, []error) {
responseHeaders := &commons.ResponseHeaders{
Code: 0,
Headers: make(map[string]string),
}
errs := make([]error, 0)
dgst := digest.Digest(info.Digest)
blobID, err := r.dbBlobLinkExists(ctx, dgst, info)
if err != nil {
errs = append(errs, errcode.FromUnknownError(err))
return responseHeaders, errs
}
blob, err := r.blobRepo.FindByID(ctx, blobID)
if err != nil {
errs = append(errs, errcode.FromUnknownError(err))
return responseHeaders, errs
}
responseHeaders.Headers[HeaderEtag] = fmt.Sprintf(`"%s"`, dgst)
responseHeaders.Headers[HeaderCacheControl] = fmt.Sprintf(
"max-age=%.f",
blobCacheControlMaxAge.Seconds(),
)
responseHeaders.Headers[HeaderDockerContentDigest] = dgst.String()
responseHeaders.Headers[HeaderContentType] = "application/octet-stream"
responseHeaders.Headers[HeaderContentLength] = fmt.Sprint(blob.Size)
return responseHeaders, errs
}
func (r *LocalRegistry) PullManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifest manifest.Manifest, errs []error) {
responseHeaders, descriptor, manifest, errs = r.ManifestExist(ctx, artInfo, acceptHeaders, ifNoneMatchHeader)
return responseHeaders, descriptor, manifest, errs
}
func (r *LocalRegistry) getDigestByTag(ctx context.Context, artInfo pkg.RegistryInfo) (digest.Digest, error) {
desc, err := r.getTag(ctx, artInfo)
if err != nil {
var tagUnknownError manifest.TagUnknownError
if errors.As(err, &tagUnknownError) {
return "", errcode.ErrCodeManifestUnknown.WithDetail(err)
}
return "", err
}
return desc.Digest, nil
}
func getDigestFromInfo(artInfo pkg.RegistryInfo) digest.Digest {
if artInfo.Digest != "" {
return digest.Digest(artInfo.Digest)
}
return digest.Digest(artInfo.Reference)
}
func (r *LocalRegistry) getDigest(ctx context.Context, artInfo pkg.RegistryInfo) (digest.Digest, error) {
if artInfo.Tag != "" {
return r.getDigestByTag(ctx, artInfo)
}
return getDigestFromInfo(artInfo), nil
}
func (r *LocalRegistry) ManifestExist(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifestResult manifest.Manifest,
errs []error,
) {
tag := artInfo.Tag
supports := r.getSupportsList(acceptHeaders)
d, err := r.getDigest(ctx, artInfo)
if err != nil {
return responseHeaders, descriptor, manifestResult, []error{err}
}
if etagMatch(ifNoneMatchHeader, d.String()) {
r2 := &commons.ResponseHeaders{
Code: http.StatusNotModified,
}
return r2, manifest.Descriptor{Digest: d}, nil, nil
}
manifestResult, err = r.getManifest(ctx, d, artInfo.Image, artInfo)
if err != nil {
var manifestUnknownRevisionError manifest.UnknownRevisionError
if errors.As(err, &manifestUnknownRevisionError) {
errs = append(errs, errcode.ErrCodeManifestUnknown.WithDetail(err))
}
return responseHeaders, descriptor, manifestResult, errs
}
// determine the type of the returned manifest
manifestType := manifestSchema2
manifestList, isManifestList := manifestResult.(*manifestlist.DeserializedManifestList)
if _, isOCImanifest := manifestResult.(*ocischema.DeserializedManifest); isOCImanifest {
manifestType = ociSchema
} else if isManifestList {
switch manifestList.MediaType {
case manifestlist.MediaTypeManifestList:
manifestType = manifestlistSchema
case v1.MediaTypeImageIndex:
manifestType = ociImageIndexSchema
}
}
if manifestType == ociSchema && !supports[ociSchema] {
errs = append(
errs,
errcode.ErrCodeManifestUnknown.WithMessage(
"OCI manifest found, but accept header does not support OCI manifests",
),
)
return responseHeaders, descriptor, manifestResult, errs
}
if manifestType == ociImageIndexSchema && !supports[ociImageIndexSchema] {
errs = append(
errs,
errcode.ErrCodeManifestUnknown.WithMessage(
"OCI index found, but accept header does not support OCI indexes",
),
)
return responseHeaders, descriptor, manifestResult, errs
}
if tag != "" && manifestType == manifestlistSchema && !supports[manifestlistSchema] {
d, manifestResult, err = r.rewriteManifest(ctx, artInfo, d, manifestList, supports)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
}
ct, p, err := manifestResult.Payload()
if err != nil {
return responseHeaders, descriptor, manifestResult, errs
}
r2 := &commons.ResponseHeaders{
Headers: map[string]string{
"Content-Type": ct,
"Content-Length": fmt.Sprint(len(p)),
"Docker-Content-Digest": d.String(),
"Etag": fmt.Sprintf(`"%s"`, d),
},
}
return r2, manifest.Descriptor{Digest: d}, manifestResult, nil
}
func (r *LocalRegistry) rewriteManifest(
ctx context.Context, artInfo pkg.RegistryInfo, d digest.Digest, manifestList *manifestlist.DeserializedManifestList,
supports [4]bool,
) (digest.Digest, manifest.Manifest, error) {
// Rewrite manifest in schema1 format
log.Ctx(ctx).Info().Msgf(
"rewriting manifest list %s in schema1 format to support old client", d.String(),
)
// Find the image manifest corresponding to the default
// platform
var manifestDigest digest.Digest
for _, manifestDescriptor := range manifestList.Manifests {
if manifestDescriptor.Platform.Architecture == defaultArch &&
manifestDescriptor.Platform.OS == defaultOS {
manifestDigest = manifestDescriptor.Digest
break
}
}
if manifestDigest == "" {
return "", nil, errcode.ErrCodeManifestUnknown
}
manifestResult, err := r.getManifest(ctx, manifestDigest, artInfo.Image, artInfo)
if err != nil {
var manifestUnknownRevisionError manifest.UnknownRevisionError
if errors.As(err, &manifestUnknownRevisionError) {
return "", nil, errcode.ErrCodeManifestUnknown.WithDetail(err)
}
return "", nil, err
}
if _, isSchema2 := manifestResult.(*schema2.DeserializedManifest); isSchema2 && !supports[manifestSchema2] {
return "", manifestResult, errcode.ErrCodeManifestInvalid.WithMessage("Schema 2 manifest not supported by client")
}
d = manifestDigest
return d, manifestResult, nil
}
func (r *LocalRegistry) getSupportsList(acceptHeaders []string) [4]bool {
var supports [numStorageTypes]bool
// this parsing of Accept Headers is not quite as full-featured as
// godoc.org's parser, but we don't care about "q=" values
// https://github.com/golang/gddo/blob/
// e91d4165076d7474d20abda83f92d15c7ebc3e81/httputil/header/header.go#L165-L202
for _, acceptHeader := range acceptHeaders {
// r.Header[...] is a slice in case the request contains
// the same header more than once
// if the header isn't set, we'll get the zero value,
// which "range" will handle gracefully
// we need to split each header value on "," to get the full
// list of "Accept" values (per RFC 2616)
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
for mediaType := range strings.SplitSeq(acceptHeader, ",") {
mediaType = strings.TrimSpace(mediaType)
if _, _, err := mime.ParseMediaType(mediaType); err != nil {
continue
}
switch mediaType {
case schema2.MediaTypeManifest:
supports[manifestSchema2] = true
case manifestlist.MediaTypeManifestList:
supports[manifestlistSchema] = true
case v1.MediaTypeImageManifest:
supports[ociSchema] = true
case v1.MediaTypeImageIndex:
supports[ociImageIndexSchema] = true
}
}
}
return supports
}
func (r *LocalRegistry) appendPutError(err error, errList []error) []error {
// TODO: Move this error list inside the context
if errors.Is(err, manifest.ErrUnsupported) {
errList = append(errList, errcode.ErrCodeUnsupported)
return errList
}
if errors.Is(err, manifest.ErrAccessDenied) {
errList = append(errList, errcode.ErrCodeDenied)
return errList
}
if errors.Is(err, manifest.ErrSchemaV1Unsupported) {
errList = append(
errList,
errcode.ErrCodeManifestInvalid.WithDetail(
"manifest type unsupported",
),
)
return errList
}
if errors.Is(err, digest.ErrDigestInvalidFormat) {
errList = append(errList, errcode.ErrCodeDigestInvalid.WithDetail(err))
return errList
}
switch {
case errors.As(err, &manifest.VerificationErrors{}):
var verificationError manifest.VerificationErrors
errors.As(err, &verificationError)
for _, verificationError := range verificationError {
switch {
case errors.As(verificationError, &manifest.BlobUnknownError{}):
var manifestBlobUnknownError manifest.BlobUnknownError
errors.As(verificationError, &manifestBlobUnknownError)
errList = append(
errList, errcode.ErrCodeManifestBlobUnknown.WithDetail(
manifestBlobUnknownError.Digest,
),
)
case errors.As(verificationError, &manifest.NameInvalidError{}):
errList = append(
errList, errcode.ErrCodeNameInvalid.WithDetail(err),
)
case errors.As(verificationError, &manifest.UnverifiedError{}):
errList = append(errList, errcode.ErrCodeManifestUnverified)
case errors.As(verificationError, &manifest.ReferencesExceedLimitError{}):
errList = append(
errList, errcode.ErrCodeManifestReferenceLimit.WithDetail(err),
)
case errors.As(verificationError, &manifest.PayloadSizeExceedsLimitError{}):
errList = append(
errList, errcode.ErrCodeManifestPayloadSizeLimit.WithDetail(err.Error()),
)
default:
if errors.Is(verificationError, digest.ErrDigestInvalidFormat) {
errList = append(errList, errcode.ErrCodeDigestInvalid)
} else {
errList = append(errList, errcode.FromUnknownError(verificationError))
}
}
}
case errors.As(err, &errcode.Error{}):
errList = append(errList, err)
default:
errList = append(errList, errcode.FromUnknownError(err))
}
return errList
}
func (r *LocalRegistry) PutManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
mediaType string,
body io.ReadCloser,
length int64,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
var jsonBuf bytes.Buffer
d, _ := digest.Parse(artInfo.Digest)
tag := artInfo.Tag
log.Ctx(ctx).Info().Msgf("Pushing manifest %s, digest: %q, tag: %s", artInfo.RegIdentifier, d, tag)
responseHeaders = &commons.ResponseHeaders{
Headers: map[string]string{},
Code: http.StatusCreated,
}
if err := copyFullPayload(ctx, length, body, &jsonBuf, "image manifest PUT"); err != nil {
// copyFullPayload reports the error if necessary
errs = append(errs, errcode.ErrCodeManifestInvalid.WithDetail(err.Error()))
return responseHeaders, errs
}
unmarshalManifest, desc, err := manifest.UnmarshalManifest(mediaType, jsonBuf.Bytes())
if err != nil {
errs = append(errs, errcode.ErrCodeManifestInvalid.WithDetail(err))
return responseHeaders, errs
}
if d != "" {
if desc.Digest != d {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("payload digest does not match: %q != %q", desc.Digest, d)
errs = append(errs, errcode.ErrCodeDigestInvalid)
return responseHeaders, errs
}
} else {
if tag != "" {
d = desc.Digest
log.Ctx(ctx).Debug().Msgf("payload digest: %q", d)
} else {
errs = append(errs, errcode.ErrCodeTagInvalid.WithDetail("no tag or digest specified"))
return responseHeaders, errs
}
}
isAnOCIManifest := mediaType == v1.MediaTypeImageManifest ||
mediaType == v1.MediaTypeImageIndex
if isAnOCIManifest {
log.Ctx(ctx).Debug().Msg("Putting an OCI Manifest!")
} else {
log.Ctx(ctx).Debug().Msg("Putting a Docker Manifest!")
}
// We don't need to store manifest file in S3 storage
// manifestServicePut(ctx, _manifest, options...)
if err = r.ms.DBPut(ctx, unmarshalManifest, d, responseHeaders, artInfo); err != nil {
errs = r.appendPutError(err, errs)
return responseHeaders, errs
}
// Tag this manifest
if tag != "" {
if err = r.ms.DBTag(ctx, unmarshalManifest, d, tag, responseHeaders, artInfo); err != nil {
errs = r.appendPutError(err, errs)
return responseHeaders, errs
}
}
if err != nil {
return r.handlePutManifestErrors(err, errs, responseHeaders)
}
// Tag this manifest
if tag != "" {
err = tagserviceTag()
// err = tags.Tag(imh, Tag, desc)
if err != nil {
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err))
return responseHeaders, errs
}
}
// Construct a canonical url for the uploaded manifest.
name, _ := reference.WithName(fmt.Sprintf("%s/%s/%s", artInfo.PathRoot, artInfo.RegIdentifier, artInfo.Image))
canonicalRef, err := reference.WithDigest(name, d)
if err != nil {
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err))
return responseHeaders, errs
}
builder := artInfo.URLBuilder
location, err := builder.BuildManifestURL(canonicalRef)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(
err,
).Msgf("error building manifest url from digest: %v", err)
}
responseHeaders.Headers["Location"] = location
responseHeaders.Headers["Docker-Content-Digest"] = d.String()
responseHeaders.Code = http.StatusCreated
log.Ctx(ctx).Debug().Msgf("Succeeded in putting manifest: %s", d.String())
return responseHeaders, errs
}
func (r *LocalRegistry) handlePutManifestErrors(
err error, errs []error, responseHeaders *commons.ResponseHeaders,
) (*commons.ResponseHeaders, []error) {
if errors.Is(err, manifest.ErrUnsupported) {
errs = append(errs, errcode.ErrCodeUnsupported)
return responseHeaders, errs
}
if errors.Is(err, manifest.ErrAccessDenied) {
errs = append(errs, errcode.ErrCodeDenied)
return responseHeaders, errs
}
switch {
case errors.As(err, &manifest.VerificationErrors{}):
var verificationError manifest.VerificationErrors
errors.As(err, &verificationError)
for _, verificationError := range verificationError {
switch {
case errors.As(verificationError, &manifest.BlobUnknownError{}):
var manifestBlobUnknownError manifest.BlobUnknownError
errors.As(verificationError, &manifestBlobUnknownError)
errs = append(
errs,
errcode.ErrCodeManifestBlobUnknown.WithDetail(
manifestBlobUnknownError.Digest,
),
)
case errors.As(verificationError, &manifest.NameInvalidError{}):
errs = append(
errs,
errcode.ErrCodeNameInvalid.WithDetail(err),
)
case errors.As(verificationError, &manifest.UnverifiedError{}):
errs = append(errs, errcode.ErrCodeManifestUnverified)
default:
if errors.Is(verificationError, digest.ErrDigestInvalidFormat) {
errs = append(errs, errcode.ErrCodeDigestInvalid)
} else {
errs = append(errs, errcode.ErrCodeUnknown, verificationError)
}
}
}
case errors.As(err, &errcode.Error{}):
errs = append(errs, err)
default:
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err))
}
return responseHeaders, errs
}
func tagserviceTag() error {
// TODO: implement this
return nil
}
func (r *LocalRegistry) PushBlobMonolith(
_ context.Context,
_ pkg.RegistryInfo,
_ int64,
_ io.Reader,
) error {
return nil
}
func (r *LocalRegistry) InitBlobUpload(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
fromRepo, mountDigest string,
) (*commons.ResponseHeaders, []error) {
blobCtx := r.App.GetBlobsContext(ctx2, artInfo, nil)
var errList []error
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
digest := digest.Digest(mountDigest)
//nolint:nestif
if mountDigest != "" && fromRepo != "" {
err := r.dbMountBlob(blobCtx, fromRepo, artInfo.RegIdentifier, digest, artInfo) //nolint:contextcheck
if err != nil {
e := fmt.Errorf("failed to mount blob in database: %w", err)
if errors.Is(err, store2.ErrResourceNotFound) {
errList = append(errList, errcode.ErrCodeRegNotFound.WithDetail(e))
} else {
errList = append(errList, errcode.FromUnknownError(e))
}
}
if err = writeBlobCreatedHeaders(
blobCtx, digest,
responseHeaders, artInfo,
); err != nil {
errList = append(errList, errcode.ErrCodeUnknown.WithDetail(err))
}
return responseHeaders, errList
}
blobs := blobCtx.OciBlobStore
upload, err := blobs.Create(blobCtx.Context) //nolint:contextcheck
if err != nil {
if errors.Is(err, storage.ErrUnsupported) {
errList = append(errList, errcode.ErrCodeUnsupported)
} else {
errList = append(errList, errcode.ErrCodeUnknown.WithDetail(err))
}
return responseHeaders, errList
}
blobCtx.Upload = upload
if err = blobUploadResponse(
blobCtx, responseHeaders,
artInfo.RegIdentifier, artInfo,
); err != nil {
errList = append(errList, errcode.ErrCodeUnknown.WithDetail(err))
return responseHeaders, errList
}
responseHeaders.Headers[storage.HeaderDockerUploadUUID] = blobCtx.Upload.ID()
responseHeaders.Code = http.StatusAccepted
return responseHeaders, nil
}
func (r *LocalRegistry) PushBlobMonolithWithDigest(
_ context.Context,
_ pkg.RegistryInfo,
_ int64,
_ io.Reader,
) error {
return nil
}
func (r *LocalRegistry) PushBlobChunk(
ctx *Context,
artInfo pkg.RegistryInfo,
contentType string,
contentRange string,
contentLength string,
body io.ReadCloser,
contentLengthFromRequest int64,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
responseHeaders = &commons.ResponseHeaders{
Code: 0,
Headers: make(map[string]string),
}
errs = make([]error, 0)
if ctx.Upload == nil {
e := errcode.ErrCodeBlobUploadUnknown
errs = append(errs, e)
return responseHeaders, errs
}
if contentType != "" && contentType != "application/octet-stream" {
e := errcode.ErrCodeUnknown.WithDetail(fmt.Errorf("bad Content-Type"))
errs = append(errs, e)
return responseHeaders, errs
}
if contentRange != "" && contentLength != "" {
start, end, err := parseContentRange(contentRange)
if err != nil {
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err.Error()))
return responseHeaders, errs
}
if start > end || start != ctx.Upload.Size() {
errs = append(errs, errcode.ErrCodeRangeInvalid)
return responseHeaders, errs
}
clInt, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err.Error()))
return responseHeaders, errs
}
if clInt != (end-start)+1 {
errs = append(errs, errcode.ErrCodeSizeInvalid)
return responseHeaders, errs
}
}
if err := copyFullPayload(
ctx, contentLengthFromRequest, body, ctx.Upload,
"blob PATCH",
); err != nil {
errs = append(
errs,
errcode.ErrCodeUnknown.WithDetail(err.Error()),
)
return responseHeaders, errs
}
if err := blobUploadResponse(
ctx, responseHeaders,
artInfo.RegIdentifier, artInfo,
); err != nil {
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err))
return responseHeaders, errs
}
responseHeaders.Code = http.StatusAccepted
return responseHeaders, errs
}
func (r *LocalRegistry) PushBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
body io.ReadCloser,
contentLength int64,
stateToken string,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
errs = make([]error, 0)
responseHeaders = &commons.ResponseHeaders{
Code: 0,
Headers: make(map[string]string),
}
ctx := r.App.GetBlobsContext(ctx2, artInfo, nil)
if ctx.UUID != "" {
resumeErrs := ResumeBlobUpload(ctx, stateToken) //nolint:contextcheck
errs = append(errs, resumeErrs...)
}
if ctx.Upload == nil {
err := errcode.ErrCodeBlobUploadUnknown
errs = append(errs, err)
return responseHeaders, errs
}
defer ctx.Upload.Close()
if artInfo.Digest == "" {
// no digest? return error, but allow retry.
err := errcode.ErrCodeDigestInvalid.WithDetail("digest missing")
errs = append(errs, err)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | true |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/wire.go | registry/app/pkg/docker/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 docker
import (
"context"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
gitnessstore "github.com/harness/gitness/app/store"
"github.com/harness/gitness/app/url"
storagedriver "github.com/harness/gitness/registry/app/driver"
"github.com/harness/gitness/registry/app/event"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/events/replication"
"github.com/harness/gitness/registry/app/manifest/manifestlist"
"github.com/harness/gitness/registry/app/manifest/schema2"
"github.com/harness/gitness/registry/app/pkg"
proxy2 "github.com/harness/gitness/registry/app/remote/controller/proxy"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/gc"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/google/wire"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
func LocalRegistryProvider(
app *App, ms ManifestService, blobRepo store.BlobRepository,
registryDao store.RegistryRepository, manifestDao store.ManifestRepository,
registryBlobDao store.RegistryBlobRepository,
mtRepository store.MediaTypesRepository,
tagDao store.TagRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository,
bandwidthStatDao store.BandwidthStatRepository, downloadStatDao store.DownloadStatRepository,
gcService gc.Service, tx dbtx.Transactor, quarantineArtifactDao store.QuarantineArtifactRepository,
replicationReporter replication.Reporter,
bucketService BucketService,
) *LocalRegistry {
registry, ok := NewLocalRegistry(
app, ms, manifestDao, registryDao, registryBlobDao, blobRepo,
mtRepository, tagDao, imageDao, artifactDao, bandwidthStatDao, downloadStatDao,
gcService, tx, quarantineArtifactDao, bucketService, replicationReporter,
).(*LocalRegistry)
if !ok {
return nil
}
return registry
}
func ManifestServiceProvider(
registryDao store.RegistryRepository,
manifestDao store.ManifestRepository, blobRepo store.BlobRepository, mtRepository store.MediaTypesRepository,
manifestRefDao store.ManifestReferenceRepository, tagDao store.TagRepository, imageDao store.ImageRepository,
artifactDao store.ArtifactRepository, layerDao store.LayerRepository,
gcService gc.Service, tx dbtx.Transactor, reporter event.Reporter, spaceFinder refcache.SpaceFinder,
ociImageIndexMappingDao store.OCIImageIndexMappingRepository,
artifactEventReporter *registryevents.Reporter,
urlProvider url.Provider,
) ManifestService {
return NewManifestService(
registryDao, manifestDao, blobRepo, mtRepository, tagDao, imageDao,
artifactDao, layerDao, manifestRefDao, tx, gcService, reporter, spaceFinder,
ociImageIndexMappingDao, *artifactEventReporter, urlProvider, func(_ context.Context) bool {
return true
})
}
func RemoteRegistryProvider(
local *LocalRegistry, app *App, upstreamProxyConfigRepo store.UpstreamProxyConfigRepository,
spaceFinder refcache.SpaceFinder, secretService secret.Service, proxyCtrl proxy2.Controller,
) *RemoteRegistry {
registry, ok := NewRemoteRegistry(local, app, upstreamProxyConfigRepo, spaceFinder, secretService,
proxyCtrl).(*RemoteRegistry)
if !ok {
return nil
}
return registry
}
func ControllerProvider(
local *LocalRegistry,
remote *RemoteRegistry,
controller *pkg.CoreController,
spaceStore gitnessstore.SpaceStore,
authorizer authz.Authorizer,
dBStore *DBStore,
spaceFinder refcache.SpaceFinder,
) *Controller {
return NewController(local, remote, controller, spaceStore, authorizer, dBStore, spaceFinder)
}
func DBStoreProvider(
blobRepo store.BlobRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
bandwidthStatDao store.BandwidthStatRepository,
downloadStatDao store.DownloadStatRepository,
manifestDao store.ManifestRepository,
quarantineDao store.QuarantineArtifactRepository,
) *DBStore {
return NewDBStore(blobRepo, imageDao, artifactDao, bandwidthStatDao, downloadStatDao, manifestDao, quarantineDao)
}
func StorageServiceProvider(cfg *types.Config, driver storagedriver.StorageDriver) *storage.Service {
return GetStorageService(cfg, driver)
}
func ProvideReporter() event.Reporter {
return &event.Noop{}
}
func ProvideProxyController(
registry *LocalRegistry, ms ManifestService, secretService secret.Service,
spaceFinder refcache.SpaceFinder,
) proxy2.Controller {
manifestCacheHandler := getManifestCacheHandler(registry, ms)
return proxy2.NewProxyController(registry, ms, secretService, spaceFinder, manifestCacheHandler)
}
func getManifestCacheHandler(
registry *LocalRegistry, ms ManifestService,
) map[string]proxy2.ManifestCacheHandler {
cache := proxy2.GetManifestCache(registry, ms)
listCache := proxy2.GetManifestListCache(registry)
return map[string]proxy2.ManifestCacheHandler{
manifestlist.MediaTypeManifestList: listCache,
v1.MediaTypeImageIndex: listCache,
schema2.MediaTypeManifest: cache,
proxy2.DefaultHandler: cache,
}
}
var ControllerSet = wire.NewSet(ControllerProvider)
var DBStoreSet = wire.NewSet(DBStoreProvider)
var RegistrySet = wire.NewSet(LocalRegistryProvider, ManifestServiceProvider, RemoteRegistryProvider)
var ProxySet = wire.NewSet(ProvideProxyController)
var StorageServiceSet = wire.NewSet(StorageServiceProvider)
var AppSet = wire.NewSet(NewApp)
// OciBlobStoreFactory is a function that creates an OciBlobStore with the provided context and identifiers.
type OciBlobStoreFactory func(ctx context.Context, repoKey string, rootParentRef string) storage.OciBlobStore
// ProvideOciBlobStore returns a factory function that creates an OciBlobStore with the provided context.
func ProvideOciBlobStore(storageService *storage.Service) OciBlobStoreFactory {
return storageService.OciBlobsStore
}
func ProvideBucketService(_ OciBlobStoreFactory) BucketService {
return &noOpBucketService{}
}
// noOpBucketService is a no-op implementation for open-source version.
type noOpBucketService struct{}
func (n *noOpBucketService) GetBlobStore(
_ context.Context, _ string, _ string,
_ any, _ string,
) *BlobStore {
return nil
}
var OciBlobStoreSet = wire.NewSet(ProvideOciBlobStore)
var BucketServiceSet = wire.NewSet(ProvideBucketService)
// WireSet is used without the OciBlobStore and BucketService.
var WireSet = wire.NewSet(
ControllerSet,
DBStoreSet,
RegistrySet,
StorageServiceSet,
AppSet,
ProxySet,
)
// OpenSourceWireSet is used by the open-source version.
var OpenSourceWireSet = wire.NewSet(
WireSet,
OciBlobStoreSet,
BucketServiceSet,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/manifest_service.go | registry/app/pkg/docker/manifest_service.go | // Source: https://gitlab.com/gitlab-org/container-registry
// Copyright 2019 Gitlab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"database/sql"
"errors"
"fmt"
"slices"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/event"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/manifest/manifestlist"
"github.com/harness/gitness/registry/app/manifest/ocischema"
"github.com/harness/gitness/registry/app/manifest/schema2"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/gc"
"github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/registry/types"
gitnessstore "github.com/harness/gitness/store"
db "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/distribution/distribution/v3"
"github.com/distribution/distribution/v3/registry/api/errcode"
"github.com/opencontainers/go-digest"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog/log"
)
type manifestService struct {
registryDao store.RegistryRepository
manifestDao store.ManifestRepository
layerDao store.LayerRepository
blobRepo store.BlobRepository
mtRepository store.MediaTypesRepository
tagDao store.TagRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
manifestRefDao store.ManifestReferenceRepository
ociImageIndexMappingDao store.OCIImageIndexMappingRepository
spaceFinder refcache.SpaceFinder
gcService gc.Service
tx dbtx.Transactor
reporter event.Reporter
artifactEventReporter registryevents.Reporter
urlProvider urlprovider.Provider
untaggedImagesEnabled func(ctx context.Context) bool
}
func NewManifestService(
registryDao store.RegistryRepository, manifestDao store.ManifestRepository,
blobRepo store.BlobRepository, mtRepository store.MediaTypesRepository, tagDao store.TagRepository,
imageDao store.ImageRepository, artifactDao store.ArtifactRepository,
layerDao store.LayerRepository, manifestRefDao store.ManifestReferenceRepository,
tx dbtx.Transactor, gcService gc.Service, reporter event.Reporter, spaceFinder refcache.SpaceFinder,
ociImageIndexMappingDao store.OCIImageIndexMappingRepository, artifactEventReporter registryevents.Reporter,
urlProvider urlprovider.Provider, untaggedImagesEnabled func(ctx context.Context) bool,
) ManifestService {
return &manifestService{
registryDao: registryDao,
manifestDao: manifestDao,
layerDao: layerDao,
blobRepo: blobRepo,
mtRepository: mtRepository,
tagDao: tagDao,
artifactDao: artifactDao,
imageDao: imageDao,
manifestRefDao: manifestRefDao,
gcService: gcService,
tx: tx,
reporter: reporter,
spaceFinder: spaceFinder,
ociImageIndexMappingDao: ociImageIndexMappingDao,
artifactEventReporter: artifactEventReporter,
urlProvider: urlProvider,
untaggedImagesEnabled: untaggedImagesEnabled,
}
}
type ManifestService interface {
// GetTags gets the tags of a repository
DBTag(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
tag string,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error
DBPut(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error
DeleteTag(ctx context.Context, repoKey string, tag string, info pkg.RegistryInfo) (bool, error)
DeleteManifest(ctx context.Context, repoKey string, d digest.Digest, info pkg.RegistryInfo) error
AddManifestAssociation(ctx context.Context, repoKey string, digest digest.Digest, info pkg.RegistryInfo) error
DBFindRepositoryBlob(
ctx context.Context, desc manifest.Descriptor, repoID int64, imageName string,
) (*types.Blob, error)
UpsertImage(ctx context.Context, info pkg.RegistryInfo) error
AddTagsToManifest(
ctx context.Context,
dgst digest.Digest,
tags []string,
imageName string,
info pkg.RegistryInfo,
) error
}
func (l *manifestService) DBTag(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
tag string,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
imageName := info.Image
if err := l.dbTagManifest(ctx, d, tag, imageName, info); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create tag in database")
err2 := l.handleTagError(ctx, mfst, d, tag, headers, info, err, imageName)
if err2 != nil {
return err2
}
}
return nil
}
func (l *manifestService) handleTagError(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
tag string,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
err error,
imageName string,
) error {
if errors.Is(err, util.ErrManifestNotFound) {
// If online GC was already reviewing the manifest that we want to tag, and that manifest had no
// tags before the review start, the API is unable to stop the GC from deleting the manifest (as
// the GC already acquired the lock on the corresponding queue row). This means that once the API
// is unblocked and tries to create the tag, a foreign key violation error will occur (because we're
// trying to create a tag for a manifest that no longer exists) and lead to this specific error.
// This should be extremely rare, if it ever occurs, but if it does, we should recreate the manifest
// and tag it, instead of returning a "manifest not found response" to clients. It's expected that
// this route handles the creation of a manifest if it doesn't exist already.
if err = l.DBPut(ctx, mfst, "", headers, info); err != nil {
return fmt.Errorf("failed to recreate manifest in database: %w", err)
}
if err = l.dbTagManifest(ctx, d, tag, imageName, info); err != nil {
return fmt.Errorf("failed to create tag in database after manifest recreate: %w", err)
}
} else {
return fmt.Errorf("failed to create tag in database: %w", err)
}
return nil
}
func (l *manifestService) dbTagManifest(
ctx context.Context,
dgst digest.Digest,
tagName, imageName string,
info pkg.RegistryInfo,
) error {
dbRegistry := info.Registry
newDigest, err := types.NewDigest(dgst)
if err != nil {
return formatFailedToTagErr(err)
}
dbManifest, err := l.manifestDao.FindManifestByDigest(ctx, dbRegistry.ID, info.Image, newDigest)
if errors.Is(err, gitnessstore.ErrResourceNotFound) {
return fmt.Errorf("manifest %s not found in database", dgst)
}
if err != nil {
return formatFailedToTagErr(err)
}
err = l.addTagsWithTx(ctx, dbRegistry, dbManifest, []string{tagName}, imageName)
if err != nil {
return formatFailedToTagErr(err)
}
spacePath, packageType, err := l.getSpacePathAndPackageType(ctx, &dbRegistry)
if err == nil {
session, _ := request.AuthSessionFrom(ctx)
l.reportEvents(ctx, dgst, info, imageName, tagName, packageType, spacePath, dbManifest, session)
} else {
log.Ctx(ctx).Err(err).Msg("Failed to find spacePath, not publishing event")
}
return nil
}
func (l *manifestService) AddTagsToManifest(
ctx context.Context,
dgst digest.Digest,
tags []string, imageName string,
info pkg.RegistryInfo,
) error {
dbRegistry := info.Registry
digest, err := types.NewDigest(dgst)
if err != nil {
return formatFailedToTagErr(err)
}
dbManifest, err := l.manifestDao.FindManifestByDigest(ctx, dbRegistry.ID, info.Image, digest)
if errors.Is(err, gitnessstore.ErrResourceNotFound) {
return fmt.Errorf("manifest %s not found in database", dgst)
}
if err != nil {
return formatFailedToTagErr(err)
}
var newTags []string
existingTags, err := l.tagDao.GetTagsByManifestID(ctx, dbManifest.ID)
if err != nil {
return formatFailedToTagErr(err)
}
for _, t := range tags {
if !slices.Contains(*existingTags, t) {
newTags = append(newTags, t)
} else {
log.Info().Ctx(ctx).Msgf("tag: %s is already assigned to manifest: %s", t, digest.String())
}
}
err = l.addTagsWithTx(ctx, dbRegistry, dbManifest, newTags, imageName)
if err != nil {
return formatFailedToTagErr(err)
}
spacePath, packageType, err := l.getSpacePathAndPackageType(ctx, &dbRegistry)
if err != nil {
log.Ctx(ctx).Err(err).Msg("Failed to find spacePath, not publishing event")
}
session, _ := request.AuthSessionFrom(ctx)
for _, tag := range newTags {
l.reportEvents(ctx, dgst, info, imageName, tag, packageType, spacePath, dbManifest, session)
}
return nil
}
func (l *manifestService) addTagsWithTx(
ctx context.Context,
dbRegistry types.Registry,
dbManifest *types.Manifest,
tags []string,
imageName string,
) error {
err := l.tx.WithTx(ctx, func(ctx context.Context) error {
// Prevent long running transactions by setting an upper limit of manifestTagGCLockTimeout. If the GC is holding
// the lock of a related review record, the processing there should be fast enough to avoid this. Regardless, we
// should not let transactions open (and clients waiting) for too long. If this sensible timeout is exceeded, abort
// the tag creation and let the client retry. This will bubble up and lead to a 503 Service Unavailable response.
// Set timeout for the transaction to prevent long-running operations
ctx, cancel := context.WithTimeout(ctx, manifestTagGCLockTimeout)
defer cancel()
// Attempt to find and lock the manifest for GC review
if err := l.lockManifestForGC(ctx, dbRegistry.ID, dbManifest.ID); err != nil {
return formatFailedToTagErr(err)
}
for _, tag := range tags {
if err := l.upsertTag(ctx, dbRegistry.ID, dbManifest.ID, imageName, tag); err != nil {
return formatFailedToTagErr(err)
}
}
return nil
})
return err
}
func (l *manifestService) reportEvents(
ctx context.Context,
dgst digest.Digest,
info pkg.RegistryInfo,
imageName string,
tag string,
packageType event.PackageType,
spacePath string,
dbManifest *types.Manifest,
session *auth.Session,
) {
reg := info.Registry
if !l.untaggedImagesEnabled(ctx) {
l.reportEventAsync(
ctx, reg.ID, info.RegIdentifier, imageName, tag, packageType,
spacePath, dbManifest.ID,
)
}
createPayload := webhook.GetArtifactCreatedPayload(ctx, info, session.Principal.ID,
reg.ID, reg.Name, tag, dgst.String(), l.urlProvider)
l.artifactEventReporter.ArtifactCreated(ctx, &createPayload)
}
func formatFailedToTagErr(err error) error {
return fmt.Errorf("failed to tag manifest: %w", err)
}
// Locks the manifest for GC review.
func (l *manifestService) lockManifestForGC(ctx context.Context, repoID, manifestID int64) error {
_, err := l.gcService.ManifestFindAndLockBefore(
ctx, repoID, manifestID,
time.Now().Add(manifestTagGCReviewWindow),
)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
// Use ProcessSQLErrorf for handling the SQL error abstraction
return db.ProcessSQLErrorf(
ctx,
err,
"failed to lock manifest for GC review [repoID: %d, manifestID: %d]", repoID, manifestID,
)
}
return nil
}
// Creates or updates artifact and tag records.
func (l *manifestService) upsertTag(
ctx context.Context,
registryID,
manifestID int64,
imageName,
tagName string,
) error {
tag := &types.Tag{
Name: tagName,
ImageName: imageName,
RegistryID: registryID,
ManifestID: manifestID,
}
return l.tagDao.CreateOrUpdate(ctx, tag)
}
// Retrieves the spacePath and packageType.
func (l *manifestService) getSpacePathAndPackageType(
ctx context.Context,
dbRepo *types.Registry,
) (string, event.PackageType, error) {
spacePath, err := l.spaceFinder.FindByID(ctx, dbRepo.ParentID)
if err != nil {
log.Ctx(ctx).Err(err).Msg("Failed to find spacePath")
return "", event.PackageType(0), err
}
packageType, err := event.GetPackageTypeFromString(string(dbRepo.PackageType))
if err != nil {
log.Ctx(ctx).Err(err).Msg("Failed to find packageType")
return "", event.PackageType(0), err
}
return spacePath.Path, packageType, nil
}
// Reports event asynchronously.
func (l *manifestService) reportEventAsync(
ctx context.Context,
regID int64,
regName,
imageName,
version string,
packageType event.PackageType,
spacePath string,
manifestID int64,
) {
artifactDetails := &event.ArtifactDetails{
RegistryID: regID,
RegistryName: regName,
PackageType: packageType,
ManifestID: manifestID,
ImagePath: imageName + ":" + version,
}
//Todo: update this to include digest instead of tag after STO step fix
// if l.untaggedImagesEnabled(ctx) {
// artifactDetails.ImagePath = imageName + "@" + version
// } else {
// artifactDetails.ImagePath = imageName + ":" + version
// }
go l.reporter.ReportEvent(ctx, artifactDetails, spacePath)
}
func (l *manifestService) DBPut(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
_, payload, err := mfst.Payload()
if err != nil {
return err
}
err = l.dbPutManifest(ctx, mfst, payload, d, headers, info)
if err == nil && l.untaggedImagesEnabled(ctx) {
dgst, err := types.NewDigest(d)
if err != nil {
return err
}
dbManifest, err := l.manifestDao.FindManifestByDigest(ctx, info.Registry.ID, info.Image, dgst)
if err != nil {
return err
}
spacePath, packageType, err := l.getSpacePathAndPackageType(ctx, &info.Registry)
if err != nil {
return err
}
l.reportEventAsync(
ctx, info.Registry.ID, info.RegIdentifier, info.Image, info.Tag, packageType,
spacePath, dbManifest.ID,
)
}
var mtErr util.UnknownMediaTypeError
if errors.As(err, &mtErr) {
return errcode.ErrorCodeManifestInvalid.WithDetail(mtErr.Error())
}
return err
}
func (l *manifestService) dbPutManifest(
ctx context.Context,
manifest manifest.Manifest,
payload []byte,
d digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
switch reqManifest := manifest.(type) {
case *schema2.DeserializedManifest:
log.Ctx(ctx).Debug().Msgf("Putting schema2 manifest %s to database", d.String())
if err := l.dbPutManifestSchema2(ctx, reqManifest, payload, d, headers, info); err != nil {
return err
}
return l.upsertImageAndArtifact(ctx, d, info)
case *ocischema.DeserializedManifest:
log.Ctx(ctx).Debug().Msgf("Putting ocischema manifest %s to database", d.String())
if err := l.dbPutManifestOCI(ctx, reqManifest, payload, d, headers, info); err != nil {
return err
}
return l.upsertImageAndArtifact(ctx, d, info)
case *manifestlist.DeserializedManifestList:
log.Ctx(ctx).Debug().Msgf("Putting manifestlist manifest %s to database", d.String())
if err := l.dbPutManifestList(ctx, reqManifest, payload, d, headers, info); err != nil {
return err
}
return l.upsertImageAndArtifact(ctx, d, info)
case *ocischema.DeserializedImageIndex:
log.Ctx(ctx).Debug().Msgf("Putting ocischema image index %s to database", d.String())
if err := l.dbPutImageIndex(ctx, reqManifest, payload, d, headers, info); err != nil {
return err
}
return l.upsertImageAndArtifact(ctx, d, info)
default:
log.Ctx(ctx).Info().Msgf("Invalid manifest type: %T", reqManifest)
return errcode.ErrorCodeManifestInvalid.WithDetail("manifest type unsupported")
}
}
func (l *manifestService) upsertImageAndArtifact(ctx context.Context, d digest.Digest, info pkg.RegistryInfo) error {
dbRepo := info.Registry
dbImage := &types.Image{
Name: info.Image,
RegistryID: dbRepo.ID,
Enabled: true,
}
if err := l.imageDao.CreateOrUpdate(ctx, dbImage); err != nil {
return err
}
dgst, err := types.NewDigest(d)
if err != nil {
return err
}
dbArtifact := &types.Artifact{
ImageID: dbImage.ID,
Version: dgst.String(),
}
if _, err := l.artifactDao.CreateOrUpdate(ctx, dbArtifact); err != nil {
return err
}
return nil
}
func (l *manifestService) UpsertImage(
ctx context.Context,
info pkg.RegistryInfo,
) error {
dbRepo := info.Registry
image, err := l.imageDao.GetByName(ctx, dbRepo.ID, info.Image)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return err
} else if image != nil {
return nil
}
dbImage := &types.Image{
Name: info.Image,
RegistryID: dbRepo.ID,
Enabled: false,
}
if err := l.imageDao.CreateOrUpdate(ctx, dbImage); err != nil {
return err
}
return nil
}
func (l *manifestService) dbPutManifestSchema2(
ctx context.Context,
manifest *schema2.DeserializedManifest,
payload []byte,
d digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
return l.dbPutManifestV2(ctx, manifest, payload, false, d, headers, info)
}
func (l *manifestService) dbPutManifestV2(
ctx context.Context,
mfst manifest.ManifestV2,
payload []byte,
nonConformant bool,
digest digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
// find target repository
dbRepo := info.Registry
// Find the config now to ensure that the config's blob is associated with the repository.
dbCfgBlob, err := l.DBFindRepositoryBlob(ctx, mfst.Config(), dbRepo.ID, info.Image)
if err != nil {
return err
}
dgst, err := types.NewDigest(digest)
if err != nil {
return err
}
dbManifest, err := l.manifestDao.FindManifestByDigest(ctx, dbRepo.ID, info.Image, dgst)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return err
}
if dbManifest != nil {
return nil
}
log.Ctx(ctx).Debug().Msgf("manifest %s not found in database", dgst.String())
cfg := &types.Configuration{
MediaType: mfst.Config().MediaType,
Digest: dbCfgBlob.Digest,
BlobID: dbCfgBlob.ID,
}
//TODO: check if we need to store the config payload in the database
// skip retrieval and caching of config payload if its size is over the limit
/*if dbCfgBlob.Size <= datastore.ConfigSizeLimit {
// Since filesystem writes may be optional, We cannot be sure that the
// repository scoped filesystem blob service will have a link to the
// configuration blob; however, since we check for repository scoped access
// via the database above, we may retrieve the blob directly common storage.
cfgPayload, err := imh.blobProvider.Get(imh, dbCfgBlob.Digest)
if err != nil {
return err
}
cfg.Payload = cfgPayload
}*/
m := &types.Manifest{
RegistryID: dbRepo.ID,
TotalSize: mfst.TotalSize(),
SchemaVersion: mfst.Version().SchemaVersion,
MediaType: mfst.Version().MediaType,
Digest: digest,
Payload: payload,
Configuration: cfg,
NonConformant: nonConformant,
ImageName: info.Image,
}
var artifactMediaType sql.NullString
ocim, ok := mfst.(manifest.ManifestOCI)
if ok {
subjectHandlingError := l.handleSubject(
ctx, ocim.Subject(), ocim.ArtifactType(),
ocim.Annotations(), &dbRepo, m, headers, info,
)
if subjectHandlingError != nil {
return subjectHandlingError
}
if ocim.ArtifactType() != "" {
artifactMediaType.Valid = true
artifactMediaType.String = ocim.ArtifactType()
m.ArtifactType = artifactMediaType
}
} else if mfst.Config().MediaType != "" {
artifactMediaType.Valid = true
artifactMediaType.String = mfst.Config().MediaType
m.ArtifactType = artifactMediaType
}
// check if the manifest references non-distributable layers and mark it as such on the DB
ll := mfst.DistributableLayers()
m.NonDistributableLayers = len(ll) < len(mfst.Layers())
// Use CreateOrFind to prevent race conditions while pushing the same manifest with digest for different tags
if err := l.manifestDao.CreateOrFind(ctx, m); err != nil {
return err
}
dbManifest = m
// find and associate distributable manifest layer blobs
for _, reqLayer := range mfst.DistributableLayers() {
log.Ctx(ctx).Debug().Msgf("associating layer %s with manifest %s", reqLayer.Digest.String(), digest.String())
dbBlob, err := l.DBFindRepositoryBlob(ctx, reqLayer, dbRepo.ID, info.Image)
if err != nil {
return err
}
// Overwrite the media type from common blob storage with the one
// specified in the manifest json for the layer entity. The layer entity
// has a 1-1 relationship with with the manifest, so we want to reflect
// the manifest's description of the layer. Multiple manifest can reference
// the same blob, so the common blob storage should remain generic.
if ok2 := l.layerMediaTypeExists(ctx, reqLayer.MediaType); ok2 {
dbBlob.MediaType = reqLayer.MediaType
}
if err2 := l.layerDao.AssociateLayerBlob(ctx, dbManifest, dbBlob); err2 != nil {
return err2
}
}
return nil
}
func (l *manifestService) DBFindRepositoryBlob(
ctx context.Context, desc manifest.Descriptor,
repoID int64, imageName string,
) (*types.Blob, error) {
b, err := l.blobRepo.FindByDigestAndRepoID(ctx, desc.Digest, repoID, imageName)
if err != nil {
if errors.Is(err, gitnessstore.ErrResourceNotFound) {
return nil, fmt.Errorf("blob not found in database")
}
return nil, err
}
return b, nil
}
// AddManifestAssociation This updates the manifestRefs for all new childDigests to their already existing parent
// manifests. This is used when a manifest from a manifest list is pulled from the remote and manifest list already
// exists in the database.
func (l *manifestService) AddManifestAssociation(
ctx context.Context, repoKey string, childDigest digest.Digest, info pkg.RegistryInfo,
) error {
newDigest, err2 := types.NewDigest(childDigest)
if err2 != nil {
return fmt.Errorf("failed to create digest: %s %w", childDigest, err2)
}
r, err := l.registryDao.GetByParentIDAndName(ctx, info.ParentID, repoKey)
if err != nil {
return fmt.Errorf("failed to get registry: %s %w", repoKey, err)
}
childManifest, err2 := l.manifestDao.FindManifestByDigest(ctx, r.ID, info.Image, newDigest)
if err2 != nil {
return fmt.Errorf("failed to find manifest by digest. Repo: %d Image: %s %w", r.ID, info.Image, err2)
}
mappings, err := l.ociImageIndexMappingDao.GetAllByChildDigest(ctx, r.ID, childManifest.ImageName, newDigest)
if err != nil {
return fmt.Errorf("failed to get oci image index mappings. Repo: %d Image: %s %w",
r.ID,
childManifest.ImageName,
err)
}
for _, mapping := range mappings {
parentManifest, err := l.manifestDao.Get(ctx, mapping.ParentManifestID)
if err != nil {
return fmt.Errorf("failed to get manifest with ID: %d %w", mapping.ParentManifestID, err)
}
if err := l.manifestRefDao.AssociateManifest(ctx, parentManifest, childManifest); err != nil {
if errors.Is(err, util.ErrRefManifestNotFound) {
// This can only happen if the online GC deleted one
// of the referenced manifests (because they were
// untagged/unreferenced) between the call to
// `FindAndLockNBefore` and `AssociateManifest`. For now
// we need to return this error to mimic the behaviour
// of the corresponding filesystem validation.
log.Error().
Msgf("Failed to associate manifest Ref Manifest not found. parentDigest:%s childDigest:%s %v",
parentManifest.Digest.String(),
childManifest.Digest.String(),
err)
return err
}
}
}
return nil
}
func (l *manifestService) handleSubject(
ctx context.Context, subject manifest.Descriptor,
artifactType string, annotations map[string]string, dbRepo *types.Registry,
m *types.Manifest, headers *commons.ResponseHeaders, info pkg.RegistryInfo,
) error {
if subject.Digest.String() != "" {
// Fetch subject_id from digest
subjectDigest, err := types.NewDigest(subject.Digest)
if err != nil {
return err
}
dbSubject, err := l.manifestDao.FindManifestByDigest(ctx, dbRepo.ID, info.Image, subjectDigest)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return err
}
if errors.Is(err, gitnessstore.ErrResourceNotFound) {
// in case something happened to the referenced manifest after validation
// return distribution.ManifestBlobUnknownError{Digest: subject.Digest}
log.Ctx(ctx).Warn().Msgf("subject manifest not found in database")
} else {
m.SubjectID.Int64 = dbSubject.ID
m.SubjectID.Valid = true
}
m.SubjectDigest = subject.Digest
headers.Headers["OCI-Subject"] = subject.Digest.String()
}
if artifactType != "" {
m.ArtifactType.String = artifactType
m.ArtifactType.Valid = true
}
m.Annotations = annotations
return nil
}
func (l *manifestService) dbPutManifestOCI(
ctx context.Context,
manifest *ocischema.DeserializedManifest,
payload []byte,
d digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
return l.dbPutManifestV2(ctx, manifest, payload, false, d, headers, info)
}
func (l *manifestService) dbPutManifestList(
ctx context.Context,
manifestList *manifestlist.DeserializedManifestList,
payload []byte,
digest digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
if LikelyBuildxCache(manifestList) {
return l.dbPutBuildkitIndex(ctx, manifestList, payload, digest, headers, info)
}
r := info.Registry
dgst, err := types.NewDigest(digest)
if err != nil {
return err
}
ml, err := l.manifestDao.FindManifestByDigest(ctx, r.ID, info.Image, dgst)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return err
}
// Media type can be either Docker (`application/vnd.docker.distribution.manifest.list.v2+json`)
// or OCI (empty).
// We need to make it explicit if empty, otherwise we're not able to distinguish between media types.
mediaType := manifestList.MediaType
if mediaType == "" {
mediaType = v1.MediaTypeImageIndex
}
ml = &types.Manifest{
RegistryID: r.ID,
SchemaVersion: manifestList.SchemaVersion,
MediaType: mediaType,
Digest: digest,
Payload: payload,
ImageName: info.Image,
}
mm, ids, err2 := l.validateManifestList(ctx, manifestList, info)
if err2 != nil {
return err2
}
err = l.tx.WithTx(
ctx, func(ctx context.Context) error {
// Prevent long running transactions by setting an upper limit of
// manifestListCreateGCLockTimeout. If the GC is
// holding the lock of a related review record, the processing
// there should be fast enough to avoid this.
// Regardless, we should not let transactions open (and clients waiting)
// for too long. If this sensible timeout
// is exceeded, abort the request and let the client retry.
// This will bubble up and lead to a 503 Service
// Unavailable response.
ctx, cancel := context.WithTimeout(ctx, manifestListCreateGCLockTimeout)
defer cancel()
if _, err := l.gcService.ManifestFindAndLockNBefore(
ctx, r.ID, ids,
time.Now().Add(manifestListCreateGCReviewWindow),
); err != nil {
return err
}
// use CreateOrFind to prevent race conditions when the same digest is used by different tags
// and pushed at the same time
if err := l.manifestDao.CreateOrFind(ctx, ml); err != nil {
return err
}
// Associate manifests to the manifest list.
for _, m := range mm {
if err := l.manifestRefDao.AssociateManifest(ctx, ml, m); err != nil {
if errors.Is(err, util.ErrRefManifestNotFound) {
// This can only happen if the online GC deleted one
// of the referenced manifests (because they were
// untagged/unreferenced) between the call to
// `FindAndLockNBefore` and `AssociateManifest`. For now
// we need to return this error to mimic the behaviour
// of the corresponding filesystem validation.
return distribution.ErrManifestVerification{
distribution.ErrManifestBlobUnknown{Digest: m.Digest},
}
}
return err
}
}
err = l.mapManifestList(ctx, ml.ID, manifestList, &info.Registry)
if err != nil {
return fmt.Errorf("failed to map manifest list: %w", err)
}
return nil
},
)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to create manifest list in database: %v", err)
return fmt.Errorf("failed to create manifest list in database: %w", err)
}
return nil
}
func (l *manifestService) validateManifestIndex(
ctx context.Context, manifestList *ocischema.DeserializedImageIndex, r *types.Registry, info pkg.RegistryInfo,
) ([]*types.Manifest, []int64, error) {
mm := make([]*types.Manifest, 0, len(manifestList.Manifests))
ids := make([]int64, 0, len(manifestList.Manifests))
for _, desc := range manifestList.Manifests {
m, err := l.dbFindManifestListManifest(ctx, r, info.Image, desc.Digest)
if errors.Is(err, gitnessstore.ErrResourceNotFound) && r.Type == artifact.RegistryTypeUPSTREAM {
continue
}
if err != nil {
return nil, nil, err
}
mm = append(mm, m)
ids = append(ids, m.ID)
}
log.Ctx(ctx).Debug().Msgf("validated %d / %d manifests in index", len(mm), len(manifestList.Manifests))
return mm, ids, nil
}
func (l *manifestService) mapManifestIndex(
ctx context.Context, mi int64, manifestList *ocischema.DeserializedImageIndex, r *types.Registry,
) error {
if r.Type != artifact.RegistryTypeUPSTREAM {
return nil
}
for _, desc := range manifestList.Manifests {
err := l.ociImageIndexMappingDao.Create(ctx, &types.OCIImageIndexMapping{
ParentManifestID: mi,
ChildManifestDigest: desc.Digest,
})
if err != nil {
log.Ctx(ctx).Error().Err(err).
Msgf("failed to create oci image index manifest for digest %s", desc.Digest)
return fmt.Errorf("failed to create oci image index manifest: %w", err)
}
}
log.Ctx(ctx).Debug().Msgf("successfully mapped manifest index %d with its manifests", mi)
return nil
}
func (l *manifestService) validateManifestList(
ctx context.Context,
manifestList *manifestlist.DeserializedManifestList,
info pkg.RegistryInfo,
) ([]*types.Manifest, []int64, error) {
mm := make([]*types.Manifest, 0, len(manifestList.Manifests))
ids := make([]int64, 0, len(manifestList.Manifests))
for _, desc := range manifestList.Manifests {
m, err := l.dbFindManifestListManifest(ctx, &info.Registry, info.Image, desc.Digest)
if errors.Is(err, gitnessstore.ErrResourceNotFound) && info.Registry.Type == artifact.RegistryTypeUPSTREAM {
continue
}
if err != nil {
return nil, nil, err
}
mm = append(mm, m)
ids = append(ids, m.ID)
}
log.Ctx(ctx).Debug().Msgf("validated %d / %d manifests in list", len(mm), len(manifestList.Manifests))
return mm, ids, nil
}
func (l *manifestService) mapManifestList(
ctx context.Context, mi int64, manifestList *manifestlist.DeserializedManifestList, r *types.Registry,
) error {
if r.Type != artifact.RegistryTypeUPSTREAM {
return nil
}
for _, desc := range manifestList.Manifests {
err := l.ociImageIndexMappingDao.Create(ctx, &types.OCIImageIndexMapping{
ParentManifestID: mi,
ChildManifestDigest: desc.Digest,
})
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to create oci image index manifest for digest %s", desc.Digest)
return fmt.Errorf("failed to create oci image index manifest: %w", err)
}
}
log.Ctx(ctx).Debug().Msgf("successfully mapped manifest list %d with its manifests", mi)
return nil
}
func (l *manifestService) dbPutImageIndex(
ctx context.Context,
imageIndex *ocischema.DeserializedImageIndex,
payload []byte,
digest digest.Digest,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error {
r, err := l.registryDao.GetByParentIDAndName(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return err
}
if r == nil {
return errors.New("repository not found in database")
}
dgst, err := types.NewDigest(digest)
if err != nil {
return err
}
mi, err := l.manifestDao.FindManifestByDigest(ctx, r.ID, info.Image, dgst)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | true |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/remote.go | registry/app/pkg/docker/remote.go | // Source: https://github.com/goharbor/harbor
// Copyright 2016 Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/common/lib/errors"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/manifest/manifestlist"
"github.com/harness/gitness/registry/app/manifest/schema2"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
proxy2 "github.com/harness/gitness/registry/app/remote/controller/proxy"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog/log"
)
const (
contentLength = "Content-Length"
contentType = "Content-Type"
dockerContentDigest = "Docker-Content-Digest"
etag = "Etag"
ensureTagInterval = 10 * time.Second
ensureTagMaxRetry = 60
)
func NewRemoteRegistry(
local *LocalRegistry, app *App, upstreamProxyConfigRepo store.UpstreamProxyConfigRepository,
spaceFinder refcache.SpaceFinder, secretService secret.Service, proxyCtl proxy2.Controller,
) Registry {
cache := proxy2.GetManifestCache(local, local.ms)
listCache := proxy2.GetManifestListCache(local)
registry := map[string]proxy2.ManifestCacheHandler{
manifestlist.MediaTypeManifestList: listCache,
v1.MediaTypeImageIndex: listCache,
schema2.MediaTypeManifest: cache,
proxy2.DefaultHandler: cache,
}
return &RemoteRegistry{
local: local,
App: app,
upstreamProxyConfigRepo: upstreamProxyConfigRepo,
spaceFinder: spaceFinder,
secretService: secretService,
manifestCacheHandlerMap: registry,
proxyCtl: proxyCtl,
}
}
func (r *RemoteRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *RemoteRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeDOCKER, artifact.PackageTypeHELM}
}
type RemoteRegistry struct {
local *LocalRegistry
App *App
upstreamProxyConfigRepo store.UpstreamProxyConfigRepository
spaceFinder refcache.SpaceFinder
secretService secret.Service
proxyCtl proxy2.Controller
manifestCacheHandlerMap map[string]proxy2.ManifestCacheHandler
}
func (r *RemoteRegistry) Base() error {
panic("Not implemented yet, will be done during Replication flows")
}
func proxyManifestHead(
ctx context.Context,
responseHeaders *commons.ResponseHeaders,
ctl proxy2.Controller,
art pkg.RegistryInfo,
remote proxy2.RemoteInterface,
info pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) error {
// remote call
exist, desc, err := ctl.HeadManifest(ctx, art, remote)
if err != nil {
return err
}
if !exist || desc == nil {
return errors.NotFoundError(fmt.Errorf("the tag %v:%v is not found", art.Image, art.Tag))
}
// This goRoutine is to update the tag of recently pulled manifest if required
if len(art.Tag) > 0 {
go func(art pkg.RegistryInfo) {
// Write function to update local storage.
session, _ := request.AuthSessionFrom(ctx)
ctx2 := request.WithAuthSession(ctx, session)
ctx2 = context.WithoutCancel(ctx2)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "EnsureTag")
tag := art.Tag
art.Tag = ""
art.Digest = desc.Digest.String()
var count = 0
for range ensureTagMaxRetry {
time.Sleep(ensureTagInterval)
count++
log.Ctx(ctx2).Info().Msgf("Tag %s for image: %s, retry: %d", tag,
info.Image,
count)
e := ctl.EnsureTag(ctx2, responseHeaders, art, acceptHeaders, ifNoneMatchHeader)
if e != nil {
log.Ctx(ctx2).Warn().Err(e).Msgf("Failed to update tag: %s for image: %s",
tag, info.Image)
} else {
log.Ctx(ctx2).Info().Msgf("Tag updated: %s for image: %s", tag,
info.Image)
return
}
}
}(art)
}
responseHeaders.Headers[contentLength] = fmt.Sprintf("%v", desc.Size)
responseHeaders.Headers[contentType] = desc.MediaType
responseHeaders.Headers[dockerContentDigest] = string(desc.Digest)
responseHeaders.Headers[etag] = string(desc.Digest)
return nil
}
func (r *RemoteRegistry) ManifestExist(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifestResult manifest.Manifest,
errs []error,
) {
responseHeaders = &commons.ResponseHeaders{
Headers: make(map[string]string),
}
registryInfo := artInfo
if !canProxy() {
errs = append(errs, errors.New("Proxy is down"))
return responseHeaders, descriptor, manifestResult, errs
}
upstreamProxy, err := r.upstreamProxyConfigRepo.GetByRegistryIdentifier(
ctx, artInfo.ParentID, artInfo.RegIdentifier,
)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
remoteHelper, err := proxy2.NewRemoteHelper(ctx, r.spaceFinder, r.secretService, artInfo.RegIdentifier,
*upstreamProxy)
if err != nil {
errs = append(errs, errors.New("Proxy is down"))
return responseHeaders, descriptor, manifestResult, errs
}
artInfo.Image, err = remoteHelper.GetImageName(ctx, r.spaceFinder, artInfo.Image)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
useLocal, man, err := r.proxyCtl.UseLocalManifest(ctx, registryInfo, remoteHelper, acceptHeaders, ifNoneMatchHeader)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
if useLocal {
if man != nil {
responseHeaders.Headers[contentLength] = fmt.Sprintf("%v", len(man.Content))
responseHeaders.Headers[contentType] = man.ContentType
responseHeaders.Headers[dockerContentDigest] = man.Digest
responseHeaders.Headers[etag] = man.Digest
manifestResult, descriptor, err = manifest.UnmarshalManifest(man.ContentType, man.Content)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
return responseHeaders, descriptor, manifestResult, errs
}
errs = append(errs, errors.New("Not found"))
}
log.Ctx(ctx).Debug().Msgf("the tag is %s, digest is %s", registryInfo.Tag, registryInfo.Digest)
err = proxyManifestHead(
ctx,
responseHeaders,
r.proxyCtl,
registryInfo,
remoteHelper,
artInfo,
acceptHeaders,
ifNoneMatchHeader,
)
if err != nil {
errs = append(errs, err)
log.Ctx(ctx).Warn().Msgf(
"Proxy to remote failed, fallback to next registry: %s",
err.Error(),
)
}
return responseHeaders, descriptor, manifestResult, errs
}
func (r *RemoteRegistry) PullManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifestResult manifest.Manifest,
errs []error,
) {
responseHeaders = &commons.ResponseHeaders{
Headers: make(map[string]string),
}
registryInfo := artInfo
if !canProxy() {
errs = append(errs, errors.New("Proxy is down"))
return responseHeaders, descriptor, manifestResult, errs
}
upstreamProxy, err := r.upstreamProxyConfigRepo.GetByRegistryIdentifier(
ctx, artInfo.ParentID, artInfo.RegIdentifier,
)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
remoteHelper, err := proxy2.NewRemoteHelper(ctx, r.spaceFinder, r.secretService, artInfo.RegIdentifier,
*upstreamProxy)
if err != nil {
errs = append(errs, errors.New("Proxy is down"))
return responseHeaders, descriptor, manifestResult, errs
}
artInfo.Image, err = remoteHelper.GetImageName(ctx, r.spaceFinder, artInfo.Image)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
useLocal, man, err := r.proxyCtl.UseLocalManifest(ctx, registryInfo, remoteHelper, acceptHeaders, ifNoneMatchHeader)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
if useLocal {
if man != nil {
responseHeaders.Headers[contentLength] = fmt.Sprintf("%v", len(man.Content))
responseHeaders.Headers[contentType] = man.ContentType
responseHeaders.Headers[dockerContentDigest] = man.Digest
responseHeaders.Headers[etag] = man.Digest
manifestResult, descriptor, err = manifest.UnmarshalManifest(man.ContentType, man.Content)
if err != nil {
errs = append(errs, err)
return responseHeaders, descriptor, manifestResult, errs
}
return responseHeaders, descriptor, manifestResult, errs
}
errs = append(errs, errors.New("Not found"))
}
log.Ctx(ctx).Debug().Msgf("the tag is %s, digest is %s", registryInfo.Tag, registryInfo.Digest)
log.Ctx(ctx).Warn().
Msgf(
"Artifact: %s:%v, digest:%v is not found in proxy cache, fetch it from remote registry",
artInfo.RegIdentifier, registryInfo.Tag, registryInfo.Digest,
)
manifestResult, err = proxyManifestGet(
ctx,
responseHeaders,
r.proxyCtl,
registryInfo,
remoteHelper,
artInfo.RegIdentifier,
artInfo.Image,
acceptHeaders,
ifNoneMatchHeader,
)
if err != nil {
errs = append(errs, err)
log.Ctx(ctx).Warn().Msgf("Proxy to remote failed, fallback to next registry: %s", err.Error())
}
return responseHeaders, descriptor, manifestResult, errs
}
func (r *RemoteRegistry) HeadBlob(
ctx context.Context,
_ pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
log.Ctx(ctx).Warn().Msgf("HeadBlob for proxy not implemented")
errs = append(errs, errors.New("not implemented"))
return nil, errs
}
// TODO (Arvind): There is a known issue where if the remote itself
// is a proxy, then the first pull will fail with error: `error pulling image configuration:
// image config verification failed for digest` and the second pull will succeed. This is a
// known issue and is being worked on. The workaround is to pull the image twice.
func (r *RemoteRegistry) GetBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, fr *storage.FileReader, size int64, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
return r.fetchBlobInternal(ctx2, artInfo.RegIdentifier, http.MethodGet, artInfo)
}
func (r *RemoteRegistry) fetchBlobInternal(
ctx context.Context,
repoKey string,
method string,
info pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, fr *storage.FileReader, size int64, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
responseHeaders = &commons.ResponseHeaders{
Headers: make(map[string]string),
}
log.Ctx(ctx).Info().Msgf("Proxy: %s", repoKey)
registryInfo := info
if !canProxy() {
errs = append(errs, errors.New("Blob not found"))
}
if r.proxyCtl.UseLocalBlob(ctx, registryInfo) {
switch method {
case http.MethodGet:
headers, reader, s, closer, url, e := r.local.GetBlob(ctx, info)
return headers, reader, s, closer, url, e
default:
errs = append(errs, errors.New("Method not supported"))
return responseHeaders, fr, size, readCloser, redirectURL, errs
}
}
upstreamProxy, err := r.upstreamProxyConfigRepo.GetByRegistryIdentifier(ctx, info.ParentID, repoKey)
if err != nil {
errs = append(errs, err)
}
// This is start of proxy Code.
size, readCloser, err = r.proxyCtl.ProxyBlob(ctx, registryInfo, repoKey, *upstreamProxy)
if err != nil {
errs = append(errs, err)
return responseHeaders, fr, size, readCloser, redirectURL, errs
}
setHeaders(responseHeaders, size, "", registryInfo.Digest)
return responseHeaders, fr, size, readCloser, redirectURL, errs
}
func proxyManifestGet(
ctx context.Context,
responseHeaders *commons.ResponseHeaders,
ctl proxy2.Controller,
registryInfo pkg.RegistryInfo,
remote proxy2.RemoteInterface,
repoKey string,
imageName string,
acceptHeader []string,
ifNoneMatchHeader []string,
) (man manifest.Manifest, err error) {
man, err = ctl.ProxyManifest(ctx, registryInfo, remote, repoKey, imageName, acceptHeader, ifNoneMatchHeader)
if err != nil {
return
}
ct, payload, err := man.Payload()
if err != nil {
return
}
setHeaders(responseHeaders, int64(len(payload)), ct, registryInfo.Digest)
return
}
func setHeaders(
responseHeaders *commons.ResponseHeaders, size int64,
mediaType string, dig string,
) {
responseHeaders.Headers[contentLength] = fmt.Sprintf("%v", size)
if len(mediaType) > 0 {
responseHeaders.Headers[contentType] = mediaType
}
responseHeaders.Headers[dockerContentDigest] = dig
responseHeaders.Headers[etag] = dig
}
func canProxy() bool {
// TODO Health check.
return true
}
func (r *RemoteRegistry) PushBlobMonolith(
_ context.Context,
_ pkg.RegistryInfo,
_ int64,
_ io.Reader,
) error {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) InitBlobUpload(
_ context.Context,
_ pkg.RegistryInfo,
_, _ string,
) (*commons.ResponseHeaders, []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) PushBlobMonolithWithDigest(
_ context.Context,
_ pkg.RegistryInfo,
_ int64,
_ io.Reader,
) error {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) PushBlobChunk(
_ *Context,
_ pkg.RegistryInfo,
_ string,
_ string,
_ string,
_ io.ReadCloser,
_ int64,
) (*commons.ResponseHeaders, []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) PushBlob(
_ context.Context,
_ pkg.RegistryInfo,
_ io.ReadCloser,
_ int64,
_ string,
) (*commons.ResponseHeaders, []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) PutManifest(
_ context.Context,
_ pkg.RegistryInfo,
_ string,
_ io.ReadCloser,
_ int64,
) (*commons.ResponseHeaders, []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) ListTags(
_ context.Context,
_ string,
_ int,
_ string,
_ pkg.RegistryInfo,
) (*commons.ResponseHeaders, []string, error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) ListFilteredTags(
_ context.Context,
_ int,
_, _ string,
_ pkg.RegistryInfo,
) (tags []string, err error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) DeleteManifest(
_ context.Context,
_ pkg.RegistryInfo,
) (errs []error, responseHeaders *commons.ResponseHeaders) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) DeleteBlob(
_ *Context,
_ pkg.RegistryInfo,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) MountBlob(
_ context.Context,
_ pkg.RegistryInfo,
_, _ string,
) (err error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) ListReferrers(
_ context.Context,
_ pkg.RegistryInfo,
_ string,
) (index *v1.Index, responseHeaders *commons.ResponseHeaders, err error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) GetBlobUploadStatus(
_ *Context,
_ pkg.RegistryInfo,
_ string,
) (*commons.ResponseHeaders, []error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) GetCatalog() (repositories []string, err error) {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) DeleteTag(
_, _ string,
_ pkg.RegistryInfo,
) error {
panic("Not implemented yet, will be done during Replication flows")
}
func (r *RemoteRegistry) PullBlobChunk(
_, _ string,
_, _, _ int64,
_ pkg.RegistryInfo,
) (size int64, blob io.ReadCloser, err error) {
panic(
"Not implemented yet, will be done during Replication flows",
)
}
func (r *RemoteRegistry) CanBeMount() (mount bool, repository string, err error) {
panic("Not implemented yet, will be done during Replication flows")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/registry.go | registry/app/pkg/docker/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"io"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
/*
Registry defines the capabilities that an artifact registry should have. It should support following methods:
// Manifest - GET, HEAD, PUT, DELETE
// Catalog - GET
// Tag - GET, DELETE
// Blob - GET, HEAD, DELETE
// Blob Upload - GET, HEAD, POST, PATCH, PUT, DELETE
ref: https://github.com/opencontainers/distribution-spec/blob/main/spec.md
Endpoints to support:
| ID | Method | API Endpoint | Success | Failure
| ------- | -------------- | -------------------------------------------------------------- | ----------- | -----------
| end-1 | `GET` | `/v2/` | `200` | `404`/`401`
| end-2 | `GET` / `HEAD` | `/v2/<name>/blobs/<digest>` | `200` | `404`
| end-3 | `GET` / `HEAD` | `/v2/<name>/manifests/<reference>` | `200` | `404`
| end-4a | `POST` | `/v2/<name>/blobs/uploads/` | `202` | `404`
| end-4b | `POST` | `/v2/<name>/blobs/uploads/?digest=<digest>` | `201`/`202` | `404`/`400`
| end-5 | `PATCH` | `/v2/<name>/blobs/uploads/<reference>` | `202` | `404`/`416`
| end-6 | `PUT` | `/v2/<name>/blobs/uploads/<reference>?digest=<digest>` | `201` | `404`/`400`
| end-7 | `PUT` | `/v2/<name>/manifests/<reference>` | `201` | `404`
| end-8a | `GET` | `/v2/<name>/tags/list` | `200` | `404`
| end-8b | `GET` | `/v2/<name>/tags/list?n=<integer>&last=<tagname>` | `200` | `404`
| end-9 | `DELETE` | `/v2/<name>/manifests/<reference>` | `202` | `404`/`400`
| | | | | /`405`
| end-10 | `DELETE` | `/v2/<name>/blobs/<digest>` | `202` | `404`/`405`
| end-11 | `POST` | `/v2/<name>/blobs/uploads/?mount=<digest>&from=<other_name>` | `201` | `404`
| end-12a | `GET` | `/v2/<name>/referrers/<digest>` | `200` | `404`/`400`
| end-12b | `GET` | `/v2/<name>/referrers/<digest>?artifactType=<artifactType>` | `200` | `404`/`400`
| end-13 | `GET` | `/v2/<name>/blobs/uploads/<reference>` | `204` | `404`
|.
*/
type Registry interface {
pkg.Artifact
// end-1.
Base() error
// end-2 HEAD / GET
HeadBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, errs []error,
)
GetBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, fr *storage.FileReader, size int64,
readCloser io.ReadCloser, redirectURL string, errs []error,
)
// end-3 HEAD
ManifestExist(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifest manifest.Manifest,
Errors []error,
)
// end-3 GET
PullManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders, descriptor manifest.Descriptor, manifest manifest.Manifest,
Errors []error,
)
// end-4a.
PushBlobMonolith(ctx context.Context, artInfo pkg.RegistryInfo, size int64, blob io.Reader) error
InitBlobUpload(
ctx context.Context,
artInfo pkg.RegistryInfo,
fromRepo, mountDigest string,
) (*commons.ResponseHeaders, []error)
// end-4b
PushBlobMonolithWithDigest(ctx context.Context, artInfo pkg.RegistryInfo, size int64, blob io.Reader) error
// end-5
PushBlobChunk(
ctx *Context,
artInfo pkg.RegistryInfo,
contentType string,
contentRange string,
contentLength string,
body io.ReadCloser,
contentLengthFromRequest int64,
) (*commons.ResponseHeaders, []error)
// end-6
PushBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
body io.ReadCloser,
contentLength int64,
stateToken string,
) (*commons.ResponseHeaders, []error)
// end-7
PutManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
mediaType string,
body io.ReadCloser,
length int64,
) (*commons.ResponseHeaders, []error)
// end-8a
ListTags(
c context.Context,
lastEntry string,
maxEntries int,
origURL string,
artInfo pkg.RegistryInfo,
) (*commons.ResponseHeaders, []string, error)
// end-8b
ListFilteredTags(
ctx context.Context,
n int,
last, repository string,
artInfo pkg.RegistryInfo,
) (tags []string, err error)
// end-9
DeleteManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
) (errs []error, responseHeaders *commons.ResponseHeaders)
// the "reference" can be "tag" or "digest", the function needs to handle both
// end-10.
DeleteBlob(ctx *Context, artInfo pkg.RegistryInfo) (responseHeaders *commons.ResponseHeaders, errs []error)
// end-11.
MountBlob(ctx context.Context, artInfo pkg.RegistryInfo, srcRepository, dstRepository string) (err error)
// end-12a/12b
ListReferrers(
ctx context.Context,
artInfo pkg.RegistryInfo,
artifactType string,
) (index *v1.Index, responseHeaders *commons.ResponseHeaders, err error)
// end-13.
GetBlobUploadStatus(ctx *Context, artInfo pkg.RegistryInfo, stateToken string) (*commons.ResponseHeaders, []error)
// Catalog GET.
GetCatalog() (repositories []string, err error)
// Tag DELETE.
DeleteTag(repository, tag string, artInfo pkg.RegistryInfo) error
// Blob chunk PULL
PullBlobChunk(
repository, digest string,
blobSize, start, end int64,
artInfo pkg.RegistryInfo,
) (size int64, blob io.ReadCloser, err error)
// Mount check
CanBeMount() (mount bool, repository string, err error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/response.go | registry/app/pkg/docker/response.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"io"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
type Response interface {
GetErrors() []error
SetError(error)
}
var _ Response = (*GetManifestResponse)(nil)
var _ Response = (*PutManifestResponse)(nil)
var _ Response = (*DeleteManifestResponse)(nil)
type GetManifestResponse struct {
Errors []error
ResponseHeaders *commons.ResponseHeaders
descriptor manifest.Descriptor
Manifest manifest.Manifest
}
func (r *GetManifestResponse) GetErrors() []error {
return r.Errors
}
func (r *GetManifestResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
type PutManifestResponse struct {
Errors []error
}
func (r *PutManifestResponse) GetErrors() []error {
return r.Errors
}
func (r *PutManifestResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
type DeleteManifestResponse struct {
Errors []error
}
func (r *DeleteManifestResponse) GetErrors() []error {
return r.Errors
}
func (r *DeleteManifestResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
type GetBlobResponse struct {
Errors []error
ResponseHeaders *commons.ResponseHeaders
Body *storage.FileReader
Size int64
ReadCloser io.ReadCloser
RedirectURL string
}
func (r *GetBlobResponse) GetErrors() []error {
return r.Errors
}
func (r *GetBlobResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/catalog.go | registry/app/pkg/docker/catalog.go | // Source: https://gitlab.com/gitlab-org/container-registry
// Copyright 2019 Gitlab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"encoding/base64"
"fmt"
"net/url"
"strconv"
repostore "github.com/harness/gitness/registry/app/store/database"
"github.com/harness/gitness/registry/types"
)
const (
linkPrevious = "previous"
linkNext = "next"
encodingSeparator = "|"
NQueryParamKey = "n"
PublishedAtQueryParamKey = "published_at"
BeforeQueryParamKey = "before"
TagNameQueryParamKey = "name"
SortQueryParamKey = "sort"
LastQueryParamKey = "last"
)
// Use the original URL from the request to create a new URL for
// the link header.
func CreateLinkEntry(
origURL string,
filters types.FilterParams,
publishedBefore, publishedLast string,
) (string, error) {
var combinedURL string
if filters.BeforeEntry != "" {
beforeURL, err := generateLink(origURL, linkPrevious, filters, publishedBefore, publishedLast)
if err != nil {
return "", err
}
combinedURL = beforeURL
}
if filters.LastEntry != "" {
lastURL, err := generateLink(origURL, linkNext, filters, publishedBefore, publishedLast)
if err != nil {
return "", err
}
if filters.BeforeEntry == "" {
combinedURL = lastURL
} else {
// Put the "previous" URL first and then "next" as shown in the
// RFC5988 examples https://datatracker.ietf.org/doc/html/rfc5988#section-5.5.
combinedURL = fmt.Sprintf("%s, %s", combinedURL, lastURL)
}
}
return combinedURL, nil
}
func generateLink(
originalURL, rel string,
filters types.FilterParams,
publishedBefore, publishedLast string,
) (string, error) {
calledURL, err := url.Parse(originalURL)
if err != nil {
return "", err
}
qValues := url.Values{}
qValues.Add(NQueryParamKey, strconv.Itoa(filters.MaxEntries))
switch rel {
case linkPrevious:
before := filters.BeforeEntry
if filters.OrderBy == PublishedAtQueryParamKey && publishedBefore != "" {
before = EncodeFilter(publishedBefore, filters.BeforeEntry)
}
qValues.Add(BeforeQueryParamKey, before)
case linkNext:
last := filters.LastEntry
if filters.OrderBy == PublishedAtQueryParamKey && publishedLast != "" {
last = EncodeFilter(publishedLast, filters.LastEntry)
}
qValues.Add(LastQueryParamKey, last)
}
if filters.Name != "" {
qValues.Add(TagNameQueryParamKey, filters.Name)
}
orderBy := filters.OrderBy
if orderBy != "" {
if filters.SortOrder == repostore.OrderDesc {
orderBy = "-" + orderBy
}
qValues.Add(SortQueryParamKey, orderBy)
}
calledURL.RawQuery = qValues.Encode()
calledURL.Fragment = ""
urlStr := fmt.Sprintf("<%s>; rel=\"%s\"", calledURL.String(), rel)
return urlStr, nil
}
// EncodeFilter base64 encode by concatenating the published_at value with the tagName using an encodingSeparator.
func EncodeFilter(publishedAt, tagName string) (v string) {
return base64.StdEncoding.EncodeToString(
fmt.Appendf(nil, "%s%s%s", publishedAt, encodingSeparator, tagName),
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/bucket_service.go | registry/app/pkg/docker/bucket_service.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"github.com/harness/gitness/registry/app/storage"
)
// BlobStore represents the result of a blob store lookup.
type BlobStore struct {
OciStore storage.OciBlobStore
GenericStore storage.GenericBlobStore
}
// BucketService defines a unified interface for multi-bucket blob serving functionality.
// It supports both OCI registry blobs and generic file blobs with geolocation-based routing.
type BucketService interface {
// GetBlobStore returns the appropriate blob store for the closest bucket based on geolocation.
// For OCI operations, pass repoKey. For generic operations, pass empty string for repoKey.
// blobID can be int64 for OCI blobs or string for generic blobs.
// If no suitable bucket is found, returns nil and the caller should fall back to using their default blob store.
GetBlobStore(ctx context.Context, repoKey string, rootIdentifier string,
blobID any, digest string) *BlobStore
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/controller.go | registry/app/pkg/docker/controller.go | // Source: https://gitlab.com/gitlab-org/container-registry
// Copyright 2019 Gitlab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
"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/storage"
"github.com/harness/gitness/registry/app/store"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/types/enum"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog/log"
)
type Controller struct {
*pkg.CoreController
local *LocalRegistry
remote *RemoteRegistry
spaceStore corestore.SpaceStore
authorizer authz.Authorizer
DBStore *DBStore
SpaceFinder refcache.SpaceFinder
}
type DBStore struct {
BlobRepo store.BlobRepository
ManifestDao store.ManifestRepository
ImageDao store.ImageRepository
ArtifactDao store.ArtifactRepository
BandwidthStatDao store.BandwidthStatRepository
DownloadStatDao store.DownloadStatRepository
QuarantineDao store.QuarantineArtifactRepository
}
type TagsAPIResponse struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}
var _ pkg.Artifact = (*LocalRegistry)(nil)
var _ pkg.Artifact = (*RemoteRegistry)(nil)
func NewController(
local *LocalRegistry,
remote *RemoteRegistry,
coreController *pkg.CoreController,
spaceStore corestore.SpaceStore,
authorizer authz.Authorizer,
dBStore *DBStore,
spaceFinder refcache.SpaceFinder,
) *Controller {
c := &Controller{
CoreController: coreController,
local: local,
remote: remote,
spaceStore: spaceStore,
authorizer: authorizer,
DBStore: dBStore,
SpaceFinder: spaceFinder,
}
pkg.TypeRegistry[pkg.LocalRegistry] = local
pkg.TypeRegistry[pkg.RemoteRegistry] = remote
return c
}
func NewDBStore(
blobRepo store.BlobRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
bandwidthStatDao store.BandwidthStatRepository,
downloadStatDao store.DownloadStatRepository,
manifestDao store.ManifestRepository,
quarantineDao store.QuarantineArtifactRepository,
) *DBStore {
return &DBStore{
BlobRepo: blobRepo,
ImageDao: imageDao,
ArtifactDao: artifactDao,
BandwidthStatDao: bandwidthStatDao,
DownloadStatDao: downloadStatDao,
ManifestDao: manifestDao,
QuarantineDao: quarantineDao,
}
}
const (
ResourceTypeBlob = "blob"
ResourceTypeManifest = "manifest"
)
func (c *Controller) ProxyWrapper(
ctx context.Context, f func(
registry registrytypes.Registry, imageName string,
artInfo pkg.Artifact,
) Response, info pkg.RegistryInfo, resourceType string,
) (Response, error) {
none := pkg.RegistryInfo{}
var response Response
if info == none {
log.Ctx(ctx).Error().Stack().Msg("artifactinfo is not found")
return response, errors.New("bad Request: artifactinfo is not found")
}
imageName := info.Image
repos, err := c.GetOrderedRepos(ctx, info)
if err != nil {
return response, err
}
for _, registry := range repos {
log.Ctx(ctx).Info().Msgf("Using Repository: %s, Type: %s", registry.Name, registry.Type)
artifact, ok := c.GetArtifact(ctx, registry).(Registry)
if !ok {
log.Ctx(ctx).Warn().Msgf("artifact %s is not a registry", registry.Name)
continue
}
if artifact != nil {
response = f(registry, imageName, artifact)
if pkg.IsEmpty(response.GetErrors()) {
return response, nil
}
log.Ctx(ctx).Warn().Msgf("Repository: %s, Type: %s, errors: %v", registry.Name, registry.Type,
response.GetErrors())
}
}
if response != nil && !pkg.IsEmpty(response.GetErrors()) {
switch resourceType {
case ResourceTypeManifest:
if errors.Is(response.GetErrors()[0], usererror.ErrQuarantinedArtifact) {
response.SetError(errcode.ErrCodeManifestQuarantined)
} else {
response.SetError(errcode.ErrCodeManifestUnknown)
}
case ResourceTypeBlob:
response.SetError(errcode.ErrCodeBlobUnknown)
default:
// do nothing
}
}
return response, nil
}
func (c *Controller) HeadManifest(
ctx context.Context,
art pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) Response {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, art.ParentID, *art.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return &GetManifestResponse{
Errors: []error{errcode.ErrCodeDenied},
}
}
f := func(registry registrytypes.Registry, imageName string, a pkg.Artifact) Response {
art.UpdateRegistryInfo(registry)
// Need to reassign original imageName to art because we are updating image name based on upstream proxy source inside
art.Image = imageName
//nolint:errcheck
headers, desc, man, e := a.(Registry).ManifestExist(ctx, art, acceptHeaders, ifNoneMatchHeader)
response := &GetManifestResponse{e, headers, desc, man}
return response
}
result, err := c.ProxyWrapper(ctx, f, art, ResourceTypeManifest)
if err != nil {
return &GetManifestResponse{
Errors: []error{err},
}
}
return result
}
func (c *Controller) PullManifest(
ctx context.Context,
art pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) Response {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, art.ParentID, *art.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return &GetManifestResponse{
Errors: []error{errcode.ErrCodeDenied},
}
}
f := func(registry registrytypes.Registry, imageName string, a pkg.Artifact) Response {
art.UpdateRegistryInfo(registry)
// Need to reassign original imageName to art because we are updating image name based on upstream proxy source inside
art.Image = imageName
// Check quarantine status using the finder
err := c.QuarantineFinder.CheckOCIManifestQuarantineStatus(ctx, art.RegistryID, art.Image, art.Tag, art.Digest)
if err != nil {
return handleQuarantineError(ctx, err, art.Image, art.Tag, art.Digest)
}
headers, desc, man, e := a.(Registry).PullManifest(ctx, art, acceptHeaders, ifNoneMatchHeader) //nolint:errcheck
response := &GetManifestResponse{e, headers, desc, man}
return response
}
result, err := c.ProxyWrapper(ctx, f, art, ResourceTypeManifest)
if err != nil {
return &GetManifestResponse{
Errors: []error{err},
}
}
return result
}
func (c *Controller) PutManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
mediaType string,
body io.ReadCloser,
length int64,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, artInfo.ParentID, *artInfo.ArtifactInfo,
enum.PermissionArtifactsUpload, enum.PermissionArtifactsDownload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
return c.local.PutManifest(ctx, artInfo, mediaType, body, length)
}
func (c *Controller) DeleteManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
) (errs []error, responseHeaders *commons.ResponseHeaders) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, artInfo.ParentID, *artInfo.ArtifactInfo,
enum.PermissionArtifactsDelete)
if err != nil {
return []error{errcode.ErrCodeDenied}, nil
}
return c.local.DeleteManifest(ctx, artInfo)
}
func (c *Controller) HeadBlob(
ctx context.Context,
info pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
return c.local.HeadBlob(ctx, info)
}
func (c *Controller) GetBlob(ctx context.Context, info pkg.RegistryInfo) Response {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return &GetBlobResponse{
Errors: []error{errcode.ErrCodeDenied},
}
}
f := func(registry registrytypes.Registry, imageName string, a pkg.Artifact) Response {
info.UpdateRegistryInfo(registry)
info.Image = imageName
//nolint:errcheck
headers, body, size, readCloser, redirectURL, errs := a.(Registry).GetBlob(ctx, info)
return &GetBlobResponse{errs, headers, body, size, readCloser, redirectURL}
}
result, err := c.ProxyWrapper(ctx, f, info, ResourceTypeBlob)
if err != nil {
return &GetBlobResponse{
Errors: []error{err},
}
}
return result
}
func (c *Controller) InitiateUploadBlob(
ctx context.Context,
info pkg.RegistryInfo,
fromImageRef string,
mountDigest string,
) (*commons.ResponseHeaders, []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsUpload, enum.PermissionArtifactsDownload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
return c.local.InitBlobUpload(ctx, info, fromImageRef, mountDigest)
}
func (c *Controller) GetUploadBlobStatus(
ctx context.Context,
info pkg.RegistryInfo,
token string,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
blobCtx := c.local.App.GetBlobsContext(ctx, info, nil)
//nolint:contextcheck
return c.local.GetBlobUploadStatus(blobCtx, info, token)
}
func (c *Controller) PatchBlobUpload(
ctx context.Context,
info pkg.RegistryInfo,
ct string,
cr string,
cl string,
length int64,
token string,
body io.ReadCloser,
) (responseHeaders *commons.ResponseHeaders, errors []error) {
blobCtx := c.local.App.GetBlobsContext(ctx, info, nil)
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload, enum.PermissionArtifactsUpload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
errors = make([]error, 0)
if blobCtx.UUID != "" {
//nolint:contextcheck
errs := ResumeBlobUpload(blobCtx, token)
errors = append(errors, errs...)
}
if blobCtx.Upload != nil {
defer blobCtx.Upload.Close()
}
//nolint:contextcheck
rs, errs := c.local.PushBlobChunk(blobCtx, info, ct, cr, cl, body, length)
if !commons.IsEmpty(errs) {
errors = append(errors, errs...)
}
return rs, errors
}
func (c *Controller) CompleteBlobUpload(
ctx context.Context,
info pkg.RegistryInfo,
body io.ReadCloser,
length int64,
stateToken string,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsUpload, enum.PermissionArtifactsDownload)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
return c.local.PushBlob(ctx, info, body, length, stateToken)
}
func (c *Controller) CancelBlobUpload(
ctx context.Context,
info pkg.RegistryInfo,
stateToken string,
) (responseHeaders *commons.ResponseHeaders, errors []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDelete)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
blobCtx := c.local.App.GetBlobsContext(ctx, info, nil)
errors = make([]error, 0)
if blobCtx.UUID != "" {
//nolint:contextcheck
errs := ResumeBlobUpload(blobCtx, stateToken)
errors = append(errors, errs...)
}
if blobCtx.Upload == nil {
e := errcode.ErrCodeBlobUploadUnknown
errors = append(errors, e)
return responseHeaders, errors
}
defer blobCtx.Upload.Close()
responseHeaders = &commons.ResponseHeaders{
Headers: map[string]string{"Docker-Upload-UUID": blobCtx.UUID},
}
//nolint:contextcheck
if err := blobCtx.Upload.Cancel(blobCtx); err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("error encountered canceling upload: %v", err)
errors = append(errors, errcode.ErrCodeUnknown.WithDetail(err))
}
responseHeaders.Code = http.StatusNoContent
return responseHeaders, errors
}
func (c *Controller) DeleteBlob(
ctx context.Context,
info pkg.RegistryInfo,
) (responseHeaders *commons.ResponseHeaders, errs []error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDelete)
if err != nil {
return nil, []error{errcode.ErrCodeDenied}
}
blobCtx := c.local.App.GetBlobsContext(ctx, info, nil)
//nolint:contextcheck
return c.local.DeleteBlob(blobCtx, info)
}
func (c *Controller) GetTags(
ctx context.Context,
lastEntry string,
maxEntries int,
origURL string,
artInfo pkg.RegistryInfo,
) (*commons.ResponseHeaders, []string, error) {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, artInfo.ParentID, *artInfo.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return nil, nil, errcode.ErrCodeDenied
}
return c.local.ListTags(ctx, lastEntry, maxEntries, origURL, artInfo)
}
func (c *Controller) GetCatalog(_ http.ResponseWriter, _ *http.Request) {
log.Info().Msgf("Not implemented yet!")
}
func (c *Controller) GetReferrers(
ctx context.Context,
artInfo pkg.RegistryInfo,
artifactType string,
) (index *v1.Index, responseHeaders *commons.ResponseHeaders, err error) {
accessErr := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, artInfo.ParentID, *artInfo.ArtifactInfo,
enum.PermissionArtifactsDownload)
if accessErr != nil {
return nil, nil, errcode.ErrCodeDenied
}
return c.local.ListReferrers(ctx, artInfo, artifactType)
}
func ResumeBlobUpload(ctx *Context, stateToken string) []error {
var errs []error
state, err := hmacKey(ctx.App.Config.Registry.HTTP.Secret).unpackUploadState(stateToken)
if err != nil {
log.Ctx(ctx).Info().Msgf("error resolving upload: %v", err)
errs = append(errs, errcode.ErrCodeBlobUploadInvalid.WithDetail(err))
return errs
}
ctx.State = state
if state.Path != ctx.OciBlobStore.Path() {
log.Ctx(ctx).Info().Msgf("mismatched path in upload state: %q != %q", state.Path, ctx.OciBlobStore.Path())
errs = append(errs, errcode.ErrCodeBlobUploadInvalid.WithDetail(err))
return errs
}
if state.UUID != ctx.UUID {
log.Ctx(ctx).Info().Msgf("mismatched uuid in upload state: %q != %q", state.UUID, ctx.UUID)
errs = append(errs, errcode.ErrCodeBlobUploadInvalid.WithDetail(err))
return errs
}
blobs := ctx.OciBlobStore
upload, err := blobs.Resume(ctx.Context, ctx.UUID)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("error resolving upload: %v", err)
if errors.Is(err, storage.ErrBlobUploadUnknown) {
errs = append(errs, errcode.ErrCodeBlobUploadUnknown.WithDetail(err))
return errs
}
errs = append(errs, errcode.ErrCodeUnknown.WithDetail(err))
return errs
}
ctx.Upload = upload
if size := upload.Size(); size != ctx.State.Offset {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("upload resumed at wrong offset: %d != %d", size, ctx.State.Offset)
errs = append(errs, errcode.ErrCodeRangeInvalid.WithDetail(err))
return errs
}
return errs
}
// unpackUploadState unpacks and validates the blob upload state from the
// token, using the hmacKey secret.
func (secret hmacKey) unpackUploadState(token string) (BlobUploadState, error) {
var state BlobUploadState
tokenBytes, err := base64.URLEncoding.DecodeString(token)
if err != nil {
return state, fmt.Errorf("failed to decode token: %w", err)
}
mac := hmac.New(sha256.New, []byte(secret))
if len(tokenBytes) < mac.Size() {
return state, errInvalidSecret
}
macBytes := tokenBytes[:mac.Size()]
messageBytes := tokenBytes[mac.Size():]
mac.Write(messageBytes)
if !hmac.Equal(mac.Sum(nil), macBytes) {
return state, errInvalidSecret
}
if err := json.Unmarshal(messageBytes, &state); err != nil {
return state, err
}
return state, nil
}
// handleQuarantineError handles quarantine check errors and returns an appropriate response.
func handleQuarantineError(ctx context.Context, err error, image, tag, digest string) *GetManifestResponse {
if errors.Is(err, usererror.ErrQuarantinedArtifact) {
log.Ctx(ctx).Warn().Stack().Err(err).Msgf("artifact"+
" is quarantined with name: [%s], tag: [%s], digest: [%s]",
image, tag, digest)
return &GetManifestResponse{
Errors: []error{err},
}
}
log.Ctx(ctx).Warn().Stack().Err(err).Msgf("error"+
" while checking the quarantine status of artifact: [%s], tag: [%s], digest: [%s]",
image, tag, digest)
return &GetManifestResponse{
Errors: []error{err},
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/context.go | registry/app/pkg/docker/context.go | // Source: https://github.com/distribution/distribution
// Copyright 2014 https://github.com/distribution/distribution Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"github.com/harness/gitness/registry/app/storage"
v2 "github.com/distribution/distribution/v3/registry/api/v2"
"github.com/opencontainers/go-digest"
)
// Context should contain the request specific context for use in across
// handlers. Resources that don't need to be shared across handlers should not
// be on this object.
type Context struct {
*App
context.Context
URLBuilder *v2.URLBuilder
OciBlobStore storage.OciBlobStore
Upload storage.BlobWriter
UUID string
Digest digest.Digest
State BlobUploadState
}
// Value overrides context.Context.Value to ensure that calls are routed to
// correct context.
func (ctx *Context) Value(key any) any {
return ctx.Context.Value(key)
}
// blobUploadState captures the state serializable state of the blob upload.
type BlobUploadState struct {
// name is the primary repository under which the blob will be linked.
Name string
Path string
// UUID identifies the upload.
UUID string
// offset contains the current progress of the upload.
Offset int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/docker/app.go | registry/app/pkg/docker/app.go | //nolint:goheader
// Source: https://github.com/distribution/distribution
// Copyright 2014 https://github.com/distribution/distribution Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"context"
"crypto/rand"
"fmt"
corestore "github.com/harness/gitness/app/store"
"github.com/harness/gitness/registry/app/dist_temp/dcontext"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
storagedriver "github.com/harness/gitness/registry/app/driver"
"github.com/harness/gitness/registry/app/pkg"
registrystorage "github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/gc"
"github.com/harness/gitness/types"
"github.com/opencontainers/go-digest"
"github.com/rs/zerolog/log"
)
// randomSecretSize is the number of random bytes to generate if no secret
// was specified.
const randomSecretSize = 32
// App is a global registry application object. Shared resources can be placed
// on this object that will be accessible from all requests. Any writable
// fields should be protected.
type App struct {
context.Context
Config *types.Config
storageService *registrystorage.Service
bucketService BucketService
}
// NewApp takes a configuration and returns a configured app.
func NewApp(
ctx context.Context, storageDeleter storagedriver.StorageDeleter,
blobRepo store.BlobRepository, spaceStore corestore.SpaceStore,
cfg *types.Config, storageService *registrystorage.Service,
gcService gc.Service,
bucketService BucketService,
) *App {
app := &App{
Context: ctx,
Config: cfg,
storageService: storageService,
bucketService: bucketService,
}
app.configureSecret(cfg) //nolint:contextcheck
gcService.Start(ctx, spaceStore, blobRepo, storageDeleter, cfg)
return app
}
// StorageService returns the storage service for this app.
func (app *App) StorageService() *registrystorage.Service {
return app.storageService
}
func GetStorageService(cfg *types.Config, driver storagedriver.StorageDriver) *registrystorage.Service {
options := registrystorage.GetRegistryOptions()
if cfg.Registry.Storage.S3Storage.Delete {
options = append(options, registrystorage.EnableDelete)
}
if cfg.Registry.Storage.S3Storage.Redirect {
options = append(options, registrystorage.EnableRedirect)
} else {
log.Info().Msg("backend redirection disabled")
}
storageService, err := registrystorage.NewStorageService(driver, options...)
if err != nil {
panic("could not create storage service: " + err.Error())
}
return storageService
}
func LogError(errList errcode.Errors) {
for _, e1 := range errList {
log.Error().Err(e1).Msgf("error: %v", e1)
}
}
// configureSecret creates a random secret if a secret wasn't included in the
// configuration.
func (app *App) configureSecret(configuration *types.Config) {
if configuration.Registry.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte
if _, err := rand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
}
configuration.Registry.HTTP.Secret = string(secretBytes[:])
dcontext.GetLogger(app, log.Warn()).
Msg(
"No HTTP secret provided - generated random secret. This may cause problems with uploads if" +
" multiple registries are behind a load-balancer. To provide a shared secret," +
" set the GITNESS_REGISTRY_HTTP_SECRET environment variable.",
)
}
}
// context constructs the context object for the application. This only be
// called once per request.
func (app *App) GetBlobsContext(c context.Context, info pkg.RegistryInfo, blobID any) *Context {
ctx := &Context{
App: app,
Context: c,
UUID: info.Reference,
Digest: digest.Digest(info.Digest),
URLBuilder: info.URLBuilder,
OciBlobStore: nil,
}
if result := app.bucketService.GetBlobStore(c, info.RegIdentifier, info.RootIdentifier, blobID,
digest.Digest(info.Digest).String()); result != nil {
ctx.OciBlobStore = result.OciStore
}
if ctx.OciBlobStore == nil {
ctx.OciBlobStore = app.storageService.OciBlobsStore(c, info.RegIdentifier, info.RootIdentifier)
}
return ctx
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/quarantine/wire.go | registry/app/pkg/quarantine/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 quarantine
import (
"context"
"time"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/cache"
"github.com/harness/gitness/pubsub"
"github.com/harness/gitness/registry/app/store"
"github.com/google/wire"
)
const (
quarantineCacheDuration = 5 * time.Minute
pubsubNamespace = "cache-evictor"
pubsubTopicQuarantineUpdate = "artifact-quarantine-update"
)
// WireSet provides the quarantine service and finder.
var WireSet = wire.NewSet(
ProvideService,
ProvideQuarantineCache,
ProvideFinder,
ProvideEvictorQuarantine,
)
func ProvideEvictorQuarantine(pubsub pubsub.PubSub) cache2.Evictor[*CacheKey] {
return cache2.NewEvictor[*CacheKey](pubsubNamespace, pubsubTopicQuarantineUpdate, pubsub)
}
// ProvideService provides the quarantine service (repository layer only).
func ProvideService(
quarantineRepo store.QuarantineArtifactRepository,
manifestRepo store.ManifestRepository,
) *Service {
return NewService(quarantineRepo, manifestRepo)
}
// ProvideQuarantineCache provides the quarantine cache.
func ProvideQuarantineCache(
appCtx context.Context,
service *Service,
evictor cache2.Evictor[*CacheKey],
) cache.Cache[CacheKey, bool] {
getter := quarantineCacheGetter{service: service}
c := cache.New[CacheKey, bool](getter, quarantineCacheDuration)
evictor.Subscribe(appCtx, func(key *CacheKey) error {
c.Evict(appCtx, *key)
return nil
})
return c
}
// ProvideFinder provides the quarantine finder (with caching).
func ProvideFinder(
service *Service,
quarantineCache cache.Cache[CacheKey, bool],
evictor cache2.Evictor[*CacheKey],
) Finder {
return NewFinder(service, quarantineCache, evictor)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/quarantine/finder.go | registry/app/pkg/quarantine/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 quarantine
import (
"context"
"fmt"
"github.com/harness/gitness/app/api/usererror"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/cache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
// CacheKey represents the cache key for quarantine status.
type CacheKey struct {
RegistryID int64
Image string
Version string
artifactType *artifact.ArtifactType
}
// Finder provides cached access to quarantine status checks.
type Finder interface {
// CheckArtifactQuarantineStatus checks if an artifact is quarantined using cache.
CheckArtifactQuarantineStatus(
ctx context.Context,
registryID int64,
image string,
version string,
artifactType *artifact.ArtifactType,
) error
// CheckOCIManifestQuarantineStatus checks if an OCI manifest is quarantined using cache.
CheckOCIManifestQuarantineStatus(
ctx context.Context,
registryID int64,
image string,
tag string,
digestStr string,
) error
// EvictCache evicts the cache entry for a specific artifact.
EvictCache(
ctx context.Context,
registryID int64,
image string,
version string,
artifactType *artifact.ArtifactType,
)
}
// finder implements the Finder interface with caching.
type finder struct {
service *Service
quarantineCache cache.Cache[CacheKey, bool]
evictor cache2.Evictor[*CacheKey]
}
// NewFinder creates a new quarantine finder that handles caching.
func NewFinder(
service *Service,
quarantineCache cache.Cache[CacheKey, bool],
evictor cache2.Evictor[*CacheKey],
) Finder {
return &finder{
service: service,
quarantineCache: quarantineCache,
evictor: evictor,
}
}
// CheckArtifactQuarantineStatus checks if an artifact is quarantined.
// It returns nil if the artifact is not quarantined, or an error if it is quarantined.
// Uses cache to avoid repeated database queries.
func (f *finder) CheckArtifactQuarantineStatus(
ctx context.Context,
registryID int64,
image string,
version string,
artifactType *artifact.ArtifactType,
) error {
cacheKey := CacheKey{
RegistryID: registryID,
Image: image,
Version: version,
artifactType: artifactType,
}
// Check cache first
isQuarantined, err := f.quarantineCache.Get(ctx, cacheKey)
if err != nil {
return fmt.Errorf("failed to check quarantine status: %w", err)
}
if isQuarantined {
return usererror.ErrQuarantinedArtifact
}
return nil
}
// CheckOCIManifestQuarantineStatus checks if an OCI manifest is quarantined.
// It handles digest resolution from tags and uses the cache for performance.
// Returns nil if not quarantined, or an error if quarantined.
func (f *finder) CheckOCIManifestQuarantineStatus(
ctx context.Context,
registryID int64,
image string,
tag string,
digestStr string,
) error {
// Resolve the digest using the service
parsedDigest, err := f.service.ResolveDigest(ctx, registryID, image, tag, digestStr)
if err != nil {
return fmt.Errorf("error while checking the quarantine status, failed to parse digest: %w", err)
}
// If no digest could be resolved, nothing to check
if parsedDigest == "" {
return nil
}
typesDigest, err := types.NewDigest(parsedDigest)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to parse digest to check quarantine status")
return fmt.Errorf("error while checking the quarantine status, failed to create digest: %w", err)
}
return f.CheckArtifactQuarantineStatus(ctx, registryID, image, typesDigest.String(), nil)
}
// EvictCache evicts the cache entry for a specific artifact.
// This should be called when quarantine status changes.
// It uses the evictor to both evict the cache and publish events.
func (f *finder) EvictCache(
ctx context.Context,
registryID int64,
image string,
version string,
artifactType *artifact.ArtifactType,
) {
cacheKey := CacheKey{
RegistryID: registryID,
Image: image,
Version: version,
artifactType: artifactType,
}
// Use evictor to evict cache and publish event
f.evictor.Evict(ctx, &cacheKey)
}
// quarantineCacheGetter implements the cache getter interface.
type quarantineCacheGetter struct {
service *Service
}
func (g quarantineCacheGetter) Find(ctx context.Context, key CacheKey) (bool, error) {
return g.service.CheckArtifactQuarantineStatus(ctx, key.RegistryID, key.Image, key.Version, key.artifactType)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/quarantine/service.go | registry/app/pkg/quarantine/service.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package quarantine
import (
"context"
"fmt"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/store"
"github.com/opencontainers/go-digest"
"github.com/rs/zerolog/log"
)
// Service provides quarantine-related operations at the repository layer.
type Service struct {
quarantineRepo store.QuarantineArtifactRepository
manifestRepo store.ManifestRepository
}
// NewService creates a new quarantine service.
func NewService(
quarantineRepo store.QuarantineArtifactRepository,
manifestRepo store.ManifestRepository,
) *Service {
return &Service{
quarantineRepo: quarantineRepo,
manifestRepo: manifestRepo,
}
}
// CheckArtifactQuarantineStatus checks if an artifact is quarantined by querying the repository.
// Returns true if quarantined, false otherwise.
func (s *Service) CheckArtifactQuarantineStatus(
ctx context.Context,
registryID int64,
image string,
version string,
artifactType *artifact.ArtifactType,
) (bool, error) {
quarantineArtifacts, err := s.quarantineRepo.GetByFilePath(
ctx, "", registryID, image, version, artifactType,
)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to check quarantine status")
return false, fmt.Errorf("failed to check quarantine status: %w", err)
}
return len(quarantineArtifacts) > 0, nil
}
// ResolveDigest resolves a digest from either a digest string or a tag name.
// Returns empty string if neither is provided.
func (s *Service) ResolveDigest(
ctx context.Context,
registryID int64,
image string,
tag string,
digestStr string,
) (digest.Digest, error) {
if digestStr != "" {
parsedDigest, err := digest.Parse(digestStr)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to parse digest to check quarantine status")
return "", fmt.Errorf("failed to parse digest to check quarantine status: %w", err)
}
return parsedDigest, nil
}
if tag != "" {
dbManifest, err := s.manifestRepo.FindManifestDigestByTagName(ctx, registryID, image, tag)
if err != nil {
return "", fmt.Errorf("failed to find manifest digest: %w", err)
}
parsedDigest, err := dbManifest.Parse()
if err != nil {
return "", fmt.Errorf("failed to parse digest: %w", err)
}
return parsedDigest, nil
}
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/pkg/types/python/types.go | registry/app/pkg/types/python/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package python
import (
"github.com/harness/gitness/registry/app/metadata/python"
"github.com/harness/gitness/registry/app/pkg"
)
// Metadata represents the metadata for a Python package.
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
Filename string
Metadata python.Metadata
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
func (a ArtifactInfo) GetFileName() string {
return a.Filename
}
type File struct {
FileURL string
Name string
RequiresPython string
}
type PackageMetadata struct {
Name string
Files []File
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/commons/types.go | registry/app/pkg/types/commons/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commons
import (
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
FilePath string
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
func (a ArtifactInfo) GetFileName() string {
return a.FilePath
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/generic/types.go | registry/app/pkg/types/generic/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
FileName string
FilePath string
Version string
Description string
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
func (a ArtifactInfo) GetFileName() string {
return a.FileName
}
type File struct {
FileURL string
Name string
}
type PackageMetadata struct {
Name string
Files []File
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/huggingface/types.go | registry/app/pkg/types/huggingface/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import (
apicontract "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
huggingfacemetadata "github.com/harness/gitness/registry/app/metadata/huggingface"
"github.com/harness/gitness/registry/app/pkg"
)
// ArtifactInfo represents information about a Huggingface artifact.
type ArtifactInfo struct {
pkg.ArtifactInfo
Repo string
Revision string
RepoType apicontract.ArtifactType
SHA256 string
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
// GetImageVersion returns the image and version information.
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Repo != "" && a.Revision != "" {
return true, pkg.JoinWithSeparator(":", a.Repo, a.Revision)
}
return false, ""
}
// GetVersion returns the version (revision) of the Huggingface artifact.
func (a ArtifactInfo) GetVersion() string {
return a.Revision
}
func (a ArtifactInfo) GetFileName() string {
return a.SHA256
}
// File represents a file in a Huggingface package.
type File struct {
FileURL string
Name string
RepoType string
}
// PackageMetadata represents metadata for a Huggingface package.
type PackageMetadata struct {
RepoID string
RepoType string
Files []File
}
type Debug struct {
Message *string `json:"message"`
Type *string `json:"type"`
Help *string `json:"help"`
}
type ValidateYamlRequest struct {
Content *string `json:"content"`
RepoType *string `json:"repoType"` //nolint:tagliatelle
}
type ValidateYamlResponse struct {
Errors *[]Debug `json:"errors"`
Warnings *[]Debug `json:"warnings"`
}
type PreUploadResponse struct {
Files *[]PreUploadResponseFile `json:"files"`
}
type PreUploadRequest struct {
Files *[]PreUploadRequestFile `json:"files"`
}
type PreUploadResponseFile struct {
Path string `json:"path"`
UploadMode UploadMode `json:"uploadMode"` //nolint:tagliatelle
ShouldIgnore bool `json:"shouldIgnore"` // NEW //nolint:tagliatelle
}
type PreUploadRequestFile struct {
Path string `json:"path"`
Sample *string `json:"sample"`
Size int64 `json:"size"` // NEW
}
type RevisionInfoResponse struct {
huggingfacemetadata.Metadata
XetEnabled bool `json:"xetEnabled"` //nolint:tagliatelle
}
type LfsInfoRequest struct {
Operation string `json:"operation"` // "upload", "download"
Transfers []string `json:"transfers"` // "basic", "multipart"
Objects *[]LfsObjectRequest `json:"objects"`
HashAlgo *string `json:"hash_algo,omitempty"`
Ref *LfsRefRequest `json:"ref,omitempty"`
}
type LfsObjectRequest struct {
Oid string `json:"oid"`
Size int64 `json:"size"`
}
type LfsRefRequest struct {
Name string `json:"name"`
}
type LfsInfoResponse struct {
Objects *[]LfsObjectResponse `json:"objects"`
}
type LfsVerifyResponse struct {
Success bool `json:"success"`
Error *LfsError `json:"error,omitempty"`
}
type LfsUploadResponse struct {
Success bool `json:"success"`
Error *LfsError `json:"error,omitempty"`
}
type CommitRevisionResponse struct {
CommitURL string `json:"commitUrl"` //nolint:tagliatelle
CommitMessage string `json:"commitMessage"` //nolint:tagliatelle
CommitDescription string `json:"commitDescription"` //nolint:tagliatelle
OID string `json:"commitOid"` //nolint:tagliatelle
Success bool `json:"success"`
Error *LfsError `json:"error,omitempty"`
}
type CommitEntry struct {
Key string `json:"key"`
Value any `json:"value"` // Value can be HeaderInfo or LFSFileInfo
}
type HeaderInfo struct {
Summary string `json:"summary"`
Description string `json:"description"`
}
type LfsFileInfo struct {
Path string `json:"path"`
Algo string `json:"algo"`
Oid string `json:"oid"`
Size int64 `json:"size"`
}
type LfsAction struct {
Href string `json:"href"`
Header map[string]string `json:"header,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
}
type LfsError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type LfsObjectResponse struct {
Oid string `json:"oid"`
Size int64 `json:"size"`
Actions *map[string]LfsAction `json:"actions,omitempty"`
Error *LfsError `json:"error,omitempty"`
}
// UploadMode represents the mode for uploading files.
type UploadMode string
const (
// Regular represents regular file upload mode.
RegularUpload UploadMode = "regular"
// LFS represents Large File Storage upload mode.
LFSUpload UploadMode = "lfs"
)
// NewPreUploadResponseFile creates a new PreUploadResponseFile with default values.
func NewPreUploadResponseFile(path string) PreUploadResponseFile {
return PreUploadResponseFile{
Path: path,
UploadMode: LFSUpload, // Default to LFS upload mode
ShouldIgnore: false,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/rpm/types.go | registry/app/pkg/types/rpm/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpm
import (
"github.com/harness/gitness/registry/app/metadata/rpm"
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
Arch string
FileName string
PackagePath string
Metadata rpm.Metadata
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetFileName() string {
return a.FileName
}
type File struct {
FileURL string
Name string
}
type PackageMetadata struct {
Name string
Files []File
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/gopackage/types.go | registry/app/pkg/types/gopackage/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"github.com/harness/gitness/registry/app/metadata/gopackage"
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
FileName string
Metadata gopackage.VersionMetadata
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetFileName() string {
return a.FileName
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/nuget/types.go | registry/app/pkg/types/nuget/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"encoding/xml"
"net/http"
"regexp"
"strings"
"time"
"github.com/harness/gitness/registry/app/metadata/nuget"
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
Filename string
ProxyEndpoint string
NestedPath string
Metadata nuget.Metadata
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
var searchTermExtract = regexp.MustCompile(`'([^']+)'`)
func GetSearchTerm(r *http.Request) string {
searchTerm := strings.Trim(r.URL.Query().Get("searchTerm"), "'")
if searchTerm == "" {
// $filter contains a query like:
// (((Id ne null) and substringof('microsoft',tolower(Id)))
// We don't support these queries, just extract the search term.
match := searchTermExtract.FindStringSubmatch(r.URL.Query().Get("$filter"))
if len(match) == 2 {
searchTerm = strings.TrimSpace(match[1])
}
}
return searchTerm
}
func (a ArtifactInfo) GetFileName() string {
return a.Filename
}
type File struct {
FileURL string
Name string
}
type PackageMetadata struct {
Name string
Files []File
}
type ServiceEndpoint struct {
Version string `json:"version"`
Resources []Resource `json:"resources"`
}
type Resource struct {
//nolint:revive
ID string `json:"@id"`
Type string `json:"@type"`
}
type AtomTitle struct {
Type string `xml:"type,attr"`
//nolint: tagliatelle
Text string `xml:",chardata"`
}
type ServiceCollection struct {
Href string `xml:"href,attr"`
Title AtomTitle `xml:"atom:title"`
}
type ServiceWorkspace struct {
Title AtomTitle `xml:"atom:title"`
Collection ServiceCollection `xml:"collection"`
}
type ServiceMetadataV2 struct {
XMLName xml.Name `xml:"edmx:Edmx"`
XmlnsEdmx string `xml:"xmlns:edmx,attr"`
//nolint: tagliatelle
Version string `xml:"Version,attr"`
DataServices EdmxDataServices `xml:"edmx:DataServices"`
}
type ServiceEndpointV2 struct {
XMLName xml.Name `xml:"service"`
Base string `xml:"base,attr"`
Xmlns string `xml:"xmlns,attr"`
XmlnsAtom string `xml:"xmlns:atom,attr"`
Workspace ServiceWorkspace `xml:"workspace"`
}
type EdmxPropertyRef struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
}
type EdmxProperty struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
//nolint: tagliatelle
Type string `xml:"Type,attr"`
//nolint: tagliatelle
Nullable bool `xml:"Nullable,attr"`
}
type EdmxEntityType struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
HasStream bool `xml:"m:HasStream,attr"`
//nolint: tagliatelle
Keys []EdmxPropertyRef `xml:"Key>PropertyRef"`
//nolint: tagliatelle
Properties []EdmxProperty `xml:"Property"`
}
type EdmxFunctionParameter struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
//nolint: tagliatelle
Type string `xml:"Type,attr"`
}
type EdmxFunctionImport struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
//nolint: tagliatelle
ReturnType string `xml:"ReturnType,attr"`
//nolint: tagliatelle
EntitySet string `xml:"EntitySet,attr"`
//nolint: tagliatelle
Parameter []EdmxFunctionParameter `xml:"Parameter"`
}
type EdmxEntitySet struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
//nolint: tagliatelle
EntityType string `xml:"EntityType,attr"`
}
type EdmxEntityContainer struct {
//nolint: tagliatelle
Name string `xml:"Name,attr"`
IsDefaultEntityContainer bool `xml:"m:IsDefaultEntityContainer,attr"`
//nolint: tagliatelle
EntitySet EdmxEntitySet `xml:"EntitySet"`
//nolint: tagliatelle
FunctionImports []EdmxFunctionImport `xml:"FunctionImport"`
}
type EdmxSchema struct {
Xmlns string `xml:"xmlns,attr"`
//nolint: tagliatelle
Namespace string `xml:"Namespace,attr"`
//nolint: tagliatelle
EntityType *EdmxEntityType `xml:"EntityType,omitempty"`
//nolint: tagliatelle
EntityContainer *EdmxEntityContainer `xml:"EntityContainer,omitempty"`
}
type EdmxDataServices struct {
XmlnsM string `xml:"xmlns:m,attr"`
DataServiceVersion string `xml:"m:DataServiceVersion,attr"`
MaxDataServiceVersion string `xml:"m:MaxDataServiceVersion,attr"`
//nolint: tagliatelle
Schema []EdmxSchema `xml:"Schema"`
}
type PackageVersion struct {
Versions []string `json:"versions"`
}
type RegistrationResponse interface {
isRegistrationResponse()
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#response
type RegistrationIndexResponse struct {
RegistrationIndexURL string `json:"@id"`
Count int `json:"count"`
Pages []*RegistrationIndexPageResponse `json:"items"`
}
func (r RegistrationIndexResponse) isRegistrationResponse() {
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object
type RegistrationIndexPageResponse struct {
RegistrationPageURL string `json:"@id"`
Lower string `json:"lower"`
Upper string `json:"upper"`
Count int `json:"count"`
Items []*RegistrationIndexPageItem `json:"items,omitempty"`
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page
type RegistrationIndexPageItem struct {
RegistrationLeafURL string `json:"@id"`
//nolint: tagliatelle
PackageContentURL string `json:"packageContent"`
//nolint: tagliatelle
CatalogEntry *CatalogEntry `json:"catalogEntry"`
}
func (r RegistrationIndexPageResponse) isRegistrationResponse() {
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf
type RegistrationLeafResponse struct {
RegistrationLeafURL string `json:"@id"`
Type []string `json:"@type"`
Listed bool `json:"listed"`
//nolint: tagliatelle
PackageContentURL string `json:"packageContent"`
Published time.Time `json:"published"`
RegistrationIndexURL string `json:"registration"`
}
// https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedQueryBuilder.cs
type FeedEntryResponse struct {
XMLName xml.Name `xml:"entry"`
Xmlns string `xml:"xmlns,attr,omitempty"`
XmlnsD string `xml:"xmlns:d,attr,omitempty"`
XmlnsM string `xml:"xmlns:m,attr,omitempty"`
Base string `xml:"xml:base,attr,omitempty"`
ID string `xml:"id,omitempty"`
Category FeedEntryCategory `xml:"category"`
Title TypedValue[string] `xml:"title"`
Updated time.Time `xml:"updated"`
Author string `xml:"author>name"`
Summary string `xml:"summary"`
//nolint: tagliatelle
Content string `xml:",innerxml"`
Properties *FeedEntryProperties `xml:"m:properties"`
DownloadContent *FeedEntryContent `xml:"content,omitempty"`
}
type FeedResponse struct {
XMLName xml.Name `xml:"feed"`
Xmlns string `xml:"xmlns,attr,omitempty"`
XmlnsD string `xml:"xmlns:d,attr,omitempty"`
XmlnsM string `xml:"xmlns:m,attr,omitempty"`
Base string `xml:"xml:base,attr,omitempty"`
ID string `xml:"id"`
Title TypedValue[string] `xml:"title"`
Updated time.Time `xml:"updated"`
Links []FeedEntryLink `xml:"link"`
Entries []*FeedEntryResponse `xml:"entry"`
Count int64 `xml:"m:count"`
}
// https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#response
type SearchResultResponse struct {
//nolint: tagliatelle
TotalHits int64 `json:"totalHits"`
Data []*SearchResult `json:"data"`
}
// https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result
type SearchResult struct {
ID string `json:"id"`
Version string `json:"version"`
Versions []*SearchResultVersion `json:"versions"`
Description string `json:"description"`
Authors []string `json:"authors"`
//nolint: tagliatelle
ProjectURL string `json:"projectURL"`
RegistrationIndexURL string `json:"registration"`
}
// https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result
type SearchResultVersion struct {
RegistrationLeafURL string `json:"@id"`
Version string `json:"version"`
}
type FeedEntryCategory struct {
Term string `xml:"term,attr"`
Scheme string `xml:"scheme,attr"`
}
type FeedEntryContent struct {
Type string `xml:"type,attr,omitempty"`
Source string `xml:"src,attr,omitempty"`
}
type FeedEntryLink struct {
Rel string `xml:"rel,attr"`
Href xml.CharData `xml:"href,attr"`
}
type TypedValue[T any] struct {
Type string `xml:"m:type,attr,omitempty"`
//nolint: tagliatelle
Value T `xml:",chardata"`
}
type FeedEntryProperties struct {
ID string `xml:"d:Id"`
Version string `xml:"d:Version"`
NormalizedVersion string `xml:"d:NormalizedVersion"`
Authors string `xml:"d:Authors"`
Dependencies string `xml:"d:Dependencies"`
Description string `xml:"d:Description"`
VersionDownloadCount TypedValue[int64] `xml:"d:VersionDownloadCount"`
DownloadCount TypedValue[int64] `xml:"d:DownloadCount"`
PackageSize TypedValue[int64] `xml:"d:PackageSize"`
Created TypedValue[time.Time] `xml:"d:Created"`
LastUpdated TypedValue[time.Time] `xml:"d:LastUpdated"`
Published TypedValue[time.Time] `xml:"d:Published"`
ProjectURL string `xml:"d:ProjectUrl,omitempty"`
ReleaseNotes string `xml:"d:ReleaseNotes,omitempty"`
RequireLicenseAcceptance TypedValue[bool] `xml:"d:RequireLicenseAcceptance"`
Title string `xml:"d:Title"`
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#catalog-entry
type CatalogEntry struct {
CatalogLeafURL string `json:"@id"`
//nolint: tagliatelle
PackageContentURL string `json:"packageContent"`
ID string `json:"id"`
Version string `json:"version"`
Description string `json:"description"`
//nolint: tagliatelle
ReleaseNotes string `json:"releaseNotes"`
Authors string `json:"authors"`
//nolint: tagliatelle
RequireLicenseAcceptance bool `json:"requireLicenseAcceptance"`
//nolint: tagliatelle
ProjectURL string `json:"projectURL"`
//nolint: tagliatelle
DependencyGroups []*PackageDependencyGroup `json:"dependencyGroups,omitempty"`
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency-group
type PackageDependencyGroup struct {
//nolint: tagliatelle
TargetFramework string `json:"targetFramework"`
Dependencies []*PackageDependency `json:"dependencies"`
}
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency
type PackageDependency struct {
ID string `json:"id"`
Range string `json:"range"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/npm/types.go | registry/app/pkg/types/npm/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"github.com/harness/gitness/registry/app/metadata/npm"
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Metadata npm.PackageMetadata
Version string
DistTags []string
Filename string
ParentRegIdentifier string
}
type File struct {
FileURL string
Name string
}
type PackageMetadata struct {
Name string
Files []File
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
func (a ArtifactInfo) GetFileName() string {
return a.Filename
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/types/cargo/types.go | registry/app/pkg/types/cargo/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargo
import (
"github.com/harness/gitness/registry/app/pkg"
)
type ArtifactInfo struct {
pkg.ArtifactInfo
Version string
Arch string
FileName string
}
func (a ArtifactInfo) GetVersion() string {
return a.Version
}
// BaseArtifactInfo implements pkg.PackageArtifactInfo interface.
func (a ArtifactInfo) BaseArtifactInfo() pkg.ArtifactInfo {
return a.ArtifactInfo
}
func (a ArtifactInfo) GetImageVersion() (exists bool, imageVersion string) {
if a.Image != "" && a.Version != "" {
return true, pkg.JoinWithSeparator(":", a.Image, a.Version)
}
return false, ""
}
type SearchPackageRequestParams struct {
SearchTerm *string
Size *int32
}
type SearchPackageRequestInfo struct {
SearchTerm string
Limit int
Offset int
SortField string
SortOrder string
}
func (a ArtifactInfo) GetFileName() string {
return a.FileName
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/local.go | registry/app/pkg/rpm/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"io"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
registryHelper RegistryHelper
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
registryHelper RegistryHelper,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
registryHelper: registryHelper,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeRPM}
}
func (c *localRegistry) UploadPackageFile(
ctx context.Context,
info rpmtype.ArtifactInfo,
file io.Reader,
fileName string,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
return c.registryHelper.UploadPackage(ctx, info, file, fileName)
}
func (c *localRegistry) GetRepoData(
ctx context.Context,
info rpmtype.ArtifactInfo,
fileName string,
) (*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
) {
return getRepoData(ctx, info, fileName, c.fileManager)
}
func (c *localRegistry) DownloadPackageFile(
ctx context.Context,
info rpmtype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
return downloadPackageFile(ctx, info, c.localBase)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/wire.go | registry/app/pkg/rpm/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 rpm
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
registryHelper RegistryHelper,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager, proxyStore, tx, registryDao,
imageDao, artifactDao, urlProvider, registryHelper)
base.Register(registry)
return registry
}
func RegistryHelperProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
postProcessingReporter *asyncprocessing.Reporter,
) RegistryHelper {
return NewRegistryHelper(
localBase,
fileManager,
postProcessingReporter,
)
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
localBase base.LocalBase,
registryHelper RegistryHelper,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) Proxy {
proxy := NewProxy(
fileManager,
proxyStore,
tx,
registryDao,
imageDao,
artifactDao,
urlProvider,
localBase,
registryHelper,
spaceFinder,
service,
)
base.Register(proxy)
return proxy
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, RegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/proxy.go | registry/app/pkg/rpm/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"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/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/remote/adapter/rpm" // This is required to init rpm adapter
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
localBase base.LocalBase
registryHelper RegistryHelper
spaceFinder refcache.SpaceFinder
service secret.Service
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
localBase base.LocalBase,
registryHelper RegistryHelper,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) Proxy {
return &proxy{
proxyStore: proxyStore,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
fileManager: fileManager,
tx: tx,
urlProvider: urlProvider,
localBase: localBase,
registryHelper: registryHelper,
spaceFinder: spaceFinder,
service: service,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeRPM}
}
func (r *proxy) DownloadPackageFile(
ctx context.Context,
info rpmtype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
headers, fileReader, readcloser, redirect, err := downloadPackageFile(ctx, info, r.localBase)
if err == nil {
return headers, fileReader, readcloser, redirect, err
}
log.Warn().Ctx(ctx).Msgf("failed to download from local, err: %v", err)
if info.PackagePath == "" {
log.Ctx(ctx).Error().Msgf("Package path is empty for registry %s", info.RegIdentifier)
return nil, nil, nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("package path is empty"))
}
upstream, err := r.proxyStore.Get(ctx, info.RegistryID)
if err != nil {
return nil, nil, nil, "", err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstream, r.service)
if err != nil {
return nil, nil, nil, "", err
}
closer, err := helper.GetPackage(ctx, info.PackagePath)
if err != nil {
return nil, nil, nil, "", err
}
go func() {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
closer2, err2 := helper.GetPackage(ctx2, info.PackagePath)
if err2 != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf("error while putting file to localRegistry, %v", err)
return
}
_, filename, err := paths.DisectLeaf(info.PackagePath)
if err != nil {
log.Ctx(ctx2).Error().Msgf("error while disecting file name for [%s]: %v", info.PackagePath, err)
return
}
_, _, err = r.registryHelper.UploadPackage(ctx2, info, closer2, filename)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf("error while putting file to localRegistry, %v", err)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated file: %s, registry: %s", info.FileName, info.RegIdentifier)
}()
return &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: http.StatusOK,
}, nil, closer, "", nil
}
// GetRepoData returns the metadata of a RPM package.
func (r *proxy) GetRepoData(
ctx context.Context,
info rpmtype.ArtifactInfo,
fileName string,
) (*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
) {
return getRepoData(ctx, info, fileName, r.fileManager)
}
// UploadPackageFile FIXME: Extract this upload function for all types of packageTypes
// uploads the package file to the storage.
func (r *proxy) UploadPackageFile(
ctx context.Context,
_ rpmtype.ArtifactInfo,
_ io.Reader,
_ string,
) (*commons.ResponseHeaders, string, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/registry.go | registry/app/pkg/rpm/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpm
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/rpm"
"github.com/harness/gitness/registry/app/storage"
rpmutil "github.com/harness/gitness/registry/app/utils/rpm"
)
type Registry interface {
pkg.Artifact
UploadPackageFile(
ctx context.Context,
info rpm.ArtifactInfo,
file io.Reader,
fileName string,
) (*commons.ResponseHeaders, string, error)
DownloadPackageFile(ctx context.Context, info rpm.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
)
GetRepoData(ctx context.Context, info rpm.ArtifactInfo, fileName string) (*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error)
}
func downloadPackageFile(
ctx context.Context,
info rpm.ArtifactInfo,
localBase base.LocalBase,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
var versionWithArch = info.Version
var epoch string
var versionPath string
var version string
epochSeparatorIndex := strings.Index(info.Version, ":")
if epochSeparatorIndex != -1 {
epoch = versionWithArch[:epochSeparatorIndex]
versionWithArch = versionWithArch[epochSeparatorIndex+1:]
}
lastDotIndex := strings.LastIndex(versionWithArch, ".")
if lastDotIndex == -1 {
return nil, nil, nil, "", fmt.Errorf("invalid version: %s", info.Version)
}
version = versionWithArch[:lastDotIndex]
if epoch != "" {
versionPath = version + "/" + info.Arch + "/" + epoch
} else {
versionPath = version + "/" + info.Arch
}
headers, fileReader, redirectURL, err := localBase.Download(
ctx, info.ArtifactInfo, versionPath, info.FileName,
)
if err != nil {
return nil, nil, nil, "", err
}
return headers, fileReader, nil, redirectURL, nil
}
func getRepoData(
ctx context.Context,
info rpm.ArtifactInfo,
fileName string,
fileManager filemanager.FileManager,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
fileReader, _, redirectURL, err := fileManager.DownloadFile(
ctx, "/"+rpmutil.RepoDataPrefix+fileName, info.RegistryID, info.RegIdentifier, info.RootIdentifier, true,
)
if err != nil {
return responseHeaders, nil, nil, "", err
}
responseHeaders.Code = http.StatusOK
return responseHeaders, fileReader, nil, redirectURL, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/helper.go | registry/app/pkg/rpm/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 rpm
import (
"context"
"fmt"
"io"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
rpmmetadata "github.com/harness/gitness/registry/app/metadata/rpm"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/rpm"
rpmutil "github.com/harness/gitness/registry/app/utils/rpm"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type RegistryHelper interface {
UploadPackage(
ctx context.Context,
info rpm.ArtifactInfo,
file io.Reader,
fileName string,
) (*commons.ResponseHeaders, string, error)
}
type registryHelper struct {
localBase base.LocalBase
fileManager filemanager.FileManager
postProcessingReporter *asyncprocessing.Reporter
}
func NewRegistryHelper(
localBase base.LocalBase,
fileManager filemanager.FileManager,
postProcessingReporter *asyncprocessing.Reporter,
) RegistryHelper {
return ®istryHelper{
localBase: localBase,
fileManager: fileManager,
postProcessingReporter: postProcessingReporter,
}
}
func (c *registryHelper) UploadPackage(
ctx context.Context,
info rpm.ArtifactInfo,
file io.Reader,
fileName string,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
fileInfo, tempFileName, err := c.fileManager.UploadTempFile(ctx, info.RootIdentifier, nil, fileName, file)
if err != nil {
return nil, "", err
}
r, _, err := c.fileManager.DownloadTempFile(ctx, fileInfo.Size, tempFileName, info.RootIdentifier)
if err != nil {
return nil, "", err
}
defer r.Close()
p, err := rpmutil.ParsePackage(r)
if err != nil {
log.Printf("failded to parse rpm package: %v", err)
return nil, "", err
}
artifactVersion := p.Version + "." + p.FileMetadata.Architecture
if p.FileMetadata.Epoch != "" && p.FileMetadata.Epoch != "0" {
artifactVersion = fmt.Sprintf("%s:%s", p.FileMetadata.Epoch, artifactVersion)
}
info.Image = p.Name
info.Version = artifactVersion
info.Metadata = rpmmetadata.Metadata{
VersionMetadata: *p.VersionMetadata,
FileMetadata: *p.FileMetadata,
}
pathVersion := fmt.Sprintf("%s/%s", p.Version, p.FileMetadata.Architecture)
if p.FileMetadata.Epoch != "" && p.FileMetadata.Epoch != "0" {
pathVersion = fmt.Sprintf("%s/%s", pathVersion, p.FileMetadata.Epoch)
}
rpmFileName := fmt.Sprintf("%s-%s.%s.rpm", p.Name, p.Version, p.FileMetadata.Architecture)
path := fmt.Sprintf("%s/%s/%s", p.Name, pathVersion, rpmFileName)
fileInfo.Filename = rpmFileName
rs, sha256, artifactID, existent, err := c.localBase.MoveTempFileAndCreateArtifact(ctx, info.ArtifactInfo,
tempFileName, info.Version, path,
&rpmmetadata.RpmMetadata{
Metadata: info.Metadata,
}, fileInfo, true)
if err != nil {
return nil, "", err
}
if !existent {
sources := make([]types.SourceRef, 0)
sources = append(sources, types.SourceRef{Type: types.SourceTypeArtifact, ID: artifactID})
c.postProcessingReporter.BuildRegistryIndex(ctx, info.RegistryID, sources)
}
return rs, sha256, err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/rpm/remote_helper.go | registry/app/pkg/rpm/remote_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 rpm
import (
"context"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
GetMetadataFile(ctx context.Context, filePath string) (io.ReadCloser, error)
GetPackage(ctx context.Context, pkg string) (io.ReadCloser, error)
}
type remoteRegistryHelper struct {
adapter registry.RpmRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, err
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypeRPM)
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
rpmReg, ok := adpt.(registry.RpmRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to rpm registry")
return err
}
r.adapter = rpmReg
return nil
}
func (r *remoteRegistryHelper) GetMetadataFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
v2, err := r.adapter.GetMetadataFile(ctx, filePath)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata file: %s", filePath)
}
return v2, err
}
func (r *remoteRegistryHelper) GetPackage(ctx context.Context, pkg string) (io.ReadCloser, error) {
packages, err := r.adapter.GetPackage(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
return packages, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/local.go | registry/app/pkg/gopackage/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
"github.com/harness/gitness/app/api/request"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/api/utils"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
gopackagemetadata "github.com/harness/gitness/registry/app/metadata/gopackage"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
gopackageutils "github.com/harness/gitness/registry/app/pkg/gopackage/utils"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/services/webhook"
gitnessstore "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database/dbtx"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
artifactEventReporter *registryevents.Reporter
postProcessingReporter *asyncprocessing.Reporter
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
artifactEventReporter: artifactEventReporter,
postProcessingReporter: postProcessingReporter,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeGO}
}
func (c *localRegistry) UploadPackage(
ctx context.Context, info gopackagetype.ArtifactInfo,
modfile io.ReadCloser, zipfile io.ReadCloser,
) (*commons.ResponseHeaders, error) {
// Check if version exists
checkIfVersionExists, err := c.localBase.CheckIfVersionExists(ctx, info)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return nil, fmt.Errorf("failed to check if version exists: %w", err)
}
if checkIfVersionExists {
return nil, fmt.Errorf("version %s already exists", info.Version)
}
// Get file path
filePath, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, info.Version)
if err != nil {
return nil, fmt.Errorf("failed to get file path: %w", err)
}
// upload .zip
zipFileName := info.Version + ".zip"
zipFilePath := filepath.Join(filePath, zipFileName)
response, err := c.uploadFile(ctx, info, &info.Metadata, zipfile, zipFileName, zipFilePath)
if err != nil {
return response, fmt.Errorf("failed to upload zip file: %w", err)
}
// upload .mod
modFileName := info.Version + ".mod"
modFilePath := filepath.Join(filePath, modFileName)
response, err = c.uploadFile(ctx, info, &info.Metadata, modfile, modFileName, modFilePath)
if err != nil {
return response, fmt.Errorf("failed to upload mod file: %w", err)
}
// upload .info
infoFileName := info.Version + ".info"
infoFilePath := filepath.Join(filePath, infoFileName)
infoFile, err := metadataToReadCloser(info.Metadata)
if err != nil {
return nil, fmt.Errorf("failed to convert metadata to io.ReadCloser: %w", err)
}
response, err = c.uploadFile(ctx, info, &info.Metadata, infoFile, infoFileName, infoFilePath)
if err != nil {
return response, fmt.Errorf("failed to upload info file: %w", err)
}
// publish artifact created event
c.publishArtifactCreatedEvent(ctx, info)
// regenerate package index for go package
c.regeneratePackageIndex(ctx, info)
// regenerate package metadata for go package
c.regeneratePackageMetadata(ctx, info)
return response, nil
}
func metadataToReadCloser(meta gopackagemetadata.VersionMetadata) (io.ReadCloser, error) {
b, err := json.Marshal(meta)
if err != nil {
return nil, err
}
return io.NopCloser(bytes.NewReader(b)), nil
}
func (c *localRegistry) uploadFile(
ctx context.Context, info gopackagetype.ArtifactInfo,
metadata *gopackagemetadata.VersionMetadata, fileReader io.ReadCloser,
filename string, path string,
) (responseHeaders *commons.ResponseHeaders, err error) {
response, _, err := c.localBase.Upload(
ctx, info.ArtifactInfo, filename, info.Version, path, fileReader,
&gopackagemetadata.VersionMetadataDB{
VersionMetadata: *metadata,
})
if err != nil {
return response, fmt.Errorf("failed to upload file %s: %w", filename, err)
}
return response, nil
}
func (c *localRegistry) publishArtifactCreatedEvent(
ctx context.Context, info gopackagetype.ArtifactInfo,
) {
session, _ := request.AuthSessionFrom(ctx)
payload := webhook.GetArtifactCreatedPayloadForCommonArtifacts(
session.Principal.ID,
info.RegistryID,
artifact.PackageTypeGO,
info.Image,
info.Version,
)
c.artifactEventReporter.ArtifactCreated(ctx, &payload)
}
func (c *localRegistry) regeneratePackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) {
c.postProcessingReporter.BuildPackageIndex(ctx, info.RegistryID, info.Image)
}
func (c *localRegistry) regeneratePackageMetadata(
ctx context.Context, info gopackagetype.ArtifactInfo,
) {
c.postProcessingReporter.BuildPackageMetadata(
ctx, info.RegistryID, info.Image, info.Version,
)
}
func (c *localRegistry) DownloadPackageFile(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
if info.Version == "" {
// If version is empty, it is an index file
return c.DownloadPackageIndex(ctx, info)
}
if info.Version == LatestVersionKey {
// Download latest version
return c.DownloadPackageLatestVersionInfo(ctx, info)
}
path, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, info.Version)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get file path: %w", err)
}
filePath := filepath.Join(path, info.FileName)
response, fileReader, redirectURL, err := c.downloadFileInternal(ctx, info, filePath)
if err != nil {
return response, nil, nil, "", fmt.Errorf("failed to download package file: %w", err)
}
return response, fileReader, nil, redirectURL, nil
}
func (c *localRegistry) DownloadPackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
filePath := gopackageutils.GetIndexFilePath(info.Image)
response, fileReader, redirectURL, err := c.downloadFileInternal(ctx, info, filePath)
if err != nil {
return response, nil, nil, "", fmt.Errorf("failed to download package index: %w", err)
}
return response, fileReader, nil, redirectURL, nil
}
func (c *localRegistry) DownloadPackageLatestVersionInfo(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
image, err := c.imageDao.GetByRepoAndName(ctx, info.ParentID, info.RegIdentifier, info.Image)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get image: %w", err)
}
artifact, err := c.artifactDao.GetLatestByImageID(ctx, image.ID)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get latest artifact: %w", err)
}
info.Version = artifact.Version
info.FileName = artifact.Version + ".info"
// Prevent infinite recursion
if artifact.Version == LatestVersionKey {
return nil, nil, nil, "", fmt.Errorf("artifact version cannot be %s", LatestVersionKey)
}
return c.DownloadPackageFile(ctx, info)
}
func (c *localRegistry) downloadFileInternal(
ctx context.Context, info gopackagetype.ArtifactInfo, path string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
fileReader, _, redirectURL, err := c.fileManager.DownloadFile(ctx, path, info.RegistryID,
info.RegIdentifier, info.RootIdentifier, true)
if err != nil {
return responseHeaders, nil, "", fmt.Errorf("failed to download file %s: %w", path, err)
}
return responseHeaders, fileReader, redirectURL, nil
}
func (c *localRegistry) RegeneratePackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
c.regeneratePackageIndex(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
func (c *localRegistry) RegeneratePackageMetadata(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
c.regeneratePackageMetadata(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/wire.go | registry/app/pkg/gopackage/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 gopackage
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistry {
registry := NewLocalRegistry(
localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider, artifactEventReporter, postProcessingReporter,
)
base.Register(registry)
return registry
}
func ProxyProvider(
localBase base.LocalBase,
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
artifactEventReporter *registryevents.Reporter,
localRegistryHelper LocalRegistryHelper,
) Proxy {
proxy := NewProxy(localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao, urlProvider,
spaceFinder, service, artifactEventReporter, localRegistryHelper)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(
localRegistry LocalRegistry,
localBase base.LocalBase,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase, postProcessingReporter)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/proxy.go | registry/app/pkg/gopackage/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"fmt"
"io"
"net/http"
"path/filepath"
"time"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/api/utils"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
gopackagemetadata "github.com/harness/gitness/registry/app/metadata/gopackage"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
artifactEventReporter *registryevents.Reporter
localRegistryHelper LocalRegistryHelper
}
type Proxy interface {
Registry
}
func NewProxy(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
artifactEventReporter *registryevents.Reporter,
localRegistryHelper LocalRegistryHelper,
) Proxy {
return &proxy{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
artifactEventReporter: artifactEventReporter,
localRegistryHelper: localRegistryHelper,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeGO}
}
func (r *proxy) UploadPackage(
ctx context.Context, _ gopackagetype.ArtifactInfo,
_ io.ReadCloser, _ io.ReadCloser,
) (*commons.ResponseHeaders, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) DownloadPackageFile(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
if info.Version == "" {
// If version is empty, it is an index file
response, reader, fileReader, err := r.DownloadPackageIndex(ctx, info)
return response, reader, fileReader, "", err
}
if info.Version == LatestVersionKey {
// Download latest version
response, reader, fileReader, err := r.DownloadPackageLatestVersionInfo(ctx, info)
return response, reader, fileReader, "", err
}
path, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, info.Version)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get file path: %w", err)
}
filePath := filepath.Join(path, info.FileName)
// Check if the file exists in the local registry
exists := r.localRegistryHelper.FileExists(ctx, info, filePath)
if exists {
headers, fileReader, reader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, reader, redirectURL, nil
}
// If file exists in local registry, but download failed, we should try to download from remote
log.Warn().Ctx(ctx).Msgf("failed to pull from local, attempting streaming from remote, %v", err)
}
// fetch it from upstream
pathForUpstream, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, "")
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get file path: %w", err)
}
filePathForUpstream := filepath.Join(pathForUpstream, info.FileName)
response, helper, fileReader, err := r.downloadFileFromUpstream(ctx, info, filePathForUpstream)
if err != nil {
return response, nil, nil, "", fmt.Errorf("failed to download package file from upstream: %w", err)
}
// cache all package files if its zip file
if filepath.Ext(info.FileName) == ".zip" {
go func(info gopackagetype.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = r.putFileToLocal(ctx2, &info, helper)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf(
"error while putting cargo file to localRegistry, %v", err,
)
return
}
log.Ctx(ctx2).Info().Msgf(
"Successfully updated for image: %s, version: %s in registry: %s",
info.Image, info.Version, info.RegIdentifier,
)
}(info)
}
return response, nil, fileReader, "", nil
}
// do not cache package index always get it from upstream.
func (r *proxy) DownloadPackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, error) {
path, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, "")
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get file path: %w", err)
}
filePath := filepath.Join(path, "list")
response, _, reader, err := r.downloadFileFromUpstream(ctx, info, filePath)
if err != nil {
return response, nil, nil, fmt.Errorf("failed to download package index: %w", err)
}
return response, nil, reader, nil
}
// do not cache latest version always get it from upstream.
func (r *proxy) DownloadPackageLatestVersionInfo(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, error) {
filePath := filepath.Join(info.Image, LatestVersionKey)
response, _, reader, err := r.downloadFileFromUpstream(ctx, info, filePath)
if err != nil {
return response, nil, nil, fmt.Errorf("failed to download package latest version: %w", err)
}
return response, nil, reader, nil
}
func (r *proxy) downloadFileFromUpstream(
ctx context.Context, info gopackagetype.ArtifactInfo, path string,
) (*commons.ResponseHeaders, RemoteRegistryHelper, io.ReadCloser, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return responseHeaders, nil, nil, fmt.Errorf("failed to get upstream proxy: %w", err)
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return responseHeaders, nil, nil, fmt.Errorf("failed to create remote registry helper: %w", err)
}
file, err := helper.GetPackageFile(ctx, info.Image, path)
if err != nil {
return responseHeaders, nil, nil, fmt.Errorf("failed to get package file: %w", err)
}
responseHeaders.Code = http.StatusOK
return responseHeaders, helper, file, nil
}
func (r *proxy) putFileToLocal(
ctx context.Context, info *gopackagetype.ArtifactInfo,
remote RemoteRegistryHelper,
) error {
// path for upstream proxy file
path, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, "")
if err != nil {
return fmt.Errorf("failed to get file path: %w", err)
}
// cache .info file
info.FileName = info.Version + ".info"
infoFilePath := filepath.Join(path, info.FileName)
err = r.cacheFileAndCreateOrUpdateVersion(ctx, info, infoFilePath, remote)
if err != nil {
return fmt.Errorf("failed to cache info file: %w", err)
}
// cache .mod file
info.FileName = info.Version + ".mod"
modFilePath := filepath.Join(path, info.FileName)
err = r.cacheFileAndCreateOrUpdateVersion(ctx, info, modFilePath, remote)
if err != nil {
return fmt.Errorf("failed to cache mod file: %w", err)
}
// cache .zip file
info.FileName = info.Version + ".zip"
zipFilePath := filepath.Join(path, info.FileName)
err = r.cacheFileAndCreateOrUpdateVersion(ctx, info, zipFilePath, remote)
if err != nil {
return fmt.Errorf("failed to cache zip file: %w", err)
}
// regenerate package index
r.localRegistryHelper.RegeneratePackageIndex(ctx, *info)
// regenerate package metadata
r.localRegistryHelper.RegeneratePackageMetadata(ctx, *info)
return nil
}
func (r *proxy) cacheFileAndCreateOrUpdateVersion(
ctx context.Context, info *gopackagetype.ArtifactInfo,
filePath string, remote RemoteRegistryHelper,
) error {
// Get pacakage from upstream source
file, err := remote.GetPackageFile(ctx, info.Image, filePath)
if err != nil {
return fmt.Errorf("failed to get package file: %w", err)
}
defer file.Close()
// upload to file path
path, err := utils.GetFilePath(artifact.PackageTypeGO, info.Image, info.Version)
if err != nil {
return fmt.Errorf("failed to get file path: %w", err)
}
filePathForLocal := filepath.Join(path, info.FileName)
_, _, err = r.localBase.Upload(
ctx, info.ArtifactInfo, info.FileName, info.Version, filePathForLocal, file,
&gopackagemetadata.VersionMetadataDB{
VersionMetadata: gopackagemetadata.VersionMetadata{
Name: info.Image,
Version: info.Version,
Time: time.Now().Format(time.RFC3339), // get time in "2025-07-15T14:37:08.552428Z" format
},
})
if err != nil {
return fmt.Errorf("failed to upload file %s: %w", filePath, err)
}
return nil
}
func (r *proxy) RegeneratePackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
r.localRegistryHelper.RegeneratePackageIndex(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
func (r *proxy) RegeneratePackageMetadata(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
r.localRegistryHelper.RegeneratePackageMetadata(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/registry.go | registry/app/pkg/gopackage/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/app/storage"
)
const (
LatestVersionKey = "@latest"
)
type Registry interface {
pkg.Artifact
// Upload package to registry using harness CLI
UploadPackage(
ctx context.Context, info gopackagetype.ArtifactInfo,
mod io.ReadCloser, zip io.ReadCloser,
) (responseHeaders *commons.ResponseHeaders, err error)
// download package file
DownloadPackageFile(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error)
// regenerate package index
RegeneratePackageIndex(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error)
// regenerate package metadata
RegeneratePackageMetadata(
ctx context.Context, info gopackagetype.ArtifactInfo,
) (*commons.ResponseHeaders, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/remote_helper.go | registry/app/pkg/gopackage/remote_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 gopackage
import (
"context"
"fmt"
"io"
"strings"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/goproxy"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
// GetFile Downloads the file for the given package and filename
GetPackageFile(ctx context.Context, pkg string, version string) (io.ReadCloser, error)
}
type remoteRegistryHelper struct {
adapter registry.GoPackageRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, err
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypeGO)
if r.registry.Source == string(artifact.UpstreamConfigSourceGoProxy) {
r.registry.RepoURL = goproxy.GoProxyURL
}
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
goPackageReg, ok := adpt.(registry.GoPackageRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to go registry")
return err
}
r.adapter = goPackageReg
return nil
}
func (r *remoteRegistryHelper) GetPackageFile(
ctx context.Context, pkg string, filePath string,
) (io.ReadCloser, error) {
// remove first / from filepath
filePath = strings.TrimPrefix(filePath, "/")
data, err := r.adapter.GetPackageFile(ctx, filePath)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get package file: %s, %s", pkg, filePath)
return nil, fmt.Errorf("failed to get package file: %s, %s, %w", pkg, filePath, err)
}
if data == nil {
log.Ctx(ctx).Error().Msgf("file not found for package: %s, %s", pkg, filePath)
return nil, fmt.Errorf("file not found for package: %s, %s", pkg, filePath)
}
return data, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/local_helper.go | registry/app/pkg/gopackage/local_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 gopackage
import (
"context"
"io"
"strings"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/gopackage"
"github.com/harness/gitness/registry/app/storage"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info gopackage.ArtifactInfo, filepath string) bool
RegeneratePackageIndex(ctx context.Context, info gopackage.ArtifactInfo)
RegeneratePackageMetadata(ctx context.Context, info gopackage.ArtifactInfo)
DownloadFile(ctx context.Context, info gopackage.ArtifactInfo) (
*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error,
)
}
type localRegistryHelper struct {
localRegistry LocalRegistry
localBase base.LocalBase
postProcessingReporter *asyncprocessing.Reporter
}
func NewLocalRegistryHelper(
localRegistry LocalRegistry, localBase base.LocalBase,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistryHelper {
return &localRegistryHelper{
localRegistry: localRegistry,
localBase: localBase,
postProcessingReporter: postProcessingReporter,
}
}
func (h *localRegistryHelper) FileExists(
ctx context.Context, info gopackage.ArtifactInfo, filepath string,
) bool {
return h.localBase.Exists(ctx, info.ArtifactInfo, strings.TrimLeft(filepath, "/"))
}
func (h *localRegistryHelper) RegeneratePackageIndex(
ctx context.Context, info gopackage.ArtifactInfo,
) {
h.postProcessingReporter.BuildPackageIndex(ctx, info.RegistryID, info.Image)
}
func (h *localRegistryHelper) RegeneratePackageMetadata(
ctx context.Context, info gopackage.ArtifactInfo,
) {
h.postProcessingReporter.BuildPackageMetadata(ctx, info.RegistryID, info.Image, info.Version)
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info gopackage.ArtifactInfo) (
*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error,
) {
return h.localRegistry.DownloadPackageFile(ctx, info)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/gopackage/utils/utils.go | registry/app/pkg/gopackage/utils/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 (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
gopackagemetadata "github.com/harness/gitness/registry/app/metadata/gopackage"
zs "github.com/harness/gitness/registry/app/pkg/commons/zipreader"
"golang.org/x/mod/modfile"
)
// get the module name from mod file.
func GetModuleNameFromModFile(modBytes io.Reader) (string, error) {
moduleName := ""
scanner := bufio.NewScanner(modBytes)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if after, ok := strings.CutPrefix(line, "module "); ok {
moduleName = strings.TrimSpace(after)
break
}
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("error scanning mod file: %w", err)
}
if moduleName == "" {
return "", fmt.Errorf("module name not found in mod file")
}
return moduleName, nil
}
func getImageAndFileNameFromURL(path string) (string, string, error) {
parts := strings.SplitN(path, "/@v/", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid download path: %s", path)
}
image := parts[0]
filename := parts[1]
return image, filename, nil
}
func getVersionFromFileName(filename string) (string, error) {
switch filename {
case "list":
return "", nil
default:
// v1.0.0.zip => v1.0.0
ext := filepath.Ext(filename) // e.g., ".zip"
version := strings.TrimSuffix(filename, ext) // remove extension
if version == "" {
return "", fmt.Errorf("empty version in file name: %s", filename)
}
return version, nil
}
}
func GetArtifactInfoFromURL(path string) (string, string, string, error) {
var (
image string
version string
filename string
)
// sample endpoint pkg/artifact-registry/go-repo/go/example.com/hello/@latest
if strings.HasSuffix(path, "/@latest") {
image = strings.Replace(path, "/@latest", "", 1)
return image, "@latest", "", nil
}
// sample endpoint pkg/artifact-registry/go-repo/go/example.com/hello/@v/v1.0.2.zip
// pkg/artifact-registry/go-repo/go/example.com/hello/@v/list
image, filename, err := getImageAndFileNameFromURL(path)
if err != nil {
return "", "", "", fmt.Errorf("failed to get image and file name from URL: %w", err)
}
version, err = getVersionFromFileName(filename)
if err != nil {
return "", "", "", fmt.Errorf("failed to get version from file name: %w", err)
}
return image, version, filename, nil
}
func GetIndexFilePath(image string) string {
return filepath.Join("/", image, "index")
}
// get the package metadata from info file.
func GetPackageMetadataFromInfoFile(infoBytes *bytes.Buffer) (gopackagemetadata.VersionMetadata, error) {
var metadata gopackagemetadata.VersionMetadata
if err := json.NewDecoder(infoBytes).Decode(&metadata); err != nil {
return gopackagemetadata.VersionMetadata{}, fmt.Errorf("error decoding info file: %w", err)
}
return metadata, nil
}
func UpdateMetadataFromModFile(
modBytes *bytes.Buffer, metadata *gopackagemetadata.VersionMetadata,
) error {
data := modBytes.Bytes()
modFile, err := modfile.Parse("go.mod", data, nil)
if err != nil {
return fmt.Errorf("error parsing mod file: %w", err)
}
var deps []gopackagemetadata.Dependency
for _, r := range modFile.Require {
deps = append(deps, gopackagemetadata.Dependency{
Name: r.Mod.Path,
Version: r.Mod.Version,
})
}
metadata.Dependencies = deps
return nil
}
func UpdateMetadataFromZipFile(
reader io.ReadCloser, metadata *gopackagemetadata.VersionMetadata,
) error {
zr := zs.NewReader(reader)
for {
header, err := zr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("failed to read zip file with error: %w", err)
}
if strings.HasSuffix(header.Name, "README.md") || strings.HasSuffix(header.Name, "README") {
readme, err := parseReadme(zr)
if err != nil {
return fmt.Errorf("failed to parse metadata from README.md file: %w", err)
}
if readme != "" {
metadata.Readme = readme
}
}
}
return nil
}
func parseReadme(f io.Reader) (readme string, err error) {
data, err := io.ReadAll(f)
if err != nil {
return "", err
}
return string(data), nil
}
func IsMainArtifactFile(filename string) bool {
return filepath.Ext(filename) == ".zip"
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/filemanager/wire.go | registry/app/pkg/filemanager/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 filemanager
import (
"github.com/harness/gitness/registry/app/events/replication"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
gitnesstypes "github.com/harness/gitness/types"
"github.com/google/wire"
)
func Provider(
registryDao store.RegistryRepository, genericBlobDao store.GenericBlobRepository,
nodesDao store.NodesRepository,
tx dbtx.Transactor,
config *gitnesstypes.Config,
storageService *storage.Service,
bucketService docker.BucketService,
replicationReporter replication.Reporter,
) FileManager {
// Pass the BucketService to use the unified implementation
return NewFileManager(registryDao, genericBlobDao, nodesDao, tx,
config, storageService, bucketService, replicationReporter)
}
var Set = wire.NewSet(Provider)
var WireSet = wire.NewSet(Set)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/filemanager/context.go | registry/app/pkg/filemanager/context.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package filemanager
import (
"context"
"github.com/harness/gitness/registry/app/storage"
v2 "github.com/distribution/distribution/v3/registry/api/v2"
)
// Context should contain the request specific context for use in across
// handlers. Resources that don't need to be shared across handlers should not
// be on this object.
type Context struct {
context.Context
URLBuilder *v2.URLBuilder
genericBlobStore storage.GenericBlobStore
Upload storage.BlobWriter
}
// Value overrides context.Context.Value to ensure that calls are routed to
// correct context.
func (ctx *Context) Value(key any) any {
return ctx.Context.Value(key)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/filemanager/file_manager.go | registry/app/pkg/filemanager/file_manager.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package filemanager
import (
"context"
"fmt"
"io"
"mime/multipart"
"path"
"strings"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/registry/app/events/replication"
"github.com/harness/gitness/registry/app/pkg/docker"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/store/database/dbtx"
gitnesstypes "github.com/harness/gitness/types"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
const (
rootPathString = "/"
tmp = "tmp"
files = "files"
nodeLimit = 1000
pathFormat = "for path: %s, with error %w"
failedToGetFile = "failed to get the file for path: %s, with error %w"
)
func NewFileManager(
registryDao store.RegistryRepository, genericBlobDao store.GenericBlobRepository,
nodesDao store.NodesRepository, tx dbtx.Transactor,
config *gitnesstypes.Config, storageService *storage.Service,
bucketService docker.BucketService, replicationReporter replication.Reporter,
) FileManager {
return FileManager{
registryDao: registryDao,
genericBlobDao: genericBlobDao,
nodesDao: nodesDao,
tx: tx,
config: config,
storageService: storageService,
bucketService: bucketService,
replicationReporter: replicationReporter,
}
}
type FileManager struct {
config *gitnesstypes.Config
storageService *storage.Service
registryDao store.RegistryRepository
genericBlobDao store.GenericBlobRepository
nodesDao store.NodesRepository
tx dbtx.Transactor
bucketService docker.BucketService
replicationReporter replication.Reporter
}
func (f *FileManager) UploadFile(
ctx context.Context,
filePath string,
regID int64,
rootParentID int64,
rootIdentifier string,
file multipart.File,
fileReader io.Reader,
fileName string,
principalID int64,
) (types.FileInfo, error) {
// uploading the file to temporary path in file storage
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
tmpFileName := uuid.NewString()
fileInfo, tmpPath, err := f.uploadTempFileInternal(ctx, blobContext, rootIdentifier,
file, fileName, fileReader, tmpFileName)
if err != nil {
return fileInfo, err
}
fileInfo.Filename = fileName
err = f.moveFile(ctx, rootIdentifier, fileInfo, blobContext, tmpPath)
if err != nil {
return fileInfo, err
}
blobID, created, err := f.dbSaveFile(ctx, filePath, regID, rootParentID, fileInfo, principalID)
if err != nil {
return fileInfo, err
}
// Emit blob create event
if created {
destinations := []replication.CloudLocation{}
f.replicationReporter.ReportEventAsync(ctx, rootIdentifier, replication.BlobCreate, 0, blobID, fileInfo.Sha256,
f.config, destinations)
}
return fileInfo, nil
}
// GetBlobsContext context constructs the context object for the application. This only be
// called once per request.
func (f *FileManager) GetBlobsContext(
c context.Context, registryIdentifier,
rootIdentifier, blobID, sha256 string,
) *Context {
ctx := &Context{Context: c}
if f.bucketService != nil && blobID != "" {
if result := f.bucketService.GetBlobStore(c, registryIdentifier, rootIdentifier, blobID,
sha256); result != nil {
ctx.genericBlobStore = result.GenericStore
return ctx
}
}
// use blob store from the default bucket
ctx.genericBlobStore = f.storageService.GenericBlobsStore(rootIdentifier)
return ctx
}
func (f *FileManager) GetOCIBlobStore(
ctx context.Context,
registryIdentifier string,
rootIdentifier string,
) storage.OciBlobStore {
return f.storageService.OciBlobsStore(ctx, registryIdentifier, rootIdentifier)
}
func (f *FileManager) dbSaveFile(
ctx context.Context,
filePath string,
regID int64,
rootParentID int64,
fileInfo types.FileInfo,
createdBy int64,
) (string, bool, error) {
// Saving in the generic blobs table
var blobID = ""
gb := &types.GenericBlob{
RootParentID: rootParentID,
Sha1: fileInfo.Sha1,
Sha256: fileInfo.Sha256,
Sha512: fileInfo.Sha512,
MD5: fileInfo.MD5,
Size: fileInfo.Size,
CreatedBy: createdBy,
}
created, err := f.genericBlobDao.Create(ctx, gb)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to save generic blob in db with "+
"sha256 : %s, err: %s", fileInfo.Sha256, err.Error())
return "", false, fmt.Errorf("failed to save generic blob"+
" in db with sha256 : %s, err: %w", fileInfo.Sha256, err)
}
blobID = gb.ID
// Saving the nodes
err = f.tx.WithTx(ctx, func(ctx context.Context) error {
err = f.createNodes(ctx, filePath, blobID, regID, createdBy)
if err != nil {
return err
}
return nil
})
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to save nodes for file : %s, with "+
"path : %s, err: %s", fileInfo.Filename, filePath, err)
return "", false, fmt.Errorf("failed to save nodes for"+
" file : %s, with path : %s, err: %w", fileInfo.Filename, filePath, err)
}
return blobID, created, nil
}
func (f *FileManager) SaveNodes(
ctx context.Context,
filePath string,
regID int64,
rootParentID int64,
createdBy int64,
sha256 string,
) error {
gb, err := f.genericBlobDao.FindBySha256AndRootParentID(ctx, sha256, rootParentID)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to find generic blob in db with "+
"sha256 : %s, err: %s", sha256, err.Error())
return fmt.Errorf("failed to find generic blob"+
" in db with sha256 : %s, err: %w", sha256, err)
}
// Saving the nodes
err = f.createNodes(ctx, filePath, gb.ID, regID, createdBy)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to save nodes for file with "+
"path : %s, err: %s", filePath, err)
return fmt.Errorf("failed to save nodes for file with path : %s, err: %w", filePath, err)
}
return nil
}
func (f *FileManager) SaveNodesTx(
ctx context.Context,
filePath string,
regID int64,
rootParentID int64,
createdBy int64,
sha256 string,
) error {
return f.tx.WithTx(ctx, func(ctx context.Context) error {
return f.SaveNodes(ctx, filePath, regID, rootParentID, createdBy, sha256)
})
}
func (f *FileManager) CreateNodesWithoutFileNode(
ctx context.Context,
path string,
regID int64,
principalID int64,
) error {
segments := strings.Split(path, rootPathString)
parentID := ""
// Start with root (-1)
// Iterate through segments and create Node objects
nodePath := ""
for i, segment := range segments {
if i >= nodeLimit { // Stop after 1000 iterations
break
}
if segment == "" {
continue // Skip empty segments
}
var nodeID string
var err error
nodePath += rootPathString + segment
nodeID, err = f.SaveNode(ctx, path, "", regID, segment,
parentID, nodePath, false, principalID)
if err != nil {
return err
}
parentID = nodeID
}
return nil
}
func (f *FileManager) moveFile(
ctx context.Context,
rootIdentifier string,
fileInfo types.FileInfo,
blobContext *Context,
tmpPath string,
) error {
// Moving the file to permanent path in file storage
fileStoragePath := path.Join(rootPathString, rootIdentifier, files, fileInfo.Sha256)
err := blobContext.genericBlobStore.Move(ctx, tmpPath, fileStoragePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to Move the file on permanent location "+
"with name : %s with error : %s", fileInfo.Filename, err.Error())
return fmt.Errorf("failed to Move the file on permanent"+
" location with name : %s with error : %w", fileInfo.Filename, err)
}
return nil
}
func (f *FileManager) createNodes(
ctx context.Context,
filePath string,
blobID string,
regID int64,
principalID int64,
) error {
segments := strings.Split(filePath, rootPathString)
parentID := ""
// Start with root (-1)
// Iterate through segments and create Node objects
nodePath := ""
for i, segment := range segments {
if i >= nodeLimit { // Stop after 1000 iterations
break
}
if segment == "" {
continue // Skip empty segments
}
var nodeID string
var err error
nodePath += rootPathString + segment
if i == len(segments)-1 {
nodeID, err = f.SaveNode(ctx, filePath, blobID, regID, segment,
parentID, nodePath, true, principalID)
if err != nil {
return err
}
} else {
nodeID, err = f.SaveNode(ctx, filePath, "", regID, segment,
parentID, nodePath, false, principalID)
if err != nil {
return err
}
}
parentID = nodeID
}
return nil
}
func (f *FileManager) SaveNode(
ctx context.Context, filePath string, blobID string, regID int64, segment string,
parentID string, nodePath string, isFile bool, createdBy int64,
) (string, error) {
node := &types.Node{
Name: segment,
RegistryID: regID,
ParentNodeID: parentID,
IsFile: isFile,
NodePath: nodePath,
BlobID: blobID,
CreatedBy: createdBy,
}
err := f.nodesDao.Create(ctx, node)
if err != nil {
return "", fmt.Errorf("failed to create the node: %s, "+
"for path := %s, %w", segment, filePath, err)
}
return node.ID, nil
}
func (f *FileManager) CopyNodes(
ctx context.Context,
rootParentID int64,
sourceRegistryID int64,
targetRegistryID int64,
sourcePathPrefix string,
) error {
nodes, err := f.nodesDao.GetAllFileNodesByPathPrefixAndRegistryID(ctx, sourceRegistryID, sourcePathPrefix)
if err != nil || nodes == nil || len(*nodes) == 0 {
return fmt.Errorf("failed to get nodes from source registry: %w", err)
}
// FIXME: Optimize this flow
for _, node := range *nodes {
blob, err := f.genericBlobDao.FindByID(ctx, node.BlobID)
if err != nil {
return fmt.Errorf("failed to get blob: %s, %w", node.BlobID, err)
}
err = f.SaveNodes(ctx, node.NodePath, targetRegistryID, rootParentID, node.CreatedBy, blob.Sha256)
if err != nil {
return fmt.Errorf("failed to save nodes: %w", err)
}
}
return nil
}
func (f *FileManager) DownloadFile(
ctx context.Context,
filePath string,
registryID int64,
registryIdentifier string,
rootIdentifier string,
allowRedirect bool,
) (fileReader *storage.FileReader, size int64, redirectURL string, err error) {
node, err := f.nodesDao.GetByPathAndRegistryID(ctx, registryID, filePath)
if err != nil {
return nil, 0, "", usererror.NotFoundf("file not found for registry [%s], path: [%s]", registryIdentifier,
filePath)
}
blob, err := f.genericBlobDao.FindByID(ctx, node.BlobID)
if err != nil {
return nil, 0, "", usererror.NotFoundf("failed to get the blob for path: %s, "+
"with blob id: %s, with error %s", filePath, node.BlobID, err)
}
completeFilaPath := path.Join(rootPathString + rootIdentifier + rootPathString + files + rootPathString + blob.Sha256)
blobContext := f.GetBlobsContext(ctx, registryIdentifier, rootIdentifier, blob.ID, blob.Sha256)
if allowRedirect {
fileReader, redirectURL, err = blobContext.genericBlobStore.Get(ctx, completeFilaPath, blob.Size, node.Name)
} else {
fileReader, err = blobContext.genericBlobStore.GetWithNoRedirect(ctx, completeFilaPath, blob.Size)
}
if err != nil {
return nil, 0, "", fmt.Errorf(failedToGetFile, completeFilaPath, err)
}
return fileReader, blob.Size, redirectURL, nil
}
func (f *FileManager) DeleteNode(
ctx context.Context,
regID int64,
filePath string,
) error {
err := f.nodesDao.DeleteByNodePathAndRegistryID(ctx, filePath, regID)
if err != nil {
return fmt.Errorf("failed to delete file for path: %s, with error: %w", filePath, err)
}
return nil
}
func (f *FileManager) DeleteLeafNode(
ctx context.Context,
regID int64,
filePath string,
) error {
if len(filePath) > 0 && !strings.HasPrefix(filePath, rootPathString) {
filePath = rootPathString + filePath
}
err := f.nodesDao.DeleteByLeafNodePathAndRegistryID(ctx, filePath, regID)
if err != nil {
return fmt.Errorf("failed to delete file for path: %s, with error: %w", filePath, err)
}
return nil
}
func (f *FileManager) GetNode(
ctx context.Context,
regID int64,
filePath string,
) (*types.Node, error) {
node, err := f.nodesDao.GetByPathAndRegistryID(ctx, regID, filePath)
if err != nil {
return nil, fmt.Errorf("failed to delete file for path: %s, with error: %w", filePath, err)
}
return node, nil
}
func (f *FileManager) HeadFile(
ctx context.Context,
filePath string,
regID int64,
) (sha256 string, size int64, err error) {
node, err := f.nodesDao.GetByPathAndRegistryID(ctx, regID, filePath)
if err != nil {
return "", 0, fmt.Errorf("failed to get the node path mapping for path: %s, "+
"with error %w", filePath, err)
}
blob, err := f.genericBlobDao.FindByID(ctx, node.BlobID)
if err != nil {
return "", 0, fmt.Errorf("failed to get the blob for path: %s, with blob id: %s,"+
" with error %w", filePath, node.BlobID, err)
}
return blob.Sha256, blob.Size, nil
}
func (f *FileManager) HeadSHA256(
ctx context.Context,
sha256 string,
regID int64,
rootParentID int64,
) (string, error) {
blob, err := f.genericBlobDao.FindBySha256AndRootParentID(ctx, sha256, rootParentID)
if blob == nil || err != nil {
log.Ctx(ctx).Error().Msgf("failed to get the blob for sha256: %s, with root parent id: %d, with error %v",
sha256, rootParentID, err)
return "", fmt.Errorf("failed to get the blob for sha256: %s, with root parent id: %d, with error %w", sha256,
rootParentID, err)
}
node, err := f.nodesDao.GetByBlobIDAndRegistryID(ctx, blob.ID, regID)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to get the node for blob id: %s, with registry id: %d, with error %v",
blob.ID, regID, err)
return "", fmt.Errorf("failed to get the node for blob id: %s, with registry id: %d, with error %w", blob.ID,
regID, err)
}
return node.NodePath, nil
}
func (f *FileManager) FindLatestFilePath(
ctx context.Context, registryID int64,
filepathPrefix, filename string,
) (string, error) {
fileNode, err := f.nodesDao.FindByPathAndRegistryID(ctx, registryID, filepathPrefix, filename)
if err != nil {
return "", fmt.Errorf("failed to get the node for path: %s, file name: %s, with registry id: %d,"+
" with error %w", filepathPrefix, filename, registryID, err)
}
return fileNode.NodePath, nil
}
func (f *FileManager) HeadBlob(
ctx context.Context,
sha256 string,
rootParentID int64,
) (string, error) {
blob, err := f.genericBlobDao.FindBySha256AndRootParentID(ctx, sha256, rootParentID)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to get the blob for sha256: %s, with root parent id: %d, with error %v",
sha256, rootParentID, err)
return "", fmt.Errorf("failed to get the blob for sha256: %s, with root parent id: %d, with error %w", sha256,
rootParentID, err)
}
return blob.ID, nil
}
func (f *FileManager) GetFileMetadata(
ctx context.Context,
filePath string,
regID int64,
) (types.FileInfo, error) {
node, err := f.nodesDao.GetByPathAndRegistryID(ctx, regID, filePath)
if err != nil {
return types.FileInfo{}, fmt.Errorf("failed to get the node path mapping "+
pathFormat, filePath, err)
}
blob, err := f.genericBlobDao.FindByID(ctx, node.BlobID)
if err != nil {
return types.FileInfo{}, fmt.Errorf("failed to get the blob for path: %s, "+
"with blob id: %s, with error %s", filePath, node.BlobID, err)
}
return types.FileInfo{
Sha1: blob.Sha1,
Size: blob.Size,
Sha256: blob.Sha256,
Sha512: blob.Sha512,
MD5: blob.MD5,
Filename: node.Name,
}, nil
}
func (f *FileManager) GetFilesMetadata(
ctx context.Context,
filePath string,
regID int64,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (*[]types.FileNodeMetadata, error) {
node, err := f.nodesDao.GetFilesMetadataByPathAndRegistryID(ctx, regID, filePath,
sortByField,
sortByOrder,
limit,
offset,
search)
if err != nil {
return &[]types.FileNodeMetadata{}, fmt.Errorf("failed to get the files "+
pathFormat, filePath, err)
}
return node, nil
}
func (f *FileManager) CountFilesByPath(
ctx context.Context,
filePath string,
regID int64,
) (int64, error) {
count, err := f.nodesDao.CountByPathAndRegistryID(ctx, regID, filePath)
if err != nil {
return -1, fmt.Errorf("failed to get the count of files"+
pathFormat, filePath, err)
}
return count, nil
}
func (f *FileManager) UploadTempFile(
ctx context.Context,
rootIdentifier string,
file multipart.File,
fileName string,
fileReader io.Reader,
) (types.FileInfo, string, error) {
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
tempFileName := uuid.NewString()
fileInfo, _, err := f.uploadTempFileInternal(ctx, blobContext, rootIdentifier,
file, fileName, fileReader, tempFileName)
if err != nil {
return fileInfo, tempFileName, err
}
return fileInfo, tempFileName, nil
}
func (f *FileManager) UploadTempFileToPath(
ctx context.Context,
rootIdentifier string,
file multipart.File,
fileName string,
tempFileName string,
fileReader io.Reader,
) (types.FileInfo, string, error) {
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
fileInfo, _, err := f.uploadTempFileInternal(ctx, blobContext, rootIdentifier,
file, fileName, fileReader, tempFileName)
if err != nil {
return fileInfo, tempFileName, err
}
return fileInfo, tempFileName, nil
}
func (f *FileManager) FileExists(
ctx context.Context,
rootIdentifier string,
filePath string,
) (bool, int64, error) {
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
size, err := blobContext.genericBlobStore.Stat(ctx, filePath)
if err != nil {
return false, -1, err
}
return size > 0, size, nil
}
func (f *FileManager) uploadTempFileInternal(
ctx context.Context,
blobContext *Context,
rootIdentifier string,
file multipart.File,
fileName string,
fileReader io.Reader,
tempFileName string,
) (types.FileInfo, string, error) {
tmpPath := path.Join(rootPathString, rootIdentifier, tmp, tempFileName)
fw, err := blobContext.genericBlobStore.Create(ctx, tmpPath)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to initiate the file upload for file with"+
" name : %s with error : %s", fileName, err.Error())
return types.FileInfo{}, tmpPath, fmt.Errorf("failed to initiate the file upload "+
"for file with name : %s with error : %w", fileName, err)
}
defer fw.Close()
fileInfo, err := blobContext.genericBlobStore.Write(ctx, fw, file, fileReader)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to upload the file on temparary location"+
" with name : %s with error : %s", fileName, err.Error())
return types.FileInfo{}, tmpPath, fmt.Errorf("failed to upload the file on temparary "+
"location with name : %s with error : %w", fileName, err)
}
return fileInfo, tmpPath, nil
}
func (f *FileManager) DownloadTempFile(
ctx context.Context,
fileSize int64,
fileName string,
rootIdentifier string,
) (fileReader *storage.FileReader, size int64, err error) {
tmpPath := path.Join(rootPathString, rootIdentifier, tmp, fileName)
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
reader, err := blobContext.genericBlobStore.GetWithNoRedirect(ctx, tmpPath, fileSize)
if err != nil {
return nil, 0, fmt.Errorf(failedToGetFile, tmpPath, err)
}
return reader, fileSize, nil
}
func (f *FileManager) MoveTempFile(
ctx context.Context,
filePath string,
regID int64,
rootParentID int64,
rootIdentifier string,
fileInfo types.FileInfo,
tempFileName string,
principalID int64,
) error {
// uploading the file to temporary path in file storage
blobContext := f.GetBlobsContext(ctx, rootIdentifier, "", "", "")
tmpPath := path.Join(rootPathString, rootIdentifier, tmp, tempFileName)
err := f.moveFile(ctx, rootIdentifier, fileInfo, blobContext, tmpPath)
if err != nil {
return err
}
blobID, created, err := f.dbSaveFile(ctx, filePath, regID, rootParentID, fileInfo, principalID)
if err != nil {
return err
}
// Emit blob create event
if created {
destinations := []replication.CloudLocation{}
f.replicationReporter.ReportEventAsync(ctx, rootIdentifier, replication.BlobCreate, 0, blobID, fileInfo.Sha256,
f.config, destinations)
}
return nil
}
func (f *FileManager) GetFileMetadataByPathAndRegistryID(
ctx context.Context,
registryID int64,
path string,
) (*types.FileNodeMetadata, error) {
metadata, err := f.nodesDao.GetFileMetadataByPathAndRegistryID(ctx, registryID, path)
if err != nil {
return nil, fmt.Errorf("failed to get [%s] for registry [%d], error: %w", path, registryID, err)
}
return metadata, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/local.go | registry/app/pkg/maven/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
"github.com/harness/gitness/registry/app/metadata"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/maven/utils"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/types"
gitnessstore "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
const (
ArtifactTypeLocalRegistry = "Local Registry"
)
func NewLocalRegistry(
localBase base.LocalBase,
dBStore *DBStore,
tx dbtx.Transactor,
fileManager filemanager.FileManager,
) Registry {
return &LocalRegistry{
localBase: localBase,
DBStore: dBStore,
tx: tx,
fileManager: fileManager,
}
}
type LocalRegistry struct {
localBase base.LocalBase
DBStore *DBStore
tx dbtx.Transactor
fileManager filemanager.FileManager
}
func (r *LocalRegistry) GetMavenArtifactType() string {
return ArtifactTypeLocalRegistry
}
func (r *LocalRegistry) HeadArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
responseHeaders, _, _, _, errs = r.FetchArtifact(ctx, info, false)
return responseHeaders, errs
}
func (r *LocalRegistry) GetArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
return r.FetchArtifact(ctx, info, true)
}
func (r *LocalRegistry) FetchArtifact(ctx context.Context, info pkg.MavenArtifactInfo, serveFile bool) (
responseHeaders *commons.ResponseHeaders,
body *storage.FileReader,
readCloser io.ReadCloser,
redirectURL string,
errs []error,
) {
filePath := utils.GetFilePath(info)
name := info.GroupID + ":" + info.ArtifactID
dbImage, err2 := r.DBStore.ImageDao.GetByName(ctx, info.RegistryID, name)
if err2 != nil {
return processError(err2)
}
if !utils.IsMetadataFile(info.FileName) || info.Version != "" {
_, err2 = r.DBStore.ArtifactDao.GetByName(ctx, dbImage.ID, info.Version)
if err2 != nil {
log.Ctx(ctx).Error().Msgf("Failed to get artifact for image ID: %d, version: %s with error: %v",
dbImage.ID, info.Version, err2)
return processError(err2)
}
}
fileInfo, err := r.fileManager.GetFileMetadata(ctx, filePath, info.RegistryID)
if err != nil {
return processError(err)
}
var fileReader *storage.FileReader
if serveFile {
fileReader, _, redirectURL, err = r.fileManager.DownloadFile(ctx, filePath, info.RegistryID,
info.RootIdentifier, info.RootIdentifier, true)
if err != nil {
return processError(err)
}
}
responseHeaders = utils.SetHeaders(info, fileInfo)
return responseHeaders, fileReader, nil, redirectURL, nil
}
func (r *LocalRegistry) PutArtifact(ctx context.Context, info pkg.MavenArtifactInfo, fileReader io.Reader) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
filePath := utils.GetFilePath(info)
// if package file belongs to maven-metadata file, then file override is expected.
if !utils.IsMetadataFile(info.FileName) {
artifactExists, err := r.localBase.CheckIfVersionExists(ctx, info)
if err != nil && !errors.Is(err, gitnessstore.ErrResourceNotFound) {
return responseHeaders, []error{fmt.Errorf("failed to check if version: %s with artifact: %s "+
"exists: %w", info.Version, info.Image, err)}
}
fileExists, err := r.localBase.ExistsByFilePath(ctx, info.RegistryID, strings.TrimPrefix(filePath, "/"))
if err != nil {
return responseHeaders, []error{fmt.Errorf("failed to check if file with path: %s exists: %w",
filePath, err)}
}
if artifactExists && fileExists {
log.Ctx(ctx).Info().Msgf("file with path: %s already exists for artifact: %s with version: %s",
filePath, info.Image, info.Version)
responseHeaders = &commons.ResponseHeaders{Code: http.StatusOK}
return responseHeaders, nil
}
}
session, _ := request.AuthSessionFrom(ctx)
fileInfo, err := r.fileManager.UploadFile(ctx, filePath,
info.RegistryID, info.RootParentID, info.RootIdentifier, nil, fileReader, info.FileName, session.Principal.ID)
if err != nil {
return responseHeaders, []error{errcode.ErrCodeUnknown.WithDetail(err)}
}
err = r.tx.WithTx(
ctx, func(ctx context.Context) error {
name := info.GroupID + ":" + info.ArtifactID
dbImage := &types.Image{
Name: name,
RegistryID: info.RegistryID,
Enabled: true,
}
err2 := r.DBStore.ImageDao.CreateOrUpdate(ctx, dbImage)
if err2 != nil {
return err2
}
if info.Version == "" {
return nil
}
metadata := &metadata.MavenMetadata{}
dbArtifact, err3 := r.DBStore.ArtifactDao.GetByName(ctx, dbImage.ID, info.Version)
if err3 != nil && !strings.Contains(err3.Error(), "resource not found") {
return err3
}
err3 = r.updateArtifactMetadata(dbArtifact, metadata, info, fileInfo)
if err3 != nil {
return err3
}
metadataJSON, err3 := json.Marshal(metadata)
if err3 != nil {
return err3
}
dbArtifact = &types.Artifact{
ImageID: dbImage.ID,
Version: info.Version,
Metadata: metadataJSON,
}
_, err2 = r.DBStore.ArtifactDao.CreateOrUpdate(ctx, dbArtifact)
if err2 != nil {
return err2
}
return nil
})
if err != nil {
return responseHeaders, []error{errcode.ErrCodeUnknown.WithDetail(err)}
}
responseHeaders = &commons.ResponseHeaders{
Headers: map[string]string{},
Code: http.StatusCreated,
}
return responseHeaders, nil
}
func (r *LocalRegistry) updateArtifactMetadata(
dbArtifact *types.Artifact, mavenMetadata *metadata.MavenMetadata,
info pkg.MavenArtifactInfo, fileInfo types.FileInfo,
) error {
var files []metadata.File
if dbArtifact != nil {
err := json.Unmarshal(dbArtifact.Metadata, mavenMetadata)
if err != nil {
return err
}
fileExist := false
files = mavenMetadata.Files
for _, file := range files {
if file.Filename == info.FileName {
fileExist = true
}
}
if !fileExist {
files = append(files, metadata.File{
Size: fileInfo.Size, Filename: fileInfo.Filename,
CreatedAt: time.Now().UnixMilli(),
})
mavenMetadata.Files = files
mavenMetadata.FileCount++
mavenMetadata.UpdateSize(fileInfo.Size)
}
} else {
files = append(files, metadata.File{
Size: fileInfo.Size, Filename: fileInfo.Filename,
CreatedAt: time.Now().UnixMilli(),
})
mavenMetadata.Files = files
mavenMetadata.FileCount++
mavenMetadata.UpdateSize(fileInfo.Size)
}
return nil
}
func processError(err error) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
if strings.Contains(err.Error(), sql.ErrNoRows.Error()) ||
strings.Contains(err.Error(), "resource not found") ||
strings.Contains(err.Error(), "http status code: 404") {
return responseHeaders, nil, nil, "", []error{commons.NotFoundError(err.Error(), err)}
}
return responseHeaders, nil, nil, "", []error{err}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/wire.go | registry/app/pkg/maven/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 maven
import (
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/quarantine"
"github.com/harness/gitness/registry/app/remote/controller/proxy/maven"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
dBStore *DBStore,
tx dbtx.Transactor,
fileManager filemanager.FileManager,
) *LocalRegistry {
//nolint:errcheck
return NewLocalRegistry(localBase,
dBStore,
tx,
fileManager,
).(*LocalRegistry)
}
func RemoteRegistryProvider(
dBStore *DBStore,
tx dbtx.Transactor,
local *LocalRegistry,
proxyController maven.Controller,
) *RemoteRegistry {
//nolint:errcheck
return NewRemoteRegistry(dBStore, tx, local, proxyController).(*RemoteRegistry)
}
func ControllerProvider(
local *LocalRegistry,
remote *RemoteRegistry,
authorizer authz.Authorizer,
dBStore *DBStore,
spaceFinder refcache.SpaceFinder,
quarantineFinder quarantine.Finder,
) *Controller {
return NewController(local, remote, authorizer, dBStore, spaceFinder, quarantineFinder)
}
func DBStoreProvider(
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
spaceStore corestore.SpaceStore,
bandwidthStatDao store.BandwidthStatRepository,
downloadStatDao store.DownloadStatRepository,
nodeDao store.NodesRepository,
upstreamProxyDao store.UpstreamProxyConfigRepository,
) *DBStore {
//nolint:errcheck
return NewDBStore(registryDao, imageDao, artifactDao, spaceStore, bandwidthStatDao,
downloadStatDao,
nodeDao,
upstreamProxyDao)
}
func ProvideProxyController(
registry *LocalRegistry, secretService secret.Service,
spaceFinder refcache.SpaceFinder,
) maven.Controller {
return maven.NewProxyController(registry, secretService, spaceFinder)
}
var ControllerSet = wire.NewSet(ControllerProvider)
var DBStoreSet = wire.NewSet(DBStoreProvider)
var RegistrySet = wire.NewSet(LocalRegistryProvider, RemoteRegistryProvider)
var ProxySet = wire.NewSet(ProvideProxyController)
var WireSet = wire.NewSet(ControllerSet, DBStoreSet, RegistrySet, ProxySet)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/remote.go | registry/app/pkg/maven/remote.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/remote/controller/proxy/maven"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
const (
ArtifactTypeRemoteRegistry = "Remote Registry"
)
func NewRemoteRegistry(
dBStore *DBStore, tx dbtx.Transactor, local *LocalRegistry,
proxyController maven.Controller,
) Registry {
return &RemoteRegistry{
DBStore: dBStore,
tx: tx,
local: local,
proxyController: proxyController,
}
}
type RemoteRegistry struct {
local *LocalRegistry
proxyController maven.Controller
DBStore *DBStore
tx dbtx.Transactor
}
func (r *RemoteRegistry) GetMavenArtifactType() string {
return ArtifactTypeRemoteRegistry
}
func (r *RemoteRegistry) HeadArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
responseHeaders, _, _, _, errs = r.fetchArtifact(ctx, info, false)
return responseHeaders, errs
}
func (r *RemoteRegistry) GetArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
return r.fetchArtifact(ctx, info, true)
}
func (r *RemoteRegistry) PutArtifact(ctx context.Context, _ pkg.MavenArtifactInfo, _ io.Reader) (
responseHeaders *commons.ResponseHeaders, errs []error,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, nil
}
func (r *RemoteRegistry) fetchArtifact(ctx context.Context, info pkg.MavenArtifactInfo, serveFile bool) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, readCloser io.ReadCloser,
redirectURL string, errs []error,
) {
log.Ctx(ctx).Info().Msgf("Maven Proxy: %s", info.RegIdentifier)
responseHeaders, body, redirectURL, useLocal := r.proxyController.UseLocalFile(ctx, info)
if useLocal {
return responseHeaders, body, readCloser, redirectURL, errs
}
upstreamProxy, err := r.DBStore.UpstreamProxyDao.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return processError(err)
}
// This is start of proxy Code.
responseHeaders, readCloser, err = r.proxyController.ProxyFile(ctx, info, *upstreamProxy, serveFile)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to proxy file: %s", info.RegIdentifier)
return processError(err)
}
return responseHeaders, nil, readCloser, "", errs
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/registry.go | registry/app/pkg/maven/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
Artifact
HeadArtifact(ctx context.Context, artInfo pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, errs []error,
)
GetArtifact(ctx context.Context, artInfo pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, readCloser io.ReadCloser,
redirectURL string, errs []error,
)
PutArtifact(ctx context.Context, artInfo pkg.MavenArtifactInfo, fileReader io.Reader) (
responseHeaders *commons.ResponseHeaders, errs []error,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/response.go | registry/app/pkg/maven/response.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"io"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
type Response interface {
GetErrors() []error
SetError(error)
}
var _ Response = (*HeadArtifactResponse)(nil)
var _ Response = (*GetArtifactResponse)(nil)
var _ Response = (*PutArtifactResponse)(nil)
type HeadArtifactResponse struct {
Errors []error
ResponseHeaders *commons.ResponseHeaders
}
func (r *HeadArtifactResponse) GetErrors() []error {
return r.Errors
}
func (r *HeadArtifactResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
type GetArtifactResponse struct {
Errors []error
ResponseHeaders *commons.ResponseHeaders
RedirectURL string
Body *storage.FileReader
ReadCloser io.ReadCloser
}
func (r *GetArtifactResponse) GetErrors() []error {
return r.Errors
}
func (r *GetArtifactResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
type PutArtifactResponse struct {
Errors []error
ResponseHeaders *commons.ResponseHeaders
}
func (r *PutArtifactResponse) GetErrors() []error {
return r.Errors
}
func (r *PutArtifactResponse) SetError(err error) {
r.Errors = make([]error, 1)
r.Errors[0] = err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/controller.go | registry/app/pkg/maven/controller.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maven
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
corestore "github.com/harness/gitness/app/store"
"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/quarantine"
"github.com/harness/gitness/registry/app/store"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
var _ Artifact = (*LocalRegistry)(nil)
var _ Artifact = (*RemoteRegistry)(nil)
type ArtifactType int
const (
LocalRegistryType ArtifactType = 1 << iota
RemoteRegistryType
)
var TypeRegistry = map[ArtifactType]Artifact{}
type Controller struct {
local *LocalRegistry
remote *RemoteRegistry
authorizer authz.Authorizer
DBStore *DBStore
_ dbtx.Transactor
SpaceFinder refcache.SpaceFinder
quarantineFinder quarantine.Finder
}
type DBStore struct {
RegistryDao store.RegistryRepository
ImageDao store.ImageRepository
ArtifactDao store.ArtifactRepository
SpaceStore corestore.SpaceStore
BandwidthStatDao store.BandwidthStatRepository
DownloadStatDao store.DownloadStatRepository
NodeDao store.NodesRepository
UpstreamProxyDao store.UpstreamProxyConfigRepository
}
func NewController(
local *LocalRegistry,
remote *RemoteRegistry,
authorizer authz.Authorizer,
dBStore *DBStore,
spaceFinder refcache.SpaceFinder,
quarantineFinder quarantine.Finder,
) *Controller {
c := &Controller{
local: local,
remote: remote,
authorizer: authorizer,
DBStore: dBStore,
SpaceFinder: spaceFinder,
quarantineFinder: quarantineFinder,
}
TypeRegistry[LocalRegistryType] = local
TypeRegistry[RemoteRegistryType] = remote
return c
}
func NewDBStore(
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
spaceStore corestore.SpaceStore,
bandwidthStatDao store.BandwidthStatRepository,
downloadStatDao store.DownloadStatRepository,
nodeDao store.NodesRepository,
upstreamProxyDao store.UpstreamProxyConfigRepository,
) *DBStore {
return &DBStore{
RegistryDao: registryDao,
SpaceStore: spaceStore,
ImageDao: imageDao,
ArtifactDao: artifactDao,
BandwidthStatDao: bandwidthStatDao,
DownloadStatDao: downloadStatDao,
NodeDao: nodeDao,
UpstreamProxyDao: upstreamProxyDao,
}
}
func (c *Controller) factory(ctx context.Context, t ArtifactType) Artifact {
switch t {
case LocalRegistryType:
return TypeRegistry[t]
case RemoteRegistryType:
return TypeRegistry[t]
default:
log.Ctx(ctx).Error().Stack().Msgf("Invalid artifact type %v", t)
return nil
}
}
func (c *Controller) GetArtifactRegistry(ctx context.Context, registry registrytypes.Registry) Artifact {
if string(registry.Type) == string(artifact.RegistryTypeVIRTUAL) {
return c.factory(ctx, LocalRegistryType)
}
return c.factory(ctx, RemoteRegistryType)
}
func (c *Controller) GetArtifact(ctx context.Context, info pkg.MavenArtifactInfo) *GetArtifactResponse {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return &GetArtifactResponse{
Errors: []error{errcode.ErrCodeDenied},
}
}
f := func(registry registrytypes.Registry, a Artifact) Response {
info.UpdateRegistryInfo(registry)
r, ok := a.(Registry)
if !ok {
log.Ctx(ctx).Error().Stack().Msgf("Proxy wrapper has invalid registry set")
return nil
}
err := c.quarantineFinder.CheckArtifactQuarantineStatus(ctx, registry.ID, info.Image, info.Version, nil)
if err != nil {
if errors.Is(err, usererror.ErrQuarantinedArtifact) {
return &GetArtifactResponse{
Errors: []error{err},
}
}
log.Ctx(ctx).Error().Stack().Err(err).Msgf("error "+
"while checking the quarantine status of artifact: [%s], version: [%s], %v",
info.Image, info.Version, err)
return &GetArtifactResponse{
Errors: []error{err},
}
}
headers, body, fileReader, redirectURL, e := r.GetArtifact(ctx, info) //nolint:errcheck
return &GetArtifactResponse{
e, headers, redirectURL,
body, fileReader,
}
}
result := c.ProxyWrapper(ctx, f, info)
getArtifactResponse, ok := result.(*GetArtifactResponse)
if !ok {
return &GetArtifactResponse{
[]error{fmt.Errorf("invalid response type: expected GetArtifactResponse")},
nil, "", nil, nil}
}
return getArtifactResponse
}
func (c *Controller) HeadArtifact(ctx context.Context, info pkg.MavenArtifactInfo) *HeadArtifactResponse {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsDownload)
if err != nil {
return &HeadArtifactResponse{
Errors: []error{errcode.ErrCodeDenied},
}
}
f := func(registry registrytypes.Registry, a Artifact) Response {
info.UpdateRegistryInfo(registry)
r, ok := a.(Registry)
if !ok {
log.Ctx(ctx).Error().Stack().Msgf("Proxy wrapper has invalid registry set")
return nil
}
headers, e := r.HeadArtifact(ctx, info)
return &HeadArtifactResponse{e, headers}
}
result := c.ProxyWrapper(ctx, f, info)
headArtifactResponse, ok := result.(*HeadArtifactResponse)
if !ok {
return &HeadArtifactResponse{
[]error{fmt.Errorf("invalid response type: expected HeadArtifactResponse")},
nil}
}
return headArtifactResponse
}
func (c *Controller) PutArtifact(
ctx context.Context,
info pkg.MavenArtifactInfo,
fileReader io.Reader,
) *PutArtifactResponse {
err := pkg.GetRegistryCheckAccess(ctx, c.authorizer, c.SpaceFinder, info.ParentID, *info.ArtifactInfo,
enum.PermissionArtifactsUpload)
if err != nil {
responseHeaders := &commons.ResponseHeaders{
Code: http.StatusForbidden,
}
return &PutArtifactResponse{
ResponseHeaders: responseHeaders,
Errors: []error{errcode.ErrCodeDenied},
}
}
responseHeaders, errs := c.local.PutArtifact(ctx, info, fileReader)
return &PutArtifactResponse{
ResponseHeaders: responseHeaders,
Errors: errs,
}
}
func (c *Controller) ProxyWrapper(
ctx context.Context,
f func(registry registrytypes.Registry, a Artifact) Response,
info pkg.MavenArtifactInfo,
) Response {
none := pkg.MavenArtifactInfo{}
if info == none {
log.Ctx(ctx).Error().Stack().Msg("artifactinfo is not found")
return nil
}
var response Response
requestRepoKey := info.RegIdentifier
if repos, err := c.GetOrderedRepos(ctx, requestRepoKey, *info.BaseInfo); err == nil {
for _, registry := range repos {
log.Ctx(ctx).Info().Msgf("Using Repository: %s, Type: %s", registry.Name, registry.Type)
artifact, ok := c.GetArtifactRegistry(ctx, registry).(Registry)
if !ok {
log.Ctx(ctx).Warn().Msgf("artifact %s is not a registry", registry.Name)
continue
}
if artifact != nil {
response = f(registry, artifact)
if pkg.IsEmpty(response.GetErrors()) {
return response
}
log.Ctx(ctx).Warn().Msgf("Repository: %s, Type: %s, errors: %v", registry.Name, registry.Type,
response.GetErrors())
}
}
}
return response
}
func (c *Controller) GetOrderedRepos(
ctx context.Context,
repoKey string,
artInfo pkg.BaseInfo,
) ([]registrytypes.Registry, error) {
var result []registrytypes.Registry
if registry, err := c.DBStore.RegistryDao.GetByParentIDAndName(ctx, artInfo.ParentID, repoKey); err == nil {
result = append(result, *registry)
proxies := registry.UpstreamProxies
if len(proxies) > 0 {
upstreamRepos, err := c.DBStore.RegistryDao.GetByIDIn(ctx, proxies)
if err != nil {
return result, err
}
result = append(result, *upstreamRepos...)
}
} else {
return result, err
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/artifact.go | registry/app/pkg/maven/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
type Artifact interface {
GetMavenArtifactType() string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/maven/utils/utils.go | registry/app/pkg/maven/utils/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"
"net/http"
"path/filepath"
"slices"
"strings"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/types"
)
const (
mavenMetadataFile = "maven-metadata.xml"
extensionXML = ".xml"
extensionMD5 = ".md5"
extensionSHA1 = ".sha1"
extensionSHA256 = ".sha256"
extensionSHA512 = ".sha512"
extensionPom = ".pom"
extensionJar = ".jar"
contentTypeJar = "application/java-archive"
contentTypeXML = "text/xml"
contentTypePlainText = "text/plain"
)
const (
Jar = ".jar"
War = ".war"
Ear = ".ear"
Zip = ".zip"
TarGz = ".tar.gz"
So = ".so"
Dll = ".dll"
Dylib = ".dylib"
Rpm = ".rpm"
Deb = ".deb"
Exe = ".exe"
)
var MainArtifactFileExtensions = []string{
Jar,
War,
Ear,
Zip,
TarGz,
So,
Dll,
Dylib,
Rpm,
Deb,
Exe,
}
func GetFilePath(info pkg.MavenArtifactInfo) string {
groupIDPath := strings.ReplaceAll(info.GroupID, ".", "/")
path := "/" + groupIDPath + "/" + info.ArtifactID
if info.Version != "" {
path += "/" + info.Version
}
return path + "/" + info.FileName
}
func IsMainArtifactFile(info pkg.MavenArtifactInfo) bool {
filePath := GetFilePath(info)
fileExtension := strings.ToLower(filepath.Ext(filePath))
return slices.Contains(MainArtifactFileExtensions, fileExtension)
}
func IsMetadataFile(filename string) bool {
return filename == mavenMetadataFile ||
filename == mavenMetadataFile+extensionMD5 ||
filename == mavenMetadataFile+extensionSHA1 ||
filename == mavenMetadataFile+extensionSHA256 ||
filename == mavenMetadataFile+extensionSHA512
}
func SetHeaders(
info pkg.MavenArtifactInfo,
fileInfo types.FileInfo,
) *commons.ResponseHeaders {
responseHeaders := &commons.ResponseHeaders{
Headers: map[string]string{},
Code: http.StatusOK,
}
filePath := GetFilePath(info)
ext := strings.ToLower(filepath.Ext(filePath))
responseHeaders.Code = http.StatusOK
responseHeaders.Headers["Content-Length"] = fmt.Sprintf("%d", fileInfo.Size)
responseHeaders.Headers["LastModified"] = fmt.Sprintf("%d", fileInfo.CreatedAt.Unix())
responseHeaders.Headers["FileName"] = fileInfo.Filename
switch ext {
case extensionJar:
responseHeaders.Headers["Content-Type"] = contentTypeJar
case extensionPom, extensionXML:
responseHeaders.Headers["Content-Type"] = contentTypeXML
case extensionMD5, extensionSHA1, extensionSHA256, extensionSHA512:
responseHeaders.Headers["Content-Type"] = contentTypePlainText
}
return responseHeaders
}
func IsSnapshotVersion(info pkg.MavenArtifactInfo) bool {
return strings.HasSuffix(info.Version, "-SNAPSHOT")
}
func AddLikeBeforeExtension(info pkg.MavenArtifactInfo) string {
filePath := GetFilePath(info)
ext := strings.ToLower(filepath.Ext(filePath))
extIndex := len(filePath) - len(ext)
return filePath[:extIndex] + "%" + ext
}
func ParseResponseHeaders(resp *http.Response) *commons.ResponseHeaders {
headers := make(map[string]string)
if resp.Header != nil {
for key, values := range resp.Header {
headers[key] = values[0]
}
}
return &commons.ResponseHeaders{
Headers: headers,
Code: 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/pkg/nuget/local.go | registry/app/pkg/nuget/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
urlprovider "github.com/harness/gitness/app/url"
apicontract "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
nugetmetadata "github.com/harness/gitness/registry/app/metadata/nuget"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
zs "github.com/harness/gitness/registry/app/pkg/commons/zipreader"
"github.com/harness/gitness/registry/app/pkg/filemanager"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
var IDMatch = regexp.MustCompile(`\A\w+(?:[.-]\w+)*\z`)
type FileBundleType int
const (
DependencyPackageExtension = ".nupkg"
SymbolsPackageExtension = ".snupkg"
)
const (
DependencyFile FileBundleType = iota + 1
SymbolsFile
)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
}
func (c *localRegistry) GetServiceEndpoint(
ctx context.Context,
info nugettype.ArtifactInfo,
) *nugettype.ServiceEndpoint {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
serviceEndpoints := buildServiceEndpoint(packageURL)
return serviceEndpoints
}
func (c *localRegistry) GetServiceEndpointV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) *nugettype.ServiceEndpointV2 {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
serviceEndpoints := buildServiceV2Endpoint(packageURL)
return serviceEndpoints
}
func (c *localRegistry) GetServiceMetadataV2(_ context.Context,
_ nugettype.ArtifactInfo) *nugettype.ServiceMetadataV2 {
return getServiceMetadataV2()
}
func (c *localRegistry) ListPackageVersion(
ctx context.Context,
info nugettype.ArtifactInfo,
) (response *nugettype.PackageVersion, err error) {
artifacts, err2 := c.artifactDao.GetByRegistryIDAndImage(ctx, info.RegistryID, info.Image)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
} else if artifacts == nil || len(*artifacts) == 0 {
return nil, fmt.Errorf(
"no artifacts found for registry: %d and image: %s", info.RegistryID, info.Image)
}
var versions []string
for _, artifact := range *artifacts {
versions = append(versions, artifact.Version)
}
return &nugettype.PackageVersion{
Versions: versions,
}, nil
}
func (c *localRegistry) ListPackageVersionV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (response *nugettype.FeedResponse, err error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
artifacts, err2 := c.artifactDao.GetByRegistryIDAndImage(ctx, info.RegistryID, info.Image)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
} else if artifacts == nil || len(*artifacts) == 0 {
return nil, fmt.Errorf(
"no artifacts found for registry: %d and image: %s", info.RegistryID, info.Image)
}
return createFeedResponse(packageURL, info, artifacts)
}
func (c *localRegistry) CountPackageVersionV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (count int64, err error) {
count, err = c.artifactDao.CountByImageName(ctx, info.RegistryID, info.Image)
if err != nil {
return 0, fmt.Errorf(
"failed to get artifacts count for registry: %d and image: %s: %w", info.RegistryID, info.Image, err)
}
return count, nil
}
func (c *localRegistry) CountPackageV2(ctx context.Context, info nugettype.ArtifactInfo,
searchTerm string) (count int64, err error) {
count, err = c.artifactDao.CountByImageName(ctx, info.RegistryID, strings.ToLower(searchTerm))
if err != nil {
return 0, fmt.Errorf(
"failed to get artifacts count for registry: %d and image: %s: %w", info.RegistryID, searchTerm, err)
}
return count, nil
}
func (c *localRegistry) SearchPackageV2(ctx context.Context, info nugettype.ArtifactInfo,
searchTerm string, limit int, offset int) (*nugettype.FeedResponse, error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
artifacts, err := c.artifactDao.SearchByImageName(ctx, info.RegistryID, strings.ToLower(searchTerm), limit, offset)
if err != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, searchTerm, err)
}
return createSearchV2Response(packageURL, artifacts, searchTerm, limit, offset)
}
func (c *localRegistry) SearchPackage(ctx context.Context,
info nugettype.ArtifactInfo,
searchTerm string, limit int, offset int) (*nugettype.SearchResultResponse, error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
artifacts, err := c.artifactDao.SearchByImageName(ctx, info.RegistryID, strings.ToLower(searchTerm), limit, offset)
if err != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, searchTerm, err)
}
count, err2 := c.artifactDao.CountByImageName(ctx, info.RegistryID, strings.ToLower(searchTerm))
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts count for registry: %d and image: %s: %w",
info.RegistryID, info.Image, err2)
}
return createSearchResponse(packageURL, artifacts, count)
}
func (c *localRegistry) GetPackageMetadata(
ctx context.Context,
info nugettype.ArtifactInfo,
) (nugettype.RegistrationResponse, error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
artifacts, err2 := c.artifactDao.GetByRegistryIDAndImage(ctx, info.RegistryID, info.Image)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
} else if artifacts == nil || len(*artifacts) == 0 {
return nil, fmt.Errorf(
"no artifacts found for registry: %d and image: %s", info.RegistryID, info.Image)
}
return createRegistrationIndexResponse(packageURL, info, artifacts)
}
func (c *localRegistry) GetPackageVersionMetadataV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*nugettype.FeedEntryResponse, error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
image, err2 := c.imageDao.GetByName(ctx, info.RegistryID, info.Image)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get image for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
}
artifact, err2 := c.artifactDao.GetByName(ctx, image.ID, info.Version)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
}
return createFeedEntryResponse(packageURL, info, artifact)
}
func (c *localRegistry) GetPackageVersionMetadata(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*nugettype.RegistrationLeafResponse, error) {
packageURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
image, err2 := c.imageDao.GetByName(ctx, info.RegistryID, info.Image)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get image for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
}
artifact, err2 := c.artifactDao.GetByName(ctx, image.ID, info.Version)
if err2 != nil {
return nil, fmt.Errorf(
"failed to get artifacts for registry: %d and image: %s: %w", info.RegistryID, info.Image, err2)
}
return createRegistrationLeafResponse(packageURL, info, artifact), nil
}
func (c *localRegistry) UploadPackage(
ctx context.Context, info nugettype.ArtifactInfo,
fileReader io.ReadCloser, fileBundleType FileBundleType,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
tmpFileName := info.RootIdentifier + "-" + uuid.NewString()
var fileExtension string
metadata := nugetmetadata.Metadata{}
fileInfo, tempFileName, err := c.fileManager.UploadTempFile(ctx, info.RootIdentifier,
nil, tmpFileName, fileReader)
if err != nil {
return headers, "", fmt.Errorf(
"failed to upload file: %s with registry: %d with error: %w", tmpFileName, info.RegistryID, err)
}
r, _, err := c.fileManager.DownloadTempFile(ctx, fileInfo.Size, tempFileName, info.RootIdentifier)
if err != nil {
return headers, "", fmt.Errorf(
"failed to download file: %s with registry: %d with error: %w", tempFileName,
info.RegistryID, err)
}
defer r.Close()
metadata, err = c.buildMetadata(r)
if err != nil {
return headers, "", fmt.Errorf(
"failed to build metadata for file: %s with registry: %d with error: %w", tempFileName,
info.RegistryID, err)
}
info.Image = strings.ToLower(metadata.PackageMetadata.ID)
info.Version = metadata.PackageMetadata.Version
normalisedVersion, err2 := validateAndNormaliseVersion(info.Version)
if err2 != nil {
return headers, "", fmt.Errorf("nuspec file contains an invalid version: %s with "+
"package name: %s, registry name: %s", info.Version, info.Image, info.RegIdentifier)
}
info.Version = normalisedVersion
info.Metadata = metadata
if fileBundleType == SymbolsFile {
versionExists, err3 := c.localBase.CheckIfVersionExists(ctx, info)
if err3 != nil {
return headers, "", fmt.Errorf(
"failed to check package version existence for id: %s , version: %s "+
"with registry: %d with error: %w", info.Image, info.Version, info.RegistryID, err)
} else if !versionExists {
return headers, "", fmt.Errorf(
"can't push symbol package as package doesn't exists for id: %s , version: %s "+
"with registry: %d with error: %w", info.Image, info.Version, info.RegistryID, err)
}
fileExtension = SymbolsPackageExtension
} else {
fileExtension = DependencyPackageExtension
}
fileName := strings.ToLower(fmt.Sprintf("%s.%s%s",
metadata.PackageMetadata.ID, metadata.PackageMetadata.Version, fileExtension))
info.Filename = fileName
fileInfo.Filename = fileName
var path string
if info.NestedPath != "" {
path = info.Image + "/" + info.Version + "/" + info.NestedPath + "/" + fileName
} else {
path = info.Image + "/" + info.Version + "/" + fileName
}
h, checkSum, _, _, err := c.localBase.MoveTempFileAndCreateArtifact(ctx, info.ArtifactInfo,
tempFileName, info.Version, path,
&nugetmetadata.NugetMetadata{
Metadata: info.Metadata,
}, fileInfo, false)
return h, checkSum, err
}
func (c *localRegistry) buildMetadata(fileReader io.Reader) (metadata nugetmetadata.Metadata, err error) {
var readme string
zr := zs.NewReader(fileReader)
for {
header, err2 := zr.Next()
if errors.Is(err2, io.EOF) {
break
}
if err2 != nil {
return metadata, fmt.Errorf("failed to read zip file with error: %w", err2)
}
if strings.HasSuffix(header.Name, ".nuspec") {
metadata, err = c.parseMetadata(zr)
if err != nil {
return metadata, fmt.Errorf("failed to parse metadata from .nuspec file: %w", err2)
}
} else if strings.HasSuffix(header.Name, "README.md") {
readme, err2 = c.parseReadme(zr)
if err2 != nil {
return metadata, fmt.Errorf("failed to parse metadata from README.md file: %w", err2)
}
}
}
if readme != "" {
metadata.PackageMetadata.Readme = readme
} else if metadata.PackageMetadata.Description != "" {
metadata.PackageMetadata.Readme = metadata.PackageMetadata.Description
}
return metadata, nil
}
func (c *localRegistry) parseMetadata(f io.Reader) (metadata nugetmetadata.Metadata, err error) {
var p nugetmetadata.Metadata
if err = xml.NewDecoder(f).Decode(&p); err != nil {
return metadata, fmt.Errorf("failed to parse .nuspec file with error: %w", err)
}
if !IDMatch.MatchString(p.PackageMetadata.ID) {
return metadata, fmt.Errorf("invalid package id: %s", p.PackageMetadata.ID)
}
return p, nil
}
func (c *localRegistry) parseReadme(f io.Reader) (readme string, err error) {
data, err := io.ReadAll(f)
if err != nil {
return "", err
}
return string(data), nil
}
func (c *localRegistry) DownloadPackage(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, string, io.ReadCloser, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
path, err := c.fileManager.FindLatestFilePath(ctx, info.RegistryID,
"/"+info.Image+"/"+info.Version, info.Filename)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to find file node for id: %s , version: %s "+
"with registry: %d with error: %v", info.Image, info.Version, info.RegistryID, err)
return responseHeaders, nil, "", nil, fmt.Errorf("failed to find file node for id: %s , version: %s "+
"with registry: %d with error: %w", info.Image, info.Version, info.RegistryID, err)
}
fileReader, size, redirectURL, err := c.fileManager.DownloadFile(ctx, path,
info.RegistryID,
info.RegIdentifier, info.RootIdentifier, true)
if err != nil {
return responseHeaders, nil, "", nil, err
}
responseHeaders.Code = http.StatusOK
responseHeaders.Headers["Content-Type"] = "application/octet-stream"
responseHeaders.Headers["Content-Length"] = strconv.FormatInt(size, 10)
return responseHeaders, fileReader, redirectURL, nil, nil
}
func (c *localRegistry) DeletePackage(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
err := c.localBase.DeleteVersion(ctx, info)
if err != nil {
return responseHeaders, fmt.Errorf("failed to delete package version with package: %s, version: %s and "+
"registry: %d with error: %w", info.Image, info.Version, info.RegistryID, err)
}
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
}
}
func (c *localRegistry) GetArtifactType() apicontract.RegistryType {
return apicontract.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []apicontract.PackageType {
return []apicontract.PackageType{apicontract.PackageTypeNUGET}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/nuget/wire.go | registry/app/pkg/nuget/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 nuget
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider)
base.Register(registry)
return registry
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
proxy := NewProxy(fileManager, proxyStore, tx, registryDao, imageDao, artifactDao, urlProvider,
spaceFinder, service, localRegistryHelper)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/nuget/proxy.go | registry/app/pkg/nuget/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"regexp"
"time"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"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/filemanager"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/remote/adapter/nuget" // This is required to init nuget adapter
)
const (
// XML namespace constants for NuGet feed responses.
xmlnsDataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlnsDataServicesMetadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
localRegistryHelper LocalRegistryHelper
}
func (r *proxy) UploadPackage(
ctx context.Context, _ nugettype.ArtifactInfo,
_ io.ReadCloser, _ FileBundleType,
) (*commons.ResponseHeaders, string, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) DownloadPackage(ctx context.Context, info nugettype.ArtifactInfo) (*commons.ResponseHeaders,
*storage.FileReader, string, io.ReadCloser, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, nil, "", nil, err
}
exists := r.localRegistryHelper.FileExists(ctx, info)
if exists {
headers, fileReader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, redirectURL, nil, nil
}
log.Warn().Ctx(ctx).Msgf("failed to pull from local, attempting streaming from remote, %v", err)
}
remote, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, nil, "", nil, err
}
file, err := remote.GetFile(ctx, info.Image, info.Version, info.ProxyEndpoint, info.Filename)
if err != nil {
return nil, nil, "", nil, err
}
go func(info nugettype.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = r.putFileToLocal(ctx2, &info, remote)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf("error while putting file to localRegistry, %v", err)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated file: %s, registry: %s", info.Filename, info.RegIdentifier)
}(info)
return nil, nil, "", file, nil
}
func (r *proxy) DeletePackage(
ctx context.Context,
_ nugettype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) CountPackageVersionV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (count int64, err error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return 0, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return 0, err
}
// Use the adapter's CountPackageVersionV2 method directly
count, err = helper.CountPackageVersionV2(ctx, info.Image)
if err != nil {
return 0, err
}
return count, nil
}
func (r *proxy) CountPackageV2(
ctx context.Context, info nugettype.ArtifactInfo,
searchTerm string,
) (count int64, err error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return 0, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return 0, err
}
// Use the adapter's CountPackageV2 method directly
count, err = helper.CountPackageV2(ctx, searchTerm)
if err != nil {
return 0, err
}
return count, nil
}
func (r *proxy) SearchPackageV2(
ctx context.Context, info nugettype.ArtifactInfo,
searchTerm string, limit int, offset int,
) (*nugettype.FeedResponse, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return &nugettype.FeedResponse{}, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return &nugettype.FeedResponse{}, err
}
fileReader, err := helper.SearchPackageV2(ctx, searchTerm, limit, offset)
if err != nil {
return &nugettype.FeedResponse{}, err
}
defer fileReader.Close()
var result nugettype.FeedResponse
if err = xml.NewDecoder(fileReader).Decode(&result); err != nil {
return &nugettype.FeedResponse{}, err
}
// Update URLs to point to our proxy, similar to ListPackageVersionV2
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
result.Xmlns = "http://www.w3.org/2005/Atom"
result.XmlnsD = xmlnsDataServices
result.XmlnsM = xmlnsDataServicesMetadata
result.Base = packageURL
result.ID = "http://schemas.datacontract.org/2004/07/"
result.Updated = time.Now()
links := []nugettype.FeedEntryLink{
{Rel: "self", Href: xml.CharData(packageURL)},
}
result.Links = links
// Update each entry's content URLs to point to our proxy
for _, entry := range result.Entries {
re := regexp.MustCompile(`Version='([^']+)'`)
matches := re.FindStringSubmatch(entry.ID)
if len(matches) > 1 {
version := matches[1]
err = modifyContent(entry, packageURL, info.Image, version)
if err != nil {
return &nugettype.FeedResponse{}, fmt.Errorf("failed to modify content: %w", err)
}
}
}
return &result, nil
}
func (r *proxy) SearchPackage(
ctx context.Context, info nugettype.ArtifactInfo,
searchTerm string, limit int, offset int,
) (*nugettype.SearchResultResponse, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, err
}
// Use the v3 search API directly
fileReader, err := helper.SearchPackage(ctx, searchTerm, limit, offset)
if err != nil {
return nil, err
}
defer fileReader.Close()
// Parse the v3 search response directly
var result nugettype.SearchResultResponse
if err = json.NewDecoder(fileReader).Decode(&result); err != nil {
return nil, err
}
// Update URLs in search results to point to our proxy
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
for _, searchResult := range result.Data {
if searchResult != nil {
// Update RegistrationIndexURL to point to our proxy
if searchResult.RegistrationIndexURL != "" {
registrationURL := getRegistrationIndexURL(packageURL, searchResult.ID)
searchResult.RegistrationIndexURL = registrationURL
}
// Update RegistrationLeafURL in versions to point to our proxy
for _, version := range searchResult.Versions {
if version != nil && version.RegistrationLeafURL != "" {
registrationURL := getRegistrationIndexURL(packageURL, searchResult.ID)
version.RegistrationLeafURL = getProxyURL(registrationURL, version.RegistrationLeafURL)
}
}
}
}
return &result, nil
}
func (r *proxy) ListPackageVersion(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*nugettype.PackageVersion, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return &nugettype.PackageVersion{}, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return &nugettype.PackageVersion{}, err
}
fileReader, err := helper.ListPackageVersion(ctx, info.Image)
if err != nil {
return &nugettype.PackageVersion{}, err
}
var result nugettype.PackageVersion
if err = json.NewDecoder(fileReader).Decode(&result); err != nil {
return &nugettype.PackageVersion{}, err
}
return &result, nil
}
func (r *proxy) GetPackageMetadata(
ctx context.Context,
info nugettype.ArtifactInfo,
) (nugettype.RegistrationResponse, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return &nugettype.RegistrationIndexResponse{}, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return &nugettype.RegistrationIndexResponse{}, err
}
fileReader, err := helper.GetPackageMetadata(ctx, info.Image, info.ProxyEndpoint)
if err != nil {
return &nugettype.RegistrationIndexResponse{}, err
}
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
if info.ProxyEndpoint != "" {
metadata, err2 := parseRegistrationIndexPageResponse(fileReader)
if err2 != nil {
//todo: add handling for registration leaf
return &nugettype.RegistrationIndexPageResponse{}, err
}
updateRegistrationIndexPageResponse(metadata, packageURL, info.Image)
return metadata, nil
}
metadata, err2 := parseRegistrationIndexResponse(fileReader)
if err2 != nil {
return &nugettype.RegistrationIndexResponse{}, err
}
updateRegistrationIndexResponse(metadata, packageURL, info.Image)
return metadata, nil
}
func (r *proxy) ListPackageVersionV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*nugettype.FeedResponse, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return &nugettype.FeedResponse{}, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return &nugettype.FeedResponse{}, err
}
fileReader, err := helper.ListPackageVersionV2(ctx, info.Image)
if err != nil {
return &nugettype.FeedResponse{}, err
}
var result nugettype.FeedResponse
if err = xml.NewDecoder(fileReader).Decode(&result); err != nil {
return &nugettype.FeedResponse{}, err
}
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
result.Xmlns = "http://www.w3.org/2005/Atom"
result.XmlnsD = xmlnsDataServices
result.XmlnsM = xmlnsDataServicesMetadata
result.Base = packageURL
result.ID = "http://schemas.datacontract.org/2004/07/"
result.Updated = time.Now()
links := []nugettype.FeedEntryLink{
{Rel: "self", Href: xml.CharData(packageURL)},
}
result.Links = links
for _, entry := range result.Entries {
re := regexp.MustCompile(`Version='([^']+)'`)
matches := re.FindStringSubmatch(entry.ID)
if len(matches) > 1 {
version := matches[1]
err = modifyContent(entry, packageURL, info.Image, version)
if err != nil {
return &nugettype.FeedResponse{}, fmt.Errorf("failed to modify content: %w", err)
}
}
}
return &result, nil
}
func (r *proxy) GetPackageVersionMetadataV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) (*nugettype.FeedEntryResponse, error) {
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return &nugettype.FeedEntryResponse{}, err
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return &nugettype.FeedEntryResponse{}, err
}
fileReader, err := helper.GetPackageVersionMetadataV2(ctx, info.Image, info.Version)
if err != nil {
return &nugettype.FeedEntryResponse{}, err
}
var result nugettype.FeedEntryResponse
if err = xml.NewDecoder(fileReader).Decode(&result); err != nil {
return &nugettype.FeedEntryResponse{}, err
}
result.XmlnsD = xmlnsDataServices
result.XmlnsM = xmlnsDataServicesMetadata
err = modifyContent(&result, packageURL, info.Image, info.Version)
if err != nil {
return &nugettype.FeedEntryResponse{}, fmt.Errorf("failed to modify content: %w", err)
}
return &result, nil
}
func parseRegistrationIndexResponse(r io.ReadCloser) (*nugettype.RegistrationIndexResponse, error) {
var result nugettype.RegistrationIndexResponse
if err := json.NewDecoder(r).Decode(&result); err != nil {
return &nugettype.RegistrationIndexResponse{}, err
}
return &result, nil
}
func parseRegistrationIndexPageResponse(r io.ReadCloser) (*nugettype.RegistrationIndexPageResponse, error) {
var result nugettype.RegistrationIndexPageResponse
if err := json.NewDecoder(r).Decode(&result); err != nil {
return &nugettype.RegistrationIndexPageResponse{}, err
}
return &result, nil
}
func updateRegistrationIndexPageResponse(r *nugettype.RegistrationIndexPageResponse, packageURL, pkg string) {
registrationURL := getRegistrationIndexURL(packageURL, pkg)
if r.RegistrationPageURL != "" {
r.RegistrationPageURL = getProxyURL(registrationURL, r.RegistrationPageURL)
}
for _, item := range r.Items {
if item.RegistrationLeafURL != "" {
item.RegistrationLeafURL = getProxyURL(registrationURL, item.RegistrationLeafURL)
}
if item.CatalogEntry != nil {
packageContentURL := getPackageDownloadURL(packageURL, pkg, item.CatalogEntry.Version)
item.PackageContentURL = packageContentURL
item.CatalogEntry.PackageContentURL = item.PackageContentURL
}
}
}
func updateRegistrationIndexResponse(r *nugettype.RegistrationIndexResponse, packageURL, pkg string) {
registrationURL := getRegistrationIndexURL(packageURL, pkg)
if r.RegistrationIndexURL != "" {
r.RegistrationIndexURL = registrationURL
}
for _, page := range r.Pages {
updateRegistrationIndexPageResponse(page, packageURL, pkg)
}
}
func (r *proxy) GetPackageVersionMetadata(
ctx context.Context,
_ nugettype.ArtifactInfo,
) (*nugettype.RegistrationLeafResponse, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) GetServiceEndpoint(ctx context.Context, info nugettype.ArtifactInfo) *nugettype.ServiceEndpoint {
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
serviceEndpoints := buildServiceEndpoint(packageURL)
return serviceEndpoints
}
func (r *proxy) GetServiceEndpointV2(
ctx context.Context,
info nugettype.ArtifactInfo,
) *nugettype.ServiceEndpointV2 {
packageURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget")
serviceEndpoints := buildServiceV2Endpoint(packageURL)
return serviceEndpoints
}
func (r *proxy) GetServiceMetadataV2(_ context.Context, _ nugettype.ArtifactInfo) *nugettype.ServiceMetadataV2 {
return getServiceMetadataV2()
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
return &proxy{
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
localRegistryHelper: localRegistryHelper,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeNUGET}
}
func (r *proxy) putFileToLocal(
ctx context.Context, info *nugettype.ArtifactInfo,
remote RemoteRegistryHelper,
) error {
file, err := remote.GetFile(ctx, info.Image, info.Version, info.ProxyEndpoint, info.Filename)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("fetching file for pkg: %s failed, %v", info.Image, err)
return err
}
defer file.Close()
_, sha256, err2 := r.localRegistryHelper.UploadPackageFile(ctx, *info, file)
if err2 != nil {
log.Ctx(ctx).Error().Stack().Err(err2).Msgf("uploading file for pkg: %s failed, %v", info.Image, err)
return err2
}
log.Ctx(ctx).Info().Msgf("Successfully uploaded file for pkg: %s , version: %s with SHA256: %s",
info.Image, info.Version, sha256)
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/pkg/nuget/registry.go | registry/app/pkg/nuget/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
pkg.Artifact
UploadPackage(ctx context.Context, info nuget.ArtifactInfo, fileReader io.ReadCloser,
fileBundleType FileBundleType) (*commons.ResponseHeaders, string, error)
DownloadPackage(ctx context.Context, info nuget.ArtifactInfo) (*commons.ResponseHeaders,
*storage.FileReader, string, io.ReadCloser, error)
DeletePackage(ctx context.Context, info nuget.ArtifactInfo) (*commons.ResponseHeaders, error)
ListPackageVersion(ctx context.Context, info nuget.ArtifactInfo) (*nuget.PackageVersion, error)
ListPackageVersionV2(ctx context.Context, info nuget.ArtifactInfo) (*nuget.FeedResponse, error)
CountPackageVersionV2(ctx context.Context, info nuget.ArtifactInfo) (int64, error)
SearchPackageV2(ctx context.Context, info nuget.ArtifactInfo,
searchTerm string, limit int, offset int) (*nuget.FeedResponse, error)
SearchPackage(ctx context.Context, info nuget.ArtifactInfo,
searchTerm string, limit int, offset int) (*nuget.SearchResultResponse, error)
CountPackageV2(ctx context.Context, info nuget.ArtifactInfo, searchTerm string) (int64, error)
GetPackageMetadata(ctx context.Context, info nuget.ArtifactInfo) (nuget.RegistrationResponse, error)
GetPackageVersionMetadataV2(ctx context.Context, info nuget.ArtifactInfo) (*nuget.FeedEntryResponse, error)
GetPackageVersionMetadata(ctx context.Context, info nuget.ArtifactInfo) (*nuget.RegistrationLeafResponse, error)
GetServiceEndpoint(ctx context.Context, info nuget.ArtifactInfo) *nuget.ServiceEndpoint
GetServiceEndpointV2(ctx context.Context, info nuget.ArtifactInfo) *nuget.ServiceEndpointV2
GetServiceMetadataV2(ctx context.Context, info nuget.ArtifactInfo) *nuget.ServiceMetadataV2
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/nuget/helper.go | registry/app/pkg/nuget/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 nuget
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
nugetmetadata "github.com/harness/gitness/registry/app/metadata/nuget"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/types"
)
// XML namespace constants.
const (
XMLNamespaceApp = "http://www.w3.org/2007/app"
XMLNamespaceAtom = "http://www.w3.org/2005/Atom"
XMLNamespaceDataContract = "http://schemas.datacontract.org/2004/07/"
XMLNamespaceDataServicesMetadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
XMLNamespaceDataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"
XMLNamespaceEdmx = "http://schemas.microsoft.com/ado/2007/06/edmx"
)
var semverRegexp = regexp.MustCompile("^" + SemverRegexpRaw + "$")
const SemverRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` +
`(-([0-9]+[0-9A-Za-z\-]*(\.[0-9A-Za-z\-]+)*)|(-([A-Za-z\-]+[0-9A-Za-z\-]*(\.[0-9A-Za-z\-]+)*)))?` +
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
`?`
func buildServiceEndpoint(baseURL string) *nuget.ServiceEndpoint {
return &nuget.ServiceEndpoint{
Version: "3.0.0",
Resources: []nuget.Resource{
{
ID: baseURL + "/query",
Type: "SearchQueryService",
},
{
ID: baseURL + "/registration",
Type: "RegistrationsBaseUrl",
},
{
ID: baseURL + "/package",
Type: "PackageBaseAddress/3.0.0",
},
{
ID: baseURL,
Type: "PackagePublish/2.0.0",
},
{
ID: baseURL + "/symbolpackage",
Type: "SymbolPackagePublish/4.9.0",
},
{
ID: baseURL + "/query",
Type: "SearchQueryService/3.0.0-rc",
},
{
ID: baseURL + "/registration",
Type: "RegistrationsBaseUrl/3.0.0-rc",
},
{
ID: baseURL + "/query",
Type: "SearchQueryService/3.0.0-beta",
},
{
ID: baseURL + "/registration",
Type: "RegistrationsBaseUrl/3.0.0-beta",
},
},
}
}
func buildServiceV2Endpoint(baseURL string) *nuget.ServiceEndpointV2 {
return &nuget.ServiceEndpointV2{
Base: baseURL,
Xmlns: XMLNamespaceApp,
XmlnsAtom: XMLNamespaceAtom,
Workspace: nuget.ServiceWorkspace{
Title: nuget.AtomTitle{
Type: "text",
Text: "Default",
},
Collection: nuget.ServiceCollection{
Href: "Packages",
Title: nuget.AtomTitle{
Type: "text",
Text: "Packages",
},
},
},
}
}
// getRegistrationIndexURL builds the registration index url.
func getRegistrationIndexURL(baseURL, id string) string {
return fmt.Sprintf("%s/registration/%s/index.json", baseURL, id)
}
// getRegistrationLeafURL builds the registration leaf url.
func getRegistrationLeafURL(baseURL, id, version string) string {
return fmt.Sprintf("%s/registration/%s/%s.json", baseURL, id, version)
}
// getPackageDownloadURL builds the download url.
func getPackageDownloadURL(baseURL, id, version string) string {
return fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", baseURL, id, version, id, version)
}
// GetPackageMetadataURL builds the package metadata url.
func getPackageMetadataURL(baseURL, id, version string) string {
return fmt.Sprintf("%s/Packages(Id='%s',Version='%s')", baseURL, id, version)
}
func getProxyURL(baseURL, proxyEndpoint string) string {
return fmt.Sprintf("%s?proxy_endpoint=%s", baseURL, proxyEndpoint)
}
func getInnerXMLField(baseURL, id, version string) string {
packageMetadataURL := getPackageMetadataURL(baseURL, id, version)
packageDownloadURL := getPackageDownloadURL(baseURL, id, version)
return fmt.Sprintf(`<id>%s</id>
<content type="application/zip" src="%s"/>
<link rel="edit" href="%s"/>
<link rel="edit" href="%s"/>`,
packageMetadataURL, packageDownloadURL,
packageMetadataURL, packageMetadataURL)
}
// https://learn.microsoft.com/en-us/nuget/concepts/package-versioning#normalized-version-numbers
// https://github.com/NuGet/NuGet.Client/blob/dccbd304b11103e08b97abf4cf4bcc1499d9235a/
// src/NuGet.Core/NuGet.Versioning/VersionFormatter.cs#L121.
func validateAndNormaliseVersion(v string) (string, error) {
matches := semverRegexp.FindStringSubmatch(v)
if matches == nil {
return "", fmt.Errorf("malformed version: %s", v)
}
segmentsStr := strings.Split(matches[1], ".")
if len(segmentsStr) > 4 {
return "", fmt.Errorf("malformed version: %s", v)
}
segments := make([]int64, len(segmentsStr))
for i, str := range segmentsStr {
val, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return "", fmt.Errorf(
"error parsing version: %w", err)
}
segments[i] = val
}
// Even though we could support more than three segments, if we
// got less than three, pad it with 0s. This is to cover the basic
// default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum
for i := len(segments); i < 3; i++ {
//nolint:makezero
segments = append(segments, 0)
}
normalizedVersion := fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2])
if len(segments) > 3 && segments[3] > 0 {
normalizedVersion = fmt.Sprintf("%s.%d", normalizedVersion, segments[3])
}
if len(matches) > 3 && matches[3] != "" {
normalizedVersion = fmt.Sprintf("%s%s", normalizedVersion, matches[3])
}
return normalizedVersion, nil
}
func createRegistrationIndexResponse(baseURL string, info nuget.ArtifactInfo, artifacts *[]types.Artifact) (
*nuget.RegistrationIndexResponse, error) {
sort.Slice(*artifacts, func(i, j int) bool {
return (*artifacts)[i].Version < (*artifacts)[j].Version
})
items := make([]*nuget.RegistrationIndexPageItem, 0, len(*artifacts))
for _, p := range *artifacts {
registrationItem, err := createRegistrationIndexPageItem(baseURL, info, &p)
if err != nil {
return nil, fmt.Errorf("error creating registration index page item: %w", err)
}
items = append(items, registrationItem)
}
return &nuget.RegistrationIndexResponse{
RegistrationIndexURL: getRegistrationIndexURL(baseURL, info.Image),
Count: 1,
Pages: []*nuget.RegistrationIndexPageResponse{
{
RegistrationPageURL: getRegistrationIndexURL(baseURL, info.Image),
Count: len(*artifacts),
Lower: (*artifacts)[0].Version,
Upper: (*artifacts)[len(*artifacts)-1].Version,
Items: items,
},
},
}, nil
}
func createSearchV2Response(baseURL string, artifacts *[]types.ArtifactMetadata,
searchTerm string, limit int, offset int) (
*nuget.FeedResponse, error) {
links := []nuget.FeedEntryLink{
{Rel: "self", Href: xml.CharData(baseURL)},
}
if artifacts == nil || len(*artifacts) == 0 {
return &nuget.FeedResponse{
Xmlns: XMLNamespaceAtom,
Base: baseURL,
XmlnsD: XMLNamespaceDataServices,
XmlnsM: XMLNamespaceDataServicesMetadata,
ID: XMLNamespaceDataContract,
Updated: time.Now(),
Links: links,
Count: 0,
}, nil
}
nextURL := ""
if len(*artifacts) == limit {
u, _ := url.Parse(baseURL)
u = u.JoinPath("Search()")
q := u.Query()
q.Add("$skip", strconv.Itoa(limit+offset))
q.Add("$top", strconv.Itoa(limit))
if searchTerm != "" {
q.Add("searchTerm", searchTerm)
}
u.RawQuery = q.Encode()
nextURL = u.String()
}
if nextURL != "" {
links = append(links, nuget.FeedEntryLink{
Rel: "next",
Href: xml.CharData(nextURL),
})
}
entries := make([]*nuget.FeedEntryResponse, 0, len(*artifacts))
for _, p := range *artifacts {
feedEntry, err := createFeedEntryResponse(baseURL,
nuget.ArtifactInfo{ArtifactInfo: pkg.ArtifactInfo{Image: p.Name}},
&types.Artifact{Version: p.Version, CreatedAt: p.CreatedAt, Metadata: p.Metadata, UpdatedAt: p.ModifiedAt})
if err != nil {
return nil, fmt.Errorf("error creating feed entry: %w", err)
}
entries = append(entries, feedEntry)
}
return &nuget.FeedResponse{
Xmlns: XMLNamespaceAtom,
Base: baseURL,
XmlnsD: XMLNamespaceDataServices,
XmlnsM: XMLNamespaceDataServicesMetadata,
ID: XMLNamespaceDataContract,
Updated: time.Now(),
Links: links,
Count: int64(len(*artifacts)),
Entries: entries,
}, nil
}
func createSearchResponse(baseURL string, artifacts *[]types.ArtifactMetadata, totalHits int64) (
*nuget.SearchResultResponse, error) {
if artifacts == nil || len(*artifacts) == 0 {
return &nuget.SearchResultResponse{
TotalHits: totalHits,
}, nil
}
var items []*nuget.SearchResult
currentArtifact := ""
for i := 0; i < len(*artifacts); i++ {
if currentArtifact != (*artifacts)[i].Name {
currentArtifact = (*artifacts)[i].Name
searchResultItem, err := createSearchResultItem(baseURL, artifacts, currentArtifact, i)
if err != nil {
return nil, fmt.Errorf("error creating search result page item: %w", err)
}
items = append(items, searchResultItem)
}
}
return &nuget.SearchResultResponse{
TotalHits: totalHits,
Data: items,
}, nil
}
func createSearchResultItem(baseURL string, artifacts *[]types.ArtifactMetadata,
currentArtifact string, key int) (
*nuget.SearchResult, error) {
var items []*nuget.SearchResultVersion
searchArtifact := &nuget.SearchResult{
ID: currentArtifact,
RegistrationIndexURL: getRegistrationIndexURL(baseURL, currentArtifact),
Versions: items,
}
for i := key; i < len(*artifacts); i++ {
searchVersion := &nuget.SearchResultVersion{
Version: (*artifacts)[i].Version,
RegistrationLeafURL: getRegistrationLeafURL(baseURL, (*artifacts)[i].Name, (*artifacts)[i].Version),
}
if (*artifacts)[i].Name != currentArtifact ||
((*artifacts)[i].Name == currentArtifact && i == len(*artifacts)-1) {
artifactMetadata := &nugetmetadata.NugetMetadata{}
j := i - 1
if (*artifacts)[i].Name == currentArtifact && i == len(*artifacts)-1 {
items = append(items, searchVersion)
j = i
}
err := json.Unmarshal((*artifacts)[j].Metadata, artifactMetadata)
if err != nil {
return nil, fmt.Errorf("error unmarshalling nuget metadata: %w", err)
}
searchArtifact.Description = artifactMetadata.PackageMetadata.Description
searchArtifact.Authors = []string{artifactMetadata.PackageMetadata.Authors}
searchArtifact.ProjectURL = artifactMetadata.PackageMetadata.ProjectURL
searchArtifact.Version = (*artifacts)[j].Version
searchArtifact.Versions = items
return searchArtifact, nil
}
items = append(items, searchVersion)
}
return searchArtifact, nil
}
func modifyContent(feed *nuget.FeedEntryResponse, packageURL, pkg, version string) error {
updatedID, err := replaceBaseWithURL(feed.ID, packageURL)
if err != nil {
return fmt.Errorf("error replacing base url: %w", err)
}
feed.Content = strings.ReplaceAll(feed.Content, feed.ID, updatedID)
feed.Content = strings.ReplaceAll(feed.Content, feed.DownloadContent.Source,
getProxyURL(getPackageDownloadURL(packageURL, pkg, version), feed.DownloadContent.Source))
feed.ID = ""
feed.DownloadContent = nil
return nil
}
func replaceBaseWithURL(input, baseURL string) (string, error) {
// The input is not a pure URL — it has extra after the path,
// so we first find the index of "/Packages"
// assuming the path always starts with "/Packages"
const marker = "/Packages"
idx := strings.Index(input, marker)
if idx == -1 {
return "", fmt.Errorf("cannot find %q in input", marker)
}
base := input[:idx] // the base URL part, e.g. "https://www.nuget.org/api/v2"
path := input[idx:] // the rest starting from "/Packages..."
// Verify base is a valid URL:
_, err := url.ParseRequestURI(base)
if err != nil {
return "", fmt.Errorf("invalid base URL: %w", err)
}
// Return with base replaced by "url"
return baseURL + path, nil
}
func getServiceMetadataV2() *nuget.ServiceMetadataV2 {
return &nuget.ServiceMetadataV2{
XmlnsEdmx: XMLNamespaceEdmx,
Version: "1.0",
DataServices: nuget.EdmxDataServices{
XmlnsM: XMLNamespaceDataServicesMetadata,
DataServiceVersion: "2.0",
MaxDataServiceVersion: "2.0",
Schema: []nuget.EdmxSchema{
{
Xmlns: "http://schemas.microsoft.com/ado/2006/04/edm",
Namespace: "NuGetGallery.OData",
EntityType: &nuget.EdmxEntityType{
Name: "V2FeedPackage",
HasStream: true,
Keys: []nuget.EdmxPropertyRef{
{Name: "Id"},
{Name: "Version"},
},
Properties: []nuget.EdmxProperty{
{
Name: "Id",
Type: "Edm.String",
},
{
Name: "Version",
Type: "Edm.String",
},
{
Name: "NormalizedVersion",
Type: "Edm.String",
Nullable: true,
},
{
Name: "Authors",
Type: "Edm.String",
Nullable: true,
},
{
Name: "Created",
Type: "Edm.DateTime",
},
{
Name: "Dependencies",
Type: "Edm.String",
},
{
Name: "Description",
Type: "Edm.String",
},
{
Name: "DownloadCount",
Type: "Edm.Int64",
},
{
Name: "LastUpdated",
Type: "Edm.DateTime",
},
{
Name: "Published",
Type: "Edm.DateTime",
},
{
Name: "PackageSize",
Type: "Edm.Int64",
},
{
Name: "ProjectUrl",
Type: "Edm.String",
Nullable: true,
},
{
Name: "ReleaseNotes",
Type: "Edm.String",
Nullable: true,
},
{
Name: "RequireLicenseAcceptance",
Type: "Edm.Boolean",
Nullable: false,
},
{
Name: "Title",
Type: "Edm.String",
Nullable: true,
},
{
Name: "VersionDownloadCount",
Type: "Edm.Int64",
Nullable: false,
},
},
},
},
{
Xmlns: "http://schemas.microsoft.com/ado/2006/04/edm",
Namespace: "NuGetGallery",
EntityContainer: &nuget.EdmxEntityContainer{
Name: "V2FeedContext",
IsDefaultEntityContainer: true,
EntitySet: nuget.EdmxEntitySet{
Name: "Packages",
EntityType: "NuGetGallery.OData.V2FeedPackage",
},
FunctionImports: []nuget.EdmxFunctionImport{
{
Name: "Search",
ReturnType: "Collection(NuGetGallery.OData.V2FeedPackage)",
EntitySet: "Packages",
Parameter: []nuget.EdmxFunctionParameter{
{
Name: "searchTerm",
Type: "Edm.String",
},
},
},
{
Name: "FindPackagesById",
ReturnType: "Collection(NuGetGallery.OData.V2FeedPackage)",
EntitySet: "Packages",
Parameter: []nuget.EdmxFunctionParameter{
{
Name: "id",
Type: "Edm.String",
},
},
},
},
},
},
},
},
}
}
func createFeedResponse(baseURL string, info nuget.ArtifactInfo,
artifacts *[]types.Artifact) (*nuget.FeedResponse, error) {
sort.Slice(*artifacts, func(i, j int) bool {
return (*artifacts)[i].Version < (*artifacts)[j].Version
})
links := []nuget.FeedEntryLink{
{Rel: "self", Href: xml.CharData(baseURL)},
}
entries := make([]*nuget.FeedEntryResponse, 0, len(*artifacts))
for _, p := range *artifacts {
feedEntry, err := createFeedEntryResponse(baseURL, info, &p)
if err != nil {
return nil, fmt.Errorf("error creating feed entry: %w", err)
}
entries = append(entries, feedEntry)
}
return &nuget.FeedResponse{
Xmlns: XMLNamespaceAtom,
Base: baseURL,
XmlnsD: XMLNamespaceDataServices,
XmlnsM: XMLNamespaceDataServicesMetadata,
ID: XMLNamespaceDataContract,
Updated: time.Now(),
Links: links,
Count: int64(len(*artifacts)),
Entries: entries,
}, nil
}
func createFeedEntryResponse(baseURL string, info nuget.ArtifactInfo, artifact *types.Artifact) (
*nuget.FeedEntryResponse, error) {
metadata := &nugetmetadata.NugetMetadata{}
err := json.Unmarshal(artifact.Metadata, metadata)
if err != nil {
return nil, fmt.Errorf("error unmarshalling nuget metadata: %w", err)
}
content := getInnerXMLField(baseURL, info.Image, artifact.Version)
createdValue := nuget.TypedValue[time.Time]{
Type: "Edm.DateTime",
Value: artifact.CreatedAt,
}
return &nuget.FeedEntryResponse{
Xmlns: XMLNamespaceAtom,
Base: baseURL,
XmlnsD: XMLNamespaceDataServices,
XmlnsM: XMLNamespaceDataServicesMetadata,
Category: nuget.FeedEntryCategory{Term: "NuGetGallery.OData.V2FeedPackage",
Scheme: "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"},
Title: nuget.TypedValue[string]{Type: "text", Value: info.Image},
Updated: artifact.UpdatedAt,
Author: metadata.PackageMetadata.Authors,
Content: content,
Properties: &nuget.FeedEntryProperties{
ID: info.Image,
Version: artifact.Version,
NormalizedVersion: artifact.Version,
Authors: metadata.PackageMetadata.Authors,
Dependencies: buildDependencyString(metadata),
Description: metadata.PackageMetadata.Description,
VersionDownloadCount: nuget.TypedValue[int64]{Type: "Edm.Int64", Value: 0}, //todo: fix this download count
DownloadCount: nuget.TypedValue[int64]{Type: "Edm.Int64", Value: 0},
PackageSize: nuget.TypedValue[int64]{Type: "Edm.Int64", Value: metadata.Size},
Created: createdValue,
LastUpdated: createdValue,
Published: createdValue,
ProjectURL: metadata.PackageMetadata.ProjectURL,
ReleaseNotes: metadata.PackageMetadata.ReleaseNotes,
RequireLicenseAcceptance: nuget.TypedValue[bool]{Type: "Edm.Boolean",
Value: metadata.PackageMetadata.RequireLicenseAcceptance},
Title: info.Image,
},
}, nil
}
func buildDependencyString(metadata *nugetmetadata.NugetMetadata) string {
var b strings.Builder
first := true
if metadata.PackageMetadata.Dependencies == nil || metadata.PackageMetadata.Dependencies.Groups == nil {
return ""
}
for _, deps := range metadata.PackageMetadata.Dependencies.Groups {
for _, dep := range deps.Dependencies {
if !first {
b.WriteByte('|')
}
first = false
b.WriteString(dep.ID)
b.WriteByte(':')
b.WriteString(dep.Version)
b.WriteByte(':')
b.WriteString(deps.TargetFramework)
}
}
return b.String()
}
func createRegistrationLeafResponse(baseURL string, info nuget.ArtifactInfo,
artifact *types.Artifact) *nuget.RegistrationLeafResponse {
return &nuget.RegistrationLeafResponse{
Type: []string{"Package", "http://schema.nuget.org/catalog#Permalink"},
Listed: true,
Published: artifact.CreatedAt,
RegistrationLeafURL: getRegistrationLeafURL(baseURL, info.Image, info.Version),
PackageContentURL: getPackageDownloadURL(baseURL, info.Image, info.Version),
RegistrationIndexURL: getRegistrationIndexURL(baseURL, info.Image),
}
}
func createRegistrationIndexPageItem(baseURL string, info nuget.ArtifactInfo, artifact *types.Artifact) (
*nuget.RegistrationIndexPageItem, error) {
metadata := &nugetmetadata.NugetMetadata{}
err := json.Unmarshal(artifact.Metadata, metadata)
if err != nil {
return nil, fmt.Errorf("error unmarshalling nuget metadata: %w", err)
}
res := &nuget.RegistrationIndexPageItem{
RegistrationLeafURL: getRegistrationLeafURL(baseURL, info.Image, artifact.Version),
PackageContentURL: getPackageDownloadURL(baseURL, info.Image, artifact.Version),
CatalogEntry: &nuget.CatalogEntry{
CatalogLeafURL: getRegistrationLeafURL(baseURL, info.Image, artifact.Version),
PackageContentURL: getPackageDownloadURL(baseURL, info.Image, artifact.Version),
ID: info.Image,
Version: artifact.Version,
Description: metadata.PackageMetadata.Description,
ReleaseNotes: metadata.PackageMetadata.ReleaseNotes,
Authors: metadata.PackageMetadata.Authors,
ProjectURL: metadata.PackageMetadata.ProjectURL,
DependencyGroups: createDependencyGroups(metadata),
},
}
dependencyGroups := createDependencyGroups(metadata)
res.CatalogEntry.DependencyGroups = dependencyGroups
return res, nil
}
func createDependencyGroups(metadata *nugetmetadata.NugetMetadata) []*nuget.PackageDependencyGroup {
if metadata.PackageMetadata.Dependencies == nil {
return nil
}
dependencyGroups := make([]*nuget.PackageDependencyGroup, 0,
len(metadata.PackageMetadata.Dependencies.Groups))
for _, group := range metadata.Metadata.PackageMetadata.Dependencies.Groups {
deps := make([]*nuget.PackageDependency, 0, len(group.Dependencies))
for _, dep := range group.Dependencies {
if dep.ID == "" || dep.Version == "" {
continue
}
deps = append(deps, &nuget.PackageDependency{
ID: dep.ID,
Range: dep.Version,
})
}
if len(deps) > 0 {
dependencyGroups = append(dependencyGroups, &nuget.PackageDependencyGroup{
TargetFramework: group.TargetFramework,
Dependencies: deps,
})
}
}
return dependencyGroups
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/nuget/remote_helper.go | registry/app/pkg/nuget/remote_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 nuget
import (
"context"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/nuget"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
GetFile(ctx context.Context, pkg, version, proxyEndpoint, fileName string) (io.ReadCloser, error)
GetPackageMetadata(ctx context.Context, pkg, proxyEndpoint string) (io.ReadCloser, error)
GetPackageVersionMetadataV2(ctx context.Context, pkg, version string) (io.ReadCloser, error)
ListPackageVersion(ctx context.Context, pkg string) (io.ReadCloser, error)
ListPackageVersionV2(ctx context.Context, pkg string) (io.ReadCloser, error)
SearchPackageV2(ctx context.Context, searchTerm string, limit, offset int) (io.ReadCloser, error)
SearchPackage(ctx context.Context, searchTerm string, limit, offset int) (io.ReadCloser, error)
CountPackageV2(ctx context.Context, searchTerm string) (int64, error)
CountPackageVersionV2(ctx context.Context, pkg string) (int64, error)
}
type remoteRegistryHelper struct {
adapter registry.NugetRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, err
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypeNUGET)
if r.registry.Source == string(artifact.UpstreamConfigSourceNugetOrg) {
r.registry.RepoURL = nuget.NugetOrgURL
}
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
nugetReg, ok := adpt.(registry.NugetRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to nuget registry")
return err
}
r.adapter = nugetReg
return nil
}
func (r *remoteRegistryHelper) GetFile(ctx context.Context, pkg,
version, proxyEndpoint, fileName string) (io.ReadCloser, error) {
v2, err := r.adapter.GetPackage(ctx, pkg, version, proxyEndpoint, fileName)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get pkg: %s, version: %s", pkg, version)
}
return v2, err
}
func (r *remoteRegistryHelper) GetPackageMetadata(ctx context.Context,
pkg, proxyEndpoint string) (io.ReadCloser, error) {
metadata, err := r.adapter.GetPackageMetadata(ctx, pkg, proxyEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
return metadata, nil
}
func (r *remoteRegistryHelper) ListPackageVersion(ctx context.Context,
pkg string) (io.ReadCloser, error) {
packageVersions, err := r.adapter.ListPackageVersion(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get package version for pkg: %s", pkg)
return nil, err
}
return packageVersions, nil
}
func (r *remoteRegistryHelper) ListPackageVersionV2(ctx context.Context,
pkg string) (io.ReadCloser, error) {
packageVersions, err := r.adapter.ListPackageVersionV2(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get package version for pkg: %s", pkg)
return nil, err
}
return packageVersions, nil
}
func (r *remoteRegistryHelper) GetPackageVersionMetadataV2(ctx context.Context,
pkg, version string) (io.ReadCloser, error) {
metadata, err := r.adapter.GetPackageVersionMetadataV2(ctx, pkg, version)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
return metadata, nil
}
func (r *remoteRegistryHelper) SearchPackageV2(ctx context.Context,
searchTerm string, limit, offset int) (io.ReadCloser, error) {
searchResults, err := r.adapter.SearchPackageV2(ctx, searchTerm, limit, offset)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to search packages with term: %s", searchTerm)
return nil, err
}
return searchResults, nil
}
func (r *remoteRegistryHelper) SearchPackage(ctx context.Context,
searchTerm string, limit, offset int) (io.ReadCloser, error) {
searchResults, err := r.adapter.SearchPackage(ctx, searchTerm, limit, offset)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to search packages (v3) with term: %s", searchTerm)
return nil, err
}
return searchResults, nil
}
func (r *remoteRegistryHelper) CountPackageV2(ctx context.Context,
searchTerm string) (int64, error) {
count, err := r.adapter.CountPackageV2(ctx, searchTerm)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to count packages with term: %s", searchTerm)
return 0, err
}
return count, nil
}
func (r *remoteRegistryHelper) CountPackageVersionV2(ctx context.Context,
pkg string) (int64, error) {
count, err := r.adapter.CountPackageVersionV2(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to count package versions for pkg: %s", pkg)
return 0, err
}
return count, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/nuget/local_helper.go | registry/app/pkg/nuget/local_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 nuget
import (
"context"
"io"
"strings"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget"
"github.com/harness/gitness/registry/app/storage"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info nugettype.ArtifactInfo) bool
DownloadFile(ctx context.Context, info nugettype.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
)
UploadPackageFile(
ctx context.Context,
info nugettype.ArtifactInfo,
fileReader io.ReadCloser,
) (*commons.ResponseHeaders, string, error)
DeletePackage(ctx context.Context, info nugettype.ArtifactInfo) error
}
type localRegistryHelper struct {
localRegistry LocalRegistry
localBase base.LocalBase
}
func NewLocalRegistryHelper(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return &localRegistryHelper{
localRegistry: localRegistry,
localBase: localBase,
}
}
func (h *localRegistryHelper) FileExists(ctx context.Context, info nugettype.ArtifactInfo) bool {
return h.localBase.Exists(ctx, info.ArtifactInfo,
pkg.JoinWithSeparator("/", info.Image, info.Version, info.Filename))
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info nugettype.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
) {
return h.localBase.Download(ctx, info.ArtifactInfo, info.Version, info.Filename)
}
func (h *localRegistryHelper) DeletePackage(ctx context.Context, info nugettype.ArtifactInfo) error {
return h.localBase.DeleteVersion(ctx, info)
}
func (h *localRegistryHelper) UploadPackageFile(
ctx context.Context,
info nugettype.ArtifactInfo,
fileReader io.ReadCloser,
) (*commons.ResponseHeaders, string, error) {
fileExtension := DependencyFile
if strings.HasSuffix(info.Filename, SymbolsPackageExtension) {
fileExtension = SymbolsFile
}
return h.localRegistry.UploadPackage(ctx, info, fileReader, fileExtension)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/local.go | registry/app/pkg/npm/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"path"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
npm2 "github.com/harness/gitness/registry/app/metadata/npm"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
tagsDao store.PackageTagRepository
nodesDao store.NodesRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
}
func (c *localRegistry) HeadPackageMetadata(ctx context.Context, info npm.ArtifactInfo) (bool, error) {
return c.localBase.CheckIfVersionExists(ctx, info)
}
func (c *localRegistry) DownloadPackageFile(ctx context.Context,
info npm.ArtifactInfo) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
headers, fileReader, redirectURL, err :=
c.localBase.Download(ctx, info.ArtifactInfo, info.Version,
info.Filename)
if err != nil {
return nil, nil, nil, "", err
}
return headers, fileReader, nil, redirectURL, nil
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
tagDao store.PackageTagRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
nodesDao store.NodesRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
tagsDao: tagDao,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
nodesDao: nodesDao,
urlProvider: urlProvider,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeNPM}
}
func (c *localRegistry) UploadPackageFile(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
var packageMetadata npm2.PackageMetadata
fileInfo, tempFileName, err := c.parseAndUploadNPMPackage(ctx, info, file, &packageMetadata)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to parse npm package: %v", err)
return nil, "", err
}
log.Info().Str("packageName", info.Image).Msg("Successfully parsed and uploaded NPM package to tmp location")
info.Metadata = packageMetadata
info.Image = packageMetadata.Name
for tag := range packageMetadata.DistTags {
info.DistTags = append(info.DistTags, tag)
}
for _, meta := range packageMetadata.Versions {
info.Version = meta.Version
}
info.Filename = info.Image + "-" + info.Version + ".tgz"
fileInfo.Filename = info.Filename
filePath := path.Join(info.Image, info.Version, fileInfo.Filename)
_, sha256, _, _, err = c.localBase.MoveTempFileAndCreateArtifact(ctx, info.ArtifactInfo,
tempFileName, info.Version, filePath,
&npm2.NpmMetadata{
PackageMetadata: info.Metadata,
}, fileInfo, false)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to move npm package: %v", err)
return nil, "", err
}
_, err = c.AddTag(ctx, info)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to add tag for npm package:%s, %v", info.Image, err)
return nil, "", err
}
return nil, sha256, nil
}
func (c *localRegistry) GetPackageMetadata(ctx context.Context, info npm.ArtifactInfo) (npm2.PackageMetadata, error) {
packageMetadata := npm2.PackageMetadata{}
versions := make(map[string]*npm2.PackageMetadataVersion)
artifacts, err := c.artifactDao.GetByRegistryIDAndImage(ctx, info.RegistryID, info.Image)
if err != nil {
log.Ctx(ctx).Warn().Msgf("Failed to fetch artifact for image:[%s], Reg:[%s]",
info.BaseArtifactInfo().Image, info.BaseArtifactInfo().RegIdentifier)
return packageMetadata, usererror.ErrInternal
}
if len(*artifacts) == 0 {
return packageMetadata,
usererror.NotFound(fmt.Sprintf("no artifacts found for registry %s and image %s", info.Registry.Name, info.Image))
}
regURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "npm")
for _, artifact := range *artifacts {
metadata := &npm2.NpmMetadata{}
err = json.Unmarshal(artifact.Metadata, metadata)
if err != nil {
return packageMetadata, err
}
if packageMetadata.Name == "" {
packageMetadata = metadata.PackageMetadata
}
for _, versionMetadata := range metadata.Versions {
versions[artifact.Version] = CreatePackageMetadataVersion(regURL, versionMetadata)
}
}
distTags, err := c.ListTags(ctx, info)
if !commons.IsEmpty(err) {
return npm2.PackageMetadata{}, err
}
packageMetadata.Versions = versions
packageMetadata.DistTags = distTags
return packageMetadata, nil
}
func (c *localRegistry) SearchPackage(ctx context.Context, info npm.ArtifactInfo,
limit int, offset int) (*npm2.PackageSearch, error) {
metadataList, err := c.artifactDao.SearchLatestByName(ctx, info.RegistryID, info.Image, limit, offset)
if err != nil {
log.Err(err).Msgf("Failed to search package for search term: [%s]", info.Image)
return &npm2.PackageSearch{}, err
}
count, err := c.artifactDao.CountLatestByName(ctx, info.RegistryID, info.Image)
if err != nil {
log.Err(err).Msgf("Failed to search package for search term: [%s]", info.Image)
return &npm2.PackageSearch{}, err
}
psList := make([]*npm2.PackageSearchObject, 0)
registryURL := c.urlProvider.PackageURL(ctx,
info.BaseArtifactInfo().RootIdentifier+"/"+info.BaseArtifactInfo().RegIdentifier, "npm")
for _, metadata := range *metadataList {
pso, err := mapToPackageSearch(metadata, registryURL)
if err != nil {
log.Err(err).Msgf("Failed to map search package results: [%s]", info.Image)
return &npm2.PackageSearch{}, err
}
psList = append(psList, pso)
}
return &npm2.PackageSearch{
Objects: psList,
Total: count,
}, nil
}
func mapToPackageSearch(metadata types.Artifact, registryURL string) (*npm2.PackageSearchObject, error) {
var art *npm2.NpmMetadata
if err := json.Unmarshal(metadata.Metadata, &art); err != nil {
return &npm2.PackageSearchObject{}, err
}
for _, version := range art.Versions {
var author npm2.User
if version.Author != nil {
data, err := json.Marshal(version.Author)
if err != nil {
log.Err(err).Msgf("Failed to marshal search package results: [%s]", art.Name)
return &npm2.PackageSearchObject{}, err
}
err = json.Unmarshal(data, &author)
if err != nil {
log.Err(err).Msgf("Failed to unmarshal search package results: [%s]", art.Name)
return &npm2.PackageSearchObject{}, err
}
}
return &npm2.PackageSearchObject{
Package: &npm2.PackageSearchPackage{
Name: version.Name,
Version: version.Version,
Description: version.Description,
Date: metadata.CreatedAt,
Scope: getScope(art.Name),
Author: npm2.User{Username: author.Name},
Publisher: npm2.User{Username: author.Name},
Maintainers: getValueOrDefault(version.Maintainers, []npm2.User{}), // npm cli needs this field
Keywords: getValueOrDefault(version.Keywords, []string{}),
Links: &npm2.PackageSearchPackageLinks{
Registry: registryURL,
Homepage: registryURL,
Repository: registryURL,
},
},
}, nil
}
return &npm2.PackageSearchObject{}, fmt.Errorf("no version found in the metadata for image:[%s]", art.Name)
}
func getValueOrDefault(value any, defaultValue any) any {
if value != nil {
return value
}
return defaultValue
}
func getScope(name string) string {
if strings.HasPrefix(name, "@") {
if i := strings.Index(name, "/"); i != -1 {
return name[1:i] // Strip @ and return only the scope
}
}
return "unscoped"
}
func CreatePackageMetadataVersion(registryURL string,
metadata *npm2.PackageMetadataVersion) *npm2.PackageMetadataVersion {
return &npm2.PackageMetadataVersion{
ID: fmt.Sprintf("%s@%s", metadata.Name, metadata.Version),
Name: metadata.Name,
Version: metadata.Version,
Description: metadata.Description,
Author: metadata.Author,
Homepage: registryURL,
License: metadata.License,
Dependencies: metadata.Dependencies,
BundleDependencies: metadata.BundleDependencies,
DevDependencies: metadata.DevDependencies,
PeerDependencies: metadata.PeerDependencies,
OptionalDependencies: metadata.OptionalDependencies,
Readme: metadata.Readme,
Bin: metadata.Bin,
Dist: npm2.PackageDistribution{
Shasum: metadata.Dist.Shasum,
Integrity: metadata.Dist.Integrity,
Tarball: fmt.Sprintf("%s/%s/-/%s/%s", registryURL, metadata.Name, metadata.Version,
metadata.Name+"-"+metadata.Version+".tgz"),
},
}
}
func (c *localRegistry) ListTags(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error) {
tags, err := c.tagsDao.FindByImageNameAndRegID(ctx, info.Image, info.RegistryID)
if err != nil {
return nil, err
}
pkgTags := make(map[string]string)
for _, tag := range tags {
pkgTags[tag.Name] = tag.Version
}
return pkgTags, nil
}
func (c *localRegistry) AddTag(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error) {
image, err := c.imageDao.GetByRepoAndName(ctx, info.ParentID, info.RegIdentifier, info.Image)
if err != nil {
return nil, err
}
version, err := c.artifactDao.GetByName(ctx, image.ID, info.Version)
if err != nil {
return nil, err
}
if len(info.DistTags) == 0 {
return nil, usererror.BadRequest("Add tag error: distTags are empty")
}
packageTag := &types.PackageTag{
ID: uuid.NewString(),
Name: info.DistTags[0],
ArtifactID: version.ID,
}
_, err = c.tagsDao.Create(ctx, packageTag)
if err != nil {
return nil, err
}
return c.ListTags(ctx, info)
}
func (c *localRegistry) DeleteTag(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error) {
if len(info.DistTags) == 0 {
return nil, usererror.BadRequest("Delete tag error: distTags are empty")
}
err := c.tagsDao.DeleteByTagAndImageName(ctx, info.DistTags[0], info.Image, info.RegistryID)
if err != nil {
return nil, err
}
return c.ListTags(ctx, info)
}
func (c *localRegistry) DeletePackage(ctx context.Context, info npm.ArtifactInfo) error {
return c.localBase.DeletePackage(ctx, info)
}
func (c *localRegistry) DeleteVersion(ctx context.Context, info npm.ArtifactInfo) error {
return c.localBase.DeleteVersion(ctx, info)
}
func (c *localRegistry) parseAndUploadNPMPackage(ctx context.Context, info npm.ArtifactInfo,
reader io.Reader, packageMetadata *npm2.PackageMetadata) (types.FileInfo, string, error) {
// Use a buffered reader with controlled buffer size instead of unlimited buffering
// This prevents the JSON decoder from buffering the entire file
bufferedReader := bufio.NewReaderSize(reader, 32*1024) // 32KB buffer instead of unlimited
// Create decoder with controlled buffering
decoder := json.NewDecoder(bufferedReader)
var fileInfo types.FileInfo
var tmpFileName string
// Parse top-level fields
for {
token, err := decoder.Token()
if err != nil {
// Check for both io.EOF and any error containing "EOF" in the message
if errors.Is(err, io.EOF) || strings.Contains(err.Error(), "EOF") {
break
}
return types.FileInfo{}, "", fmt.Errorf("failed to parse JSON: %w", err)
}
//nolint:nestif
if token, ok := token.(string); ok {
switch token {
case "_id":
if err := decoder.Decode(&packageMetadata.ID); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse _id: %w", err)
}
case "name":
if err := decoder.Decode(&packageMetadata.Name); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse name: %w", err)
}
case "description":
if err := decoder.Decode(&packageMetadata.Description); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse description: %w", err)
}
case "dist-tags":
packageMetadata.DistTags = make(map[string]string)
if err := decoder.Decode(&packageMetadata.DistTags); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse dist-tags: %w", err)
}
case "versions":
packageMetadata.Versions = make(map[string]*npm2.PackageMetadataVersion)
if err := decoder.Decode(&packageMetadata.Versions); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse versions: %w", err)
}
case "readme":
if err := decoder.Decode(&packageMetadata.Readme); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse readme: %w", err)
}
case "maintainers":
if err := decoder.Decode(&packageMetadata.Maintainers); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse maintainers: %w", err)
}
case "time":
packageMetadata.Time = make(map[string]time.Time)
if err := decoder.Decode(&packageMetadata.Time); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse time: %w", err)
}
case "homepage":
if err := decoder.Decode(&packageMetadata.Homepage); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse homepage: %w", err)
}
case "keywords":
if err := decoder.Decode(&packageMetadata.Keywords); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse keywords: %w", err)
}
case "repository":
if err := decoder.Decode(&packageMetadata.Repository); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse repository: %w", err)
}
case "author":
if err := decoder.Decode(&packageMetadata.Author); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse author: %w", err)
}
case "readmeFilename":
if err := decoder.Decode(&packageMetadata.ReadmeFilename); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse readmeFilename: %w", err)
}
case "users":
if err := decoder.Decode(&packageMetadata.Users); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse users: %w", err)
}
case "license":
if err := decoder.Decode(&packageMetadata.License); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse license: %w", err)
}
case "_attachments":
// Process attachments with optimized streaming to minimize memory usage
fileInfo, tmpFileName, err = c.processAttachmentsOptimized(ctx, info, decoder, bufferedReader)
if err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to process attachments: %w", err)
}
log.Info().Str("packageName", info.Image).Msg("Successfully uploaded NPM package using optimized processing")
// We're done processing attachments, break out of the main parsing loop
return fileInfo, tmpFileName, nil
default:
var dummy any
if err := decoder.Decode(&dummy); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse field %s: %w", token, err)
}
}
}
}
return fileInfo, tmpFileName, nil
}
// processAttachmentsOptimized handles attachment processing with minimal memory buffering.
func (c *localRegistry) processAttachmentsOptimized(ctx context.Context, info npm.ArtifactInfo,
decoder *json.Decoder, bufferedReader *bufio.Reader) (types.FileInfo, string, error) {
// Parse the attachments map with minimal buffering
t, err := decoder.Token()
if err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse _attachments: %w", err)
}
if delim, ok := t.(json.Delim); !ok || delim != '{' {
return types.FileInfo{}, "", fmt.Errorf("expected '{' at start of _attachments")
}
// Process each attachment (e.g., "test-large-package-2.0.0.tgz")
for {
//nolint:govet
t, err := decoder.Token()
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "EOF") {
break
}
return types.FileInfo{}, "", fmt.Errorf("failed to parse JSON: %w", err)
}
if delim, ok := t.(json.Delim); ok && delim == '}' {
break // End of _attachments object
}
attachmentKey, ok := t.(string)
if !ok {
return types.FileInfo{}, "", fmt.Errorf("expected string key in _attachments")
}
// Expect the start of the attachment object
t, err = decoder.Token()
if err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to parse attachment %s: %w", attachmentKey, err)
}
if delim, ok := t.(json.Delim); !ok || delim != '{' {
return types.FileInfo{}, "", fmt.Errorf("expected '{' for attachment %s", attachmentKey)
}
// Process fields within the attachment object with optimized streaming
for {
//nolint:govet
t, err := decoder.Token()
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "EOF") {
break
}
return types.FileInfo{}, "", fmt.Errorf("failed to parse attachment %s fields: %w", attachmentKey, err)
}
if delim, ok := t.(json.Delim); ok && delim == '}' {
break // End of attachment object
}
field, ok := t.(string)
if !ok {
break
}
switch field {
case "data":
// Use optimized base64 streaming with minimal buffering
return c.processBase64DataOptimized(ctx, info, decoder, bufferedReader, attachmentKey)
default:
// Skip other fields efficiently
var dummy any
if err := decoder.Decode(&dummy); err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to skip field %s: %w", field, err)
}
}
}
}
return types.FileInfo{}, "", fmt.Errorf("no attachment data found")
}
// processBase64DataOptimized handles base64 data processing with minimal memory usage.
func (c *localRegistry) processBase64DataOptimized(ctx context.Context, info npm.ArtifactInfo,
decoder *json.Decoder, bufferedReader *bufio.Reader, attachmentKey string) (types.FileInfo, string, error) {
// Get the remaining data from decoder's buffer + original reader
// This avoids the memory-heavy io.MultiReader approach
combinedReader := io.MultiReader(decoder.Buffered(), bufferedReader)
// Use a smaller buffer for reading the base64 stream
streamReader := bufio.NewReaderSize(combinedReader, 8*1024) // 8KB buffer instead of default
// Expecting `:` character first
startByte, err := streamReader.ReadByte()
if err != nil {
return types.FileInfo{}, "",
fmt.Errorf("failed to upload attachment %s: Error while reading : character: %w", attachmentKey, err)
}
if startByte != ':' {
return types.FileInfo{}, "",
fmt.Errorf("failed to upload attachment %s: Expected : character, got %c", attachmentKey, startByte)
}
// Now expecting `"`, marking start of JSON string
startByte, err = streamReader.ReadByte()
if err != nil {
return types.FileInfo{}, "", fmt.Errorf("failed to upload"+
" attachment %s: Error while reading \" character: %w", attachmentKey, err)
}
if startByte != '"' {
return types.FileInfo{}, "", fmt.Errorf("failed to upload"+
" attachment %s: Expected \" character, got %c", attachmentKey, startByte)
}
// Use optimized JSON string reader with smaller buffer
b64StreamReader := NewOptimizedJSONStringStreamReader(streamReader)
// Wrap base64 decoder with error handling
base64Reader := io.NopCloser(base64.NewDecoder(base64.StdEncoding, b64StreamReader))
log.Info().Str("packageName", info.Image).Msg("Uploading NPM package with optimized streaming")
fileInfo, tmpFileName, err := c.fileManager.UploadTempFile(ctx, info.RootIdentifier, nil, "tmp", base64Reader)
if err != nil {
if strings.Contains(err.Error(), "unexpected EOF") {
return types.FileInfo{}, "",
fmt.Errorf("failed to upload attachment %s: "+
"base64 data may be corrupted or missing closing quote: %w", attachmentKey, err)
}
return types.FileInfo{}, "", fmt.Errorf("failed to upload attachment %s: %w", attachmentKey, err)
}
log.Info().Str("packageName", info.Image).Msg("Successfully uploaded NPM package with optimized streaming")
return fileInfo, tmpFileName, nil
}
// NewOptimizedJSONStringStreamReader returns an io.Reader that stops at the closing quote of a JSON string
// with optimized chunk-based processing instead of byte-by-byte reading to reduce memory overhead.
func NewOptimizedJSONStringStreamReader(r *bufio.Reader) io.Reader {
pr, pw := io.Pipe()
go func() {
defer pw.Close()
var escaped bool
buf := make([]byte, 4096) // Process in 4KB chunks instead of byte-by-byte
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
pw.CloseWithError(fmt.Errorf("error while reading base64 string: %w", err))
return
}
if n == 0 {
if err == io.EOF {
pw.CloseWithError(fmt.Errorf("unexpected EOF while reading base64 string: missing closing quote"))
}
return
}
// Process the chunk for quotes and escapes
writeStart := 0
for i := range n {
b := buf[i]
if escaped {
escaped = false
continue
}
if b == '\\' {
escaped = true
continue
}
if b == '"' {
// Found end quote - write remaining data up to this point and exit
if i > writeStart {
if _, writeErr := pw.Write(buf[writeStart:i]); writeErr != nil {
pw.CloseWithError(writeErr)
return
}
}
return
}
}
// Write the entire chunk if no end quote found
if _, writeErr := pw.Write(buf[writeStart:n]); writeErr != nil {
pw.CloseWithError(writeErr)
return
}
if err == io.EOF {
pw.CloseWithError(fmt.Errorf("unexpected EOF while reading base64 string: missing closing quote"))
return
}
}
}()
return pr
}
func (c *localRegistry) UploadPackageFileWithoutParsing(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
defer file.Close()
path := pkg.JoinWithSeparator("/", info.Image, info.Version, info.Filename)
response, sha, err := c.localBase.Upload(ctx, info.ArtifactInfo, info.Filename, info.Version, path, file,
&npm2.NpmMetadata{
PackageMetadata: info.Metadata,
})
if !commons.IsEmpty(err) {
return nil, "", err
}
_, err = c.AddTag(ctx, info)
if err != nil {
return nil, "", err
}
return response, sha, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/wire.go | registry/app/pkg/npm/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 npm
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
tagDao store.PackageTagRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
nodesDao store.NodesRepository,
urlProvider urlprovider.Provider,
) LocalRegistry {
registry := NewLocalRegistry(localBase, fileManager,
proxyStore, tx, registryDao, tagDao, imageDao, artifactDao, nodesDao,
urlProvider)
base.Register(registry)
return registry
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
proxy := NewProxy(fileManager, proxyStore, tx,
registryDao, imageDao, artifactDao, urlProvider, spaceFinder, service, localRegistryHelper)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/proxy.go | registry/app/pkg/npm/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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 (
"context"
"fmt"
"io"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"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/metadata/npm"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
npm2 "github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
localRegistryHelper LocalRegistryHelper
}
func (r *proxy) SearchPackage(_ context.Context, _ npm2.ArtifactInfo, _ int, _ int) (*npm.PackageSearch, error) {
return nil, commons.ErrNotSupported
}
func (r *proxy) UploadPackageFileReader(
_ context.Context,
_ npm2.ArtifactInfo,
) (*commons.ResponseHeaders, string, error) {
return nil, " ", commons.ErrNotSupported
}
func (r *proxy) HeadPackageMetadata(_ context.Context, _ npm2.ArtifactInfo) (bool, error) {
return false, commons.ErrNotSupported
}
func (r *proxy) ListTags(_ context.Context, _ npm2.ArtifactInfo) (map[string]string, error) {
return nil, commons.ErrNotSupported
}
func (r *proxy) AddTag(_ context.Context, _ npm2.ArtifactInfo) (map[string]string, error) {
return nil, commons.ErrNotSupported
}
func (r *proxy) DeleteTag(_ context.Context, _ npm2.ArtifactInfo) (map[string]string, error) {
return nil, commons.ErrNotSupported
}
func (r *proxy) DeletePackage(_ context.Context, _ npm2.ArtifactInfo) error {
return commons.ErrNotSupported
}
func (r *proxy) DeleteVersion(_ context.Context, _ npm2.ArtifactInfo) error {
return commons.ErrNotSupported
}
func (r *proxy) GetPackageMetadata(ctx context.Context, info npm2.ArtifactInfo) (npm.PackageMetadata, error) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return npm.PackageMetadata{}, err
}
helper, _ := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
result, err := helper.GetPackageMetadata(ctx, info.Image)
if err != nil {
return npm.PackageMetadata{}, err
}
regURL := r.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.ParentRegIdentifier, "npm")
versions := make(map[string]*npm.PackageMetadataVersion)
for _, version := range result.Versions {
versions[version.Version] = CreatePackageMetadataVersion(regURL, version)
}
result.Versions = versions
return *result, nil
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
) Proxy {
return &proxy{
proxyStore: proxyStore,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
fileManager: fileManager,
tx: tx,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
localRegistryHelper: localRegistryHelper,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeNPM}
}
func (r *proxy) DownloadPackageFile(ctx context.Context, info npm2.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
) {
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return nil, nil, nil, "", err
}
exists := r.localRegistryHelper.FileExists(ctx, info)
if exists {
headers, fileReader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, nil, redirectURL, nil
}
// If file exists in local registry, but download failed, we should try to download from remote
log.Warn().Ctx(ctx).Msgf("failed to pull from local, attempting streaming from remote, %v", err)
}
remote, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service)
if err != nil {
return nil, nil, nil, "", err
}
file, err := remote.GetPackage(ctx, info.Image, info.Version)
if err != nil {
return nil, nil, nil, "", errcode.ErrCodeUnknown.WithDetail(err)
}
go func(info npm2.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = r.putFileToLocal(ctx2, info, remote)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf("error while putting file to localRegistry, %v", err)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated file: %s, registry: %s", info.Filename, info.RegIdentifier)
}(info)
return nil, nil, file, "", nil
}
// UploadPackageFile FIXME: Extract this upload function for all types of packageTypes
// uploads the package file to the storage.
func (r *proxy) UploadPackageFile(
ctx context.Context,
_ npm2.ArtifactInfo,
_ io.ReadCloser,
) (*commons.ResponseHeaders, string, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) putFileToLocal(ctx context.Context, info npm2.ArtifactInfo, remote RemoteRegistryHelper) error {
versionMetadata, err := remote.GetVersionMetadata(ctx, info.Image, info.GetVersion())
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("fetching metadata of pkg with name %s,"+
" version %s failed, %v", info.Image, info.Version, err)
return err
}
file, err := remote.GetPackage(ctx, info.Image, info.Version)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("fetching pkg with name %s,"+
" version %s failed, %v", info.Image, info.Version, err)
return err
}
defer file.Close()
info.Metadata = *versionMetadata
_, sha256, err2 := r.localRegistryHelper.UploadPackageFile(ctx, info, file)
if err2 != nil {
log.Ctx(ctx).Error().Stack().Err(err2).Msgf("uploading file %s failed, %v", info.Filename, err)
return err2
}
log.Ctx(ctx).Info().Msgf("Successfully uploaded %s with SHA256: %s", info.Filename, sha256)
return nil
}
func (r *proxy) UploadPackageFileWithoutParsing(
ctx context.Context,
_ npm2.ArtifactInfo,
_ io.ReadCloser,
) (headers *commons.ResponseHeaders, sha256 string, err error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/registry.go | registry/app/pkg/npm/registry.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"context"
"io"
npm3 "github.com/harness/gitness/registry/app/metadata/npm"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
pkg.Artifact
UploadPackageFile(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (*commons.ResponseHeaders, string, error)
DownloadPackageFile(ctx context.Context, info npm.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
io.ReadCloser,
string,
error,
)
GetPackageMetadata(ctx context.Context, info npm.ArtifactInfo) (npm3.PackageMetadata, error)
HeadPackageMetadata(ctx context.Context, info npm.ArtifactInfo) (bool, error)
ListTags(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error)
AddTag(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error)
DeleteTag(ctx context.Context, info npm.ArtifactInfo) (map[string]string, error)
DeletePackage(ctx context.Context, info npm.ArtifactInfo) error
DeleteVersion(ctx context.Context, info npm.ArtifactInfo) error
UploadPackageFileWithoutParsing(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (headers *commons.ResponseHeaders, sha256 string, err error)
SearchPackage(ctx context.Context, info npm.ArtifactInfo, limit int, offset int) (*npm3.PackageSearch, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/remote_helper.go | registry/app/pkg/npm/remote_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 npm
import (
"context"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/metadata/npm"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/npmjs"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type RemoteRegistryHelper interface {
// GetFile Downloads the file for the given package and filename
GetPackage(ctx context.Context, pkg string, version string) (io.ReadCloser, error)
// GetMetadata Fetches the metadata for the given package for all versions
GetPackageMetadata(ctx context.Context, pkg string) (*npm.PackageMetadata, error)
GetVersionMetadata(ctx context.Context, pkg string, version string) (*npm.PackageMetadata, error)
}
type remoteRegistryHelper struct {
adapter registry.NpmRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service); err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to init remote registry for remote: %s", registry.RepoKey)
return nil, err
}
return r, nil
}
func (r *remoteRegistryHelper) init(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
service secret.Service,
) error {
key := string(artifact.PackageTypeNPM)
if r.registry.Source == string(artifact.UpstreamConfigSourceNpmJs) {
r.registry.RepoURL = npmjs.NpmjsURL
}
factory, err := adapter.GetFactory(key)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get factory " + key)
return err
}
adpt, err := factory.Create(ctx, spaceFinder, r.registry, service)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to create factory " + key)
return err
}
npmReg, ok := adpt.(registry.NpmRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to npm registry")
return err
}
r.adapter = npmReg
return nil
}
func (r *remoteRegistryHelper) GetPackage(ctx context.Context, pkg string, version string) (io.ReadCloser, error) {
v2, err := r.adapter.GetPackage(ctx, pkg, version)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get pkg: %s, version: %s", pkg, version)
}
return v2, err
}
func (r *remoteRegistryHelper) GetPackageMetadata(ctx context.Context, pkg string) (*npm.PackageMetadata, error) {
packages, err := r.adapter.GetPackageMetadata(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
return packages, nil
}
func (r *remoteRegistryHelper) GetVersionMetadata(ctx context.Context,
pkg string, version string) (*npm.PackageMetadata, error) {
metadata, err := r.adapter.GetPackageMetadata(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get metadata for pkg: %s", pkg)
return nil, err
}
for _, p := range metadata.Versions {
if p.Version == version {
metadata.Versions = map[string]*npm.PackageMetadataVersion{p.Version: p}
break
}
}
return metadata, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/local_helper.go | registry/app/pkg/npm/local_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 npm
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/app/storage"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info npm.ArtifactInfo) bool
DownloadFile(ctx context.Context, info npm.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
)
UploadPackageFile(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (*commons.ResponseHeaders, string, error)
}
type localRegistryHelper struct {
localRegistry LocalRegistry
localBase base.LocalBase
}
func NewLocalRegistryHelper(localRegistry LocalRegistry, localBase base.LocalBase) LocalRegistryHelper {
return &localRegistryHelper{
localRegistry: localRegistry,
localBase: localBase,
}
}
func (h *localRegistryHelper) FileExists(ctx context.Context, info npm.ArtifactInfo) bool {
return h.localBase.Exists(ctx, info.ArtifactInfo,
pkg.JoinWithSeparator("/", info.Image, info.Version, info.Filename))
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info npm.ArtifactInfo) (
*commons.ResponseHeaders,
*storage.FileReader,
string,
error,
) {
return h.localBase.Download(ctx, info.ArtifactInfo, info.Version, info.Filename)
}
func (h *localRegistryHelper) UploadPackageFile(
ctx context.Context,
info npm.ArtifactInfo,
file io.ReadCloser,
) (*commons.ResponseHeaders, string, error) {
return h.localRegistry.UploadPackageFileWithoutParsing(ctx, info, file)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/npm/local_test.go | registry/app/pkg/npm/local_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 npm
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"mime/multipart"
"testing"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/driver/filesystem"
"github.com/harness/gitness/registry/app/metadata"
npmmeta "github.com/harness/gitness/registry/app/metadata/npm"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/pkg/types/npm"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/stretchr/testify/assert"
)
// -----------------------
// Test Mocks (lightweight)
// -----------------------
type mockLocalBase struct {
checkIfVersionExists func(ctx context.Context, info pkg.PackageArtifactInfo) (bool, error)
download func(
ctx context.Context,
info pkg.ArtifactInfo, version, filename string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error)
deletePackage func(ctx context.Context, info pkg.PackageArtifactInfo) error
deleteVersion func(ctx context.Context, info pkg.PackageArtifactInfo) error
moveTempAndCreate func(
ctx context.Context, info pkg.ArtifactInfo,
tmp, version, path string,
md metadata.Metadata, fi types.FileInfo, failOnConflict bool,
) (*commons.ResponseHeaders, string, int64, bool, error)
}
func TestParseAndUploadNPMPackage_WithAttachment_UploadsData(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
// Prepare a temp filesystem-backed storage service
tmpDir := t.TempDir()
drv, err := filesystem.FromParameters(map[string]any{"rootdirectory": tmpDir})
if err != nil {
t.Fatalf("filesystem driver init failed: %v", err)
}
svc, err := storage.NewStorageService(drv)
if err != nil {
t.Fatalf("storage service init failed: %v", err)
}
fm := filemanager.NewFileManager(nil, nil, nil, nil, nil, svc, nil, nil)
// Wire local registry with a real file manager
lr := newLocalForTests(&mockLocalBase{}, nil, nil, nil, nil)
lr.fileManager = fm
// Prepare blob store for verification of upload
blobStore := svc.GenericBlobsStore(info.RootIdentifier)
// Prepare base64 data for attachment
content := []byte("test tarball bytes")
b64 := base64.StdEncoding.EncodeToString(content)
body := `{
"_id": "pkg",
"name": "pkg",
"description": "A sample package",
"keywords": ["x", "y"],
"homepage": "http://example",
"maintainers": [{"name": "dev"}],
"repository": {"type": "git", "url": "git://example/repo.git"},
"license": "MIT",
"readme": "# Readme",
"readmeFilename": "README.md",
"users": {"u": true},
"time": {"created": "2024-01-01T00:00:00.000Z"},
"versions": {
"1.0.0": {
"name": "pkg",
"version": "1.0.0",
"dist": {"shasum": "abc", "integrity": "xyz"}
}
},
"dist-tags": {"latest": "1.0.0"},
"_attachments": {
"pkg-1.0.0.tgz": {
"content_type":"application/octet-stream",
"length":"18",
"data":"` + b64 + `"
}
}
}`
var meta npmmeta.PackageMetadata
fi, tmp, err := lr.parseAndUploadNPMPackage(ctx, info, bytes.NewReader([]byte(body)), &meta)
assert.NoError(t, err)
// Metadata should be parsed
assert.Equal(t, "pkg", meta.Name)
assert.Equal(t, "1.0.0", meta.Versions["1.0.0"].Version)
// Upload should have occurred
assert.NotEqual(t, "", tmp)
assert.Greater(t, fi.Size, int64(0))
// Verify data present at temp path in storage
tmpPath := "/" + info.RootIdentifier + "/tmp/" + tmp
sz, statErr := blobStore.Stat(ctx, tmpPath)
assert.NoError(t, statErr)
assert.Equal(t, int64(len(content)), sz)
}
// Satisfy base.LocalBase interface with exact signatures.
func (m *mockLocalBase) UploadFile(
context.Context,
pkg.ArtifactInfo, string, string, string,
multipart.File, metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
panic("not implemented in tests")
}
func (m *mockLocalBase) Upload(
context.Context,
pkg.ArtifactInfo, string, string,
string, io.ReadCloser, metadata.Metadata,
) (*commons.ResponseHeaders, string, error) {
panic("not implemented in tests")
}
func (m *mockLocalBase) MoveTempFileAndCreateArtifact(
ctx context.Context,
info pkg.ArtifactInfo, tmp,
version, p string, md metadata.Metadata, fi types.FileInfo, foC bool,
) (*commons.ResponseHeaders, string, int64, bool, error) {
return m.moveTempAndCreate(ctx, info, tmp, version, p, md, fi, foC)
}
func (m *mockLocalBase) Download(
ctx context.Context,
info pkg.ArtifactInfo, version, filename string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error) {
return m.download(ctx, info, version, filename)
}
func (m *mockLocalBase) Exists(context.Context, pkg.ArtifactInfo, string) bool { return false }
func (m *mockLocalBase) ExistsE(context.Context, pkg.PackageArtifactInfo, string) (*commons.ResponseHeaders, error) {
return nil, nil //nolint:nilnil
}
func (m *mockLocalBase) DeleteFile(context.Context, pkg.PackageArtifactInfo, string) (*commons.ResponseHeaders, error) {
return nil, nil //nolint:nilnil
}
func (m *mockLocalBase) ExistsByFilePath(context.Context, int64, string) (bool, error) {
return false, nil
}
func (m *mockLocalBase) CheckIfVersionExists(ctx context.Context, info pkg.PackageArtifactInfo) (bool, error) {
return m.checkIfVersionExists(ctx, info)
}
func (m *mockLocalBase) DeletePackage(ctx context.Context, info pkg.PackageArtifactInfo) error {
return m.deletePackage(ctx, info)
}
func (m *mockLocalBase) DeleteVersion(ctx context.Context, info pkg.PackageArtifactInfo) error {
return m.deleteVersion(ctx, info)
}
func (m *mockLocalBase) MoveMultipleTempFilesAndCreateArtifact(
context.Context,
*pkg.ArtifactInfo, string, metadata.Metadata,
*[]types.FileInfo, func(info *pkg.ArtifactInfo, fileInfo *types.FileInfo) string, string,
) error {
return nil
}
type mockTagsDAO struct {
findByImageNameAndRegID func(ctx context.Context, image string, regID int64) ([]*types.PackageTagMetadata, error)
create func(ctx context.Context, tag *types.PackageTag) (string, error)
deleteByTagAndImageName func(ctx context.Context, tag string, image string, regID int64) error
}
func (m *mockTagsDAO) FindByImageNameAndRegID(
ctx context.Context,
image string, regID int64,
) ([]*types.PackageTagMetadata, error) {
return m.findByImageNameAndRegID(ctx, image, regID)
}
func (m *mockTagsDAO) Create(ctx context.Context, tag *types.PackageTag) (string, error) {
return m.create(ctx, tag)
}
func (m *mockTagsDAO) DeleteByTagAndImageName(ctx context.Context, tag string, image string, regID int64) error {
return m.deleteByTagAndImageName(ctx, tag, image, regID)
}
func (m *mockTagsDAO) DeleteByImageNameAndRegID(context.Context, string, int64) error { return nil } //nolint:nilnil
type mockImageDAO struct {
getByRepoAndName func(ctx context.Context, parentID int64, repo, name string) (*types.Image, error)
}
func (m *mockImageDAO) DuplicateImage(
_ context.Context,
_ *types.Image,
_ int64,
) (*types.Image, error) {
return nil, nil //nolint:nilnil
}
func (m *mockImageDAO) GetByUUID(context.Context, string) (*types.Image, error) {
return nil, nil //nolint:nilnil
}
func (m *mockImageDAO) Get(context.Context, int64) (*types.Image, error) { return nil, nil } //nolint:nilnil
func (m *mockImageDAO) GetByName(context.Context, int64, string) (*types.Image, error) {
return nil, nil //nolint:nilnil
}
func (m *mockImageDAO) GetByNameAndType(context.Context, int64, string, *artifact.ArtifactType) (*types.Image, error) {
return nil, nil //nolint:nilnil
}
func (m *mockImageDAO) GetLabelsByParentIDAndRepo(context.Context, int64, string, int, int, string) ([]string, error) {
return nil, nil //nolint:nilnil
}
func (m *mockImageDAO) CountLabelsByParentIDAndRepo(context.Context, int64, string, string) (int64, error) {
return 0, nil
}
func (m *mockImageDAO) GetByRepoAndName(ctx context.Context, parentID int64, repo, name string) (*types.Image, error) {
return m.getByRepoAndName(ctx, parentID, repo, name)
}
func (m *mockImageDAO) CreateOrUpdate(context.Context, *types.Image) error { return nil }
func (m *mockImageDAO) Update(context.Context, *types.Image) error { return nil }
func (m *mockImageDAO) UpdateStatus(context.Context, *types.Image) error { return nil }
func (m *mockImageDAO) DeleteByImageNameAndRegID(context.Context, int64, string) error { return nil }
func (m *mockImageDAO) DeleteByImageNameIfNoLinkedArtifacts(context.Context, int64, string) error {
return nil
}
type mockArtifactDAO struct {
getByUUID func(ctx context.Context, uuid string) (*types.Artifact, error)
get func(ctx context.Context, id int64) (*types.Artifact, error)
getByName func(ctx context.Context, imageID int64, version string) (*types.Artifact, error)
getByRegistryIDAndImage func(ctx context.Context, registryID int64, image string) (*[]types.Artifact, error)
searchLatestByName func(
ctx context.Context,
regID int64, name string, limit int, offset int,
) (*[]types.Artifact, error)
countLatestByName func(ctx context.Context, regID int64, name string) (int64, error)
}
func (m *mockArtifactDAO) DuplicateArtifact(
_ context.Context,
_ *types.Artifact,
_ int64,
) (*types.Artifact, error) {
return nil, nil //nolint:nilnil
}
func (m *mockArtifactDAO) GetLatestArtifactsByRepo(
_ context.Context,
_ int64, _ int, _ int64,
) (*[]types.ArtifactMetadata, error) {
// TODO implement me
panic("implement me")
}
func (m *mockArtifactDAO) GetByUUID(
ctx context.Context,
uuid string,
) (*types.Artifact, error) {
return m.getByUUID(ctx, uuid)
}
func (m *mockArtifactDAO) GetByName(
ctx context.Context,
imageID int64, version string,
) (*types.Artifact, error) {
return m.getByName(ctx, imageID, version)
}
func (m *mockArtifactDAO) GetByRegistryImageAndVersion(
context.Context,
int64, string, string,
) (*types.Artifact, error) {
return nil, nil //nolint:nilnil
}
func (m *mockArtifactDAO) CreateOrUpdate(context.Context, *types.Artifact) (int64, error) {
return 0, nil
}
func (m *mockArtifactDAO) Count(context.Context) (int64, error) { return 0, nil }
func (m *mockArtifactDAO) GetAllArtifactsByParentID(
context.Context,
int64, *[]string, string, string, int, int,
string, bool, []string,
) (*[]types.ArtifactMetadata, error) {
return &[]types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) CountAllArtifactsByParentID(
context.Context,
int64, *[]string, string, bool, []string,
) (int64, error) {
return 0, nil
}
func (m *mockArtifactDAO) GetArtifactsByRepo(
context.Context,
int64, string, string, string,
int, int, string, []string, *artifact.ArtifactType,
) (*[]types.ArtifactMetadata, error) {
return &[]types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) CountArtifactsByRepo(
context.Context,
int64, string, string, []string, *artifact.ArtifactType,
) (int64, error) {
return 0, nil
}
func (m *mockArtifactDAO) GetLatestArtifactMetadata(
context.Context,
int64, string, string,
) (*types.ArtifactMetadata, error) {
return &types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) GetAllVersionsByRepoAndImage(
context.Context,
int64, string, string, string,
int, int, string, *artifact.ArtifactType,
) (*[]types.NonOCIArtifactMetadata, error) {
return &[]types.NonOCIArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) CountAllVersionsByRepoAndImage(
context.Context,
int64, string, string, string, *artifact.ArtifactType,
) (int64, error) {
return 0, nil
}
func (m *mockArtifactDAO) GetArtifactMetadata(
context.Context,
int64, string, string, string, *artifact.ArtifactType,
) (*types.ArtifactMetadata, error) {
return &types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) UpdateArtifactMetadata(context.Context, json.RawMessage, int64) error {
return nil //nolint:nilnil
}
func (m *mockArtifactDAO) GetByRegistryIDAndImage(
ctx context.Context,
registryID int64, image string,
) (*[]types.Artifact, error) {
return m.getByRegistryIDAndImage(ctx, registryID, image)
}
func (m *mockArtifactDAO) Get(
ctx context.Context,
id int64,
) (*types.Artifact, error) {
return m.get(ctx, id)
}
func (m *mockArtifactDAO) DeleteByImageNameAndRegistryID(context.Context, int64, string) error {
return nil //nolint:nilnil
}
func (m *mockArtifactDAO) DeleteByVersionAndImageName(context.Context, string, string, int64) error {
return nil //nolint:nilnil
}
func (m *mockArtifactDAO) GetLatestByImageID(context.Context, int64) (*types.Artifact, error) {
return nil, nil //nolint:nilnil
}
func (m *mockArtifactDAO) GetAllArtifactsByRepo(
context.Context,
int64, int, int64,
) (*[]types.ArtifactMetadata, error) {
return nil, nil //nolint:nilnil
}
func (m *mockArtifactDAO) GetArtifactsByRepoAndImageBatch(
context.Context,
int64, string, int, int64,
) (*[]types.ArtifactMetadata, error) {
return &[]types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) SearchLatestByName(
ctx context.Context,
regID int64, name string, limit int, offset int,
) (*[]types.Artifact, error) {
return m.searchLatestByName(ctx, regID, name, limit, offset)
}
func (m *mockArtifactDAO) CountLatestByName(
ctx context.Context,
regID int64, name string,
) (int64, error) {
return m.countLatestByName(ctx, regID, name)
}
func (m *mockArtifactDAO) SearchByImageName(
context.Context,
int64, string, int, int,
) (*[]types.ArtifactMetadata, error) {
return &[]types.ArtifactMetadata{}, nil
}
func (m *mockArtifactDAO) CountByImageName(context.Context, int64, string) (int64, error) {
return 0, nil
}
type mockURLProvider struct {
pkgURL func(ctx context.Context, regRef string, pkgType string, params ...string) string
}
func (m *mockURLProvider) GetInternalAPIURL(_ context.Context) string { return "" }
func (m *mockURLProvider) GenerateContainerGITCloneURL(_ context.Context, _ string) string {
return ""
}
func (m *mockURLProvider) GenerateGITCloneURL(_ context.Context, _ string) string { return "" }
func (m *mockURLProvider) GenerateGITCloneSSHURL(_ context.Context, _ string) string {
return ""
}
func (m *mockURLProvider) GenerateUIRepoURL(_ context.Context, _ string) string { return "" }
func (m *mockURLProvider) GenerateUIPRURL(_ context.Context, _ string, _ int64) string {
return ""
}
func (m *mockURLProvider) GenerateUICompareURL(_ context.Context, _ string, _ string, _ string) string {
return ""
}
func (m *mockURLProvider) GenerateUIRefURL(_ context.Context, _ string, _ string) string {
return ""
}
func (m *mockURLProvider) GetAPIHostname(_ context.Context) string { return "" }
func (m *mockURLProvider) GenerateUIBuildURL(_ context.Context, _, _ string, _ int64) string {
return ""
}
func (m *mockURLProvider) GetGITHostname(_ context.Context) string { return "" }
func (m *mockURLProvider) GetAPIProto(_ context.Context) string { return "" }
func (m *mockURLProvider) RegistryURL(_ context.Context, _ ...string) string { return "" }
func (m *mockURLProvider) PackageURL(ctx context.Context, regRef string, pkgType string, params ...string) string {
if m.pkgURL != nil {
return m.pkgURL(ctx, regRef, pkgType, params...)
}
return ""
}
func (m *mockURLProvider) GetUIBaseURL(_ context.Context, _ ...string) string { return "" }
func (m *mockURLProvider) GenerateUIRegistryURL(_ context.Context, _ string, _ string) string {
return ""
}
// -----------------------
// Helpers
// -----------------------
func newLocalForTests(
lb base.LocalBase,
tags store.PackageTagRepository,
img store.ImageRepository, art store.ArtifactRepository, urlp urlprovider.Provider,
) *localRegistry {
return &localRegistry{
localBase: lb,
fileManager: filemanager.FileManager{},
proxyStore: nil,
tx: nil,
registryDao: nil,
imageDao: img,
tagsDao: tags,
nodesDao: nil,
artifactDao: art,
urlProvider: urlp,
}
}
func sampleArtifactInfo() npm.ArtifactInfo {
return npm.ArtifactInfo{
ArtifactInfo: pkg.ArtifactInfo{
BaseInfo: &pkg.BaseInfo{RootParentID: 1, RootIdentifier: "root"},
Registry: types.Registry{ID: 10, Name: "reg"},
RegistryID: 10,
RegIdentifier: "reg",
Image: "pkg",
},
Version: "1.0.0",
Filename: "pkg-1.0.0.tgz",
}
}
// -----------------------
// Tests
// -----------------------
func TestGetArtifactTypeAndPackageTypes(t *testing.T) {
lr := newLocalForTests(nil, nil, nil, nil, nil)
assert.Equal(t, artifact.RegistryTypeVIRTUAL, lr.GetArtifactType())
assert.Equal(t, []artifact.PackageType{artifact.PackageTypeNPM}, lr.GetPackageTypes())
}
func TestHeadAndDownloadAndDeleteDelegation(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
lb := &mockLocalBase{
checkIfVersionExists: func(_ context.Context, _ pkg.PackageArtifactInfo) (bool, error) { return true, nil },
download: func(
_ context.Context,
_ pkg.ArtifactInfo, _, _ string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error) {
return &commons.ResponseHeaders{Code: 200}, &storage.FileReader{}, "", nil
},
deletePackage: func(context.Context, pkg.PackageArtifactInfo) error { return nil },
deleteVersion: func(context.Context, pkg.PackageArtifactInfo) error { return nil },
}
lr := newLocalForTests(lb, nil, nil, nil, nil)
ok, err := lr.HeadPackageMetadata(ctx, info)
assert.NoError(t, err)
assert.True(t, ok)
_, fr, body, redirect, err := lr.DownloadPackageFile(ctx, info)
assert.NoError(t, err)
assert.NotNil(t, fr)
assert.Nil(t, body)
assert.Equal(t, "", redirect)
assert.NoError(t, lr.DeletePackage(ctx, info))
assert.NoError(t, lr.DeleteVersion(ctx, info))
}
func TestListTags(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
tags := []*types.PackageTagMetadata{{Name: "latest", Version: "1.0.0"}, {Name: "beta", Version: "2.0.0"}}
tdao := &mockTagsDAO{
findByImageNameAndRegID: func(_ context.Context, _ string, _ int64) ([]*types.PackageTagMetadata, error) {
return tags, nil
},
}
lr := newLocalForTests(nil, tdao, nil, nil, nil)
m, err := lr.ListTags(ctx, info)
assert.NoError(t, err)
assert.Equal(t, map[string]string{"latest": "1.0.0", "beta": "2.0.0"}, m)
}
func TestAddTag_Success(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
info.DistTags = []string{"latest"}
imgDAO := &mockImageDAO{
getByRepoAndName: func(_ context.Context, _ int64, _, _ string) (*types.Image, error) {
return &types.Image{ID: 5}, nil
},
}
artDAO := &mockArtifactDAO{
getByName: func(_ context.Context, _ int64, version string) (*types.Artifact, error) {
return &types.Artifact{ID: 7, Version: version}, nil
},
}
created := false
tdao := &mockTagsDAO{
create: func(
_ context.Context,
tag *types.PackageTag,
) (string, error) {
created = true
return tag.ID, nil
},
findByImageNameAndRegID: func(_ context.Context, _ string, _ int64) ([]*types.PackageTagMetadata, error) {
return []*types.PackageTagMetadata{{Name: "latest", Version: info.Version}}, nil
},
}
lr := newLocalForTests(nil, tdao, imgDAO, artDAO, nil)
m, err := lr.AddTag(ctx, info)
assert.NoError(t, err)
assert.True(t, created)
assert.Equal(t, map[string]string{"latest": info.Version}, m)
}
func TestAddTag_NoDistTags(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
imgDAO := &mockImageDAO{
getByRepoAndName: func(_ context.Context, _ int64, _, _ string) (*types.Image, error) {
return &types.Image{ID: 5}, nil
},
}
artDAO := &mockArtifactDAO{
getByName: func(_ context.Context, _ int64, version string) (*types.Artifact, error) {
return &types.Artifact{ID: 7, Version: version}, nil
},
}
lr := newLocalForTests(nil, &mockTagsDAO{}, imgDAO, artDAO, nil)
_, err := lr.AddTag(ctx, info)
assert.Error(t, err)
}
func TestDeleteTag_Success(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
info.DistTags = []string{"beta"}
deleted := false
tdao := &mockTagsDAO{
deleteByTagAndImageName: func(
_ context.Context,
_ string,
_ string,
_ int64,
) error {
deleted = true
return nil
},
findByImageNameAndRegID: func(_ context.Context, _ string, _ int64) ([]*types.PackageTagMetadata, error) {
return []*types.PackageTagMetadata{}, nil
},
}
lr := newLocalForTests(nil, tdao, nil, nil, nil)
m, err := lr.DeleteTag(ctx, info)
assert.NoError(t, err)
assert.True(t, deleted)
assert.Equal(t, map[string]string{}, m)
}
func TestGetPackageMetadata_Success(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
// Prepare artifact with npm metadata
meta := &npmmeta.NpmMetadata{
PackageMetadata: npmmeta.PackageMetadata{
Name: "pkg",
Versions: map[string]*npmmeta.PackageMetadataVersion{
"1.0.0": {Name: "pkg", Version: "1.0.0", Dist: npmmeta.PackageDistribution{}},
},
},
}
metaBytes, _ := json.Marshal(meta)
arts := []types.Artifact{{Version: "1.0.0", Metadata: metaBytes}}
artDAO := &mockArtifactDAO{
getByRegistryIDAndImage: func(_ context.Context, _ int64, _ string) (*[]types.Artifact, error) {
return &arts, nil
},
}
tdao := &mockTagsDAO{
findByImageNameAndRegID: func(_ context.Context, _ string, _ int64) ([]*types.PackageTagMetadata, error) {
return []*types.PackageTagMetadata{{Name: "latest", Version: "1.0.0"}}, nil
},
}
urlp := &mockURLProvider{
pkgURL: func(_ context.Context, _ string, _ string, _ ...string) string {
return "http://example.local/registry"
},
}
lr := newLocalForTests(nil, tdao, nil, artDAO, urlp)
pm, err := lr.GetPackageMetadata(ctx, info)
assert.NoError(t, err)
assert.Equal(t, "pkg", pm.Name)
assert.Contains(t, pm.Versions, "1.0.0")
assert.Equal(t, "1.0.0", pm.DistTags["latest"])
}
func TestSearchPackage_Success(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
verMeta := &npmmeta.PackageMetadataVersion{Name: "pkg", Version: "1.2.3"}
artMeta := &npmmeta.NpmMetadata{
PackageMetadata: npmmeta.PackageMetadata{
Name: "pkg",
Versions: map[string]*npmmeta.PackageMetadataVersion{"1.2.3": verMeta},
},
}
artBytes, _ := json.Marshal(artMeta)
list := []types.Artifact{{Metadata: artBytes}}
artDAO := &mockArtifactDAO{
searchLatestByName: func(_ context.Context, _ int64, _ string, _ int, _ int) (*[]types.Artifact, error) {
return &list, nil
},
countLatestByName: func(_ context.Context, _ int64, _ string) (int64, error) { return 1, nil },
}
urlp := &mockURLProvider{
pkgURL: func(_ context.Context, _ string, _ string, _ ...string) string {
return "http://example.local/r"
},
}
lr := newLocalForTests(nil, nil, nil, artDAO, urlp)
res, err := lr.SearchPackage(ctx, info, 10, 0)
assert.NoError(t, err)
assert.Equal(t, int64(1), res.Total)
assert.Len(t, res.Objects, 1)
assert.Equal(t, "pkg", res.Objects[0].Package.Name)
}
func TestMapHelpers(t *testing.T) {
// getScope
assert.Equal(t, "unscoped", getScope("pkg"))
assert.Equal(t, "myscope", getScope("@myscope/pkg"))
// getValueOrDefault
assert.Equal(t, 5, getValueOrDefault(nil, 5))
assert.Equal(t, 3, getValueOrDefault(3, 5))
// CreatePackageMetadataVersion
ver := &npmmeta.PackageMetadataVersion{
Name: "pkg",
Version: "1.0.0",
Dist: npmmeta.PackageDistribution{
Integrity: "int",
},
}
pmv := CreatePackageMetadataVersion("http://reg", ver)
assert.Equal(t, "pkg@1.0.0", pmv.ID)
assert.Contains(t, pmv.Dist.Tarball, "/pkg/-/1.0.0/pkg-1.0.0.tgz")
}
func TestParseAndUploadNPMPackage_ParseOnly_NoAttachments(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
// JSON without _attachments to avoid storage interaction
body := map[string]any{
"_id": "pkg",
"name": "pkg",
"versions": map[string]any{
"1.0.0": map[string]any{
"name": "pkg",
"version": "1.0.0", "dist": map[string]any{"shasum": "abc", "integrity": "xyz"},
},
},
"dist-tags": map[string]string{"latest": "1.0.0"},
}
buf, _ := json.Marshal(body)
lr := newLocalForTests(&mockLocalBase{}, nil, nil, nil, nil)
var meta npmmeta.PackageMetadata
fi, tmp, err := lr.parseAndUploadNPMPackage(ctx, info, bytes.NewReader(buf), &meta)
assert.NoError(t, err)
assert.Equal(t, types.FileInfo{}, fi)
assert.Equal(t, "", tmp)
assert.Equal(t, "pkg", meta.Name)
assert.Equal(t, "1.0.0", meta.Versions["1.0.0"].Version)
}
func TestProcessAttachmentsOptimized_NoData(t *testing.T) {
ctx := context.Background()
info := sampleArtifactInfo()
// _attachments exists but no data field -> expect error
jsonStr := `{"_attachments": {"pkg-1.0.0.tgz": {"length": 12}}}`
bufReader := bufio.NewReader(bytes.NewReader([]byte(jsonStr)))
dec := json.NewDecoder(bufReader)
lr := newLocalForTests(&mockLocalBase{}, nil, nil, nil, nil)
_, _, err := lr.processAttachmentsOptimized(ctx, info, dec, bufReader)
assert.Error(t, err)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/response/response.go | registry/app/pkg/response/response.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package response
type Response interface {
GetError() error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/cargo/local.go | registry/app/pkg/cargo/local.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargo
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/app/api/request"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
cargometadata "github.com/harness/gitness/registry/app/metadata/cargo"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/store/database/dbtx"
)
var _ pkg.Artifact = (*localRegistry)(nil)
var _ Registry = (*localRegistry)(nil)
type localRegistry struct {
localBase base.LocalBase
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
artifactEventReporter *registryevents.Reporter
postProcessingReporter *asyncprocessing.Reporter
}
type LocalRegistry interface {
Registry
}
func NewLocalRegistry(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistry {
return &localRegistry{
localBase: localBase,
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
artifactEventReporter: artifactEventReporter,
postProcessingReporter: postProcessingReporter,
}
}
func (c *localRegistry) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeVIRTUAL
}
func (c *localRegistry) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeCARGO}
}
func (c *localRegistry) UploadPackage(
ctx context.Context, info cargotype.ArtifactInfo,
metadata *cargometadata.VersionMetadata, crateFile io.ReadCloser,
) (*commons.ResponseHeaders, error) {
// upload crate file
response, err := c.uploadFile(ctx, info, metadata, crateFile)
if err != nil {
return response, fmt.Errorf("failed to upload crate file: %w", err)
}
// publish artifact created event
c.publishArtifactCreatedEvent(ctx, info)
// regenerate package index for cargo client to consume
c.regeneratePackageIndex(ctx, info)
return response, nil
}
func (c *localRegistry) uploadFile(
ctx context.Context, info cargotype.ArtifactInfo,
metadata *cargometadata.VersionMetadata, fileReader io.ReadCloser,
) (responseHeaders *commons.ResponseHeaders, err error) {
fileName := getCrateFileName(info.Image, info.Version)
path := getCrateFilePath(info.Image, info.Version)
response, _, err := c.localBase.Upload(
ctx, info.ArtifactInfo, fileName, info.Version, path, fileReader,
&cargometadata.VersionMetadataDB{
VersionMetadata: *metadata,
})
if err != nil {
return response, fmt.Errorf("failed to upload file: %w", err)
}
return response, nil
}
func (c *localRegistry) publishArtifactCreatedEvent(
ctx context.Context, info cargotype.ArtifactInfo,
) {
session, _ := request.AuthSessionFrom(ctx)
payload := webhook.GetArtifactCreatedPayloadForCommonArtifacts(
session.Principal.ID,
info.RegistryID,
artifact.PackageTypeCARGO,
info.Image,
info.Version,
)
c.artifactEventReporter.ArtifactCreated(ctx, &payload)
}
func (c *localRegistry) regeneratePackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
) {
c.postProcessingReporter.BuildPackageIndex(ctx, info.RegistryID, info.Image)
}
func (c *localRegistry) DownloadPackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
filePath string,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
path := getPackageIndexFilePath(filePath)
response, fileReader, redirectURL, err := c.downloadFileInternal(ctx, info, path)
if err != nil {
return response, nil, nil, "", fmt.Errorf("failed to download package index file: %w", err)
}
return response, fileReader, nil, redirectURL, nil
}
func (c *localRegistry) DownloadPackage(
ctx context.Context, info cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
path := getCrateFilePath(info.Image, info.Version)
response, fileReader, redirectURL, err := c.downloadFileInternal(ctx, info, path)
if err != nil {
return response, nil, nil, "", fmt.Errorf("failed to download package file: %w", err)
}
return response, fileReader, nil, redirectURL, nil
}
func (c *localRegistry) downloadFileInternal(
ctx context.Context, info cargotype.ArtifactInfo, path string,
) (*commons.ResponseHeaders, *storage.FileReader, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
fileReader, _, redirectURL, err := c.fileManager.DownloadFile(ctx, path, info.RegistryID,
info.RegIdentifier, info.RootIdentifier, true)
if err != nil {
return responseHeaders, nil, "", fmt.Errorf("failed to download file %s: %w", path, err)
}
return responseHeaders, fileReader, redirectURL, nil
}
func (c *localRegistry) UpdateYank(
ctx context.Context, info cargotype.ArtifactInfo,
yanked bool,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
// update yanked status in the database
err := c.updateYankInternal(ctx, info, yanked)
if err != nil {
return responseHeaders, fmt.Errorf("failed to update yank status: %w", err)
}
// regenerate package index for cargo client to consume
c.regeneratePackageIndex(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
func (c *localRegistry) updateYankInternal(ctx context.Context, info cargotype.ArtifactInfo, yanked bool) error {
a, err := c.artifactDao.GetByRegistryImageAndVersion(
ctx, info.RegistryID, info.Image, info.Version,
)
if err != nil {
return fmt.Errorf("failed to get artifact by image and version: %w", err)
}
metadata := cargometadata.VersionMetadataDB{}
err = json.Unmarshal(a.Metadata, &metadata)
if err != nil {
return fmt.Errorf("failed to unmarshal metadata for artifact %s: %w", a.Version, err)
}
// Mark the version as yanked
metadata.Yanked = yanked
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal metadata: %w", err)
}
// Update the artifact with the new metadata
a.Metadata = metadataJSON
_, err = c.artifactDao.CreateOrUpdate(ctx, a)
if err != nil {
return fmt.Errorf("failed to update artifact: %w", err)
}
return nil
}
func (c *localRegistry) RegeneratePackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
// regenerate package index for cargo client to consume
c.regeneratePackageIndex(ctx, info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/cargo/wire.go | registry/app/pkg/cargo/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 cargo
import (
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
)
func LocalRegistryProvider(
localBase base.LocalBase,
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistry {
registry := NewLocalRegistry(
localBase, fileManager, proxyStore, tx, registryDao, imageDao, artifactDao,
urlProvider, artifactEventReporter, postProcessingReporter,
)
base.Register(registry)
return registry
}
func ProxyProvider(
proxyStore store.UpstreamProxyConfigRepository,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
fileManager filemanager.FileManager,
tx dbtx.Transactor,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
artifactEventReporter *registryevents.Reporter,
) Proxy {
proxy := NewProxy(fileManager, proxyStore, tx, registryDao, imageDao, artifactDao, urlProvider,
spaceFinder, service, localRegistryHelper, artifactEventReporter)
base.Register(proxy)
return proxy
}
func LocalRegistryHelperProvider(
localRegistry LocalRegistry,
localBase base.LocalBase,
postProcessingReporter *asyncprocessing.Reporter,
) LocalRegistryHelper {
return NewLocalRegistryHelper(localRegistry, localBase, postProcessingReporter)
}
var WireSet = wire.NewSet(LocalRegistryProvider, ProxyProvider, LocalRegistryHelperProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/pkg/cargo/proxy.go | registry/app/pkg/cargo/proxy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargo
import (
"context"
"fmt"
"io"
"net/http"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/services/refcache"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/dist_temp/errcode"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
cargometadata "github.com/harness/gitness/registry/app/metadata/cargo"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/filemanager"
cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/app/store"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/secret"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
var _ pkg.Artifact = (*proxy)(nil)
var _ Registry = (*proxy)(nil)
type proxy struct {
fileManager filemanager.FileManager
proxyStore store.UpstreamProxyConfigRepository
tx dbtx.Transactor
registryDao store.RegistryRepository
imageDao store.ImageRepository
artifactDao store.ArtifactRepository
urlProvider urlprovider.Provider
spaceFinder refcache.SpaceFinder
service secret.Service
localRegistryHelper LocalRegistryHelper
artifactEventReporter *registryevents.Reporter
}
type Proxy interface {
Registry
}
func NewProxy(
fileManager filemanager.FileManager,
proxyStore store.UpstreamProxyConfigRepository,
tx dbtx.Transactor,
registryDao store.RegistryRepository,
imageDao store.ImageRepository,
artifactDao store.ArtifactRepository,
urlProvider urlprovider.Provider,
spaceFinder refcache.SpaceFinder,
service secret.Service,
localRegistryHelper LocalRegistryHelper,
artifactEventReporter *registryevents.Reporter,
) Proxy {
return &proxy{
fileManager: fileManager,
proxyStore: proxyStore,
tx: tx,
registryDao: registryDao,
imageDao: imageDao,
artifactDao: artifactDao,
urlProvider: urlProvider,
spaceFinder: spaceFinder,
service: service,
localRegistryHelper: localRegistryHelper,
artifactEventReporter: artifactEventReporter,
}
}
func (r *proxy) GetArtifactType() artifact.RegistryType {
return artifact.RegistryTypeUPSTREAM
}
func (r *proxy) GetPackageTypes() []artifact.PackageType {
return []artifact.PackageType{artifact.PackageTypeCARGO}
}
func (r *proxy) UploadPackage(
ctx context.Context, _ cargotype.ArtifactInfo,
_ *cargometadata.VersionMetadata, _ io.ReadCloser,
) (*commons.ResponseHeaders, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) DownloadPackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
filePath string,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return responseHeaders, nil, nil, "", fmt.Errorf("failed to get upstream proxy: %w", err)
}
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service, "")
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to create remote registry helper: %w", err)
}
result, err := helper.GetPackageIndex(ctx, info.Image, filePath)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get package index file: %w", err)
}
responseHeaders.Code = http.StatusOK
return responseHeaders, nil, result, "", nil
}
func (r *proxy) DownloadPackage(
ctx context.Context, info cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error) {
responseHeaders := &commons.ResponseHeaders{
Headers: make(map[string]string),
Code: 0,
}
// Get the upstream proxy configuration for the registry
upstreamProxy, err := r.proxyStore.GetByRegistryIdentifier(ctx, info.ParentID, info.RegIdentifier)
if err != nil {
return responseHeaders, nil, nil, "", fmt.Errorf("failed to get upstream proxy: %w", err)
}
// Check if the file exists in the local registry
exists := r.localRegistryHelper.FileExists(ctx, info)
if exists {
headers, fileReader, reader, redirectURL, err := r.localRegistryHelper.DownloadFile(ctx, info)
if err == nil {
return headers, fileReader, reader, redirectURL, nil
}
// If file exists in local registry, but download failed, we should try to download from remote
log.Warn().Ctx(ctx).Msgf("failed to pull from local, attempting streaming from remote, %v", err)
}
// get registry config json from upstream proxy
helper, err := NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service, "")
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to create remote registry helper: %w", err)
}
registryConfig, err := helper.GetRegistryConfig(ctx)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get registry config: %w", err)
}
// download the package file from the upstream proxy
helper, _ = NewRemoteRegistryHelper(ctx, r.spaceFinder, *upstreamProxy, r.service, registryConfig.DownloadURL)
result, err := helper.GetPackageFile(ctx, info.Image, info.Version)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("failed to get registry config: %w", err)
}
go func(info cargotype.ArtifactInfo) {
ctx2 := context.WithoutCancel(ctx)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = r.putFileToLocal(ctx2, &info, helper)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).Msgf(
"error while putting cargo file to localRegistry, %v", err,
)
return
}
log.Ctx(ctx2).Info().Msgf(
"Successfully updated for image: %s, version: %s in registry: %s",
info.Image, info.Version, info.RegIdentifier,
)
}(info)
responseHeaders.Code = http.StatusOK
return responseHeaders, nil, result, "", nil
}
func (r *proxy) UpdateYank(
ctx context.Context, _ cargotype.ArtifactInfo, _ bool,
) (*commons.ResponseHeaders, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) RegeneratePackageIndex(
ctx context.Context, _ cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, error) {
log.Error().Ctx(ctx).Msg("Not implemented")
return nil, errcode.ErrCodeInvalidRequest.WithDetail(fmt.Errorf("not implemented"))
}
func (r *proxy) putFileToLocal(
ctx context.Context, info *cargotype.ArtifactInfo,
remote RemoteRegistryHelper,
) error {
// Get pacakage from upstream source
file, err := remote.GetPackageFile(ctx, info.Image, info.Version)
if err != nil {
return fmt.Errorf("failed to get registry config: %w", err)
}
defer file.Close()
// upload to temporary path
tmpFileName := info.RootIdentifier + "-" + uuid.NewString()
fileInfo, tempFileName, err := r.fileManager.UploadTempFile(ctx, info.RootIdentifier,
nil, tmpFileName, file)
if err != nil {
return fmt.Errorf(
"failed to upload file: %s with registry: %d with error: %w", tmpFileName, info.RegistryID, err)
}
// download the temporary file
tempFile, _, err := r.fileManager.DownloadTempFile(ctx, fileInfo.Size, tempFileName, info.RootIdentifier)
if err != nil {
return fmt.Errorf(
"failed to download file: %s with registry: %d with error: %w", tempFileName,
info.RegistryID, err)
}
defer tempFile.Close()
// generate the metadata
metadata, err := generateMetadataFromFile(info, tempFile)
if err != nil {
return fmt.Errorf("failed to generate metadata: %w", err)
}
// move temporary file to correct location
fileInfo.Filename = getCrateFileName(info.Image, info.Version)
_, _, _, _, err = r.localRegistryHelper.MoveTempFile(
ctx, info, fileInfo, tempFileName, metadata,
)
if err != nil {
return fmt.Errorf("failed to move temp file: %w", err)
}
// publish artifact created event
session, _ := request.AuthSessionFrom(ctx)
payload := webhook.GetArtifactCreatedPayloadForCommonArtifacts(
session.Principal.ID,
info.RegistryID,
artifact.PackageTypeCARGO,
info.Image,
info.Version,
)
r.artifactEventReporter.ArtifactCreated(ctx, &payload)
// regenerate package index
r.localRegistryHelper.UpdatePackageIndex(ctx, *info)
log.Ctx(ctx).Info().Msgf("Successfully uploaded file for pkg: %s , version: %s",
info.Image, info.Version)
return nil
}
| 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.