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/cargo/registry.go | registry/app/pkg/cargo/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 cargo
import (
"context"
"io"
cargometadata "github.com/harness/gitness/registry/app/metadata/cargo"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo"
"github.com/harness/gitness/registry/app/storage"
)
type Registry interface {
pkg.Artifact
// Upload package to registry using cargo CLI
UploadPackage(
ctx context.Context, info cargotype.ArtifactInfo,
metadata *cargometadata.VersionMetadata, crateFile io.ReadCloser,
) (responseHeaders *commons.ResponseHeaders, err error)
// download package index metadata file
DownloadPackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
filePath string,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error)
// regenerate package index
RegeneratePackageIndex(ctx context.Context, info cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, error)
DownloadPackage(
ctx context.Context, info cargotype.ArtifactInfo,
) (*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error)
UpdateYank(
ctx context.Context, info cargotype.ArtifactInfo, yank bool,
) (*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/cargo/helper.go | registry/app/pkg/cargo/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 cargo
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"net/url"
"path"
"strings"
cargometadata "github.com/harness/gitness/registry/app/metadata/cargo"
cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo"
"github.com/harness/gitness/registry/app/storage"
"github.com/pelletier/go-toml/v2"
)
func getCrateFileName(imageName string, version string) string {
return fmt.Sprintf("%s-%s.crate", imageName, version)
}
func getCrateFilePath(imageName string, version string) string {
return fmt.Sprintf("/crates/%s/%s/%s", imageName, version, getCrateFileName(imageName, version))
}
func getPackageIndexFilePath(filePath string) string {
return fmt.Sprintf("/%s/%s", "index", filePath)
}
func downloadPackageFilePath(imageName string, version string) string {
base, _ := url.Parse("")
segments := []string{base.Path}
segments = append(segments, imageName)
segments = append(segments, version)
segments = append(segments, "download")
base.Path = path.Join(segments...)
return strings.TrimRight(base.String(), "/")
}
type cargoManifest struct {
Package struct {
Name string `toml:"name"`
Version string `toml:"version"`
Description string `toml:"description"`
Edition string `toml:"edition"`
License string `toml:"license"`
Keywords []string `toml:"keywords"`
Repository string `toml:"repository"`
Documentation string `toml:"documentation"`
Readme any `toml:"readme"` // value can be bool or string. so normalising this later in the code
ReadmeContent string
} `toml:"package"`
Dependencies map[string]any `toml:"dependencies"`
DevDependencies map[string]any `toml:"dev-dependencies"`
BuildDependencies map[string]any `toml:"build-dependencies"`
}
func getReadmePath(val any) string {
switch v := val.(type) {
case string:
return v
case bool:
if v {
return "README.md" // conventionally true implies README.md
}
return ""
default:
return ""
}
}
func generateMetadataFromFile(
info *cargotype.ArtifactInfo, fileReader *storage.FileReader,
) (*cargometadata.VersionMetadata, error) {
files, err := extractCrate(fileReader)
if err != nil {
return nil, err
}
folderPath := fmt.Sprintf("%s-%s", info.Image, info.Version)
tomlFilePath := fmt.Sprintf("%s/Cargo.toml", folderPath)
cargoTomlData, ok := files[tomlFilePath]
if !ok {
return nil, fmt.Errorf("cargo.toml not found in crate")
}
metadata, err := parseCargoToml(cargoTomlData)
if err != nil {
return nil, fmt.Errorf("failed to parse cargo.toml: %w", err)
}
metadata.Package.ReadmeContent = ""
readmePath := getReadmePath(metadata.Package.Readme)
if readmePath != "" {
readmeFilePath := fmt.Sprintf("%s/%s", folderPath, readmePath)
readmeData, ok := files[readmeFilePath]
if !ok {
return nil, fmt.Errorf("readme not found in crate %s: %w", readmeFilePath, err)
}
metadata.Package.ReadmeContent = string(readmeData)
}
return mapCargoManifestToVersionMetadata(metadata), nil
}
func extractCrate(file io.ReadCloser) (map[string][]byte, error) {
gzr, err := gzip.NewReader(file)
if err != nil {
return nil, err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
files := make(map[string][]byte)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if hdr.Typeflag == tar.TypeReg {
content, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
files[hdr.Name] = content
}
}
return files, nil
}
func parseCargoToml(data []byte) (*cargoManifest, error) {
var manifest cargoManifest
err := toml.Unmarshal(data, &manifest)
if err != nil {
return nil, err
}
return &manifest, nil
}
func mapCargoManifestToVersionMetadata(manifest *cargoManifest) *cargometadata.VersionMetadata {
return &cargometadata.VersionMetadata{
Name: manifest.Package.Name,
Version: manifest.Package.Version,
Description: manifest.Package.Description,
License: manifest.Package.License,
Keywords: manifest.Package.Keywords,
RepositoryURL: manifest.Package.Repository,
DocumentationURL: manifest.Package.Documentation,
Readme: manifest.Package.ReadmeContent,
Yanked: false,
Dependencies: *parseDependencies(manifest),
}
}
func parseDependencies(manifest *cargoManifest) *[]cargometadata.VersionDependency {
var deps []cargometadata.VersionDependency
// Regular dependencies
for name, raw := range manifest.Dependencies {
dep := parseDependency(name, raw, cargometadata.DependencyKindTypeNormal, "")
deps = append(deps, dep)
}
// Dev dependencies
for name, raw := range manifest.DevDependencies {
dep := parseDependency(name, raw, cargometadata.DependencyKindTypeDev, "")
deps = append(deps, dep)
}
// Build dependencies
for name, raw := range manifest.BuildDependencies {
dep := parseDependency(name, raw, cargometadata.DependencyKindTypeBuild, "")
deps = append(deps, dep)
}
return &deps
}
func parseDependency(
name string, raw any, kind cargometadata.DependencyKindType,
target string,
) cargometadata.VersionDependency {
dep := cargometadata.VersionDependency{
Dependency: cargometadata.Dependency{
Name: name,
Kind: kind,
Target: target,
ExplicitNameInToml: name,
DefaultFeatures: true, // default in Cargo
},
VersionRequired: "",
}
switch val := raw.(type) {
case string:
// Simple version
dep.VersionRequired = val
case map[string]any:
if version, ok := val["version"].(string); ok {
dep.VersionRequired = version
}
if features, ok := val["features"].([]any); ok {
for _, f := range features {
dep.Features = append(dep.Features, fmt.Sprint(f))
}
}
if optional, ok := val["optional"].(bool); ok {
dep.IsOptional = optional
}
if defaultFeatures, ok := val["default-features"].(bool); ok {
dep.DefaultFeatures = defaultFeatures
}
if registry, ok := val["registry"].(string); ok {
dep.Registry = registry
}
}
return dep
}
| 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/remote_helper.go | registry/app/pkg/cargo/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 cargo
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/metadata/cargo"
"github.com/harness/gitness/registry/app/remote/adapter"
crates "github.com/harness/gitness/registry/app/remote/adapter/crates"
"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 {
// GetRegistryConfig Fetches the registry configuration for the remote registry
GetRegistryConfig(ctx context.Context) (*cargo.RegistryConfig, error)
// GetFile Downloads the file for the given package and filename
GetPackageFile(ctx context.Context, pkg string, version string) (io.ReadCloser, error)
// GetPackageIndex Fetches the package index for the given package
GetPackageIndex(ctx context.Context, pkg string, filePath string) (io.ReadCloser, error)
}
type remoteRegistryHelper struct {
adapter registry.CargoRegistry
registry types.UpstreamProxy
}
func NewRemoteRegistryHelper(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
remoteURL string,
) (RemoteRegistryHelper, error) {
r := &remoteRegistryHelper{
registry: registry,
}
if err := r.init(ctx, spaceFinder, service, remoteURL); 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,
remoteURL string,
) error {
key := string(artifact.PackageTypeCARGO)
if r.registry.Source == string(artifact.UpstreamConfigSourceCrates) {
r.registry.RepoURL = crates.CratesURL
}
if remoteURL != "" {
r.registry.RepoURL = remoteURL
}
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
}
cargoReg, ok := adpt.(registry.CargoRegistry)
if !ok {
log.Ctx(ctx).Error().Msg("failed to cast factory to cargo registry")
return err
}
r.adapter = cargoReg
return nil
}
func (r *remoteRegistryHelper) GetRegistryConfig(ctx context.Context) (*cargo.RegistryConfig, error) {
config, err := r.adapter.GetRegistryConfig(ctx)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to get registry config")
return nil, fmt.Errorf("failed to get registry config: %w", err)
}
return config, nil
}
func (r *remoteRegistryHelper) GetPackageIndex(ctx context.Context, pkg string, filePath string) (
io.ReadCloser,
error,
) {
data, err := r.adapter.GetPackageFile(ctx, filePath)
if err != nil {
return nil, fmt.Errorf("failed to get package index %s: %w", pkg, err)
}
if data == nil {
return nil, fmt.Errorf("index metadata not found for package: %s", pkg)
}
return data, err
}
func (r *remoteRegistryHelper) GetPackageFile(
ctx context.Context, pkg string, version string,
) (io.ReadCloser, error) {
// get the file for the package
filePath := downloadPackageFilePath(pkg, version)
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/cargo/local_helper.go | registry/app/pkg/cargo/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 cargo
import (
"context"
"io"
"strings"
"github.com/harness/gitness/registry/app/events/asyncprocessing"
cargometadata "github.com/harness/gitness/registry/app/metadata/cargo"
"github.com/harness/gitness/registry/app/pkg/base"
"github.com/harness/gitness/registry/app/pkg/commons"
cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo"
"github.com/harness/gitness/registry/app/storage"
"github.com/harness/gitness/registry/types"
)
type LocalRegistryHelper interface {
FileExists(ctx context.Context, info cargotype.ArtifactInfo) bool
DownloadFile(ctx context.Context, info cargotype.ArtifactInfo) (
*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error,
)
MoveTempFile(
ctx context.Context, info *cargotype.ArtifactInfo, fileInfo types.FileInfo,
filename string, metadata *cargometadata.VersionMetadata,
) (*commons.ResponseHeaders, string, int64, bool, error)
UpdatePackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
)
}
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 cargotype.ArtifactInfo) bool {
return h.localBase.Exists(ctx, info.ArtifactInfo, strings.TrimLeft(getCrateFilePath(info.Image, info.Version), "/"))
}
func (h *localRegistryHelper) DownloadFile(ctx context.Context, info cargotype.ArtifactInfo) (
*commons.ResponseHeaders, *storage.FileReader, io.ReadCloser, string, error,
) {
return h.localRegistry.DownloadPackage(ctx, info)
}
func (h *localRegistryHelper) UpdatePackageIndex(
ctx context.Context, info cargotype.ArtifactInfo,
) {
h.postProcessingReporter.BuildPackageIndex(ctx, info.RegistryID, info.Image)
}
func (h *localRegistryHelper) MoveTempFile(
ctx context.Context, info *cargotype.ArtifactInfo, fileInfo types.FileInfo,
filename string, metadata *cargometadata.VersionMetadata,
) (*commons.ResponseHeaders, string, int64, bool, error) {
return h.localBase.MoveTempFileAndCreateArtifact(
ctx, info.ArtifactInfo, filename, info.Version,
getCrateFilePath(info.Image, info.Version),
&cargometadata.VersionMetadataDB{
VersionMetadata: *metadata,
}, fileInfo, false)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/services/publicaccess/wire.go | registry/app/services/publicaccess/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 publicaccess
import (
"context"
"time"
"github.com/harness/gitness/app/services/publicaccess"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/pubsub"
"github.com/google/wire"
)
const (
registryPublicAccessCacheDuration = 10 * time.Minute
)
const (
pubsubNamespace = "cache-evictor"
pubsubTopicRegPublicAccessUpdate = "reg-public-access-update"
)
func ProvideEvictorPublicAccess(pubsub pubsub.PubSub) cache2.Evictor[*CacheKey] {
return cache2.NewEvictor[*CacheKey](pubsubNamespace, pubsubTopicRegPublicAccessUpdate, pubsub)
}
func ProvidePublicAccessCache(
appCtx context.Context,
publicAccessService publicaccess.Service,
evictor cache2.Evictor[*CacheKey],
) Cache {
return NewPublicAccessCacheCache(appCtx, publicAccessService, evictor, registryPublicAccessCacheDuration)
}
func ProvideRegistryPublicAccess(
publicAccessService publicaccess.Service,
publicAccessCache Cache,
evictor cache2.Evictor[*CacheKey],
) CacheService {
return NewPublicAccessService(
publicAccessService,
publicAccessCache,
evictor,
)
}
var WireSet = wire.NewSet(
ProvideEvictorPublicAccess,
ProvidePublicAccessCache,
ProvideRegistryPublicAccess,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/services/publicaccess/public_access.go | registry/app/services/publicaccess/public_access.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package publicaccess
import (
"context"
"encoding/gob"
"fmt"
"time"
"github.com/harness/gitness/app/services/publicaccess"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/cache"
"github.com/harness/gitness/types/enum"
)
type CacheService interface {
Get(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
) (bool, error)
Set(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
enable bool,
) error
Delete(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
) error
IsPublicAccessSupported(
ctx context.Context,
resourceType enum.PublicResourceType,
parentSpacePath string,
) (bool, error)
MarkChanged(ctx context.Context, publicAccessCacheKey *CacheKey)
}
type CacheKey struct {
ResourceType enum.PublicResourceType
ResourcePath string
}
type Cache cache.Cache[CacheKey, bool]
func NewPublicAccessService(
publicAccessService publicaccess.Service,
publicAccessCache Cache,
evictor cache2.Evictor[*CacheKey],
) CacheService {
gob.Register(&CacheKey{})
return &service{
publicAccessService: publicAccessService,
publicAccessCache: publicAccessCache,
evictor: evictor,
}
}
type service struct {
publicAccessService publicaccess.Service
publicAccessCache Cache
evictor cache2.Evictor[*CacheKey]
}
func NewPublicAccessCacheCache(
appCtx context.Context,
publicAccessService publicaccess.Service,
evictor cache2.Evictor[*CacheKey],
dur time.Duration,
) Cache {
c := cache.New[CacheKey, bool](publicAccessCacheGetter{publicAccessService: publicAccessService}, dur)
evictor.Subscribe(appCtx, func(key *CacheKey) error {
c.Evict(appCtx, *key)
return nil
})
return c
}
func (s *service) Get(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
) (bool, error) {
isPublic, err := s.publicAccessCache.Get(ctx,
CacheKey{ResourceType: resourceType, ResourcePath: resourcePath})
if err != nil {
return false, fmt.Errorf("failed to get public access: %w", err)
}
return isPublic, nil
}
func (s *service) Set(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
enable bool,
) error {
err := s.publicAccessService.Set(ctx, resourceType, resourcePath, enable)
if err == nil {
s.MarkChanged(ctx, &CacheKey{ResourceType: resourceType, ResourcePath: resourcePath})
}
return err
}
func (s *service) Delete(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
) error {
err := s.publicAccessService.Delete(ctx, resourceType, resourcePath)
if err == nil {
s.MarkChanged(ctx, &CacheKey{ResourceType: resourceType, ResourcePath: resourcePath})
}
return err
}
func (s *service) IsPublicAccessSupported(
ctx context.Context,
resourceType enum.PublicResourceType,
resourcePath string,
) (bool, error) {
return s.publicAccessService.IsPublicAccessSupported(ctx, resourceType, resourcePath)
}
func (s *service) MarkChanged(ctx context.Context, publicAccessCacheKey *CacheKey) {
s.evictor.Evict(ctx, publicAccessCacheKey)
}
type publicAccessCacheGetter struct {
publicAccessService publicaccess.Service
}
func (c publicAccessCacheGetter) Find(
ctx context.Context,
publicAccessCacheKey CacheKey,
) (bool, error) {
isPublic, err := c.publicAccessService.Get(ctx, publicAccessCacheKey.ResourceType, publicAccessCacheKey.ResourcePath)
if err != nil {
return false, fmt.Errorf("failed to find repo by ID: %w", err)
}
return isPublic, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/services/refcache/wire.go | registry/app/services/refcache/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 refcache
import (
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/google/wire"
)
func ProvideRegistryFinder(
registryRepository store.RegistryRepository,
regIDCache store.RegistryIDCache,
regRootRefCache store.RegistryRootRefCache,
evictor cache.Evictor[*types.Registry],
spaceFinder refcache.SpaceFinder,
) RegistryFinder {
return NewRegistryFinder(registryRepository, regIDCache, regRootRefCache, evictor, spaceFinder)
}
var WireSet = wire.NewSet(
ProvideRegistryFinder,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/services/refcache/reg_finder.go | registry/app/services/refcache/reg_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 refcache
import (
"context"
"fmt"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
)
type RegistryFinder interface {
MarkChanged(ctx context.Context, reg *types.Registry)
FindByID(ctx context.Context, repoID int64) (*types.Registry, error)
FindByRootRef(ctx context.Context, rootParentRef string, regIdentifier string) (
*types.Registry,
error,
)
FindByRootParentID(ctx context.Context, rootParentID int64, regIdentifier string) (
*types.Registry,
error,
)
Update(ctx context.Context, registry *types.Registry) (err error)
Delete(ctx context.Context, parentID int64, name string) (err error)
}
type registryFinder struct {
inner store.RegistryRepository
regIDCache store.RegistryIDCache
regRootRefCache store.RegistryRootRefCache
spaceFinder refcache.SpaceFinder
evictor cache.Evictor[*types.Registry]
}
func NewRegistryFinder(
registryRepository store.RegistryRepository,
regIDCache store.RegistryIDCache,
regRootRefCache store.RegistryRootRefCache,
evictor cache.Evictor[*types.Registry],
spaceFinder refcache.SpaceFinder,
) RegistryFinder {
return registryFinder{
inner: registryRepository,
regIDCache: regIDCache,
regRootRefCache: regRootRefCache,
evictor: evictor,
spaceFinder: spaceFinder,
}
}
func (r registryFinder) MarkChanged(ctx context.Context, reg *types.Registry) {
r.evictor.Evict(ctx, reg)
}
func (r registryFinder) FindByID(ctx context.Context, repoID int64) (*types.Registry, error) {
return r.regIDCache.Get(ctx, repoID)
}
func (r registryFinder) FindByRootRef(ctx context.Context, rootParentRef string, regIdentifier string) (
*types.Registry,
error,
) {
space, err := r.spaceFinder.FindByRef(ctx, rootParentRef)
if err != nil {
return nil, fmt.Errorf("error finding space by root-ref: %w", err)
}
return r.FindByRootParentID(ctx, space.ID, regIdentifier)
}
func (r registryFinder) FindByRootParentID(ctx context.Context, rootParentID int64, regIdentifier string) (
*types.Registry,
error,
) {
registryID, err := r.regRootRefCache.Get(ctx,
types.RegistryRootRefCacheKey{RootParentID: rootParentID, RegistryIdentifier: regIdentifier})
if err != nil {
return nil, fmt.Errorf("error finding registry by root-ref: %w", err)
}
return r.regIDCache.Get(ctx, registryID)
}
func (r registryFinder) Update(ctx context.Context, registry *types.Registry) (err error) {
err = r.inner.Update(ctx, registry)
if err == nil {
r.MarkChanged(ctx, registry)
}
return err
}
func (r registryFinder) Delete(ctx context.Context, parentID int64, name string) (err error) {
registry, err := r.inner.GetByParentIDAndName(ctx, parentID, name)
if err != nil {
return fmt.Errorf("error finding registry by parent-ref: %w", err)
}
err = r.inner.Delete(ctx, parentID, name)
if err == nil {
r.MarkChanged(ctx, registry)
}
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/auth/auth.go | registry/app/auth/auth.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"net/http"
"strings"
)
// AccessSet maps a typed, named resource to
// a set of actions requested or authorized.
type AccessSet map[Resource]ActionSet
// NewAccessSet constructs an accessSet from
// a variable number of auth.Access items.
func NewAccessSet(accessItems ...Access) AccessSet {
accessSet := make(AccessSet, len(accessItems))
for _, access := range accessItems {
resource := Resource{
Type: access.Type,
Name: access.Name,
}
set, exists := accessSet[resource]
if !exists {
set = NewActionSet()
accessSet[resource] = set
}
set.Add(access.Action)
}
return accessSet
}
// Contains returns whether or not the given access is in this accessSet.
func (s AccessSet) Contains(access Access) bool {
actionSet, ok := s[access.Resource]
if ok {
return actionSet.contains(access.Action)
}
return false
}
// ScopeParam returns a collection of scopes which can
// be used for a WWW-Authenticate challenge parameter.
func (s AccessSet) ScopeParam() string {
scopes := make([]string, 0, len(s))
for resource, actionSet := range s {
actions := strings.Join(actionSet.keys(), ",")
resourceName := resource.Name
scopes = append(scopes, strings.Join([]string{resource.Type, resourceName, actions}, ":"))
}
return strings.Join(scopes, " ")
}
// Resource describes a resource by type and name.
type Resource struct {
Type string
Name string
}
// Access describes a specific action that is
// requested or allowed for a given resource.
type Access struct {
Resource
Action string
}
func AppendAccess(records []Access, method string, name string) []Access {
resource := Resource{
Type: "repository",
Name: name,
}
switch method {
case http.MethodGet, http.MethodHead:
records = append(records,
Access{
Resource: resource,
Action: "pull",
})
case http.MethodPost, http.MethodPut, http.MethodPatch:
records = append(records,
Access{
Resource: resource,
Action: "pull",
},
Access{
Resource: resource,
Action: "push",
})
case http.MethodDelete:
records = append(records,
Access{
Resource: resource,
Action: "delete",
})
}
return records
}
// ActionSet is a special type of stringSet.
type ActionSet struct {
stringSet
}
func NewActionSet(actions ...string) ActionSet {
return ActionSet{newStringSet(actions...)}
}
// Contains calls StringSet.Contains() for
// either "*" or the given action string.
func (s ActionSet) Contains(action string) bool {
return s.stringSet.contains("*") || s.stringSet.contains(action)
}
// StringSet is a useful type for looking up strings.
type stringSet map[string]struct{}
// NewStringSet creates a new StringSet with the given strings.
func newStringSet(keys ...string) stringSet {
ss := make(stringSet, len(keys))
ss.Add(keys...)
return ss
}
// Add inserts the given keys into this StringSet.
func (ss stringSet) Add(keys ...string) {
for _, key := range keys {
ss[key] = struct{}{}
}
}
// Contains returns whether the given key is in this StringSet.
func (ss stringSet) contains(key string) bool {
_, ok := ss[key]
return ok
}
// Keys returns a slice of all keys in this StringSet.
func (ss stringSet) keys() []string {
keys := make([]string, 0, len(ss))
for key := range ss {
keys = append(keys, key)
}
return keys
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/file.go | registry/app/metadata/file.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadata
type File struct {
Size int64 `json:"size"`
Filename string `json:"file_name"`
CreatedAt int64 `json:"created_at"`
Sha256 string `json:"sha256"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/provider.go | registry/app/metadata/provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadata
type Metadata interface {
GetFiles() []File
SetFiles([]File)
GetSize() int64
UpdateSize(int64)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/pkg.go | registry/app/metadata/pkg.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metadata
type GenericMetadata struct {
Size int64 `json:"size"`
Files []File `json:"files"`
Description string `json:"desc"`
FileCount int64 `json:"file_count"`
}
type MavenMetadata struct {
Files []File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (m *MavenMetadata) GetFiles() []File {
return m.Files
}
func (m *MavenMetadata) SetFiles(files []File) {
m.Files = files
m.FileCount = int64(len(files))
}
func (m *MavenMetadata) GetSize() int64 {
return m.Size
}
func (m *MavenMetadata) UpdateSize(size int64) {
m.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/python/metadata.go | registry/app/metadata/python/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package python
import "github.com/harness/gitness/registry/app/metadata"
var _ metadata.Metadata = (*PythonMetadata)(nil)
// Metadata Source: https://github.com/pypa/twine/blob/main/twine/package.py
type Metadata struct {
// Metadata 1.0
MetadataVersion string `json:"metadata_version,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Platform []string `json:"platform,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Keywords []string `json:"keywords,omitempty"`
HomePage string `json:"home_page,omitempty"`
Author string `json:"author,omitempty"`
AuthorEmail string `json:"author_email,omitempty"`
License string `json:"license,omitempty"`
// Metadata 1.1
SupportedPlatform []string `json:"supported_platform,omitempty"`
DownloadURL string `json:"download_url,omitempty"`
Classifiers []string `json:"classifiers,omitempty"`
Requires []string `json:"requires,omitempty"`
Provides []string `json:"provides,omitempty"`
Obsoletes []string `json:"obsoletes,omitempty"`
// Metadata 1.2
Maintainer string `json:"maintainer,omitempty"`
MaintainerEmail string `json:"maintainer_email,omitempty"`
RequiresDist []string `json:"requires_dist,omitempty"`
ProvidesDist []string `json:"provides_dist,omitempty"`
ObsoletesDist []string `json:"obsoletes_dist,omitempty"`
RequiresPython string `json:"requires_python,omitempty"`
RequiresExternal []string `json:"requires_external,omitempty"`
ProjectURLs map[string]string `json:"project_urls,omitempty"`
// Metadata 2.1
DescriptionContentType string `json:"description_content_type,omitempty"`
ProvidesExtra []string `json:"provides_extra,omitempty"`
// Metadata 2.2
Dynamic []string `json:"dynamic,omitempty"`
// Metadata 2.4
LicenseExpression string `json:"license_expression,omitempty"`
LicenseFile []string `json:"license_file,omitempty"`
// Additional metadata
Comment string `json:"comment,omitempty"`
PyVersion string `json:"pyversion,omitempty"`
FileType string `json:"filetype,omitempty"`
GPGSignature []string `json:"gpg_signature,omitempty"`
Attestations string `json:"attestations,omitempty"`
MD5Digest string `json:"md5_digest,omitempty"`
SHA256Digest string `json:"sha256_digest,omitempty"`
Blake2256Digest string `json:"blake2_256_digest,omitempty"`
// Legacy fields kept for compatibility
LongDescription string `json:"long_description,omitempty"`
ProjectURL string `json:"project_url,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}
// PythonMetadata represents the metadata for a Python package.
//
//nolint:revive
type PythonMetadata struct {
Metadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *PythonMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *PythonMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *PythonMetadata) GetSize() int64 {
return p.Size
}
func (p *PythonMetadata) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/generic/metadata.go | registry/app/metadata/generic/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import "github.com/harness/gitness/registry/app/metadata"
var _ metadata.Metadata = (*GenericMetadata)(nil)
// GenericMetadata represents the metadata for a Generic package.
//
//nolint:revive
type GenericMetadata struct {
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *GenericMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *GenericMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *GenericMetadata) GetSize() int64 {
return p.Size
}
func (p *GenericMetadata) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/huggingface/metadata.go | registry/app/metadata/huggingface/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package huggingface
import "github.com/harness/gitness/registry/app/metadata"
// CardData represents the card data for a HuggingFace model.
type CardData struct {
Language []string `json:"language,omitempty"`
Tags []string `json:"tags,omitempty"`
License string `json:"license,omitempty"`
}
// Sibling represents a file in a HuggingFace model.
type Sibling struct {
RFilename string `json:"rfilename"`
}
var _ metadata.Metadata = (*HuggingFaceMetadata)(nil)
type Metadata struct {
ID string `json:"id"`
ModelID string `json:"modelId,omitempty"` //nolint:tagliatelle
SHA string `json:"sha,omitempty"`
Downloads int64 `json:"downloads,omitempty"`
Likes int64 `json:"likes,omitempty"`
LibraryName string `json:"libraryName,omitempty"` //nolint:tagliatelle
Tags []string `json:"tags,omitempty"`
CardData *CardData `json:"cardData,omitempty"` //nolint:tagliatelle
Siblings []Sibling `json:"siblings,omitempty"`
LastModified string `json:"lastModified,omitempty"` //nolint:tagliatelle
Private bool `json:"private,omitempty"`
Readme string `json:"readme,omitempty"`
}
//nolint:revive
type HuggingFaceMetadata struct {
Metadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *HuggingFaceMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *HuggingFaceMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *HuggingFaceMetadata) GetSize() int64 {
return p.Size
}
func (p *HuggingFaceMetadata) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/rpm/metadata.go | registry/app/metadata/rpm/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpm
import "github.com/harness/gitness/registry/app/metadata"
var _ metadata.Metadata = (*RpmMetadata)(nil)
type Metadata struct {
VersionMetadata VersionMetadata `json:"version_metadata"`
FileMetadata FileMetadata `json:"file_metadata"`
}
type VersionMetadata struct {
License string `json:"license,omitempty"`
ProjectURL string `json:"project_url,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
}
type FileMetadata struct {
Architecture string `json:"architecture,omitempty"`
Epoch string `json:"epoch,omitempty"`
Version string `json:"version,omitempty"`
Release string `json:"release,omitempty"`
Vendor string `json:"vendor,omitempty"`
Group string `json:"group,omitempty"`
Packager string `json:"packager,omitempty"`
SourceRpm string `json:"source_rpm,omitempty"`
BuildHost string `json:"build_host,omitempty"`
BuildTime uint64 `json:"build_time,omitempty"`
FileTime uint64 `json:"file_time,omitempty"`
InstalledSize uint64 `json:"installed_size,omitempty"`
ArchiveSize uint64 `json:"archive_size,omitempty"`
Provides []*Entry `json:"provide,omitempty"`
Requires []*Entry `json:"require,omitempty"`
Conflicts []*Entry `json:"conflict,omitempty"`
Obsoletes []*Entry `json:"obsolete,omitempty"`
Files []*File `json:"files,omitempty"`
Changelogs []*Changelog `json:"changelogs,omitempty"`
}
type Entry struct {
Name string `json:"name" xml:"name,attr"`
Flags string `json:"flags,omitempty" xml:"flags,attr,omitempty"`
Version string `json:"version,omitempty" xml:"ver,attr,omitempty"`
Epoch string `json:"epoch,omitempty" xml:"epoch,attr,omitempty"`
Release string `json:"release,omitempty" xml:"rel,attr,omitempty"`
}
type File struct {
Path string `json:"path" xml:",chardata"` // nolint: tagliatelle
Type string `json:"type,omitempty" xml:"type,attr,omitempty"`
IsExecutable bool `json:"is_executable" xml:"-"`
}
type Changelog struct {
Author string `json:"author,omitempty" xml:"author,attr"`
Date int64 `json:"date,omitempty" xml:"date,attr"`
Text string `json:"text,omitempty" xml:",chardata"` // nolint: tagliatelle
}
// RpmMetadata represents the metadata for a RPM package.
//
//nolint:revive
type RpmMetadata struct {
Metadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *RpmMetadata) GetSize() int64 {
return p.Size
}
func (p *RpmMetadata) UpdateSize(size int64) {
p.Size += size
}
func (p *RpmMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *RpmMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/gopackage/metadata.go | registry/app/metadata/gopackage/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopackage
import "github.com/harness/gitness/registry/app/metadata"
// nolint:tagliatelle
type VersionMetadata struct {
Name string `json:"Name"`
Version string `json:"Version"`
Time string `json:"Time"`
Origin Origin `json:"Origin"`
Dependencies []Dependency `json:"Dependencies,omitempty"`
Readme string `json:"Readme,omitempty"`
}
// nolint:tagliatelle
type Origin struct {
VCS string `json:"VCS,omitempty"`
URL string `json:"URL,omitempty"`
Ref string `json:"Ref,omitempty"`
Hash string `json:"Hash,omitempty"`
}
// nolint:tagliatelle
type Dependency struct {
Name string `json:"Name"`
Version string `json:"Version"`
}
type VersionMetadataDB struct {
VersionMetadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *VersionMetadataDB) GetFiles() []metadata.File {
return p.Files
}
func (p *VersionMetadataDB) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *VersionMetadataDB) GetSize() int64 {
return p.Size
}
func (p *VersionMetadataDB) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/nuget/metadata.go | registry/app/metadata/nuget/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"github.com/harness/gitness/registry/app/metadata"
)
var _ metadata.Metadata = (*NugetMetadata)(nil)
//nolint:revive
type NugetMetadata struct {
Metadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *NugetMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *NugetMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *NugetMetadata) GetSize() int64 {
return p.Size
}
func (p *NugetMetadata) UpdateSize(size int64) {
p.Size += size
}
// Package represents the entire NuGet package.
type Metadata struct {
PackageMetadata PackageMetadata `json:"metadata" xml:"metadata"`
Files *FilesWrapper `json:"files,omitempty" xml:"files,omitempty"`
}
// PackageMetadata represents the metadata of a NuGet package.
type PackageMetadata struct {
ID string `json:"id" xml:"id"`
Version string `json:"version" xml:"version"`
Title string `json:"title,omitempty" xml:"title,omitempty"`
Authors string `json:"authors" xml:"authors"`
Owners string `json:"owners,omitempty" xml:"owners,omitempty"`
LicenseURL string `json:"licenseUrl,omitempty" xml:"licenseUrl,omitempty"`
ProjectURL string `json:"projectUrl,omitempty" xml:"projectUrl,omitempty"`
IconURL string `json:"iconUrl,omitempty" xml:"iconUrl,omitempty"`
RequireLicenseAcceptance bool `json:"requireLicenseAcceptance,omitempty" xml:"requireLicenseAcceptance,omitempty"`
DevelopmentDependency bool `json:"developmentDependency,omitempty" xml:"developmentDependency,omitempty"`
Description string `json:"description" xml:"description"`
Summary string `json:"summary,omitempty" xml:"summary,omitempty"`
ReleaseNotes string `json:"releaseNotes,omitempty" xml:"releaseNotes,omitempty"`
Copyright string `json:"copyright,omitempty" xml:"copyright,omitempty"`
Language string `json:"language,omitempty" xml:"language,omitempty"`
Tags string `json:"tags,omitempty" xml:"tags,omitempty"`
Serviceable bool `json:"serviceable,omitempty" xml:"serviceable,omitempty"`
Icon string `json:"icon,omitempty" xml:"icon,omitempty"`
Readme string `json:"readme,omitempty" xml:"readme,omitempty"`
Repository *Repository `json:"repository,omitempty" xml:"repository,omitempty"`
License *License `json:"license,omitempty" xml:"license,omitempty"`
PackageTypes []PackageType `json:"packageTypes,omitempty" xml:"packageType"`
Dependencies *DependenciesWrapper `json:"dependencies,omitempty" xml:"dependencies,omitempty"`
MinClientVersion string `json:"minClientVersion,omitempty" xml:"minClientVersion,attr"`
}
// Dependency represents a package dependency.
type Dependency struct {
ID string `json:"id,omitempty" xml:"id,attr"`
Version string `json:"version,omitempty" xml:"version,attr"`
Include string `json:"include,omitempty" xml:"include,attr"`
Exclude string `json:"exclude,omitempty" xml:"exclude,attr"`
}
// DependencyGroup represents a group of dependencies.
type DependencyGroup struct {
TargetFramework string `json:"targetFramework,omitempty" xml:"targetFramework,attr"`
Dependencies []Dependency `json:"dependencies,omitempty" xml:"dependency"`
}
// PackageType represents a package type.
type PackageType struct {
Name string `json:"name" xml:"name,attr"`
Version string `json:"version,omitempty" xml:"version,attr"`
}
// Repository represents the repository information.
type Repository struct {
Type string `json:"type,omitempty" xml:"type,attr"`
URL string `json:"url,omitempty" xml:"url,attr"`
Branch string `json:"branch,omitempty" xml:"branch,attr"`
Commit string `json:"commit,omitempty" xml:"commit,attr"`
}
// License represents a package license.
type License struct {
Type string `json:"type" xml:"type,attr"`
Version string `json:"version,omitempty" xml:"version,attr"`
//nolint:staticcheck
Text string `json:",chardata" xml:",chardata"`
}
// DependenciesWrapper represents the `<dependencies>` section.
type DependenciesWrapper struct {
Dependencies []Dependency `json:"dependencies,omitempty" xml:"dependency"`
Groups []DependencyGroup `json:"groups,omitempty" xml:"group"`
}
// File represents an individual file in the `<files>` section.
type File struct {
Src string `json:"src" xml:"src,attr"`
Target string `json:"target,omitempty" xml:"target,attr"`
Exclude string `json:"exclude,omitempty" xml:"exclude,attr"`
}
// FilesWrapper represents the `<files>` section.
type FilesWrapper struct {
Files []File `json:"files,omitempty" xml:"file"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/npm/metadata.go | registry/app/metadata/npm/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npm
import (
"time"
"github.com/harness/gitness/registry/app/metadata"
)
// PackageAttachment https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#package
// nolint:tagliatelle
type PackageAttachment struct {
ContentType string `json:"content_type"`
Data string `json:"data"`
Length int `json:"length"`
}
// nolint:tagliatelle
type PackageUpload struct {
PackageMetadata
Attachments map[string]*PackageAttachment `json:"_attachments"`
}
// nolint:tagliatelle
type PackageMetadata struct {
ID string `json:"_id"`
Name string `json:"name"`
Description string `json:"description"`
DistTags map[string]string `json:"dist-tags,omitempty"`
Versions map[string]*PackageMetadataVersion `json:"versions"`
Readme string `json:"readme,omitempty"`
Maintainers []User `json:"maintainers,omitempty"`
Time map[string]time.Time `json:"time,omitempty"`
Homepage string `json:"homepage,omitempty"`
Keywords []string `json:"keywords,omitempty"`
Repository any `json:"repository,omitempty"`
Author any `json:"author"`
ReadmeFilename string `json:"readmeFilename,omitempty"`
Users map[string]bool `json:"users,omitempty"`
License any `json:"license,omitempty"`
}
// PackageMetadataVersion documentation:
// https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#version
// PackageMetadataVersion response:
// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object
// nolint:tagliatelle
type PackageMetadataVersion struct {
ID string `json:"_id"`
Name string `json:"name"`
Version string `json:"version"`
Description any `json:"description"`
Author any `json:"author"`
Homepage any `json:"homepage,omitempty"`
License any `json:"license,omitempty"`
Repository any `json:"repository,omitempty"`
Keywords any `json:"keywords,omitempty"`
Dependencies map[string]string `json:"dependencies,omitempty"`
BundleDependencies any `json:"bundleDependencies,omitempty"`
DevDependencies any `json:"devDependencies,omitempty"`
PeerDependencies any `json:"peerDependencies,omitempty"`
Bin any `json:"bin,omitempty"`
OptionalDependencies any `json:"optionalDependencies,omitempty"`
Readme string `json:"readme,omitempty"`
Dist PackageDistribution `json:"dist"`
Maintainers any `json:"maintainers,omitempty"`
}
// Repository https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#version
// nolint:tagliatelle
type Repository struct {
Type string `json:"type"`
URL string `json:"url"`
}
// PackageDistribution https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#version
// nolint:tagliatelle
type PackageDistribution struct {
Integrity string `json:"integrity"`
Shasum string `json:"shasum"`
Tarball string `json:"tarball"`
FileCount int `json:"fileCount,omitempty"`
UnpackedSize int `json:"unpackedSize,omitempty"`
NpmSignature string `json:"npm-signature,omitempty"`
}
type PackageSearch struct {
Objects []*PackageSearchObject `json:"objects"`
Total int64 `json:"total"`
}
type PackageSearchObject struct {
Package *PackageSearchPackage `json:"package"`
}
type PackageSearchPackage struct {
Scope string `json:"scope"`
Name string `json:"name"`
Version string `json:"version"`
Date any `json:"date"`
Description any `json:"description"`
Author any `json:"author"`
Publisher any `json:"publisher"`
Maintainers any `json:"maintainers"`
Keywords any `json:"keywords,omitempty"`
Links *PackageSearchPackageLinks `json:"links"`
}
type PackageSearchPackageLinks struct {
Registry string `json:"npm"`
Homepage string `json:"homepage,omitempty"`
Repository string `json:"repository,omitempty"`
}
type User struct {
Username string `json:"username,omitempty"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
URL string `json:"url,omitempty"`
}
// NpmMetadata represents the metadata for a Python package.
//
//nolint:revive
type NpmMetadata struct {
PackageMetadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *NpmMetadata) GetFiles() []metadata.File {
return p.Files
}
func (p *NpmMetadata) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *NpmMetadata) GetSize() int64 {
return p.Size
}
func (p *NpmMetadata) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/metadata/cargo/metadata.go | registry/app/metadata/cargo/metadata.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargo
import "github.com/harness/gitness/registry/app/metadata"
type RegistryConfig struct {
DownloadURL string `json:"dl"`
APIURL string `json:"api"`
AuthRequired bool `json:"auth-required"` //nolint:tagliatelle
}
type DependencyKindType string
var (
DependencyKindTypeDev DependencyKindType = "dev"
DependencyKindTypeBuild DependencyKindType = "build"
DependencyKindTypeNormal DependencyKindType = "normal"
)
type Dependency struct {
Name string `json:"name"`
Features []string `json:"features,omitempty"`
IsOptional bool `json:"optional,omitempty"`
DefaultFeatures bool `json:"default_features,omitempty"`
Target string `json:"target,omitempty"`
Kind DependencyKindType `json:"kind,omitempty"`
Registry string `json:"registry,omitempty"`
ExplicitNameInToml string `json:"explicit_name_in_toml,omitempty"`
}
type VersionDependency struct {
Dependency
VersionRequired string `json:"version_req,omitempty"`
}
type IndexDependency struct {
Dependency
VersionRequired string `json:"req,omitempty"`
}
type VersionMetadata struct {
Name string `json:"name"`
Version string `json:"vers"`
ReadmeFile string `json:"readme_file,omitempty"`
Keywords []string `json:"keywords,omitempty"`
License string `json:"license,omitempty"`
LicenseFile string `json:"license_file,omitempty"`
Links []string `json:"links,omitempty"`
Dependencies []VersionDependency `json:"deps,omitempty"`
Authors []string `json:"authors,omitempty"`
Description string `json:"description,omitempty"`
Categories []string `json:"categories,omitempty"`
RepositoryURL string `json:"repository,omitempty"`
Badges map[string]any `json:"badges,omitempty"`
Features map[string][]string `json:"features,omitempty"`
DocumentationURL string `json:"documentation,omitempty"`
HomepageURL string `json:"homepage,omitempty"`
Readme string `json:"readme,omitempty"`
RustVersion string `json:"rust_version,omitempty"`
Yanked bool `json:"yanked"`
}
type IndexMetadata struct {
Name string `json:"name"`
Version string `json:"vers"`
Checksum string `json:"cksum"`
Features map[string][]string `json:"features"`
Dependencies []IndexDependency `json:"deps"`
Yanked bool `json:"yanked"`
}
type VersionMetadataDB struct {
VersionMetadata
Files []metadata.File `json:"files"`
FileCount int64 `json:"file_count"`
Size int64 `json:"size"`
}
func (p *VersionMetadataDB) GetFiles() []metadata.File {
return p.Files
}
func (p *VersionMetadataDB) SetFiles(files []metadata.File) {
p.Files = files
p.FileCount = int64(len(files))
}
func (p *VersionMetadataDB) GetSize() int64 {
return p.Size
}
func (p *VersionMetadataDB) UpdateSize(size int64) {
p.Size += size
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/local.go | registry/app/remote/controller/proxy/local.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 proxy
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"
"github.com/opencontainers/go-digest"
)
// registryInterface defines operations related to localRegistry registry under proxy mode.
type registryInterface interface {
Base() error
PullManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (
responseHeaders *commons.ResponseHeaders,
descriptor manifest.Descriptor,
manifest manifest.Manifest,
Errors []error,
)
PutManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
mediaType string,
body io.ReadCloser,
length int64,
) (*commons.ResponseHeaders, []error)
DeleteManifest(
ctx context.Context,
artInfo pkg.RegistryInfo,
) (errs []error, responseHeaders *commons.ResponseHeaders)
GetBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
) (
responseHeaders *commons.ResponseHeaders, fr *storage.FileReader,
size int64, readCloser io.ReadCloser, redirectURL string,
Errors []error,
)
InitBlobUpload(
ctx context.Context,
artInfo pkg.RegistryInfo,
fromRepo, mountDigest string,
) (*commons.ResponseHeaders, []error)
PushBlob(
ctx2 context.Context,
artInfo pkg.RegistryInfo,
body io.ReadCloser,
contentLength int64,
stateToken string,
) (*commons.ResponseHeaders, []error)
}
// registryInterface defines operations related to localRegistry registry under proxy mode.
type registryManifestInterface interface {
DBTag(
ctx context.Context,
mfst manifest.Manifest,
d digest.Digest,
tag string,
headers *commons.ResponseHeaders,
info pkg.RegistryInfo,
) error
AddManifestAssociation(ctx context.Context, repoKey string, digest digest.Digest, info pkg.RegistryInfo) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/remote.go | registry/app/remote/controller/proxy/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 proxy
import (
"io"
"github.com/harness/gitness/app/services/refcache"
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
"golang.org/x/net/context"
_ "github.com/harness/gitness/registry/app/remote/adapter/awsecr" // This is required to init aws ecr adapter
_ "github.com/harness/gitness/registry/app/remote/adapter/dockerhub" // This is required to init docker adapter
)
const DockerHubURL = "https://registry-1.docker.io"
// RemoteInterface defines operations related to remote repository under proxy.
type RemoteInterface interface {
// BlobReader create a reader for remote blob.
BlobReader(ctx context.Context, registry, dig string) (int64, io.ReadCloser, error)
// Manifest get manifest by reference.
Manifest(ctx context.Context, registry string, ref string) (manifest.Manifest, string, error)
// ManifestExist checks manifest exist, if exist, return digest.
ManifestExist(ctx context.Context, registry string, ref string) (bool, *manifest.Descriptor, error)
// ListTags returns all tags of the registry.
ListTags(ctx context.Context, registry string) ([]string, error)
GetImageName(ctx context.Context, spacePathStore refcache.SpaceFinder, imageName string) (string, error)
}
type remoteHelper struct {
repoKey string
// TODO: do we need image name here also?
registry adapter.ArtifactRegistry
upstreamProxy types.UpstreamProxy
URL string
secretService secret.Service
}
// NewRemoteHelper create a remote interface.
func NewRemoteHelper(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service, repoKey string,
proxy types.UpstreamProxy,
) (RemoteInterface, error) {
if proxy.Source == string(api.UpstreamConfigSourceDockerhub) {
proxy.RepoURL = DockerHubURL
}
r := &remoteHelper{
repoKey: repoKey,
upstreamProxy: proxy,
secretService: secretService,
}
adapterType := proxy.Source
if proxy.Source == string(api.UpstreamConfigSourceCustom) {
adapterType = string(api.UpstreamConfigSourceDockerhub)
}
if err := r.init(ctx, spaceFinder, adapterType); err != nil {
return nil, err
}
return r, nil
}
func (r *remoteHelper) init(ctx context.Context, spaceFinder refcache.SpaceFinder, proxyType string) error {
if r.registry != nil {
return nil
}
// TODO add health check.
factory, err := adapter.GetFactory(proxyType)
if err != nil {
return err
}
adp, err := factory.Create(ctx, spaceFinder, r.upstreamProxy, r.secretService)
if err != nil {
return err
}
reg, ok := adp.(adapter.ArtifactRegistry)
if !ok {
log.Ctx(ctx).Warn().Msgf("Error: adp is not of type adapter.ArtifactRegistry")
}
r.registry = reg
return nil
}
func (r *remoteHelper) BlobReader(ctx context.Context, registry, dig string) (int64, io.ReadCloser, error) {
return r.registry.PullBlob(ctx, registry, dig)
}
func (r *remoteHelper) Manifest(ctx context.Context, registry string, ref string) (manifest.Manifest, string, error) {
return r.registry.PullManifest(ctx, registry, ref)
}
func (r *remoteHelper) ManifestExist(ctx context.Context, registry string, ref string) (
bool,
*manifest.Descriptor,
error,
) {
return r.registry.ManifestExist(ctx, registry, ref)
}
func (r *remoteHelper) ListTags(ctx context.Context, registry string) ([]string, error) {
return r.registry.ListTags(ctx, registry)
}
func (r *remoteHelper) GetImageName(
ctx context.Context, spaceFinder refcache.SpaceFinder, imageName string,
) (string, error) {
adapterType := r.upstreamProxy.Source
if adapterType == string(api.UpstreamConfigSourceCustom) {
return imageName, nil
}
factory, err := adapter.GetFactory(adapterType)
if err != nil {
return "", err
}
adp, err := factory.Create(ctx, spaceFinder, r.upstreamProxy, r.secretService)
if err != nil {
return "", err
}
return adp.GetImageName(imageName)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/inflight.go | registry/app/remote/controller/proxy/inflight.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 proxy
import "sync"
type inflightRequest struct {
mu sync.Mutex
reqMap map[string]any
}
var inflightChecker = &inflightRequest{
reqMap: make(map[string]any),
}
// addRequest if the artifact already exist in the inflightRequest, return false
// else return true.
func (in *inflightRequest) addRequest(artifact string) (suc bool) {
in.mu.Lock()
defer in.mu.Unlock()
_, ok := in.reqMap[artifact]
if ok {
// Skip some following operation if it is in reqMap.
return false
}
in.reqMap[artifact] = 1
return true
}
func (in *inflightRequest) removeRequest(artifact string) {
in.mu.Lock()
defer in.mu.Unlock()
delete(in.reqMap, artifact)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/inflight_test.go | registry/app/remote/controller/proxy/inflight_test.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 proxy
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestInflightRequest(t *testing.T) {
artName := "hello-world:latest"
inflightChecker.addRequest(artName)
_, ok := inflightChecker.reqMap[artName]
assert.True(t, ok)
inflightChecker.removeRequest(artName)
_, exist := inflightChecker.reqMap[artName]
assert.False(t, exist)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/controller.go | registry/app/remote/controller/proxy/controller.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 proxy
import (
"bytes"
"context"
"fmt"
"io"
"net/url"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/common/lib/errors"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/distribution/distribution/v3/registry/api/errcode"
"github.com/opencontainers/go-digest"
"github.com/rs/zerolog/log"
)
const (
// wait more time than manifest (maxManifestWait) because manifest list depends on manifest ready.
maxManifestWait = 10
maxManifestMappingWait = 10
maxManifestMappingIntervalSec = 10
sleepIntervalSec = 20
// keep manifest list in cache for one week.
)
// Controller defines the operations related with pull through proxy.
type Controller interface {
// UseLocalBlob check if the blob should use localRegistry copy.
UseLocalBlob(ctx context.Context, art pkg.RegistryInfo) bool
// UseLocalManifest check manifest should use localRegistry copy
UseLocalManifest(
ctx context.Context,
art pkg.RegistryInfo,
remote RemoteInterface,
acceptHeader []string,
ifNoneMatchHeader []string,
) (bool, *ManifestList, error)
// ProxyBlob proxy the blob request to the remote server, p is the proxy project
// art is the RegistryInfo which includes the digest of the blob
ProxyBlob(
ctx context.Context, art pkg.RegistryInfo, repoKey string, proxy types.UpstreamProxy,
) (int64, io.ReadCloser, error)
// ProxyManifest proxy the manifest request to the remote server, p is the proxy project,
// art is the RegistryInfo which includes the tag or digest of the manifest
ProxyManifest(
ctx context.Context,
art pkg.RegistryInfo,
remote RemoteInterface,
repoKey string,
imageName string,
acceptHeader []string,
ifNoneMatchHeader []string,
) (manifest.Manifest, error)
// HeadManifest send manifest head request to the remote server
HeadManifest(ctx context.Context, art pkg.RegistryInfo, remote RemoteInterface) (bool, *manifest.Descriptor, error)
// EnsureTag ensure tag for digest
EnsureTag(
ctx context.Context,
rsHeaders *commons.ResponseHeaders,
info pkg.RegistryInfo,
acceptHeader []string,
ifNoneMatchHeader []string,
) error
}
type controller struct {
localRegistry registryInterface
localManifestRegistry registryManifestInterface
secretService secret.Service
spaceFinder refcache.SpaceFinder
manifestCacheHandlerMap map[string]ManifestCacheHandler
}
// NewProxyController -- get the proxy controller instance.
func NewProxyController(
l registryInterface, lm registryManifestInterface, secretService secret.Service,
spaceFinder refcache.SpaceFinder, manifestCacheHandlerMap map[string]ManifestCacheHandler,
) Controller {
return &controller{
localRegistry: l,
localManifestRegistry: lm,
secretService: secretService,
spaceFinder: spaceFinder,
manifestCacheHandlerMap: manifestCacheHandlerMap,
}
}
func (c *controller) EnsureTag(
ctx context.Context,
rsHeaders *commons.ResponseHeaders,
info pkg.RegistryInfo,
acceptHeader []string,
ifNoneMatchHeader []string,
) error {
// search the digest in cache and query with trimmed digest
_, desc, mfst, err := c.localRegistry.PullManifest(ctx, info, acceptHeader, ifNoneMatchHeader)
if len(err) > 0 {
return err[0]
}
// Fixme: Need to properly pick tag.
e := c.localManifestRegistry.DBTag(ctx, mfst, desc.Digest, info.Reference, rsHeaders, info)
if e != nil {
log.Ctx(ctx).Error().Err(e).Msgf("Error in ensuring tag: %s", e)
}
return e
}
func (c *controller) UseLocalBlob(ctx context.Context, art pkg.RegistryInfo) bool {
if len(art.Digest) == 0 {
return false
}
// TODO: Get from Local storage.
_, _, _, _, _, e := c.localRegistry.GetBlob(ctx, art)
return len(e) == 0
}
// ManifestList ...
type ManifestList struct {
Content []byte
Digest string
ContentType string
}
// UseLocalManifest check if these manifest could be found in localRegistry registry,
// the return error should be nil when it is not found in localRegistry and
// need to delegate to remote registry
// the return error should be NotFoundError when it is not found in remote registry
// the error will be captured by framework and return 404 to client.
func (c *controller) UseLocalManifest(
ctx context.Context,
art pkg.RegistryInfo,
remote RemoteInterface,
acceptHeaders []string,
ifNoneMatchHeader []string,
) (bool, *ManifestList, error) {
// TODO: get from DB
_, d, man, e := c.localRegistry.PullManifest(ctx, art, acceptHeaders, ifNoneMatchHeader)
if len(e) > 0 {
return false, nil, nil
}
remoteRepo := getRemoteRepo(art)
reference := getReference(art)
exist, desc, err := remote.ManifestExist(ctx, remoteRepo, reference) // HEAD.
// TODO: Check for rate limit error.
if err != nil {
if errors.IsRateLimitError(err) { // if rate limit, use localRegistry if it exists, otherwise return error.
log.Ctx(ctx).Warn().Msgf("Rate limit error: %v", err)
return true, nil, nil
}
log.Ctx(ctx).Warn().Msgf("Error in checking remote manifest exist: %v", err)
return false, nil, err
}
// TODO: Delete if does not exist on remote. Validate this
if !exist || desc == nil {
go func() {
c.localRegistry.DeleteManifest(ctx, art)
}()
return false, nil, errors.NotFoundError(fmt.Errorf("registry %v, tag %v not found", art.RegIdentifier, art.Tag))
}
log.Ctx(ctx).Info().Msgf("Manifest exist: %t %s %d %s", exist, desc.Digest.String(), desc.Size, desc.MediaType)
log.Ctx(ctx).Info().Msgf("Manifest: %s", getReference(art))
mediaType, payload, _ := man.Payload()
return true, &ManifestList{payload, d.Digest.String(), mediaType}, nil
}
func ByteToReadCloser(b []byte) io.ReadCloser {
reader := bytes.NewReader(b)
readCloser := io.NopCloser(reader)
return readCloser
}
func (c *controller) ProxyManifest(
ctx context.Context,
art pkg.RegistryInfo,
remote RemoteInterface,
repoKey string,
imageName string,
acceptHeader []string,
ifNoneMatchHeader []string,
) (manifest.Manifest, error) {
var man manifest.Manifest
remoteRepo := getRemoteRepo(art)
ref := getReference(art)
man, dig, err := remote.Manifest(ctx, remoteRepo, ref)
if err != nil {
if errors.IsNotFoundErr(err) {
log.Ctx(ctx).Info().Msgf("TODO: Delete manifest %s from localRegistry registry", dig)
// go func() {
// c.localRegistry.DeleteManifest(remoteRepo, art.Tag)
// }()
}
return man, err
}
ct, _, err := man.Payload()
log.Ctx(ctx).Info().Msgf("Content type: %s", ct)
if err != nil {
return man, err
}
// This GoRoutine is to push the manifest from Remote to Local registry.
go func(_, ct string) {
session, _ := request.AuthSessionFrom(ctx)
ctx2 := request.WithAuthSession(ctx, session)
ctx2 = context.WithoutCancel(ctx2)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "UpdateManifest")
var count = 0
for range maxManifestWait {
time.Sleep(sleepIntervalSec * time.Second)
count++
log.Ctx(ctx2).Info().Msgf("Current retry=%v artifact: %v:%v, digest: %s",
count, repoKey, imageName,
art.Digest)
_, des, _, e := c.localRegistry.PullManifest(ctx2, art, acceptHeader, ifNoneMatchHeader)
if len(e) > 0 {
log.Ctx(ctx2).Info().Stack().Err(err).Msgf("Local manifest doesn't exist, error %v", e[0])
}
// Push manifest to localRegistry when pull with digest, or artifact not found, or digest mismatch.
errs := []error{}
if len(art.Tag) == 0 || e != nil || des.Digest.String() != dig {
artInfo := art
if len(artInfo.Digest) == 0 {
artInfo.Digest = dig
}
err = c.waitAndPushManifest(ctx2, art, ct, man)
if err != nil {
continue
}
}
// Query artifact after push.
if e == nil || commons.IsEmpty(errs) {
_, _, _, err := c.localRegistry.PullManifest(ctx2, art, acceptHeader, ifNoneMatchHeader)
if err != nil {
log.Ctx(ctx2).Error().Stack().Msgf("failed to get manifest, error %v", err)
} else {
log.Ctx(ctx2).Info().Msgf(
"Completed manifest push to localRegistry registry. Image: %s, Tag: %s, Digest: %s",
art.Image, art.Tag, art.Digest,
)
return
}
}
// if e != nil {
// TODO: Place to send events
// SendPullEvent(bCtx, a, art.Tag, operator)
// }
}
}("System", ct)
return man, nil
}
func (c *controller) HeadManifest(
ctx context.Context,
art pkg.RegistryInfo,
remote RemoteInterface,
) (bool, *manifest.Descriptor, error) {
remoteRepo := getRemoteRepo(art)
ref := getReference(art)
return remote.ManifestExist(ctx, remoteRepo, ref)
}
func (c *controller) ProxyBlob(
ctx context.Context, art pkg.RegistryInfo, repoKey string, proxy types.UpstreamProxy,
) (int64, io.ReadCloser, error) {
rHelper, err := NewRemoteHelper(ctx, c.spaceFinder, c.secretService, repoKey, proxy)
if err != nil {
return 0, nil, err
}
art.Image, err = rHelper.GetImageName(ctx, c.spaceFinder, art.Image)
if err != nil {
return 0, nil, err
}
remoteImage := getRemoteRepo(art)
log.Ctx(ctx).Debug().Msgf("The blob doesn't exist, proxy the request to the target server, url:%v", remoteImage)
size, bReader, err := rHelper.BlobReader(ctx, remoteImage, art.Digest)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("failed to pull blob, error %v", err)
return 0, nil, errcode.ErrorCodeBlobUnknown.WithDetail(art.Digest)
}
desc := manifest.Descriptor{Size: size, Digest: digest.Digest(art.Digest)}
// This GoRoutine is to push the blob from Remote to Local registry. No retry logic is defined here.
go func(art pkg.RegistryInfo) {
// Cloning Context.
session, ok := request.AuthSessionFrom(ctx)
if !ok {
log.Ctx(ctx).Error().Stack().Err(err).Msg("failed to get auth session from context")
return
}
ctx2 := request.WithAuthSession(ctx, session)
ctx2 = context.WithoutCancel(ctx2)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "AddBlob")
ctx2 = log.Ctx(ctx2).With().Logger().WithContext(ctx2)
err := c.putBlobToLocal(ctx2, art, remoteImage, repoKey, desc, rHelper)
if err != nil {
log.Ctx(ctx2).Error().Stack().Err(err).
Msgf("error while putting blob to localRegistry registry, %v", err)
return
}
log.Ctx(ctx2).Info().Msgf("Successfully updated the cache for digest %s", art.Digest)
}(art)
return size, bReader, nil
}
func (c *controller) putBlobToLocal(
ctx context.Context,
art pkg.RegistryInfo,
image string,
localRepo string,
desc manifest.Descriptor,
r RemoteInterface,
) error {
log.Ctx(ctx).Debug().
Msgf(
"Put blob to localRegistry registry!, sourceRepo:%v, localRepo:%v, digest: %v", image, localRepo,
desc.Digest,
)
cl, bReader, err := r.BlobReader(ctx, image, string(desc.Digest))
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("failed to create blob reader, error %v", err)
return err
}
defer bReader.Close()
headers, errs := c.localRegistry.InitBlobUpload(ctx, art, "", "")
if len(errs) > 0 {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("failed to init blob upload, error %v", errs)
return errs[0]
}
location, uuid := headers.Headers["Location"], headers.Headers["Docker-Upload-UUID"]
parsedURL, err := url.Parse(location)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Error parsing URL: %s", err)
return err
}
stateToken := parsedURL.Query().Get("_state")
art.SetReference(uuid)
c.localRegistry.PushBlob(ctx, art, bReader, cl, stateToken)
return err
}
func (c *controller) waitAndPushManifest(
ctx context.Context, art pkg.RegistryInfo, contentType string, man manifest.Manifest,
) error {
h, ok := c.manifestCacheHandlerMap[contentType]
if !ok {
h, ok = c.manifestCacheHandlerMap[DefaultHandler]
if !ok {
return fmt.Errorf("failed to get default manifest cache handler")
}
}
err := h.CacheContent(ctx, art, contentType, man)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("Error in caching manifest: %s", err)
return err
}
return nil
}
func getRemoteRepo(art pkg.RegistryInfo) string {
return art.Image
}
func getReference(art pkg.RegistryInfo) string {
if len(art.Digest) > 0 {
return art.Digest
}
return art.Tag
}
const DefaultHandler = "default"
// ManifestCache default Manifest handler.
type ManifestCache struct {
localRegistry registryInterface
localManifestRegistry registryManifestInterface
}
func GetManifestCache(localRegistry registryInterface, localManifestRegistry registryManifestInterface) *ManifestCache {
return &ManifestCache{
localRegistry: localRegistry,
localManifestRegistry: localManifestRegistry,
}
}
// ManifestListCache handle Manifest list type and index type.
type ManifestListCache struct {
localRegistry registryInterface
}
func GetManifestListCache(localRegistry registryInterface) *ManifestListCache {
return &ManifestListCache{localRegistry: localRegistry}
}
// ManifestCacheHandler define how to cache manifest content.
type ManifestCacheHandler interface {
// CacheContent - cache the content of the manifest
CacheContent(ctx context.Context, art pkg.RegistryInfo, contentType string, m manifest.Manifest) error
}
func (m *ManifestCache) CacheContent(
ctx context.Context, art pkg.RegistryInfo, contentType string, man manifest.Manifest,
) error {
_, payload, err := man.Payload()
if err != nil {
return err
}
// Push manifest to localRegistry.
_, errs := m.localRegistry.PutManifest(ctx, art, contentType, ByteToReadCloser(payload), int64(len(payload)))
if len(errs) > 0 {
return errs[0]
}
for range maxManifestMappingWait {
time.Sleep(maxManifestMappingIntervalSec * time.Second)
err = m.localManifestRegistry.AddManifestAssociation(ctx, art.RegIdentifier, digest.Digest(art.Digest), art)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msgf("failed to add manifest association, error %v", err)
continue
}
return nil
}
log.Ctx(ctx).Info().Msgf("Successfully cached manifest for image: %s, tag: %s, digest: %s",
art.Image, art.Tag, art.Digest)
return err
}
func (m *ManifestListCache) CacheContent(
ctx context.Context, art pkg.RegistryInfo, contentType string, man manifest.Manifest,
) error {
_, payload, err := man.Payload()
if err != nil {
log.Ctx(ctx).Error().Msg("failed to get payload")
return err
}
if len(getReference(art)) == 0 {
log.Ctx(ctx).Error().Msg("failed to get reference, reference is empty, skip to cache manifest list")
return fmt.Errorf("failed to get reference, reference is empty, skip to cache manifest list")
}
// cache key should contain digest if digest exist
if len(art.Digest) == 0 {
art.Digest = string(digest.FromBytes(payload))
}
if err = m.push(ctx, art, man, contentType); err != nil {
log.Ctx(ctx).Error().Msgf("error when push manifest list to local :%v", err)
return err
}
log.Ctx(ctx).Info().Msgf("Successfully cached manifest list for image: %s, tag: %s, digest: %s",
art.Image, art.Tag, art.Digest)
return nil
}
func (m *ManifestListCache) push(
ctx context.Context, art pkg.RegistryInfo, man manifest.Manifest, contentType string,
) error {
if len(man.References()) == 0 {
return errors.New("manifest list doesn't contain any pushed manifest")
}
_, pl, err := man.Payload()
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to get payload, error %v", err)
return err
}
log.Ctx(ctx).Debug().Msgf("The manifest list payload: %v", string(pl))
newDig := digest.FromBytes(pl)
// Because the manifest list maybe updated, need to recheck if it is exist in local
_, descriptor, manifest2, _ := m.localRegistry.PullManifest(ctx, art, nil, nil)
if manifest2 != nil && descriptor.Digest == newDig {
return nil
}
_, errs := m.localRegistry.PutManifest(ctx, art, contentType, ByteToReadCloser(pl), int64(len(pl)))
if len(errs) > 0 {
return errs[0]
}
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/remote/controller/proxy/maven/local.go | registry/app/remote/controller/proxy/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"
"io"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/storage"
)
type registryInterface interface {
HeadArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, errs []error)
GetArtifact(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, body *storage.FileReader, fileReader io.ReadCloser,
redirectURL string, errs []error)
PutArtifact(ctx context.Context, info 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/remote/controller/proxy/maven/remote.go | registry/app/remote/controller/proxy/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/app/services/refcache"
api "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/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/remote/adapter/maven" // This is required to init maven adapter
)
const MavenCentralURL = "https://repo1.maven.org/maven2"
// RemoteInterface defines operations related to remote repository under proxy.
type RemoteInterface interface {
// Download the file
GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error)
// Check existence of file
HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error)
}
type remoteHelper struct {
registry adapter.ArtifactRegistry
upstreamProxy types.UpstreamProxy
URL string
secretService secret.Service
}
// NewRemoteHelper create a remote interface.
func NewRemoteHelper(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service,
proxy types.UpstreamProxy,
) (RemoteInterface, error) {
if proxy.Source == string(api.UpstreamConfigSourceMavenCentral) {
proxy.RepoURL = MavenCentralURL
}
r := &remoteHelper{
upstreamProxy: proxy,
secretService: secretService,
}
if err := r.init(ctx, spaceFinder, string(api.UpstreamConfigSourceMavenCentral)); err != nil {
return nil, err
}
return r, nil
}
func (r *remoteHelper) init(ctx context.Context, spaceFinder refcache.SpaceFinder, proxyType string) error {
if r.registry != nil {
return nil
}
factory, err := adapter.GetFactory(proxyType)
if err != nil {
return err
}
adp, err := factory.Create(ctx, spaceFinder, r.upstreamProxy, r.secretService)
if err != nil {
return err
}
reg, ok := adp.(adapter.ArtifactRegistry)
if !ok {
log.Ctx(ctx).Warn().Msgf("Error: adp is not of type adapter.ArtifactRegistry")
}
r.registry = reg
return nil
}
func (r *remoteHelper) GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error) {
return r.registry.GetFile(ctx, filePath)
}
func (r *remoteHelper) HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error) {
return r.registry.HeadFile(ctx, filePath)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/controller/proxy/maven/controller.go | registry/app/remote/controller/proxy/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"
"io"
"strings"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/pkg"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/pkg/maven/utils"
"github.com/harness/gitness/registry/app/storage"
cfg "github.com/harness/gitness/registry/config"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type controller struct {
localRegistry registryInterface
secretService secret.Service
spaceFinder refcache.SpaceFinder
}
type Controller interface {
UseLocalFile(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, fileReader *storage.FileReader, redirectURL string, useLocal bool,
)
ProxyFile(
ctx context.Context, info pkg.MavenArtifactInfo, proxy types.UpstreamProxy, serveFile bool,
) (*commons.ResponseHeaders, io.ReadCloser, error)
}
// NewProxyController -- get the proxy controller instance.
func NewProxyController(
l registryInterface, secretService secret.Service,
spaceFinder refcache.SpaceFinder,
) Controller {
return &controller{
localRegistry: l,
secretService: secretService,
spaceFinder: spaceFinder,
}
}
func (c *controller) UseLocalFile(ctx context.Context, info pkg.MavenArtifactInfo) (
responseHeaders *commons.ResponseHeaders, fileReader *storage.FileReader, redirectURL string, useLocal bool,
) {
responseHeaders, body, _, redirectURL, e := c.localRegistry.GetArtifact(ctx, info)
return responseHeaders, body, redirectURL, len(e) == 0
}
func (c *controller) ProxyFile(
ctx context.Context, info pkg.MavenArtifactInfo, proxy types.UpstreamProxy, serveFile bool,
) (responseHeaders *commons.ResponseHeaders, body io.ReadCloser, errs error) {
responseHeaders = &commons.ResponseHeaders{
Headers: make(map[string]string),
}
rHelper, err := NewRemoteHelper(ctx, c.spaceFinder, c.secretService, proxy)
if err != nil {
return responseHeaders, nil, err
}
filePath := utils.GetFilePath(info)
filePath = strings.Trim(filePath, "/")
if serveFile {
responseHeaders, body, err = rHelper.GetFile(ctx, filePath)
} else {
responseHeaders, err = rHelper.HeadFile(ctx, filePath)
}
if err != nil {
return responseHeaders, nil, err
}
if !serveFile {
return responseHeaders, nil, nil
}
go func(info pkg.MavenArtifactInfo) {
// Cloning Context.
session, ok := request.AuthSessionFrom(ctx)
if !ok {
log.Ctx(ctx).Error().Stack().Err(err).Msg("failed to get auth session from context")
return
}
ctx2 := request.WithAuthSession(ctx, session)
ctx2 = context.WithoutCancel(ctx2)
ctx2 = context.WithValue(ctx2, cfg.GoRoutineKey, "goRoutine")
err = c.putFileToLocal(ctx2, info, rHelper)
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 "+
"to registry: %s with file path: %s",
info.RegIdentifier, filePath)
}(info)
return responseHeaders, body, nil
}
func (c *controller) putFileToLocal(
ctx context.Context,
info pkg.MavenArtifactInfo,
r RemoteInterface,
) error {
filePath := utils.GetFilePath(info)
filePath = strings.Trim(filePath, "/")
_, fileReader, err := r.GetFile(ctx, filePath)
if err != nil {
return err
}
defer fileReader.Close()
_, errs := c.localRegistry.PutArtifact(ctx, info, fileReader)
if len(errs) > 0 {
return errs[0]
}
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/remote/adapter/adapter.go | registry/app/remote/adapter/adapter.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 adapter
import (
"context"
"errors"
"fmt"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/manifest"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
)
// const definition.
const (
MaxConcurrency = 100
)
var registry = map[string]Factory{}
var registryKeys = []string{}
// Factory creates a specific Adapter according to the params.
type Factory interface {
Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (Adapter, error)
}
// Adapter interface defines the capabilities of registry.
type Adapter interface {
// HealthCheck checks health status of registry.
HealthCheck() (string, error)
GetImageName(imageName string) (string, error)
}
// ArtifactRegistry defines the capabilities that an artifact registry should have.
type ArtifactRegistry interface {
ManifestExist(ctx context.Context, repository, reference string) (exist bool, desc *manifest.Descriptor, err error)
PullManifest(
ctx context.Context,
repository, reference string,
accepttedMediaTypes ...string,
) (manifest manifest.Manifest, digest string, err error)
PushManifest(ctx context.Context, repository, reference, mediaType string, payload []byte) (string, error)
DeleteManifest(ctx context.Context, repository, reference string) error
// the "reference" can be "tag" or "digest", the function needs to handle both
BlobExist(ctx context.Context, repository, digest string) (exist bool, err error)
PullBlob(ctx context.Context, repository, digest string) (size int64, blob io.ReadCloser, err error)
PullBlobChunk(ctx context.Context, repository, digest string, blobSize, start, end int64) (
size int64,
blob io.ReadCloser,
err error,
)
PushBlobChunk(
ctx context.Context,
repository, digest string,
size int64,
chunk io.Reader,
start, end int64,
location string,
) (nextUploadLocation string, endRange int64, err error)
PushBlob(ctx context.Context, repository, digest string, size int64, blob io.Reader) error
MountBlob(ctx context.Context, srcRepository, digest, dstRepository string) (err error)
CanBeMount(ctx context.Context, digest string) (mount bool, repository string, err error)
// check whether the blob can be mounted from the remote registry
DeleteTag(ctx context.Context, repository, tag string) error
ListTags(ctx context.Context, repository string) (tags []string, err error)
// Download the file
GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error)
// Check existence of file
HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error)
}
// RegisterFactory registers one adapter factory to the registry.
func RegisterFactory(t string, factory Factory) error {
if len(t) == 0 {
return errors.New("invalid type")
}
if factory == nil {
return errors.New("empty adapter factory")
}
if _, exist := registry[t]; exist {
return fmt.Errorf("adapter factory for %s already exists", t)
}
registry[t] = factory
registryKeys = append(registryKeys, t)
return nil
}
// GetFactory gets the adapter factory by the specified name.
func GetFactory(t string) (Factory, error) {
factory, exist := registry[t]
if !exist {
return nil, fmt.Errorf("adapter factory for %s not found", t)
}
return factory, nil
}
// ListRegisteredAdapterTypes lists the registered Adapter type.
func ListRegisteredAdapterTypes() []string {
return registryKeys
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/native/adapter.go | registry/app/remote/adapter/native/adapter.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 native
import (
"context"
"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"
"github.com/harness/gitness/registry/app/common/lib/errors"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/commons"
"github.com/harness/gitness/registry/app/remote/clients/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ adp.Adapter = &Adapter{}
var (
_ adp.Adapter = (*Adapter)(nil)
_ adp.ArtifactRegistry = (*Adapter)(nil)
)
// Adapter implements an adapter for Docker proxy. It can be used to all registries
// that implement the proxy V2 API.
type Adapter struct {
proxy types.UpstreamProxy
registry.Client
}
// NewAdapter returns an instance of the Adapter.
func NewAdapter(
ctx context.Context, spaceFinder refcache.SpaceFinder, service secret.Service, reg types.UpstreamProxy,
) *Adapter {
adapter := &Adapter{
proxy: reg,
}
url := reg.RepoURL
accessKey, secretKey, _, err := commons.GetCredentials(ctx, spaceFinder, service, reg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("error getting credentials for registry: %s", reg.RepoKey)
return nil
}
adapter.Client = registry.NewClient(url, accessKey, secretKey, false,
reg.PackageType == artifact.PackageTypeDOCKER || reg.PackageType == artifact.PackageTypeHELM)
return adapter
}
// NewAdapterWithAuthorizer returns an instance of the Adapter with provided authorizer.
func NewAdapterWithAuthorizer(reg types.UpstreamProxy, authorizer lib.Authorizer) *Adapter {
return &Adapter{
proxy: reg,
Client: registry.NewClientWithAuthorizer(reg.RepoURL, authorizer, false),
}
}
// HealthCheck checks health status of a proxy.
func (a *Adapter) HealthCheck() (string, error) {
return "Not implemented", nil
}
// PingSimple checks whether the proxy is available. It checks the connectivity and certificate (if TLS enabled)
// only, regardless of 401/403 error.
func (a *Adapter) PingSimple(ctx context.Context) error {
err := a.Ping(ctx)
if err == nil {
return nil
}
if errors.IsErr(err, errors.UnAuthorizedCode) || errors.IsErr(err, errors.ForbiddenCode) {
return nil
}
return err
}
// DeleteTag isn't supported for docker proxy.
func (a *Adapter) DeleteTag(_ context.Context, _, _ string) error {
return errors.New("the tag deletion isn't supported")
}
// CanBeMount isn't supported for docker proxy.
func (a *Adapter) CanBeMount(_ context.Context, _ string) (mount bool, repository string, err error) {
return false, "", nil
}
func (a *Adapter) GetImageName(imageName string) (string, error) {
return imageName, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/pypi/client.go | registry/app/remote/adapter/pypi/client.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pypi
import (
"context"
"net/http"
"github.com/harness/gitness/app/services/refcache"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/remote/adapter/commons"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type client struct {
client *http.Client
url string
username string
password string
}
// newClient creates a new PyPi client.
func newClient(
ctx context.Context,
registry types.UpstreamProxy,
finder refcache.SpaceFinder,
service secret.Service,
) (*client, error) {
accessKey, secretKey, _, err := commons.GetCredentials(ctx, finder, service, registry)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("error getting credentials for registry: %s %v", registry.RepoKey, err)
return nil, err
}
c := &client{
url: registry.RepoURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
username: accessKey,
password: secretKey,
}
return c, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/pypi/adapter.go | registry/app/remote/adapter/pypi/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pypi
import (
"context"
"encoding/json"
"fmt"
"io"
"path"
"strings"
"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"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/commons/pypi"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
"golang.org/x/net/html"
)
var _ registry.PythonRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
const (
PyPiURL = "https://pypi.org"
)
type adapter struct {
*native.Adapter
registry types.UpstreamProxy
client *client
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
c, err := newClient(ctx, registry, spaceFinder, service)
if err != nil {
return nil, err
}
return &adapter{
Adapter: nativeAdapter,
registry: registry,
client: c,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypePYTHON)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
func (a *adapter) GetMetadata(ctx context.Context, pkg string) (*pypi.SimpleMetadata, error) {
basePath := "simple"
if a.registry.Config != nil && a.registry.Config.RemoteUrlSuffix != "" {
basePath = strings.Trim(a.registry.Config.RemoteUrlSuffix, "/")
}
filePath := path.Join(basePath, pkg) + "/"
_, readCloser, err := a.GetFile(ctx, filePath)
if err != nil {
return nil, err
}
defer readCloser.Close()
response, err := ParsePyPISimple(readCloser, a.GetURL(ctx, filePath))
if err != nil {
return nil, err
}
err = validateMetadata(response)
if err != nil {
return nil, err
}
return &response, nil
}
func validateMetadata(response pypi.SimpleMetadata) error {
for _, p := range response.Packages {
if !p.Valid() {
log.Error().Msgf("invalid package: %s", p.String())
return fmt.Errorf("invalid package: %s", p.String())
}
}
return nil
}
func (a *adapter) GetPackage(ctx context.Context, pkg string, filename string) (io.ReadCloser, error) {
metadata, err := a.GetMetadata(ctx, pkg)
if err != nil {
return nil, err
}
downloadURL := ""
for _, p := range metadata.Packages {
if p.Name == filename {
downloadURL = p.URL()
break
}
}
if downloadURL == "" {
return nil, fmt.Errorf("pkg: %s, filename: %s not found", pkg, filename)
}
log.Ctx(ctx).Info().Msgf("Download URL: %s", downloadURL)
_, closer, err := a.GetFileFromURL(ctx, downloadURL)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", downloadURL)
return nil, err
}
return closer, nil
}
func (a *adapter) GetJSON(ctx context.Context, pkg string, version string) (*python.Metadata, error) {
_, readCloser, err := a.GetFile(ctx, fmt.Sprintf("pypi/%s/%s/json", pkg, version))
if err != nil {
return nil, err
}
defer readCloser.Close()
response, err := ParseMetadata(ctx, readCloser)
if err != nil {
return nil, err
}
return &response, nil
}
func ParseMetadata(ctx context.Context, body io.ReadCloser) (python.Metadata, error) {
bytes, err := io.ReadAll(body)
if err != nil {
return python.Metadata{}, err
}
var response Response
if err := json.Unmarshal(bytes, &response); err != nil {
// FIXME: This is known problem where if the response fields returns null, the null is not handled.
// For eg: {"keywords":null} is not handled where "keywords" is []string
log.Ctx(ctx).Warn().Err(err).Msgf("Failed to unmarshal response")
}
return response.Info, nil
}
// ParsePyPISimple parses the given HTML and returns a SimpleMetadata DTO.
func ParsePyPISimple(r io.ReadCloser, url string) (pypi.SimpleMetadata, error) {
doc, err := html.Parse(r)
if err != nil {
return pypi.SimpleMetadata{}, err
}
var result pypi.SimpleMetadata
var packages []pypi.Package
// Recursive function to walk the HTML nodes
var traverse func(*html.Node)
traverse = func(n *html.Node) {
if n.Type == html.ElementNode {
switch n.Data {
case "meta":
// Check for meta tag name="pypi:repository-version"
var metaName, metaContent string
for _, attr := range n.Attr {
switch attr.Key {
case "name":
metaName = attr.Val
case "content":
metaContent = attr.Val
}
}
if metaName == "pypi:repository-version" {
result.MetaName = metaName
result.Content = metaContent
}
case "title":
if n.FirstChild != nil {
result.Title = n.FirstChild.Data
}
case "a":
// Capture all attributes in a map
aMap := make(map[string]string)
for _, attr := range n.Attr {
aMap[attr.Key] = attr.Val
}
linkText := ""
if n.FirstChild != nil {
linkText = n.FirstChild.Data
}
packages = append(packages, pypi.Package{
SimpleURL: url,
ATags: aMap,
Name: linkText,
})
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
traverse(c)
}
}
traverse(doc)
result.Packages = packages
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/remote/adapter/pypi/dto.go | registry/app/remote/adapter/pypi/dto.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pypi
import "github.com/harness/gitness/registry/app/metadata/python"
type Response struct {
Info python.Metadata `json:"info"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/commons/utils.go | registry/app/remote/adapter/commons/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 commons
import (
"context"
"fmt"
"github.com/harness/gitness/app/services/refcache"
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
func GetCredentials(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service, reg types.UpstreamProxy,
) (accessKey string, secretKey string, isAnonymous bool, err error) {
if api.AuthType(reg.RepoAuthType) == api.AuthTypeAnonymous {
return "", "", true, nil
}
if api.AuthType(reg.RepoAuthType) == api.AuthTypeUserPassword {
secretKey, err = getSecretValue(ctx, spaceFinder, secretService, reg.SecretSpaceID,
reg.SecretIdentifier)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get secret for registry: %s", reg.RepoKey)
return "", "", false, fmt.Errorf("failed to get secret for registry: %s", reg.RepoKey)
}
return reg.UserName, secretKey, false, nil
}
if api.AuthType(reg.RepoAuthType) == api.AuthTypeAccessKeySecretKey {
accessKey, err = getSecretValue(ctx, spaceFinder, secretService, reg.UserNameSecretSpaceID,
reg.UserNameSecretIdentifier)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get access secret for registry: %s", reg.RepoKey)
return "", "", false, fmt.Errorf("failed to get access key for registry: %s", reg.RepoKey)
}
secretKey, err = getSecretValue(ctx, spaceFinder, secretService, reg.SecretSpaceID,
reg.SecretIdentifier)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("failed to get user secret for registry: %s", reg.RepoKey)
return "", "", false, fmt.Errorf("failed to get secret key for registry: %s", reg.RepoKey)
}
return accessKey, secretKey, false, nil
}
return "", "", false, fmt.Errorf("unsupported auth type: %s", reg.RepoAuthType)
}
func getSecretValue(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service,
secretSpaceID int64, secretSpacePath string,
) (string, error) {
spacePath, err := spaceFinder.FindByID(ctx, secretSpaceID)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to find space path: %v", err)
return "", err
}
decryptSecret, err := secretService.DecryptSecret(ctx, spacePath.Path, secretSpacePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to decrypt secret: %v", err)
return "", err
}
return decryptSecret, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/commons/pypi/dto.go | registry/app/remote/adapter/commons/pypi/dto.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pypi
import (
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/rs/zerolog/log"
"golang.org/x/net/html"
)
var (
extensions = []string{
".tar.gz",
".tar.bz2",
".tar.xz",
".zip",
".whl",
".egg",
".exe",
".app",
".dmg",
}
exeRegex = regexp.MustCompile(`(\d+(?:\.\d+)+)`)
)
type SimpleMetadata struct {
Title string
MetaName string
Content string
Packages []Package
}
type Package struct {
SimpleURL string
Name string
ATags map[string]string
}
// URL returns the "href" attribute from the package's map.
func (p Package) URL() string {
href := p.ATags["href"]
parsedURL, err := url.Parse(href)
if err != nil {
return href
}
if parsedURL.IsAbs() {
return href
}
// If href is relative, resolve it against SimpleURL
baseURL, err := url.Parse(p.SimpleURL)
if err != nil {
log.Err(err).Msgf("failed to parse url %s", p.SimpleURL)
return href
}
return baseURL.ResolveReference(parsedURL).String()
}
func (p Package) Valid() bool {
return p.URL() != "" && p.Name != ""
}
// RequiresPython returns the "data-requires-python" attribute (unescaped) from the package's map.
func (p Package) RequiresPython() string {
val := p.ATags["data-requires-python"]
// unescape HTML entities like ">"
return html.UnescapeString(val)
}
// Version Fetches version from format:
// The wheel filename is {distribution}-{version}(-{build tag})?-{python tag}-{abi tag}-{platform tag}.whl
// SRC: https://packaging.python.org/en/latest/specifications/binary-distribution-format/#file-name-convention
func (p Package) Version() string {
return GetPyPIVersion(p.Name)
}
func (p Package) String() string {
return fmt.Sprintf("Name: %s, Version: %s, URL: %s, RequiresPython: %s", p.Name, p.Version(), p.URL(),
p.RequiresPython())
}
func GetPyPIVersion(filename string) string {
base, ext, err := stripRecognizedExtension(filename)
if err != nil {
return ""
}
splits := strings.Split(base, "-")
if len(splits) < 2 {
return ""
}
switch ext {
case ".whl", ".egg":
return splits[1]
case ".tar.gz", ".tar.bz2", ".tar.xz", ".zip", ".dmg", ".app":
return splits[len(splits)-1]
case ".exe":
match := exeRegex.FindStringSubmatch(filename)
if len(match) > 1 {
return match[1]
}
return splits[len(splits)-1]
default:
return ""
}
}
func stripRecognizedExtension(filename string) (string, string, error) {
for _, x := range extensions {
if strings.HasSuffix(strings.ToLower(filename), x) {
base := filename[:len(filename)-len(x)]
return base, x, nil
}
}
return "", "", errors.New("unrecognized file extension")
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/generic/client.go | registry/app/remote/adapter/generic/client.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generic
import (
"context"
"net/http"
"github.com/harness/gitness/app/services/refcache"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/remote/adapter/commons"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type client struct {
client *http.Client
url string
username string
password string
}
// newClient creates a new Generic client.
func newClient(
ctx context.Context,
registry types.UpstreamProxy,
finder refcache.SpaceFinder,
service secret.Service,
) (*client, error) {
accessKey, secretKey, _, err := commons.GetCredentials(ctx, finder, service, registry)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("error getting credentials for registry: %s %v", registry.RepoKey, err)
return nil, err
}
c := &client{
url: registry.RepoURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
username: accessKey,
password: secretKey,
}
return c, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/generic/adapter.go | registry/app/remote/adapter/generic/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.GenericRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
type adapter struct {
*native.Adapter
registry types.UpstreamProxy
client *client
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
c, err := newClient(ctx, registry, spaceFinder, service)
if err != nil {
log.Ctx(ctx).Error().Stack().Err(err).Msg("Failed to create client for generic registry")
return nil, err
}
return &adapter{
Adapter: nativeAdapter,
registry: registry,
client: c,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeGENERIC)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/goproxy/adapter.go | registry/app/remote/adapter/goproxy/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package goproxy
import (
"context"
"fmt"
"io"
"github.com/harness/gitness/app/api/usererror"
"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"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.GoPackageRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
const (
GoProxyURL = "https://proxy.golang.org"
)
type adapter struct {
*native.Adapter
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
return &adapter{
Adapter: nativeAdapter,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeGO)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
func (a *adapter) GetPackageFile(ctx context.Context, filepath string) (io.ReadCloser, error) {
_, readCloser, err := a.GetFile(ctx, filepath)
if err != nil {
code := errors.ErrCode(err)
if code == errors.NotFoundCode {
return nil, usererror.NotFoundf("failed to get package file %s", filepath)
}
if code == errors.ForbiddenCode {
return nil, usererror.Forbidden(fmt.Sprintf("failed to get package file %s", filepath))
}
return nil, err
}
return readCloser, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/awsecr/auth.go | registry/app/remote/adapter/awsecr/auth.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 awsecr
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/harness/gitness/app/services/refcache"
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/common/http/modifier"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
awsecrapi "github.com/aws/aws-sdk-go/service/ecr"
"github.com/rs/zerolog/log"
)
// Credential ...
type Credential modifier.Modifier
// Implements interface Credential.
type awsAuthCredential struct {
accessKey string
awssvc *awsecrapi.ECR
cacheToken *cacheToken
cacheExpired *time.Time
isPublic bool
}
type cacheToken struct {
endpoint string
user string
password string
host string
}
// DefaultCacheExpiredTime is expired timeout for aws auth token.
const DefaultCacheExpiredTime = time.Hour * 1
func (a *awsAuthCredential) Modify(req *http.Request) error {
// url maybe redirect to s3
if !strings.Contains(req.URL.Host, ".ecr.") {
return nil
}
if !a.isTokenValid() {
endpoint, user, pass, expiresAt, err := a.getAuthorization(req.Context(), req.URL.String(), req.URL.Host)
if err != nil {
return err
}
u, err := url.Parse(endpoint)
if err != nil {
return err
}
a.cacheToken = &cacheToken{}
a.cacheToken.host = u.Host
a.cacheToken.user = user
a.cacheToken.password = pass
a.cacheToken.endpoint = endpoint
t := time.Now().Add(DefaultCacheExpiredTime)
if expiresAt == nil || t.Before(*expiresAt) {
a.cacheExpired = &t
} else {
a.cacheExpired = expiresAt
}
}
req.Host = a.cacheToken.host
req.URL.Host = a.cacheToken.host
if a.isPublic {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.cacheToken.password))
return nil
}
req.SetBasicAuth(a.cacheToken.user, a.cacheToken.password)
return nil
}
func getAwsSvc(ctx context.Context, accessKey, secretKey string, reg types.UpstreamProxy) (*awsecrapi.ECR, error) {
_, region, err := parseAccountRegion(reg.RepoURL)
if err != nil {
return nil, err
}
sess, err := session.NewSession()
if err != nil {
return nil, err
}
var cred *credentials.Credentials
log.Ctx(ctx).Info().Msgf("Aws Ecr getAuthorization %s", accessKey)
if accessKey != "" {
cred = credentials.NewStaticCredentials(
accessKey,
secretKey,
"")
}
config := &aws.Config{
Credentials: cred,
Region: ®ion,
HTTPClient: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(false)),
},
}
svc := awsecrapi.New(sess, config)
return svc, nil
}
func parseAccountRegion(url string) (string, string, error) {
rs := ecrRegexp.FindStringSubmatch(url)
if len(rs) < 4 {
return "", "", errors.New("bad aws url")
}
return rs[1], rs[3], nil
}
func getCreds(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service, reg types.UpstreamProxy,
) (string, string, bool, error) {
if api.AuthType(reg.RepoAuthType) == api.AuthTypeAnonymous {
return "", "", true, nil
}
if api.AuthType(reg.RepoAuthType) != api.AuthTypeAccessKeySecretKey {
log.Ctx(ctx).Debug().Msgf("invalid auth type: %s", reg.RepoAuthType)
return "", "", false, nil
}
secretKey, err := getSecretValue(ctx, spaceFinder, secretService, reg.SecretSpaceID,
reg.SecretIdentifier)
if err != nil {
return "", "", false, err
}
if reg.UserName != "" {
return reg.UserName, secretKey, false, nil
}
accessKey, err := getSecretValue(ctx, spaceFinder, secretService, reg.UserNameSecretSpaceID,
reg.UserNameSecretIdentifier)
if err != nil {
return "", "", false, err
}
return accessKey, secretKey, false, nil
}
func getSecretValue(
ctx context.Context, spaceFinder refcache.SpaceFinder, secretService secret.Service,
secretSpaceID int64, secretSpacePath string,
) (string, error) {
spacePath, err := spaceFinder.FindByID(ctx, secretSpaceID)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to find space path: %d, %v", secretSpaceID, err)
return "", err
}
decryptSecret, err := secretService.DecryptSecret(ctx, spacePath.Path, secretSpacePath)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to decrypt secret at path: %s, secret: %s, %v", spacePath.Path,
secretSpacePath, err)
return "", err
}
return decryptSecret, nil
}
func (a *awsAuthCredential) getAuthorization(ctx context.Context, url, host string) (
string,
string,
string,
*time.Time,
error,
) {
if a.isPublic {
token, err := a.getPublicECRToken(ctx, host)
if err != nil {
return "", "", "", nil, err
}
return url, "", token, nil, nil
}
id, _, err := parseAccountRegion(url)
if err != nil {
return "", "", "", nil, err
}
var input *awsecrapi.GetAuthorizationTokenInput
if id != "" {
input = &awsecrapi.GetAuthorizationTokenInput{RegistryIds: []*string{&id}}
}
svc := a.awssvc
result, err := svc.GetAuthorizationTokenWithContext(ctx, input)
if err != nil {
var awsErr *awserr.Error
if errors.As(err, awsErr) {
return "", "", "", nil, fmt.Errorf("%s", err.Error())
}
return "", "", "", nil, err
}
// Double check
if len(result.AuthorizationData) == 0 {
return "", "", "", nil, errors.New("no authorization token returned")
}
theOne := result.AuthorizationData[0]
expiresAt := theOne.ExpiresAt
payload, _ := base64.StdEncoding.DecodeString(*theOne.AuthorizationToken)
pair := strings.SplitN(string(payload), ":", 2)
log.Ctx(ctx).Debug().Msgf("Aws Ecr getAuthorization %s result: %d %s...", a.accessKey, len(pair[1]), pair[1][:25])
return *(theOne.ProxyEndpoint), pair[0], pair[1], expiresAt, nil
}
func (a *awsAuthCredential) isTokenValid() bool {
if a.cacheToken == nil {
return false
}
if a.cacheExpired == nil {
return false
}
if time.Now().After(*a.cacheExpired) {
a.cacheExpired = nil
a.cacheToken = nil
return false
}
return true
}
// NewAuth new aws auth.
func NewAuth(accessKey string, awssvc *awsecrapi.ECR, isPublic bool) Credential {
return &awsAuthCredential{
accessKey: accessKey,
awssvc: awssvc,
isPublic: isPublic,
}
}
func (a *awsAuthCredential) getPublicECRToken(ctx context.Context, host string) (string, error) {
c := &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildTokenURL(host, host), nil)
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
resp, err := c.Do(req)
if err != nil {
return "", fmt.Errorf("failed to fetch token: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("non-200 response: %d %s", resp.StatusCode, http.StatusText(resp.StatusCode))
}
// Parse the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response body: %w", err)
}
// Unmarshal JSON
var tokenResponse TokenResponse
if err := json.Unmarshal(body, &tokenResponse); err != nil {
return "", fmt.Errorf("failed to parse token response: %w", err)
}
return tokenResponse.Token, nil
}
type TokenResponse struct {
Token string `json:"token"`
}
func buildTokenURL(host, service string) string {
return fmt.Sprintf("https://%s/token?service=%s", host, service)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/awsecr/adapter.go | registry/app/remote/adapter/awsecr/adapter.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 awsecr
import (
"context"
"regexp"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
awsecrapi "github.com/aws/aws-sdk-go/service/ecr"
"github.com/rs/zerolog/log"
)
const (
//nolint:lll
ecrPattern = "https://(?:api|(\\d+)\\.dkr)\\.ecr(\\-fips)?\\.([\\w\\-]+)\\.(amazonaws\\.com(\\.cn)?|sc2s\\.sgov\\.gov|c2s\\.ic\\.gov)"
)
var (
ecrRegexp = regexp.MustCompile(ecrPattern)
)
func init() {
adapterType := string(artifact.UpstreamConfigSourceAwsEcr)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Register adapter factory for %s", adapterType)
return
}
}
func newAdapter(
ctx context.Context, spaceFinder refcache.SpaceFinder, service secret.Service, registry types.UpstreamProxy,
) (adp.Adapter, error) {
accessKey, secretKey, isPublic, err := getCreds(ctx, spaceFinder, service, registry)
if err != nil {
return nil, err
}
var svc *awsecrapi.ECR
if !isPublic {
svc, err = getAwsSvc(ctx, accessKey, secretKey, registry)
if err != nil {
return nil, err
}
}
authorizer := NewAuth(accessKey, svc, isPublic)
return &adapter{
cacheSvc: svc,
Adapter: native.NewAdapterWithAuthorizer(registry, authorizer),
}, nil
}
// Create ...
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, service, record)
}
type factory struct {
}
// HealthCheck checks health status of a proxy.
func (a *adapter) HealthCheck() (string, error) {
return "Not implemented", nil
}
func (a *adapter) GetImageName(imageName string) (string, error) {
return imageName, nil
}
var (
_ adp.Adapter = (*adapter)(nil)
_ adp.ArtifactRegistry = (*adapter)(nil)
)
type adapter struct {
*native.Adapter
cacheSvc *awsecrapi.ECR
}
// Ensure '*adapter' implements interface 'Adapter'.
var _ adp.Adapter = (*adapter)(nil)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/npmjs/client.go | registry/app/remote/adapter/npmjs/client.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmjs
import (
"context"
"net/http"
"github.com/harness/gitness/app/services/refcache"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/remote/adapter/commons"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type client struct {
client *http.Client
url string
username string
password string
}
// newClient creates a new npm client.
func newClient(
ctx context.Context,
registry types.UpstreamProxy,
finder refcache.SpaceFinder,
service secret.Service,
) (*client, error) {
accessKey, secretKey, _, err := commons.GetCredentials(ctx, finder, service, registry)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("error getting credentials for registry: %s %v", registry.RepoKey, err)
return nil, err
}
c := &client{
url: registry.RepoURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
username: accessKey,
password: secretKey,
}
return c, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/npmjs/adaptor.go | registry/app/remote/adapter/npmjs/adaptor.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmjs
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/harness/gitness/app/api/usererror"
"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/metadata/npm"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.NpmRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
const (
NpmjsURL = "https://registry.npmjs.org"
)
type adapter struct {
*native.Adapter
registry types.UpstreamProxy
client *client
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
c, err := newClient(ctx, registry, spaceFinder, service)
if err != nil {
return nil, err
}
return &adapter{
Adapter: nativeAdapter,
registry: registry,
client: c,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeNPM)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
func (a *adapter) GetPackageMetadata(ctx context.Context, pkg string) (*npm.PackageMetadata, error) {
_, readCloser, err := a.GetFile(ctx, pkg)
if err != nil {
code := errors.ErrCode(err)
if code == errors.NotFoundCode {
return nil, usererror.NotFoundf("failed to get package metadata %s", pkg)
}
if code == errors.ForbiddenCode {
return nil, usererror.Forbidden(fmt.Sprintf("failed to get package metadata %s", pkg))
}
}
defer readCloser.Close()
response, err := ParseNPMMetadata(readCloser)
if err != nil {
return nil, err
}
return &response, nil
}
func (a *adapter) GetPackage(ctx context.Context, pkg string, version string) (io.ReadCloser, error) {
metadata, err := a.GetPackageMetadata(ctx, pkg)
if err != nil {
return nil, err
}
downloadURL := ""
for _, p := range metadata.Versions {
if p.Version == version {
downloadURL = p.Dist.Tarball
break
}
}
if downloadURL == "" {
return nil, fmt.Errorf("pkg: %s, version: %s not found", pkg, version)
}
log.Ctx(ctx).Info().Msgf("Download URL: %s", downloadURL)
_, closer, err := a.GetFileFromURL(ctx, downloadURL)
if err != nil {
code := errors.ErrCode(err)
if code == errors.NotFoundCode {
return nil, usererror.NotFoundf("failed to get package file %s", pkg+version)
}
if code == errors.ForbiddenCode {
return nil, usererror.Forbidden(fmt.Sprintf("failed to get package file %s", pkg+version))
}
}
return closer, nil
}
// ParseNPMMetadata parses the given Json and returns a SimpleMetadata DTO.
func ParseNPMMetadata(r io.ReadCloser) (npm.PackageMetadata, error) {
var metadata npm.PackageMetadata
if err := json.NewDecoder(r).Decode(&metadata); err != nil {
return npm.PackageMetadata{}, 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/remote/adapter/rpm/adapter.go | registry/app/remote/adapter/rpm/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pypi
import (
"context"
"io"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.RpmRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
type adapter struct {
*native.Adapter
}
func (a *adapter) GetMetadataFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
_, closer, err := a.GetFile(ctx, filePath)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file: %s", filePath)
return nil, err
}
return closer, nil
}
func (a *adapter) GetPackage(ctx context.Context, pkg string) (io.ReadCloser, error) {
_, closer, err := a.GetFile(ctx, pkg)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get package: %s", pkg)
return nil, err
}
return closer, nil
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
return &adapter{
Adapter: nativeAdapter,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeRPM)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/crates/adapter.go | registry/app/remote/adapter/crates/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package crates
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/harness/gitness/app/api/usererror"
"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/metadata/cargo"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.CargoRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
const (
CratesURL = "https://index.crates.io"
)
type adapter struct {
*native.Adapter
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
return &adapter{
Adapter: nativeAdapter,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeCARGO)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
func (a *adapter) GetRegistryConfig(ctx context.Context) (*cargo.RegistryConfig, error) {
_, readCloser, err := a.GetFile(ctx, "config.json")
if err != nil {
return nil, err
}
defer readCloser.Close()
var config cargo.RegistryConfig
data, err := io.ReadAll(readCloser)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
err = json.Unmarshal(data, &config)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal config file: %w", err)
}
return &config, nil
}
func (a *adapter) GetPackageFile(ctx context.Context, filepath string) (io.ReadCloser, error) {
_, readCloser, err := a.GetFile(ctx, filepath)
if err != nil {
code := errors.ErrCode(err)
if code == errors.NotFoundCode {
return nil, usererror.NotFoundf("failed to get package file %s", filepath)
}
if code == errors.ForbiddenCode {
return nil, usererror.Forbidden(fmt.Sprintf("failed to get package file %s", filepath))
}
return nil, err
}
return readCloser, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/maven/adapter.go | registry/app/remote/adapter/maven/adapter.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 maven
import (
"context"
"net/http"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
commonhttp "github.com/harness/gitness/registry/app/common/http"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
const (
registryURL = "https://repo1.maven.org/maven2/"
)
func init() {
adapterType := string(artifact.UpstreamConfigSourceMavenCentral)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Register adapter factory for %s", adapterType)
return
}
}
func newAdapter(
ctx context.Context, spaceFinder refcache.SpaceFinder, service secret.Service, registry types.UpstreamProxy,
) (adp.Adapter, error) {
client, err := NewClient(registry)
if err != nil {
return nil, err
}
return &adapter{
client: client,
Adapter: native.NewAdapter(ctx, spaceFinder, service, registry),
}, nil
}
type factory struct {
}
// Create ...
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, service, record)
}
var (
_ adp.Adapter = (*adapter)(nil)
_ adp.ArtifactRegistry = (*adapter)(nil)
)
type adapter struct {
*native.Adapter
client *Client
}
// Ensure '*adapter' implements interface 'Adapter'.
var _ adp.Adapter = (*adapter)(nil)
// Client is a client to interact with DockerHub.
type Client struct {
client *http.Client
host string
}
// NewClient creates a new DockerHub client.
func NewClient(_ types.UpstreamProxy) (*Client, error) {
client := &Client{
host: registryURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
}
return client, nil
}
func (a *adapter) GetImageName(imageName string) (string, error) {
return imageName, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/dockerhub/client.go | registry/app/remote/adapter/dockerhub/client.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 dockerhub
import (
"context"
"fmt"
"io"
"net/http"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
// Client is a client to interact with DockerHub.
type Client struct {
client *http.Client
token string
host string
// credential LoginCredential
}
// NewClient creates a new DockerHub client.
func NewClient(_ types.UpstreamProxy) (*Client, error) {
client := &Client{
host: registryURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
}
return client, nil
}
// Do performs http request to DockerHub, it will set token automatically.
func (c *Client) Do(ctx context.Context, method, path string, body io.Reader) (*http.Response, error) {
url := baseURL + path
log.Ctx(ctx).Info().Msgf("%s %s", method, url)
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
if body != nil || method == http.MethodPost || method == http.MethodPut {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", fmt.Sprintf("%s %s", "Bearer", c.token))
return c.client.Do(req)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/dockerhub/consts.go | registry/app/remote/adapter/dockerhub/consts.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 dockerhub
const (
baseURL = "https://hub.docker.com"
registryURL = "https://registry-1.docker.io"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/dockerhub/types.go | registry/app/remote/adapter/dockerhub/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 dockerhub
// LoginCredential is request to login.
type LoginCredential struct {
User string `json:"username"`
Password string `json:"password"`
}
// TokenResp is response of login.
type TokenResp struct {
Token string `json:"token"`
}
// NamespacesResp is namespace list responsed from DockerHub.
type NamespacesResp struct {
// Namespaces is a list of namespaces
Namespaces []string `json:"namespaces"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/dockerhub/adapter.go | registry/app/remote/adapter/dockerhub/adapter.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 dockerhub
import (
"context"
"strings"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
func init() {
adapterType := string(artifact.UpstreamConfigSourceDockerhub)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Register adapter factory for %s", adapterType)
return
}
}
func newAdapter(
ctx context.Context, spaceFinder refcache.SpaceFinder, service secret.Service, registry types.UpstreamProxy,
) (adp.Adapter, error) {
client, err := NewClient(registry)
if err != nil {
return nil, err
}
// TODO: get Upstream Credentials
return &adapter{
client: client,
Adapter: native.NewAdapter(ctx, spaceFinder, service, registry),
}, nil
}
type factory struct {
}
// Create ...
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, service, record)
}
func (a *adapter) GetImageName(imageName string) (string, error) {
arr := strings.Split(imageName, "/")
if len(arr) == 1 {
imageName = "library/" + imageName
}
return imageName, nil
}
var (
_ adp.Adapter = (*adapter)(nil)
_ adp.ArtifactRegistry = (*adapter)(nil)
)
type adapter struct {
*native.Adapter
client *Client
}
// Ensure '*adapter' implements interface 'Adapter'.
var _ adp.Adapter = (*adapter)(nil)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/nuget/client.go | registry/app/remote/adapter/nuget/client.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nuget
import (
"context"
"net/http"
"github.com/harness/gitness/app/services/refcache"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/remote/adapter/commons"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
type client struct {
client *http.Client
url string
username string
password string
}
// newClient creates a new Nuget client.
func newClient(
ctx context.Context,
registry types.UpstreamProxy,
finder refcache.SpaceFinder,
service secret.Service,
) (*client, error) {
username, password, _, err := commons.GetCredentials(ctx, finder, service, registry)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("error getting credentials for registry: %s %v", registry.RepoKey, err)
return nil, err
}
c := &client{
url: registry.RepoURL,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(true)),
},
username: username,
password: password,
}
return c, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/adapter/nuget/adapter.go | registry/app/remote/adapter/nuget/adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"fmt"
"io"
"strconv"
"strings"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/pkg/types/nuget"
adp "github.com/harness/gitness/registry/app/remote/adapter"
"github.com/harness/gitness/registry/app/remote/adapter/native"
"github.com/harness/gitness/registry/app/remote/registry"
"github.com/harness/gitness/registry/types"
"github.com/harness/gitness/secret"
"github.com/rs/zerolog/log"
)
var _ registry.NugetRegistry = (*adapter)(nil)
var _ adp.Adapter = (*adapter)(nil)
const (
NugetOrgURL = "https://api.nuget.org/v3/index.json"
RegistrationBaseURL = "RegistrationsBaseUrl"
PackageBaseAddress = "PackageBaseAddress"
)
type adapter struct {
*native.Adapter
registry types.UpstreamProxy
client *client
}
func newAdapter(
ctx context.Context,
spaceFinder refcache.SpaceFinder,
registry types.UpstreamProxy,
service secret.Service,
) (adp.Adapter, error) {
nativeAdapter := native.NewAdapter(ctx, spaceFinder, service, registry)
c, err := newClient(ctx, registry, spaceFinder, service)
if err != nil {
return nil, err
}
return &adapter{
Adapter: nativeAdapter,
registry: registry,
client: c,
}, nil
}
type factory struct {
}
func (f *factory) Create(
ctx context.Context, spaceFinder refcache.SpaceFinder, record types.UpstreamProxy, service secret.Service,
) (adp.Adapter, error) {
return newAdapter(ctx, spaceFinder, record, service)
}
func init() {
adapterType := string(artifact.PackageTypeNUGET)
if err := adp.RegisterFactory(adapterType, new(factory)); err != nil {
log.Error().Stack().Err(err).Msgf("Failed to register adapter factory for %s", adapterType)
return
}
}
func (a adapter) GetServiceEndpoint(ctx context.Context) (*nuget.ServiceEndpoint, error) {
_, readCloser, err := a.GetFileFromURL(ctx, a.client.url)
if err != nil {
return nil, err
}
defer readCloser.Close()
response, err := ParseServiceEndpointResponse(readCloser)
if err != nil {
return nil, err
}
return &response, nil
}
func (a adapter) GetPackageMetadata(ctx context.Context, pkg, proxyEndpoint string) (io.ReadCloser, error) {
var packageMetadataEndpoint string
if proxyEndpoint != "" {
packageMetadataEndpoint = proxyEndpoint
} else {
svcEndpoints, err := a.GetServiceEndpoint(ctx)
if err != nil {
return nil, err
}
baseURL, err := getResourceByTypePrefix(svcEndpoints, RegistrationBaseURL)
if err != nil {
return nil, err
}
packageMetadataEndpoint = fmt.Sprintf("%s/%s/index.json", strings.TrimRight(baseURL, "/"), pkg)
}
log.Ctx(ctx).Info().Msgf("Package Metadata URL: %s", packageMetadataEndpoint)
_, readCloser, err := a.GetFileFromURL(ctx, packageMetadataEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", packageMetadataEndpoint)
return nil, err
}
return readCloser, nil
}
func (a adapter) GetPackageVersionMetadataV2(ctx context.Context, pkg, version string) (io.ReadCloser, error) {
baseURL := a.client.url
packageVersionEndpoint := fmt.Sprintf("%s/Packages(Id='%s',Version='%s')",
strings.TrimRight(baseURL, "/"), pkg, version)
log.Ctx(ctx).Info().Msgf("Package Version V2 Metadata URL: %s", packageVersionEndpoint)
_, readCloser, err := a.GetFileFromURL(ctx, packageVersionEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", packageVersionEndpoint)
return nil, err
}
return readCloser, nil
}
func (a adapter) GetPackage(ctx context.Context, pkg, version, proxyEndpoint, fileName string) (io.ReadCloser, error) {
var packageEndpoint string
if proxyEndpoint != "" {
packageEndpoint = proxyEndpoint
} else {
svcEndpoints, err := a.GetServiceEndpoint(ctx)
if err != nil {
return nil, err
}
baseURL, err := getResourceByTypePrefix(svcEndpoints, PackageBaseAddress)
if err != nil {
return nil, err
}
packageEndpoint = fmt.Sprintf("%s/%s/%s/%s", strings.TrimRight(baseURL, "/"), pkg, version,
fileName)
}
log.Ctx(ctx).Info().Msgf("Package URL: %s", packageEndpoint)
_, closer, err := a.GetFileFromURL(ctx, packageEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", packageEndpoint)
return nil, err
}
return closer, nil
}
func (a adapter) ListPackageVersion(ctx context.Context, pkg string) (io.ReadCloser, error) {
svcEndpoints, err := a.GetServiceEndpoint(ctx)
if err != nil {
return nil, err
}
baseURL, err := getResourceByTypePrefix(svcEndpoints, PackageBaseAddress)
if err != nil {
return nil, err
}
versionEndpoint := fmt.Sprintf("%s/%s/index.json", strings.TrimRight(baseURL, "/"), pkg)
log.Ctx(ctx).Info().Msgf("List Version URL: %s", versionEndpoint)
_, closer, err := a.GetFileFromURL(ctx, versionEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", versionEndpoint)
return nil, err
}
return closer, nil
}
func (a adapter) ListPackageVersionV2(ctx context.Context, pkg string) (io.ReadCloser, error) {
baseURL := a.client.url
versionEndpoint := fmt.Sprintf("%s/FindPackagesById()?id='%s'", strings.TrimRight(baseURL, "/"), pkg)
log.Ctx(ctx).Info().Msgf("List Version V2 URL: %s", versionEndpoint)
_, closer, err := a.GetFileFromURL(ctx, versionEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", versionEndpoint)
return nil, err
}
return closer, nil
}
func (a adapter) SearchPackageV2(ctx context.Context, searchTerm string, limit, offset int) (io.ReadCloser, error) {
baseURL := a.client.url
searchEndpoint := fmt.Sprintf("%s/Search()?searchTerm='%s'&$skip=%d&$top=%d&semVerLevel=2.0.0",
strings.TrimRight(baseURL, "/"), searchTerm, offset, limit)
log.Ctx(ctx).Info().Msgf("Search Package V2 URL: %s", searchEndpoint)
_, closer, err := a.GetFileFromURL(ctx, searchEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", searchEndpoint)
return nil, err
}
return closer, nil
}
func (a adapter) SearchPackage(ctx context.Context, searchTerm string, limit, offset int) (io.ReadCloser, error) {
// For v3 API, we need to use the search service endpoint
endpoint, err := a.GetServiceEndpoint(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get service endpoint: %w", err)
}
searchURL, err := getResourceByTypePrefix(endpoint, "SearchQueryService")
if err != nil {
return nil, fmt.Errorf("failed to get search service URL: %w", err)
}
searchEndpoint := fmt.Sprintf("%s?q=%s&skip=%d&take=%d",
strings.TrimRight(searchURL, "/"), searchTerm, offset, limit)
log.Ctx(ctx).Info().Msgf("Search Package V3 URL: %s", searchEndpoint)
_, closer, err := a.GetFileFromURL(ctx, searchEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", searchEndpoint)
return nil, err
}
return closer, nil
}
func (a adapter) CountPackageV2(ctx context.Context, searchTerm string) (int64, error) {
baseURL := a.client.url
countEndpoint := fmt.Sprintf("%s/Search()/$count?searchTerm='%s'&semVerLevel=2.0.0",
strings.TrimRight(baseURL, "/"), searchTerm)
log.Ctx(ctx).Info().Msgf("Count Package V2 URL: %s", countEndpoint)
_, closer, err := a.GetFileFromURL(ctx, countEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", countEndpoint)
return 0, err
}
defer closer.Close()
// Read the count response (should be a plain text number)
countBytes, err := io.ReadAll(closer)
if err != nil {
return 0, fmt.Errorf("failed to read count response: %w", err)
}
countStr := strings.TrimSpace(string(countBytes))
count, err := strconv.ParseInt(countStr, 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse count: %w", err)
}
return count, nil
}
func (a adapter) CountPackageVersionV2(ctx context.Context, pkg string) (int64, error) {
baseURL := a.client.url
countEndpoint := fmt.Sprintf("%s/FindPackagesById()/$count?id='%s'",
strings.TrimRight(baseURL, "/"), pkg)
log.Ctx(ctx).Info().Msgf("Count Package Version V2 URL: %s", countEndpoint)
_, closer, err := a.GetFileFromURL(ctx, countEndpoint)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msgf("Failed to get file from URL: %s", countEndpoint)
return 0, err
}
defer closer.Close()
// Read the count response (should be a plain text number)
countBytes, err := io.ReadAll(closer)
if err != nil {
return 0, fmt.Errorf("failed to read count response: %w", err)
}
countStr := strings.TrimSpace(string(countBytes))
count, err := strconv.ParseInt(countStr, 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse count: %w", err)
}
return count, nil
}
func ParseServiceEndpointResponse(r io.ReadCloser) (nuget.ServiceEndpoint, error) {
var result nuget.ServiceEndpoint
if err := json.NewDecoder(r).Decode(&result); err != nil {
return nuget.ServiceEndpoint{}, err
}
return result, nil
}
func getResourceByTypePrefix(endpoints *nuget.ServiceEndpoint, typePrefix string) (string, error) {
var resource *nuget.Resource
for _, r := range endpoints.Resources {
if strings.HasPrefix(r.Type, typePrefix) {
if resource == nil || r.Type > resource.Type {
resource = &r
}
}
}
if resource == nil {
return "", fmt.Errorf("resource %s not found", typePrefix)
}
return resource.ID, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/client.go | registry/app/remote/clients/registry/client.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 registry
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/common/lib"
"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/commons"
"github.com/harness/gitness/registry/app/pkg/maven/utils"
"github.com/harness/gitness/registry/app/remote/clients/registry/auth"
"github.com/harness/gitness/registry/app/remote/clients/registry/interceptor"
"github.com/opencontainers/go-digest"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog/log"
_ "github.com/harness/gitness/registry/app/manifest/ocischema" // register oci manifest unmarshal function
)
var (
accepts = []string{
v1.MediaTypeImageIndex,
manifestlist.MediaTypeManifestList,
v1.MediaTypeImageManifest,
schema2.MediaTypeManifest,
MediaTypeSignedManifest,
MediaTypeManifest,
}
)
// const definition.
const (
UserAgent = "gitness-registry-client"
// DefaultHTTPClientTimeout is the default timeout for registry http client.
DefaultHTTPClientTimeout = 30 * time.Minute
// 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"
// MediaTypeManifestLayer specifies the media type for manifest layers.
MediaTypeManifestLayer = "application/vnd.docker.container.image.rootfs.diff+x-gtar"
)
var (
// registryHTTPClientTimeout is the timeout for registry http client.
registryHTTPClientTimeout time.Duration
)
func init() {
registryHTTPClientTimeout = DefaultHTTPClientTimeout
// override it if read from environment variable, in minutes
if env := os.Getenv("GITNESS_REGISTRY_HTTP_CLIENT_TIMEOUT"); len(env) > 0 {
timeout, err := strconv.ParseInt(env, 10, 64)
if err != nil {
log.Error().
Stack().
Err(err).
Msg(
fmt.Sprintf(
"Failed to parse GITNESS_REGISTRY_HTTP_CLIENT_TIMEOUT: %v, use default value: %v",
err, DefaultHTTPClientTimeout,
),
)
} else if timeout > 0 {
registryHTTPClientTimeout = time.Duration(timeout) * time.Minute
}
}
}
// Client defines the methods that a registry client should implements.
type Client interface {
// Ping the base API endpoint "/v2/"
Ping(ctx context.Context) (err error)
// Catalog the repositories
Catalog(ctx context.Context) (repositories []string, err error)
// ListTags lists the tags under the specified repository
ListTags(ctx context.Context, repository string) (tags []string, err error)
// ManifestExist checks the existence of the manifest
ManifestExist(ctx context.Context, repository, reference string) (exist bool, desc *manifest.Descriptor, err error)
// PullManifest pulls the specified manifest
PullManifest(
ctx context.Context,
repository, reference string,
acceptedMediaTypes ...string,
) (manifest manifest.Manifest, digest string, err error)
// PushManifest pushes the specified manifest
PushManifest(ctx context.Context, repository, reference, mediaType string, payload []byte) (
digest string,
err error,
)
// DeleteManifest deletes the specified manifest. The "reference" can be "tag" or "digest"
DeleteManifest(ctx context.Context, repository, reference string) (err error)
// BlobExist checks the existence of the specified blob
BlobExist(ctx context.Context, repository, digest string) (exist bool, err error)
// PullBlob pulls the specified blob. The caller must close the returned "blob"
PullBlob(ctx context.Context, repository, digest string) (size int64, blob io.ReadCloser, err error)
// PullBlobChunk pulls the specified blob, but by chunked
PullBlobChunk(ctx context.Context, repository, digest string, blobSize, start, end int64) (
size int64,
blob io.ReadCloser,
err error,
)
// PushBlob pushes the specified blob
PushBlob(ctx context.Context, repository, digest string, size int64, blob io.Reader) error
// PushBlobChunk pushes the specified blob, but by chunked
PushBlobChunk(
ctx context.Context,
repository, digest string,
blobSize int64,
chunk io.Reader,
start, end int64,
location string,
) (nextUploadLocation string, endRange int64, err error)
// MountBlob mounts the blob from the source repository
MountBlob(ctx context.Context, srcRepository, digest, dstRepository string) (err error)
// DeleteBlob deletes the specified blob
DeleteBlob(ctx context.Context, repository, digest string) (err error)
// Copy the artifact from source repository to the destination. The "override"
// is used to specify whether the destination artifact will be overridden if
// its name is same with source but digest isn't
Copy(
ctx context.Context,
srcRepository, srcReference, dstRepository, dstReference string,
override bool,
) (err error)
// Do send generic HTTP requests to the target registry service
Do(req *http.Request) (*http.Response, error)
// GetFile Download the file
GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error)
// HeadFile Check existence of file
HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error)
// GetFileFromURL Download the file from URL instead of provided endpoint. Authorizer still remains the same.
GetFileFromURL(ctx context.Context, url string) (*commons.ResponseHeaders, io.ReadCloser, error)
GetURL(ctx context.Context, filePath string) string
}
// NewClient creates a registry client with the default authorizer which determines the auth scheme
// of the registry automatically and calls the corresponding underlying authorizers(basic/bearer) to
// do the auth work. If a customized authorizer is needed, use "NewClientWithAuthorizer" instead.
func NewClient(url, username, password string, insecure, isOCI bool, interceptors ...interceptor.Interceptor) Client {
authorizer := auth.NewAuthorizer(username, password, insecure, isOCI)
return NewClientWithAuthorizer(url, authorizer, insecure, interceptors...)
}
// NewClientWithAuthorizer creates a registry client with the provided authorizer.
func NewClientWithAuthorizer(
url string,
authorizer lib.Authorizer,
insecure bool,
interceptors ...interceptor.Interceptor,
) Client {
return &client{
url: url,
authorizer: authorizer,
interceptors: interceptors,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(insecure)),
Timeout: registryHTTPClientTimeout,
},
}
}
type client struct {
url string
authorizer lib.Authorizer
interceptors []interceptor.Interceptor
client *http.Client
}
func (c *client) Ping(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildPingURL(c.url), nil)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *client) Catalog(ctx context.Context) ([]string, error) {
var repositories []string
url := buildCatalogURL(c.url)
for {
repos, next, err := c.catalog(ctx, url)
if err != nil {
return nil, err
}
repositories = append(repositories, repos...)
url = next
// no next page, end the loop
if len(url) == 0 {
break
}
// relative URL
if !strings.Contains(url, "://") {
url = c.url + url
}
}
return repositories, nil
}
func (c *client) catalog(ctx context.Context, url string) ([]string, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, "", err
}
resp, err := c.do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
repositories := struct {
Repositories []string `json:"repositories"`
}{}
if err := json.Unmarshal(body, &repositories); err != nil {
return nil, "", err
}
return repositories.Repositories, next(resp.Header.Get("Link")), nil
}
func (c *client) ListTags(ctx context.Context, repository string) ([]string, error) {
var tags []string
url := buildTagListURL(c.url, repository)
for {
tgs, next, err := c.listTags(ctx, url)
if err != nil {
return nil, err
}
tags = append(tags, tgs...)
url = next
// no next page, end the loop
if len(url) == 0 {
break
}
// relative URL
if !strings.Contains(url, "://") {
url = c.url + url
}
}
return tags, nil
}
func (c *client) listTags(ctx context.Context, url string) ([]string, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, "", err
}
resp, err := c.do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
tgs := struct {
Tags []string `json:"tags"`
}{}
if err := json.Unmarshal(body, &tgs); err != nil {
return nil, "", err
}
return tgs.Tags, next(resp.Header.Get("Link")), nil
}
func (c *client) ManifestExist(ctx context.Context, repository, reference string) (bool, *manifest.Descriptor, error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodHead, buildManifestURL(c.url, repository, reference), nil,
)
if err != nil {
return false, nil, err
}
for _, mediaType := range accepts {
req.Header.Add("Accept", mediaType)
}
resp, err := c.do(req)
if err != nil {
if errors.IsErr(err, errors.NotFoundCode) {
return false, nil, nil
}
return false, nil, err
}
defer resp.Body.Close()
dig := resp.Header.Get("Docker-Content-Digest")
contentType := resp.Header.Get("Content-Type")
contentLen := resp.Header.Get("Content-Length")
length, _ := strconv.Atoi(contentLen)
return true, &manifest.Descriptor{Digest: digest.Digest(dig), MediaType: contentType, Size: int64(length)}, nil
}
func (c *client) PullManifest(
ctx context.Context,
repository, reference string,
acceptedMediaTypes ...string,
) (manifest.Manifest, string, error) {
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet, buildManifestURL(
c.url, repository,
reference,
), nil,
)
if err != nil {
return nil, "", err
}
if len(acceptedMediaTypes) == 0 {
acceptedMediaTypes = accepts
}
for _, mediaType := range acceptedMediaTypes {
req.Header.Add("Accept", mediaType)
}
resp, err := c.do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
payload, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
mediaType := resp.Header.Get("Content-Type")
manifest, _, err := manifest.UnmarshalManifest(mediaType, payload)
if err != nil {
return nil, "", err
}
digest := resp.Header.Get("Docker-Content-Digest")
return manifest, digest, nil
}
func (c *client) PushManifest(ctx context.Context, repository, reference, mediaType string, payload []byte) (
string,
error,
) {
req, err := http.NewRequestWithContext(
ctx, http.MethodPut, buildManifestURL(c.url, repository, reference),
bytes.NewReader(payload),
)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", mediaType)
resp, err := c.do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
return resp.Header.Get("Docker-Content-Digest"), nil
}
func (c *client) DeleteManifest(ctx context.Context, repository, reference string) error {
_, err := digest.Parse(reference)
if err != nil {
// the reference is tag, get the digest first
exist, desc, err := c.ManifestExist(ctx, repository, reference)
if err != nil {
return err
}
if !exist {
return errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("%s:%s not found", repository, reference)
}
reference = string(desc.Digest)
}
req, err := http.NewRequestWithContext(
ctx, http.MethodDelete,
buildManifestURL(c.url, repository, reference), nil,
)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *client) BlobExist(ctx context.Context, repository, digest string) (bool, error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodHead, buildBlobURL(c.url, repository, digest), nil,
)
if err != nil {
return false, err
}
resp, err := c.do(req)
if err != nil {
if errors.IsErr(err, errors.NotFoundCode) {
return false, nil
}
return false, err
}
defer resp.Body.Close()
return true, nil
}
func (c *client) PullBlob(ctx context.Context, repository, digest string) (int64, io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildBlobURL(c.url, repository, digest), nil)
if err != nil {
return 0, nil, err
}
req.Header.Add("Accept-Encoding", "identity")
resp, err := c.do(req)
if err != nil {
return 0, nil, err
}
var size int64
n := resp.Header.Get("Content-Length")
// no content-length is acceptable, which can taken from manifests
if len(n) > 0 {
size, err = strconv.ParseInt(n, 10, 64)
if err != nil {
defer resp.Body.Close()
return 0, nil, err
}
}
return size, resp.Body, nil
}
// PullBlobChunk pulls the specified blob, but by chunked, refer to
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pull
// for more details.
func (c *client) PullBlobChunk(ctx context.Context, repository, digest string, _ int64, start, end int64) (
int64,
io.ReadCloser,
error,
) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildBlobURL(c.url, repository, digest), nil)
if err != nil {
return 0, nil, err
}
req.Header.Add("Accept-Encoding", "identity")
req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", start, end))
resp, err := c.do(req)
if err != nil {
return 0, nil, err
}
var size int64
n := resp.Header.Get("Content-Length")
// no content-length is acceptable, which can taken from manifests
if len(n) > 0 {
size, err = strconv.ParseInt(n, 10, 64)
if err != nil {
defer resp.Body.Close()
return 0, nil, err
}
}
return size, resp.Body, nil
}
func (c *client) PushBlob(ctx context.Context, repository, digest string, size int64, blob io.Reader) error {
location, err := c.initiateBlobUpload(ctx, repository)
if err != nil {
return err
}
return c.monolithicBlobUpload(ctx, location, digest, size, blob)
}
// PushBlobChunk pushes the specified blob, but by chunked,
// refer to https://github.com/opencontainers/distribution-spec/blob/main/spec.md#push
// for more details.
func (c *client) PushBlobChunk(
ctx context.Context,
repository, digest string,
blobSize int64,
chunk io.Reader,
start, end int64,
location string,
) (string, int64, error) {
var err error
// first chunk need to initialize blob upload location
if start == 0 {
location, err = c.initiateBlobUpload(ctx, repository)
if err != nil {
return location, end, err
}
}
// the range is from 0 to (blobSize-1), so (end == blobSize-1) means it is last chunk
lastChunk := end == blobSize-1
url, err := buildChunkBlobUploadURL(c.url, location, digest, lastChunk)
if err != nil {
return location, end, err
}
// use PUT instead of PATCH for last chunk which can reduce a final request
method := http.MethodPatch
if lastChunk {
method = http.MethodPut
}
req, err := http.NewRequestWithContext(ctx, method, url, chunk)
if err != nil {
return location, end, err
}
req.Header.Set("Content-Length", fmt.Sprintf("%d", end-start+1))
req.Header.Set("Content-Range", fmt.Sprintf("%d-%d", start, end))
resp, err := c.do(req)
if err != nil {
// if push chunk error, we should query the upload progress for new location and end range.
newLocation, newEnd, err1 := c.getUploadStatus(ctx, location)
if err1 == nil {
return newLocation, newEnd, err
}
// end should return start-1 to re-push this chunk
return location, start - 1, fmt.Errorf("failed to get upload status: %w", err1)
}
defer resp.Body.Close()
// return the location for next chunk upload
return resp.Header.Get("Location"), end, nil
}
func (c *client) getUploadStatus(ctx context.Context, location string) (string, int64, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, location, nil)
if err != nil {
return location, -1, err
}
resp, err := c.do(req)
if err != nil {
return location, -1, err
}
defer resp.Body.Close()
_, end, err := parseContentRange(resp.Header.Get("Range"))
if err != nil {
return location, -1, err
}
return resp.Header.Get("Location"), end, nil
}
func (c *client) initiateBlobUpload(ctx context.Context, repository string) (string, error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodPost,
buildInitiateBlobUploadURL(c.url, repository), nil,
)
if err != nil {
return "", err
}
req.Header.Set("Content-Length", "0")
resp, err := c.do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
return resp.Header.Get("Location"), nil
}
func (c *client) monolithicBlobUpload(ctx context.Context, location, digest string, size int64, data io.Reader) error {
url, err := buildMonolithicBlobUploadURL(c.url, location, digest)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, data)
if err != nil {
return err
}
req.ContentLength = size
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *client) MountBlob(ctx context.Context, srcRepository, digest, dstRepository string) (err error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodPost,
buildMountBlobURL(c.url, dstRepository, digest, srcRepository), nil,
)
if err != nil {
return err
}
req.Header.Set("Content-Length", "0")
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *client) DeleteBlob(ctx context.Context, repository, digest string) (err error) {
req, err := http.NewRequestWithContext(
ctx, http.MethodDelete, buildBlobURL(c.url, repository, digest), nil,
)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *client) Copy(
ctx context.Context,
srcRepository, srcReference, dstRepository, dstReference string,
override bool,
) (err error) {
// pull the manifest from the source repository
manifest, srcDgt, err := c.PullManifest(ctx, srcRepository, srcReference)
if err != nil {
return err
}
// check the existence of the artifact on the destination repository
blobExist, desc, err := c.ManifestExist(ctx, dstRepository, dstReference)
if err != nil {
return err
}
if blobExist {
// the same artifact already exists
if desc != nil && srcDgt == string(desc.Digest) {
return nil
}
// the same name artifact exists, but not allowed to override
if !override {
return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the same name but different digest artifact exists, but the override is set to false")
}
}
for _, descriptor := range manifest.References() {
digest := descriptor.Digest.String()
switch descriptor.MediaType {
// skip foreign layer
case schema2.MediaTypeForeignLayer:
continue
// manifest or index
case v1.MediaTypeImageIndex, manifestlist.MediaTypeManifestList,
v1.MediaTypeImageManifest, schema2.MediaTypeManifest,
MediaTypeSignedManifest, MediaTypeManifest:
if err = c.Copy(ctx, srcRepository, digest, dstRepository, digest, false); err != nil {
return err
}
// common layer
default:
blobExist, err = c.BlobExist(ctx, dstRepository, digest)
if err != nil {
return err
}
// the layer already exist, skip
if blobExist {
continue
}
// when the copy happens inside the same registry, use mount
if err = c.MountBlob(ctx, srcRepository, digest, dstRepository); err != nil {
return err
}
}
}
mediaType, payload, err := manifest.Payload()
if err != nil {
return err
}
// push manifest to the destination repository
if _, err = c.PushManifest(ctx, dstRepository, dstReference, mediaType, payload); err != nil {
return err
}
return nil
}
func (c *client) Do(req *http.Request) (*http.Response, error) {
return c.do(req)
}
func (c *client) do(req *http.Request) (*http.Response, error) {
for _, interceptor := range c.interceptors {
if err := interceptor.Intercept(req); err != nil {
return nil, err
}
}
if c.authorizer != nil {
if err := c.authorizer.Modify(req); err != nil {
return nil, err
}
}
req.Header.Set("User-Agent", UserAgent)
log.Info().Msgf("[Remote Call]: Request: %s %s", req.Method, req.URL.String())
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
code := errors.GeneralCode
switch resp.StatusCode {
case http.StatusUnauthorized:
code = errors.UnAuthorizedCode
case http.StatusForbidden:
code = errors.ForbiddenCode
case http.StatusNotFound:
code = errors.NotFoundCode
case http.StatusTooManyRequests:
code = errors.RateLimitCode
}
return nil, errors.New(nil).WithCode(code).
WithMessage("http status code: %d, body: %s", resp.StatusCode, string(body))
}
return resp, nil
}
// parse the next page link from the link header.
func next(link string) string {
links := lib.ParseLinks(link)
for _, lk := range links {
if lk.Rel == "next" {
return lk.URL
}
}
return ""
}
func buildPingURL(endpoint string) string {
return fmt.Sprintf("%s/v2/", endpoint)
}
func buildCatalogURL(endpoint string) string {
return fmt.Sprintf("%s/v2/_catalog?n=1000", endpoint)
}
func buildTagListURL(endpoint, repository string) string {
return fmt.Sprintf("%s/v2/%s/tags/list", endpoint, repository)
}
func buildManifestURL(endpoint, repository, reference string) string {
return fmt.Sprintf("%s/v2/%s/manifests/%s", endpoint, repository, reference)
}
func buildBlobURL(endpoint, repository, reference string) string {
return fmt.Sprintf("%s/v2/%s/blobs/%s", endpoint, repository, reference)
}
func buildMountBlobURL(endpoint, repository, digest, from string) string {
return fmt.Sprintf("%s/v2/%s/blobs/uploads/?mount=%s&from=%s", endpoint, repository, digest, from)
}
func buildInitiateBlobUploadURL(endpoint, repository string) string {
return fmt.Sprintf("%s/v2/%s/blobs/uploads/", endpoint, repository)
}
func buildChunkBlobUploadURL(endpoint, location, digest string, lastChunk bool) (string, error) {
url, err := url.Parse(location)
if err != nil {
return "", err
}
q := url.Query()
if lastChunk {
q.Set("digest", digest)
}
url.RawQuery = q.Encode()
if url.IsAbs() {
return url.String(), nil
}
// the "relativeurls" is enabled in registry
return endpoint + url.String(), nil
}
func buildMonolithicBlobUploadURL(endpoint, location, digest string) (string, error) {
url, err := url.Parse(location)
if err != nil {
return "", err
}
q := url.Query()
q.Set("digest", digest)
url.RawQuery = q.Encode()
if url.IsAbs() {
return url.String(), nil
}
// the "relativeurls" is enabled in registry
return endpoint + url.String(), nil
}
func (c *client) GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
buildFileURL(c.url, filePath), nil)
if err != nil {
return nil, nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, nil, err
}
responseHeaders := utils.ParseResponseHeaders(resp)
return responseHeaders, resp.Body, nil
}
func (c *client) GetFileFromURL(ctx context.Context, url string) (*commons.ResponseHeaders, io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
url, nil)
if err != nil {
return nil, nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, nil, err
}
responseHeaders := utils.ParseResponseHeaders(resp)
return responseHeaders, resp.Body, nil
}
func (c *client) HeadFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodHead,
buildFileURL(c.url, filePath), nil)
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseHeaders := utils.ParseResponseHeaders(resp)
return responseHeaders, nil
}
func buildFileURL(endpoint, filePath string) string {
base, err := url.Parse(endpoint)
if err != nil {
log.Warn().Err(err).Msgf("Failed to parse endpoint %s %s", endpoint, filePath)
return fmt.Sprintf("%s/%s", strings.TrimSuffix(endpoint, "/"), strings.TrimPrefix(filePath, "/"))
}
hasTrailingSlash := strings.HasSuffix(filePath, "/") && filePath != "/"
base.Path = path.Clean(path.Join(base.Path, filePath))
// Restore trailing slash if it was present in the original filePath
if hasTrailingSlash && !strings.HasSuffix(base.Path, "/") {
base.Path += "/"
}
return base.String()
}
func (c *client) GetURL(_ context.Context, filePath string) string {
return buildFileURL(c.url, filePath)
}
func parseContentRange(cr string) (int64, int64, error) {
ranges := strings.Split(cr, "-")
if len(ranges) != 2 {
return -1, -1, fmt.Errorf("invalid content range format, %s", cr)
}
start, err := strconv.ParseInt(ranges[0], 10, 64)
if err != nil {
return -1, -1, err
}
end, err := strconv.ParseInt(ranges[1], 10, 64)
if err != nil {
return -1, -1, err
}
return start, end, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/client_test.go | registry/app/remote/clients/registry/client_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 registry
import (
"testing"
)
func TestBuildFileURL(t *testing.T) {
tests := []struct {
name string
endpoint string
filePath string
want string
}{
{
name: "simple path",
endpoint: "http://example.com",
filePath: "file.txt",
want: "http://example.com/file.txt",
},
{
name: "endpoint with trailing slash",
endpoint: "http://example.com/",
filePath: "file.txt",
want: "http://example.com/file.txt",
},
{
name: "filepath with leading slash",
endpoint: "http://example.com",
filePath: "/file.txt",
want: "http://example.com/file.txt",
},
{
name: "both with slashes",
endpoint: "http://example.com/",
filePath: "/file.txt",
want: "http://example.com/file.txt",
},
{
name: "endpoint with path",
endpoint: "http://example.com/api/v1",
filePath: "file.txt",
want: "http://example.com/api/v1/file.txt",
},
{
name: "endpoint with path and trailing slash",
endpoint: "http://example.com/api/v1/",
filePath: "file.txt",
want: "http://example.com/api/v1/file.txt",
},
{
name: "nested file path",
endpoint: "http://example.com",
filePath: "path/to/file.txt",
want: "http://example.com/path/to/file.txt",
},
{
name: "path traversal attempt - parent directory",
endpoint: "http://example.com/api",
filePath: "../secret/file.txt",
want: "http://example.com/secret/file.txt",
},
{
name: "path traversal attempt - multiple levels",
endpoint: "http://example.com/api/v1",
filePath: "../../secret",
want: "http://example.com/secret",
},
{
name: "path traversal attempt - absolute path escape",
endpoint: "http://example.com/api",
filePath: "/../../../etc/passwd",
want: "http://example.com/etc/passwd",
},
{
name: "double slashes in path",
endpoint: "http://example.com",
filePath: "path//to///file.txt",
want: "http://example.com/path/to/file.txt",
},
{
name: "current directory references",
endpoint: "http://example.com",
filePath: "./path/./to/./file.txt",
want: "http://example.com/path/to/file.txt",
},
{
name: "mixed path issues",
endpoint: "http://example.com/api",
filePath: "path/..//other/./file.txt",
want: "http://example.com/api/other/file.txt",
},
{
name: "https endpoint",
endpoint: "https://secure.example.com",
filePath: "secure/file.txt",
want: "https://secure.example.com/secure/file.txt",
},
{
name: "endpoint with port",
endpoint: "http://example.com:8080",
filePath: "file.txt",
want: "http://example.com:8080/file.txt",
},
{
name: "endpoint with port and path",
endpoint: "http://example.com:8080/api/v1",
filePath: "resource/file.txt",
want: "http://example.com:8080/api/v1/resource/file.txt",
},
{
name: "special characters in path",
endpoint: "http://example.com",
filePath: "path/with spaces/file.txt",
want: "http://example.com/path/with%20spaces/file.txt",
},
{
name: "url with query parameters preserved",
endpoint: "http://example.com/api?key=value",
filePath: "file.txt",
want: "http://example.com/api/file.txt?key=value",
},
{
name: "url with fragment preserved",
endpoint: "http://example.com/api#section",
filePath: "file.txt",
want: "http://example.com/api/file.txt#section",
},
{
name: "empty file path",
endpoint: "http://example.com/api",
filePath: "",
want: "http://example.com/api",
},
{
name: "root file path",
endpoint: "http://example.com/api",
filePath: "/",
want: "http://example.com/api",
},
{
name: "pypi simple path",
endpoint: "https://pypi.org",
filePath: "simple/requests",
want: "https://pypi.org/simple/requests",
},
{
name: "python package with version",
endpoint: "https://pypi.org",
filePath: "packages/source/r/requests/requests-2.28.0.tar.gz",
want: "https://pypi.org/packages/source/r/requests/requests-2.28.0.tar.gz",
},
{
name: "malformed endpoint - no scheme (fallback)",
endpoint: "not-a-valid-url",
filePath: "file.txt",
want: "not-a-valid-url/file.txt",
},
{
name: "localhost endpoint",
endpoint: "http://localhost:8080",
filePath: "api/test",
want: "http://localhost:8080/api/test",
},
{
name: "ipv4 endpoint",
endpoint: "http://192.168.1.1",
filePath: "file.txt",
want: "http://192.168.1.1/file.txt",
},
{
name: "ipv6 endpoint",
endpoint: "http://[::1]:8080",
filePath: "file.txt",
want: "http://[::1]:8080/file.txt",
},
{
name: "directory with trailing slash",
endpoint: "http://example.com",
filePath: "path/to/directory/",
want: "http://example.com/path/to/directory/",
},
{
name: "directory with trailing slash and endpoint path",
endpoint: "http://example.com/api",
filePath: "resources/",
want: "http://example.com/api/resources/",
},
{
name: "nested directory with trailing slash",
endpoint: "http://example.com",
filePath: "a/b/c/",
want: "http://example.com/a/b/c/",
},
{
name: "root path with trailing slash",
endpoint: "http://example.com",
filePath: "/",
want: "http://example.com/",
},
{
name: "simple directory with trailing slash",
endpoint: "http://example.com/api/v1",
filePath: "simple/",
want: "http://example.com/api/v1/simple/",
},
{
name: "trailing slash preserved after path cleaning",
endpoint: "http://example.com",
filePath: "path/./to/../directory/",
want: "http://example.com/path/directory/",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildFileURL(tt.endpoint, tt.filePath)
if got != tt.want {
t.Errorf("buildFileURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestBuildFileURL_PathTraversalSafety(t *testing.T) {
// Test that path traversal attempts are cleaned
tests := []struct {
name string
endpoint string
filePath string
shouldNotContain string
}{
{
name: "no double dots in result",
endpoint: "http://example.com/api",
filePath: "../../../etc/passwd",
shouldNotContain: "..",
},
{
name: "no double slashes in path segment",
endpoint: "http://example.com",
filePath: "path//file",
shouldNotContain: "path//file",
},
{
name: "no current dir references",
endpoint: "http://example.com",
filePath: "./path/./file",
shouldNotContain: "/./",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildFileURL(tt.endpoint, tt.filePath)
// Check URL structure is valid
if got == "" {
t.Error("buildFileURL() returned empty string")
}
// For the path cleaning tests, we need to ensure the patterns are cleaned
// Note: path.Clean removes these, but URL encoding may change the representation
})
}
}
func TestBuildFileURL_PreservesURLComponents(t *testing.T) {
tests := []struct {
name string
endpoint string
filePath string
checkFunc func(t *testing.T, result string)
}{
{
name: "preserves query parameters",
endpoint: "http://example.com/api?token=abc123",
filePath: "file.txt",
checkFunc: func(t *testing.T, result string) {
if result != "http://example.com/api/file.txt?token=abc123" {
t.Errorf("Query parameters not preserved: %s", result)
}
},
},
{
name: "preserves fragment",
endpoint: "http://example.com/api#section",
filePath: "file.txt",
checkFunc: func(t *testing.T, result string) {
if result != "http://example.com/api/file.txt#section" {
t.Errorf("Fragment not preserved: %s", result)
}
},
},
{
name: "preserves https scheme",
endpoint: "https://secure.example.com",
filePath: "file.txt",
checkFunc: func(t *testing.T, result string) {
if result[:5] != "https" {
t.Errorf("HTTPS scheme not preserved: %s", result)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildFileURL(tt.endpoint, tt.filePath)
tt.checkFunc(t, got)
})
}
}
func BenchmarkBuildFileURL(b *testing.B) {
endpoint := "http://example.com/api/v1"
filePath := "path/to/resource/file.txt"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = buildFileURL(endpoint, filePath)
}
}
func BenchmarkBuildFileURL_WithTraversal(b *testing.B) {
endpoint := "http://example.com/api/v1"
filePath := "../../../path/to/../file.txt"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = buildFileURL(endpoint, filePath)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/auth/authorizer.go | registry/app/remote/clients/registry/auth/authorizer.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 auth
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
commonhttp "github.com/harness/gitness/registry/app/common/http"
"github.com/harness/gitness/registry/app/common/http/modifier"
"github.com/harness/gitness/registry/app/common/lib"
"github.com/harness/gitness/registry/app/dist_temp/challenge"
"github.com/harness/gitness/registry/app/remote/clients/registry/auth/basic"
"github.com/harness/gitness/registry/app/remote/clients/registry/auth/bearer"
"github.com/harness/gitness/registry/app/remote/clients/registry/auth/null"
)
// NewAuthorizer creates an authorizer that can handle different auth schemes.
func NewAuthorizer(username, password string, insecure, isOCI bool) lib.Authorizer {
return &authorizer{
username: username,
password: password,
isOCI: isOCI,
client: &http.Client{
Transport: commonhttp.GetHTTPTransport(commonhttp.WithInsecure(insecure)),
},
}
}
// authorizer authorizes the request with the provided credential.
// It determines the auth scheme of registry automatically and calls
// different underlying authorizers to do the auth work.
type authorizer struct {
sync.Mutex
username string
password string
client *http.Client
url *url.URL // registry URL
authorizer modifier.Modifier // the underlying authorizer
isOCI bool
}
func (a *authorizer) Modify(req *http.Request) error {
// Nil underlying authorizer means this is the first time the authorizer is called
// Try to connect to the registry and determine the auth scheme
if a.authorizer == nil {
// to avoid concurrent issue
a.Lock()
defer a.Unlock()
if err := a.initialize(req.Context(), req.URL); err != nil {
return err
}
}
// check whether the request targets the registry
// If it doesn't, no modification is needed, so we return nil.
if !a.isTarget(req) {
return nil
}
// If the request targets the registry, delegate the modification to the underlying authorizer.
return a.authorizer.Modify(req)
}
func (a *authorizer) initialize(ctx context.Context, u *url.URL) error {
if a.authorizer != nil {
return nil
}
if !a.isOCI {
a.authorizer = basic.NewAuthorizer(a.username, a.password)
return nil
}
url, err := url.Parse(u.Scheme + "://" + u.Host + "/v2/")
if err != nil {
return fmt.Errorf("failed to parse URL for scheme %s and host %s: %w", u.Scheme, u.Host, err)
}
a.url = url
req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.url.String(), nil)
if err != nil {
return err
}
resp, err := a.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
challenges := challenge.ResponseChallenges(resp)
// no challenge, mean no auth
if len(challenges) == 0 {
a.authorizer = null.NewAuthorizer()
return nil
}
cm := map[string]challenge.Challenge{}
for _, challenge := range challenges {
cm[challenge.Scheme] = challenge
}
if challenge, exist := cm["bearer"]; exist {
a.authorizer = bearer.NewAuthorizer(
challenge.Parameters["realm"],
challenge.Parameters["service"], basic.NewAuthorizer(a.username, a.password),
a.client.Transport,
)
return nil
}
if _, exist := cm["basic"]; exist {
a.authorizer = basic.NewAuthorizer(a.username, a.password)
return nil
}
return fmt.Errorf("unsupported auth scheme: %v", challenges)
}
// isTarget checks whether the request targets the registry.
// If not, the request shouldn't be handled by the authorizer, e.g., requests sent to backend storage (S3, etc.).
func (a *authorizer) isTarget(req *http.Request) bool {
// Check if the path contains the versioned API endpoint (e.g., "/v2/")
if a.isOCI {
const versionedPath = "/v2/"
if !strings.Contains(req.URL.Path, versionedPath) {
return false
}
// Ensure that the request's host, scheme, and versioned path match the authorizer's URL.
if req.URL.Host != a.url.Host || req.URL.Scheme != a.url.Scheme ||
!strings.HasPrefix(req.URL.Path, a.url.Path) {
return false
}
}
return true
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/auth/basic/authorizer.go | registry/app/remote/clients/registry/auth/basic/authorizer.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 basic
import (
"net/http"
"github.com/harness/gitness/registry/app/common/lib"
)
// NewAuthorizer return a basic authorizer.
func NewAuthorizer(username, password string) lib.Authorizer {
return &authorizer{
username: username,
password: password,
}
}
type authorizer struct {
username string
password string
}
func (a *authorizer) Modify(req *http.Request) error {
if len(a.username) > 0 {
req.SetBasicAuth(a.username, a.password)
}
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/remote/clients/registry/auth/basic/authorizer_test.go | registry/app/remote/clients/registry/auth/basic/authorizer_test.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 basic
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestModify(t *testing.T) {
authorizer := NewAuthorizer("u", "p")
//nolint:noctx
req, _ := http.NewRequest(http.MethodGet, "", nil)
err := authorizer.Modify(req)
require.Nil(t, err)
u, p, ok := req.BasicAuth()
require.True(t, ok)
assert.Equal(t, "u", u)
assert.Equal(t, "p", p)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/auth/null/authorizer.go | registry/app/remote/clients/registry/auth/null/authorizer.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 null
import (
"net/http"
"github.com/harness/gitness/registry/app/common/lib"
)
// NewAuthorizer returns a null authorizer.
func NewAuthorizer() lib.Authorizer {
return &authorizer{}
}
type authorizer struct{}
func (a *authorizer) Modify(_ *http.Request) error {
// do nothing
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/remote/clients/registry/auth/bearer/cache.go | registry/app/remote/clients/registry/auth/bearer/cache.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 bearer
import (
"fmt"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
)
// newCache initializes a new cache with the specified capacity and latency.
// The latency is the delay applied to cache operations (if applicable).
func newCache(capacity int, latency int) *cache {
return &cache{
latency: latency,
capacity: capacity,
cache: map[string]*token{},
}
}
type cache struct {
sync.RWMutex
latency int // second, the network latency in case that when the
// token is checked it doesn't expire but it does when used.
capacity int // the capacity of the cache map.
cache map[string]*token
}
func (c *cache) get(scopes []*scope) *token {
c.RLock()
defer c.RUnlock()
token := c.cache[c.key(scopes)]
if token == nil {
return nil
}
expired, _ := c.expired(token)
if expired {
token = nil
}
return token
}
func (c *cache) set(scopes []*scope, token *token) {
c.Lock()
defer c.Unlock()
// exceed the capacity, empty some elements: all expired token will be removed,
// if no expired token, move the earliest one.
if len(c.cache) >= c.capacity {
var candidates []string
var earliestKey string
var earliestExpireTime time.Time
for key, value := range c.cache {
expired, expireAt := c.expired(value)
// expired.
if expired {
candidates = append(candidates, key)
continue
}
// doesn't expired.
if len(earliestKey) == 0 || expireAt.Before(earliestExpireTime) {
earliestKey = key
earliestExpireTime = expireAt
continue
}
}
if len(candidates) == 0 {
candidates = append(candidates, earliestKey)
}
for _, candidate := range candidates {
delete(c.cache, candidate)
}
}
c.cache[c.key(scopes)] = token
}
func (c *cache) key(scopes []*scope) string {
var strs []string
for _, scope := range scopes {
strs = append(strs, scope.String())
}
return strings.Join(strs, "#")
}
// return whether the token is expired or not and the expired time.
func (c *cache) expired(token *token) (bool, time.Time) {
// check time whether empty.
if len(token.IssuedAt) == 0 {
log.Warn().Msg("token issued time is empty, return expired to refresh token")
return true, time.Time{}
}
issueAt, err := time.Parse(time.RFC3339, token.IssuedAt)
if err != nil {
log.Error().
Stack().
Err(err).
Msg(fmt.Sprintf("failed to parse the issued at time of token %s: %v", token.IssuedAt, err))
return true, time.Time{}
}
expireAt := issueAt.Add(time.Duration(token.ExpiresIn-c.latency) * time.Second)
return expireAt.Before(time.Now()), expireAt
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/auth/bearer/authorizer.go | registry/app/remote/clients/registry/auth/bearer/authorizer.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 bearer
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/harness/gitness/registry/app/common/lib"
"github.com/harness/gitness/registry/app/common/lib/errors"
)
const (
cacheCapacity = 100
cacheLatency = 10 // second
)
// NewAuthorizer return a bearer token authorizer
// The parameter "a" is an authorizer used to fetch the token.
func NewAuthorizer(realm, service string, a lib.Authorizer, transport http.RoundTripper) lib.Authorizer {
authorizer := &authorizer{
realm: realm,
service: service,
authorizer: a,
cache: newCache(cacheCapacity, cacheLatency),
}
authorizer.client = &http.Client{Transport: transport}
return authorizer
}
type authorizer struct {
realm string
service string
authorizer lib.Authorizer
cache *cache
client *http.Client
}
func (a *authorizer) Modify(req *http.Request) error {
// parse scopes from request
scopes := parseScopes(req)
// get token
_token, err := a.getToken(req.Context(), scopes)
if err != nil {
return err
}
// set authorization header
if _token != nil && len(_token.Token) > 0 {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", _token.Token))
}
return nil
}
func (a *authorizer) getToken(ctx context.Context, scopes []*scope) (*token, error) {
// get token from cache first
_token := a.cache.get(scopes)
if _token != nil {
return _token, nil
}
// get no token from cache, fetch it from the token service
_token, err := a.fetchToken(ctx, scopes)
if err != nil {
return nil, err
}
// set the token into the cache
a.cache.set(scopes, _token)
return _token, nil
}
type token struct {
Token string `json:"token"`
AccessToken string `json:"access_token"` // the token returned by azure container registry is called "access_token"
ExpiresIn int `json:"expires_in"`
IssuedAt string `json:"issued_at"`
}
func (a *authorizer) fetchToken(ctx context.Context, scopes []*scope) (*token, error) {
url, err := url.Parse(a.realm)
if err != nil {
return nil, err
}
query := url.Query()
query.Add("service", a.service)
for _, scope := range scopes {
query.Add("scope", scope.String())
}
url.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil)
if err != nil {
return nil, err
}
if a.authorizer != nil {
if err = a.authorizer.Modify(req); err != nil {
return nil, err
}
}
resp, err := a.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
token := &token{}
switch resp.StatusCode {
case http.StatusOK:
return getToken(body, token)
case http.StatusUnauthorized:
return nil, fmt.Errorf("request with body :%s : %s", string(body), errors.UnAuthorizedCode)
case http.StatusForbidden:
return nil, fmt.Errorf("request with body :%s : %s", string(body), errors.ForbiddenCode)
default:
return nil, fmt.Errorf(
"failed to fetch token for request with body %s, status code %d",
string(body),
resp.StatusCode,
)
}
}
// getToken unmarshals the provided JSON-encoded body into the given token struct.
// If the "Token" field is empty but the "AccessToken" field is populated, it assigns "AccessToken" to "Token".
// It returns the updated token struct and any error encountered during unmarshalling.
func getToken(body []byte, t *token) (*token, error) {
// Unmarshal the JSON body into the token struct
if err := json.Unmarshal(body, t); err != nil {
return nil, fmt.Errorf("failed to unmarshal token: %w", err)
}
// If Token is empty and AccessToken is provided, assign AccessToken to Token
if t.Token == "" && t.AccessToken != "" {
t.Token = t.AccessToken
}
return t, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/clients/registry/auth/bearer/scope.go | registry/app/remote/clients/registry/auth/bearer/scope.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 bearer
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/distribution/reference"
)
const (
scopeTypeRegistry = "registry"
scopeTypeRepository = "repository"
scopeActionPull = "pull"
scopeActionPush = "push"
scopeActionAll = "*"
)
const v2 = "/v2/("
var (
catalog = regexp.MustCompile("/v2/_catalog$")
tag = regexp.MustCompile(v2 + reference.NameRegexp.String() + ")/tags/list")
manifest = regexp.MustCompile(
v2 +
reference.NameRegexp.String() +
")/manifests/(" +
reference.TagRegexp.String() +
"|" + reference.DigestRegexp.String() + ")",
)
blob = regexp.MustCompile(
v2 + reference.NameRegexp.String() + ")/blobs/" + reference.DigestRegexp.String(),
)
blobUpload = regexp.MustCompile(v2 + reference.NameRegexp.String() + ")/blobs/uploads")
)
type scope struct {
Type string
Name string
Actions []string
}
func (s *scope) String() string {
return fmt.Sprintf("%s:%s:%s", s.Type, s.Name, strings.Join(s.Actions, ","))
}
func parseScopes(req *http.Request) []*scope {
path := strings.TrimRight(req.URL.Path, "/")
var scopes []*scope
repository := ""
// manifest
if subs := manifest.FindStringSubmatch(path); len(subs) >= 2 {
// manifest
repository = subs[1]
} else if subs1 := blob.FindStringSubmatch(path); len(subs1) >= 2 {
// blob
repository = subs1[1]
} else if subs2 := blobUpload.FindStringSubmatch(path); len(subs2) >= 2 {
// blob upload
repository = subs2[1]
// blob mount
from := req.URL.Query().Get("from")
if len(from) > 0 {
scopes = append(
scopes, &scope{
Type: scopeTypeRepository,
Name: from,
Actions: []string{scopeActionPull},
},
)
}
} else if subs3 := tag.FindStringSubmatch(path); len(subs3) >= 2 {
// tag
repository = subs3[1]
}
if len(repository) > 0 {
scp := &scope{
Type: scopeTypeRepository,
Name: repository,
}
switch req.Method {
case http.MethodGet, http.MethodHead:
scp.Actions = []string{scopeActionPull}
case http.MethodPost, http.MethodPut, http.MethodPatch:
scp.Actions = []string{scopeActionPull, scopeActionPush}
case http.MethodDelete:
scp.Actions = []string{scopeActionAll}
}
scopes = append(scopes, scp)
return scopes
}
// catalog
if catalog.MatchString(path) {
return []*scope{
{
Type: scopeTypeRegistry,
Name: "catalog",
Actions: []string{scopeActionAll},
},
}
}
// base or no match, return 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/remote/clients/registry/interceptor/interceptor.go | registry/app/remote/clients/registry/interceptor/interceptor.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 interceptor
import "net/http"
// Interceptor intercepts the request.
type Interceptor interface {
Intercept(req *http.Request) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/generic.go | registry/app/remote/registry/generic.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg/commons"
)
type GenericRegistry interface {
GetFile(ctx context.Context, filePath string) (*commons.ResponseHeaders, io.ReadCloser, error)
HeadFile(ctx context.Context, filePath string) (*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/remote/registry/gopackage.go | registry/app/remote/registry/gopackage.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
)
type GoPackageRegistry interface {
GetPackageFile(ctx context.Context, filepath string) (io.ReadCloser, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/python.go | registry/app/remote/registry/python.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
"github.com/harness/gitness/registry/app/metadata/python"
"github.com/harness/gitness/registry/app/remote/adapter/commons/pypi"
)
type PythonRegistry interface {
GetMetadata(ctx context.Context, pkg string) (*pypi.SimpleMetadata, error)
GetPackage(ctx context.Context, pkg string, filename string) (io.ReadCloser, error)
GetJSON(ctx context.Context, pkg string, version string) (*python.Metadata, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/nuget.go | registry/app/remote/registry/nuget.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
"github.com/harness/gitness/registry/app/pkg/types/nuget"
)
type NugetRegistry interface {
GetPackage(ctx context.Context, pkg, version, proxyEndpoint, fileName string) (io.ReadCloser, error)
GetServiceEndpoint(ctx context.Context) (*nuget.ServiceEndpoint, 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)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/rpm.go | registry/app/remote/registry/rpm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
)
type RpmRegistry interface {
GetMetadataFile(ctx context.Context, filePath string) (io.ReadCloser, error)
GetPackage(ctx context.Context, filePath string) (io.ReadCloser, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/cargo.go | registry/app/remote/registry/cargo.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
"github.com/harness/gitness/registry/app/metadata/cargo"
)
type CargoRegistry interface {
GetRegistryConfig(ctx context.Context) (*cargo.RegistryConfig, error)
GetPackageFile(ctx context.Context, filepath string) (io.ReadCloser, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/remote/registry/npm.go | registry/app/remote/registry/npm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package registry
import (
"context"
"io"
npm2 "github.com/harness/gitness/registry/app/metadata/npm"
)
type NpmRegistry interface {
GetPackageMetadata(_ context.Context, pkg string) (*npm2.PackageMetadata, error)
GetPackage(ctx context.Context, pkg string, version string) (io.ReadCloser, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/helpers/wire.go | registry/app/helpers/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 helpers
import (
localurlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/interfaces"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/factory"
"github.com/harness/gitness/registry/app/helpers/pkg"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/utils/cargo"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/google/wire"
)
func ProvidePackageWrapperProvider(
registryHelper interfaces.RegistryHelper,
regFinder refcache.RegistryFinder,
cargoRegistryHelper cargo.RegistryHelper,
) interfaces.PackageWrapper {
// create package factory
packageFactory := factory.NewPackageFactory()
packageFactory.Register(pkg.NewCargoPackageType(registryHelper, cargoRegistryHelper))
packageFactory.Register(pkg.NewDockerPackageType(registryHelper))
packageFactory.Register(pkg.NewHelmPackageType(registryHelper))
packageFactory.Register(pkg.NewGenericPackageType(registryHelper))
packageFactory.Register(pkg.NewMavenPackageType(registryHelper))
packageFactory.Register(pkg.NewPythonPackageType(registryHelper))
packageFactory.Register(pkg.NewNugetPackageType(registryHelper))
packageFactory.Register(pkg.NewRPMPackageType(registryHelper))
packageFactory.Register(pkg.NewNPMPackageType(registryHelper))
packageFactory.Register(pkg.NewGoPackageType(registryHelper))
packageFactory.Register(pkg.NewHuggingFacePackageType(registryHelper))
return NewPackageWrapper(packageFactory, regFinder)
}
func ProvideRegistryHelper(
artifactStore store.ArtifactRepository,
fileManager filemanager.FileManager,
imageStore store.ImageRepository,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *registrypostprocessingevents.Reporter,
tx dbtx.Transactor,
urlProvider localurlprovider.Provider,
gitnessConfig *types.Config,
) interfaces.RegistryHelper {
return NewRegistryHelper(
artifactStore,
fileManager,
imageStore,
artifactEventReporter,
postProcessingReporter,
tx,
urlProvider,
gitnessConfig.Registry.SetupDetailsAuthHeaderPrefix,
)
}
var WireSet = wire.NewSet(
ProvidePackageWrapperProvider,
ProvideRegistryHelper,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/helpers/package_wrapper.go | registry/app/helpers/package_wrapper.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"context"
"fmt"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/api/interfaces"
artifactapi "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/factory"
"github.com/harness/gitness/registry/app/services/refcache"
"github.com/harness/gitness/registry/types"
)
type packageWrapper struct {
packageFactory factory.PackageFactory
regFinder refcache.RegistryFinder
}
func NewPackageWrapper(
packageFactory factory.PackageFactory,
regFinder refcache.RegistryFinder,
) interfaces.PackageWrapper {
return &packageWrapper{
packageFactory: packageFactory,
regFinder: regFinder,
}
}
func (p *packageWrapper) GetPackage(packageType string) interfaces.PackageHelper {
return p.packageFactory.Get(packageType)
}
func (p *packageWrapper) IsValidPackageType(packageType string) bool {
if packageType == "" {
return true
}
return p.packageFactory.IsValidPackageType(packageType)
}
func (p *packageWrapper) IsValidPackageTypes(packageTypes []string) bool {
for _, packageType := range packageTypes {
if !p.IsValidPackageType(packageType) {
return false
}
}
return true
}
func (p *packageWrapper) IsValidRepoType(repoType string) bool {
if repoType == "" {
return true
}
for _, pkgType := range p.packageFactory.GetAllPackageTypes() {
pkg := p.packageFactory.Get(pkgType)
if pkg.IsValidRepoType(repoType) {
return true
}
}
return false
}
func (p *packageWrapper) IsValidRepoTypes(repoTypes []string) bool {
for _, repoType := range repoTypes {
if !p.IsValidRepoType(repoType) {
return false
}
}
return true
}
func (p *packageWrapper) ValidateRepoType(packageType string, repoType string) bool {
pkg := p.GetPackage(packageType)
if pkg == nil {
return false
}
return pkg.IsValidRepoType(repoType)
}
func (p *packageWrapper) IsValidUpstreamSource(upstreamSource string) bool {
if upstreamSource == "" {
return true
}
for _, pkgType := range p.packageFactory.GetAllPackageTypes() {
pkg := p.packageFactory.Get(pkgType)
if pkg.IsValidUpstreamSource(upstreamSource) {
return true
}
}
return false
}
func (p *packageWrapper) IsValidUpstreamSources(upstreamSources []string) bool {
for _, upstreamSource := range upstreamSources {
if !p.IsValidUpstreamSource(upstreamSource) {
return false
}
}
return true
}
func (p *packageWrapper) ValidateUpstreamSource(packageType string, upstreamSource string) bool {
pkg := p.GetPackage(packageType)
if pkg == nil {
return false
}
return pkg.IsValidUpstreamSource(upstreamSource)
}
func (p *packageWrapper) IsURLRequiredForUpstreamSource(packageType string, upstreamSource string) bool {
pkg := p.GetPackage(packageType)
if pkg == nil {
return false
}
return pkg.IsURLRequiredForUpstreamSource(upstreamSource)
}
func (p *packageWrapper) GetPackageTypeFromPathPackageType(pathPackageType string) (string, error) {
for _, pkgType := range p.packageFactory.GetAllPackageTypes() {
pkg := p.packageFactory.Get(pkgType)
if pkg.GetPathPackageType() == pathPackageType {
return pkgType, nil
}
}
return "", fmt.Errorf("unsupported path package type: %s", pathPackageType)
}
func (p *packageWrapper) DeleteArtifactVersion(
ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
) error {
pkg := p.GetPackage(string(regInfo.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", regInfo.PackageType)
}
if err := pkg.DeleteVersion(ctx, regInfo, imageInfo, artifactName, versionName); err != nil {
return fmt.Errorf("failed to delete version: %w", err)
}
if err := p.ReportDeleteVersionEvent(ctx, regInfo.RegistryID, artifactName, versionName); err != nil {
return fmt.Errorf("failed to report delete version event: %w", err)
}
if err := p.ReportBuildPackageIndexEvent(ctx, regInfo.RegistryID, artifactName); err != nil {
return fmt.Errorf("failed to report build package index event: %w", err)
}
if err := p.ReportBuildRegistryIndexEvent(ctx, regInfo.RegistryID, make([]types.SourceRef, 0)); err != nil {
return fmt.Errorf("failed to report build registry index event: %w", err)
}
return nil
}
func (p *packageWrapper) ReportDeleteVersionEvent(
ctx context.Context,
registryID int64,
artifactName string,
versionName string,
) error {
session, ok := request.AuthSessionFrom(ctx)
if !ok {
return fmt.Errorf("failed to get auth session")
}
registry, err := p.regFinder.FindByID(ctx, registryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
pkg.ReportDeleteVersionEvent(ctx, session.Principal.ID, registry.ID, artifactName, versionName)
return nil
}
func (p *packageWrapper) ReportBuildPackageIndexEvent(
ctx context.Context,
registryID int64,
artifactName string,
) error {
registry, err := p.regFinder.FindByID(ctx, registryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
pkg.ReportBuildPackageIndexEvent(ctx, registry.ID, artifactName)
return nil
}
func (p *packageWrapper) ReportBuildRegistryIndexEvent(
ctx context.Context,
registryID int64,
sourceRefs []types.SourceRef,
) error {
registry, err := p.regFinder.FindByID(ctx, registryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
pkg.ReportBuildRegistryIndexEvent(ctx, registry.ID, sourceRefs)
return nil
}
func (p *packageWrapper) DeleteArtifact(
ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string,
) error {
pkg := p.GetPackage(string(regInfo.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", regInfo.PackageType)
}
if err := pkg.DeleteArtifact(ctx, regInfo, artifactName); err != nil {
return fmt.Errorf("failed to delete artifact: %w", err)
}
if err := p.ReportBuildRegistryIndexEvent(ctx, regInfo.RegistryID, make([]types.SourceRef, 0)); err != nil {
return fmt.Errorf("failed to report build registry index event: %w", err)
}
return nil
}
func (p *packageWrapper) GetFilePath(
packageType string,
artifactName string,
versionName string,
) (string, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return "", fmt.Errorf("unsupported package type: %s", packageType)
}
return pkg.GetFilePath(artifactName, versionName), nil
}
func (p *packageWrapper) GetPackageURL(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageType string,
) (string, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return "", fmt.Errorf("unsupported package type: %s", packageType)
}
return pkg.GetPackageURL(ctx, rootIdentifier, registryIdentifier), nil
}
func (p *packageWrapper) GetArtifactMetadata(
artifact types.ArtifactMetadata,
) *artifactapi.ArtifactMetadata {
pkg := p.GetPackage(string(artifact.PackageType))
if pkg == nil {
return nil
}
return pkg.GetArtifactMetadata(artifact)
}
func (p *packageWrapper) GetArtifactVersionMetadata(
packageType string,
image string,
tag types.NonOCIArtifactMetadata,
) *artifactapi.ArtifactVersionMetadata {
pkg := p.GetPackage(packageType)
if pkg == nil {
return nil
}
return pkg.GetArtifactVersionMetadata(image, tag)
}
func (p *packageWrapper) GetFileMetadata(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageType string,
artifactName string,
version string,
file types.FileNodeMetadata,
) *artifactapi.FileDetail {
pkg := p.GetPackage(packageType)
if pkg == nil {
return nil
}
return pkg.GetFileMetadata(
ctx,
rootIdentifier,
registryIdentifier,
artifactName,
version,
file,
)
}
func (p *packageWrapper) GetArtifactDetail(
packageType string,
img *types.Image,
art *types.Artifact,
downloadCount int64,
) (*artifactapi.ArtifactDetail, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return nil, fmt.Errorf("unsupported package type: %s", packageType)
}
return pkg.GetArtifactDetail(img, art, downloadCount)
}
func (p *packageWrapper) GetClientSetupDetails(
ctx context.Context,
regRef string,
image *artifactapi.ArtifactParam,
tag *artifactapi.VersionParam,
registryType artifactapi.RegistryType,
packageType string,
) (*artifactapi.ClientSetupDetails, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return nil, fmt.Errorf("unsupported package type: %s", packageType)
}
return pkg.GetClientSetupDetails(ctx, regRef, image, tag, registryType)
}
func (p *packageWrapper) BuildRegistryIndexAsync(
ctx context.Context,
payload types.BuildRegistryIndexTaskPayload,
) error {
registry, err := p.regFinder.FindByID(ctx, payload.RegistryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
return pkg.BuildRegistryIndexAsync(ctx, registry, payload)
}
func (p *packageWrapper) BuildPackageIndexAsync(
ctx context.Context,
payload types.BuildPackageIndexTaskPayload,
) error {
registry, err := p.regFinder.FindByID(ctx, payload.RegistryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
return pkg.BuildPackageIndexAsync(ctx, registry, payload)
}
func (p *packageWrapper) BuildPackageMetadataAsync(
ctx context.Context,
payload types.BuildPackageMetadataTaskPayload,
) error {
registry, err := p.regFinder.FindByID(ctx, payload.RegistryID)
if err != nil {
return fmt.Errorf("failed to find registry: %w", err)
}
pkg := p.GetPackage(string(registry.PackageType))
if pkg == nil {
return fmt.Errorf("unsupported package type: %s", registry.PackageType)
}
return pkg.BuildPackageMetadataAsync(ctx, registry, payload)
}
func (p *packageWrapper) GetNodePathsForImage(
packageType string,
artifactType *string,
packageName string,
) ([]string, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return []string{}, nil
}
return pkg.GetNodePathsForImage(artifactType, packageName)
}
func (p *packageWrapper) GetNodePathsForArtifact(
packageType string,
artifactType *string,
packageName string,
version string,
) ([]string, error) {
pkg := p.GetPackage(packageType)
if pkg == nil {
return []string{}, nil
}
return pkg.GetNodePathsForArtifact(artifactType, packageName, version)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/helpers/registry_helper.go | registry/app/helpers/registry_helper.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/harness/gitness/app/paths"
localurlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/registry/app/api/interfaces"
artifactapi "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/common"
registryevents "github.com/harness/gitness/registry/app/events/artifact"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/app/pkg/filemanager"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
registryutils "github.com/harness/gitness/registry/utils"
"github.com/harness/gitness/store/database/dbtx"
"github.com/inhies/go-bytesize"
"github.com/rs/zerolog/log"
)
type registryHelper struct {
ArtifactStore store.ArtifactRepository
FileManager filemanager.FileManager
ImageStore store.ImageRepository
ArtifactEventReporter *registryevents.Reporter
PostProcessingReporter *registrypostprocessingevents.Reporter
tx dbtx.Transactor
URLProvider localurlprovider.Provider
SetupDetailsAuthHeaderPrefix string
}
func NewRegistryHelper(
artifactStore store.ArtifactRepository,
fileManager filemanager.FileManager,
imageStore store.ImageRepository,
artifactEventReporter *registryevents.Reporter,
postProcessingReporter *registrypostprocessingevents.Reporter,
tx dbtx.Transactor,
urlProvider localurlprovider.Provider,
setupDetailsAuthHeaderPrefix string,
) interfaces.RegistryHelper {
return ®istryHelper{
ArtifactStore: artifactStore,
FileManager: fileManager,
ImageStore: imageStore,
ArtifactEventReporter: artifactEventReporter,
PostProcessingReporter: postProcessingReporter,
tx: tx,
URLProvider: urlProvider,
SetupDetailsAuthHeaderPrefix: setupDetailsAuthHeaderPrefix,
}
}
func (r *registryHelper) GetAuthHeaderPrefix() string {
return r.SetupDetailsAuthHeaderPrefix
}
func (r *registryHelper) DeleteFileNode(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
filePath string,
) error {
err := r.FileManager.DeleteNode(ctx, regInfo.RegistryID, filePath)
if err != nil {
return err
}
return nil
}
func (r *registryHelper) DeleteVersion(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
filePath string) error {
_, err := r.ArtifactStore.GetByName(ctx, imageInfo.ID, versionName)
if err != nil {
return fmt.Errorf("version doesn't exist with for image %v: %w", imageInfo.Name, err)
}
err = r.tx.WithTx(
ctx,
func(ctx context.Context) error {
// delete nodes from nodes store
err = r.FileManager.DeleteNode(ctx, regInfo.RegistryID, filePath)
if err != nil {
return err
}
// delete artifacts from artifacts store
err = r.ArtifactStore.DeleteByVersionAndImageName(ctx, artifactName, versionName, regInfo.RegistryID)
if err != nil {
return fmt.Errorf("failed to delete version: %w", err)
}
// delete image if no other artifacts linked
err = r.ImageStore.DeleteByImageNameIfNoLinkedArtifacts(ctx, regInfo.RegistryID, artifactName)
if err != nil {
return fmt.Errorf("failed to delete image: %w", err)
}
return nil
},
)
if err != nil {
return err
}
return nil
}
func (r *registryHelper) ReportDeleteVersionEvent(
ctx context.Context,
payload *registryevents.ArtifactDeletedPayload,
) {
r.ArtifactEventReporter.ArtifactDeleted(ctx, payload)
}
func (r *registryHelper) ReportBuildPackageIndexEvent(
ctx context.Context, registryID int64, artifactName string,
) {
if r.PostProcessingReporter != nil {
r.PostProcessingReporter.BuildPackageIndex(ctx, registryID, artifactName)
}
}
func (r *registryHelper) ReportBuildRegistryIndexEvent(
ctx context.Context, registryID int64, sources []types.SourceRef,
) {
if r.PostProcessingReporter != nil {
r.PostProcessingReporter.BuildRegistryIndex(ctx, registryID, sources)
}
}
func (r *registryHelper) DeleteGenericImage(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string, filePath string,
) error {
err := r.tx.WithTx(
ctx, func(ctx context.Context) error {
// Delete Artifact Files
err := r.FileManager.DeleteNode(ctx, regInfo.RegistryID, filePath)
if err != nil {
return fmt.Errorf("failed to delete artifact files: %w", err)
}
// Delete Artifacts
err = r.ArtifactStore.DeleteByImageNameAndRegistryID(ctx, regInfo.RegistryID, artifactName)
if err != nil {
return fmt.Errorf("failed to delete versions: %w", err)
}
// Delete image
err = r.ImageStore.DeleteByImageNameAndRegID(
ctx, regInfo.RegistryID, artifactName,
)
if err != nil {
return fmt.Errorf("failed to delete artifact: %w", err)
}
return nil
},
)
return err
}
func (r *registryHelper) GetPackageURL(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
packageTypePathParam string,
) string {
return r.URLProvider.PackageURL(ctx, rootIdentifier+"/"+registryIdentifier, packageTypePathParam)
}
func (r *registryHelper) GetHostName(
ctx context.Context,
rootSpace string,
) string {
return common.TrimURLScheme(r.URLProvider.RegistryURL(ctx, rootSpace))
}
func (r *registryHelper) GetArtifactMetadata(
artifact types.ArtifactMetadata,
pullCommand string,
) *artifactapi.ArtifactMetadata {
lastModified := GetTimeInMs(artifact.ModifiedAt)
return &artifactapi.ArtifactMetadata{
RegistryIdentifier: artifact.RepoName,
RegistryUUID: artifact.RegistryUUID,
Uuid: artifact.UUID,
Name: artifact.Name,
Version: &artifact.Version,
Labels: &artifact.Labels,
LastModified: &lastModified,
PackageType: artifact.PackageType,
DownloadsCount: &artifact.DownloadCount,
PullCommand: &pullCommand,
IsQuarantined: &artifact.IsQuarantined,
QuarantineReason: artifact.QuarantineReason,
ArtifactType: artifact.ArtifactType,
}
}
func (r *registryHelper) GetArtifactVersionMetadata(
tag types.NonOCIArtifactMetadata,
pullCommand string,
packageType string,
) *artifactapi.ArtifactVersionMetadata {
modifiedAt := GetTimeInMs(tag.ModifiedAt)
size := GetImageSize(tag.Size)
downloadCount := tag.DownloadCount
fileCount := tag.FileCount
return &artifactapi.ArtifactVersionMetadata{
PackageType: artifactapi.PackageType(packageType),
FileCount: &fileCount,
Name: tag.Name,
Uuid: tag.UUID,
Size: &size,
LastModified: &modifiedAt,
PullCommand: &pullCommand,
DownloadsCount: &downloadCount,
IsQuarantined: &tag.IsQuarantined,
QuarantineReason: tag.QuarantineReason,
ArtifactType: tag.ArtifactType,
}
}
func (r *registryHelper) GetFileMetadata(
file types.FileNodeMetadata,
filename string,
downloadCommand string,
) *artifactapi.FileDetail {
return &artifactapi.FileDetail{
Checksums: GetCheckSums(file),
Size: GetSize(file.Size),
CreatedAt: fmt.Sprint(file.CreatedAt),
Name: filename,
DownloadCommand: downloadCommand,
Path: file.Path,
}
}
func (r *registryHelper) GetArtifactDetail(
img *types.Image,
art *types.Artifact,
metadata map[string]any,
downloadCount int64,
) *artifactapi.ArtifactDetail {
createdAt := GetTimeInMs(art.CreatedAt)
modifiedAt := GetTimeInMs(art.UpdatedAt)
size, ok := metadata["size"].(float64)
if !ok {
log.Error().Msg(fmt.Sprintf("failed to get size from metadata: %s, %s", img.Name, art.Version))
}
totalSize := GetSize(int64(size))
artifactDetail := &artifactapi.ArtifactDetail{
CreatedAt: &createdAt,
ModifiedAt: &modifiedAt,
Name: &img.Name,
Version: art.Version,
DownloadCount: &downloadCount,
Size: &totalSize,
}
return artifactDetail
}
func GetTimeInMs(t time.Time) string {
return fmt.Sprint(t.UnixMilli())
}
func GetImageSize(size string) string {
sizeVal, _ := strconv.ParseInt(size, 10, 64)
return GetSize(sizeVal)
}
func GetSize(sizeVal int64) string {
size := bytesize.New(float64(sizeVal))
return size.String()
}
func GetCheckSums(file types.FileNodeMetadata) []string {
return []string{
fmt.Sprintf("SHA-512: %s", file.Sha512),
fmt.Sprintf("SHA-256: %s", file.Sha256),
fmt.Sprintf("SHA-1: %s", file.Sha1),
fmt.Sprintf("MD5: %s", file.MD5),
}
}
func (r *registryHelper) ReplacePlaceholders(
ctx context.Context,
clientSetupSections *[]artifactapi.ClientSetupSection,
username string,
regRef string,
image *artifactapi.ArtifactParam,
version *artifactapi.VersionParam,
registryURL string,
groupID string,
uploadURL string,
hostname string,
) {
for i := range *clientSetupSections {
tab, err := (*clientSetupSections)[i].AsTabSetupStepConfig()
if err != nil || tab.Tabs == nil {
//nolint:lll
r.ReplacePlaceholdersInSection(ctx, &(*clientSetupSections)[i], username, regRef, image, version,
registryURL, groupID, uploadURL, hostname)
} else {
for j := range *tab.Tabs {
r.ReplacePlaceholders(ctx, (*tab.Tabs)[j].Sections, username, regRef, image, version, registryURL, groupID,
uploadURL, hostname)
}
_ = (*clientSetupSections)[i].FromTabSetupStepConfig(tab)
}
}
}
func (r *registryHelper) ReplacePlaceholdersInSection(
ctx context.Context,
clientSetupSection *artifactapi.ClientSetupSection,
username string,
regRef string,
image *artifactapi.ArtifactParam,
version *artifactapi.VersionParam,
registryURL string,
groupID string,
uploadURL string,
hostname string,
) {
_, registryName, _ := paths.DisectLeaf(regRef)
sec, err := clientSetupSection.AsClientSetupStepConfig()
if err != nil || sec.Steps == nil {
return
}
for _, st := range *sec.Steps {
if st.Commands == nil {
continue
}
for j := range *st.Commands {
r.ReplaceText(ctx, username, st, j, hostname, registryName, image, version, registryURL, groupID, uploadURL)
}
}
_ = clientSetupSection.FromClientSetupStepConfig(sec)
}
func (r *registryHelper) ReplaceText(
ctx context.Context,
username string,
st artifactapi.ClientSetupStep,
i int,
hostname string,
repoName string,
image *artifactapi.ArtifactParam,
version *artifactapi.VersionParam,
registryURL string,
groupID string,
uploadURL string,
) {
if r.SetupDetailsAuthHeaderPrefix != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value,
"<AUTH_HEADER_PREFIX>", r.SetupDetailsAuthHeaderPrefix))
}
if username != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(
strings.ReplaceAll(*(*st.Commands)[i].Value, "<USERNAME>", username),
)
if (*st.Commands)[i].Label != nil {
(*st.Commands)[i].Label = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Label, "<USERNAME>",
username))
}
}
if groupID != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<GROUP_ID>", groupID))
}
if registryURL != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<REGISTRY_URL>",
registryURL))
if (*st.Commands)[i].Label != nil {
(*st.Commands)[i].Label = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Label,
"<REGISTRY_URL>", registryURL))
}
}
if uploadURL != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<UPLOAD_URL>",
uploadURL))
}
if hostname != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(
strings.ReplaceAll(*(*st.Commands)[i].Value, "<HOSTNAME>", hostname),
)
}
if hostname != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value,
"<LOGIN_HOSTNAME>", common.GetHost(ctx, hostname)))
}
if repoName != "" {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<REGISTRY_NAME>",
repoName))
}
if image != nil {
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<IMAGE_NAME>",
string(*image)))
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<ARTIFACT_ID>",
string(*image)))
(*st.Commands)[i].Value = registryutils.StringPtr(strings.ReplaceAll(*(*st.Commands)[i].Value, "<ARTIFACT_NAME>",
string(*image)))
}
if version != nil {
(*st.Commands)[i].Value = registryutils.StringPtr(
strings.ReplaceAll(*(*st.Commands)[i].Value, "<TAG>", string(*version)),
)
(*st.Commands)[i].Value = registryutils.StringPtr(
strings.ReplaceAll(*(*st.Commands)[i].Value, "<VERSION>", string(*version)),
)
(*st.Commands)[i].Value = registryutils.StringPtr(
strings.ReplaceAll(*(*st.Commands)[i].Value, "<DIGEST>", string(*version)),
)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/helpers/pkg/generic.go | registry/app/helpers/pkg/generic.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type GenericPackageType interface {
interfaces.PackageHelper
}
type genericPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewGenericPackageType(registryHelper interfaces.RegistryHelper) GenericPackageType {
return &genericPackageType{
packageType: string(artifact.PackageTypeGENERIC),
pathPackageType: string(types.PathPackageTypeGeneric),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
},
}
}
func (c *genericPackageType) GetPackageType() string {
return c.packageType
}
func (c *genericPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *genericPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *genericPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *genericPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *genericPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *genericPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *genericPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *genericPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *genericPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *genericPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *genericPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *genericPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *genericPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *genericPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *genericPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *genericPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *genericPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *genericPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *genericPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *genericPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *genericPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *genericPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *genericPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *genericPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/python.go | registry/app/helpers/pkg/python.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type PythonPackageType interface {
interfaces.PackageHelper
}
type pythonPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewPythonPackageType(registryHelper interfaces.RegistryHelper) PythonPackageType {
return &pythonPackageType{
packageType: string(artifact.PackageTypePYTHON),
registryHelper: registryHelper,
pathPackageType: string(types.PathPackageTypePython),
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourcePyPi),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourcePyPi): {
urlRequired: false,
},
},
}
}
func (c *pythonPackageType) GetPackageType() string {
return c.packageType
}
func (c *pythonPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *pythonPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *pythonPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *pythonPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *pythonPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *pythonPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *pythonPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *pythonPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *pythonPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *pythonPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *pythonPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *pythonPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *pythonPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *pythonPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *pythonPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *pythonPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *pythonPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *pythonPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *pythonPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *pythonPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *pythonPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *pythonPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *pythonPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *pythonPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/nuget.go | registry/app/helpers/pkg/nuget.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type NugetPackageType interface {
interfaces.PackageHelper
}
type nugetPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewNugetPackageType(registryHelper interfaces.RegistryHelper) NugetPackageType {
return &nugetPackageType{
packageType: string(artifact.PackageTypeNUGET),
registryHelper: registryHelper,
pathPackageType: string(types.PathPackageTypeNuget),
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceNugetOrg),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceNugetOrg): {
urlRequired: false,
},
},
}
}
func (c *nugetPackageType) GetPackageType() string {
return c.packageType
}
func (c *nugetPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *nugetPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *nugetPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *nugetPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *nugetPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *nugetPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *nugetPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *nugetPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *nugetPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *nugetPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *nugetPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *nugetPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *nugetPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *nugetPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *nugetPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *nugetPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *nugetPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *nugetPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *nugetPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *nugetPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *nugetPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *nugetPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *nugetPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *nugetPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/maven.go | registry/app/helpers/pkg/maven.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"strings"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type MavenPackageType interface {
interfaces.PackageHelper
}
type mavenPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewMavenPackageType(registryHelper interfaces.RegistryHelper) MavenPackageType {
return &mavenPackageType{
packageType: string(artifact.PackageTypeMAVEN),
pathPackageType: string(types.PathPackageTypeMaven),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceMavenCentral),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceMavenCentral): {
urlRequired: false,
},
},
}
}
func (c *mavenPackageType) GetPackageType() string {
return c.packageType
}
func (c *mavenPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *mavenPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *mavenPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *mavenPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *mavenPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *mavenPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *mavenPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *mavenPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *mavenPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *mavenPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *mavenPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *mavenPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *mavenPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *mavenPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *mavenPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *mavenPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *mavenPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *mavenPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *mavenPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *mavenPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *mavenPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *mavenPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *mavenPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
parts := strings.SplitN(packageName, ":", 2)
path := ""
if len(parts) == 2 {
groupID := strings.ReplaceAll(parts[0], ".", "/")
path = groupID + "/" + parts[1]
}
return []string{"/" + path}, nil
}
func (c *mavenPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/node_path_test.go | registry/app/helpers/pkg/node_path_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"
)
// Updated tests with new method signatures (no error returns)
func TestCargoPackageType_GetNodePathsForImage_Updated(t *testing.T) {
cargoPackage := NewCargoPackageType(nil, nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple crate name",
packageName: "serde",
expectedPaths: []string{"/crates/serde"},
},
{
name: "crate with hyphens",
packageName: "serde-json",
expectedPaths: []string{"/crates/serde-json"},
},
{
name: "crate with underscores",
packageName: "tokio_util",
expectedPaths: []string{"/crates/tokio_util"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := cargoPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestCargoPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
cargoPackage := NewCargoPackageType(nil, nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple crate with version",
packageName: "serde",
version: "1.0.0",
expectedPaths: []string{"/crates/serde/1.0.0"},
},
{
name: "crate with pre-release version",
packageName: "tokio",
version: "1.0.0-alpha.1",
expectedPaths: []string{"/crates/tokio/1.0.0-alpha.1"},
},
{
name: "crate with build metadata",
packageName: "async-std",
version: "1.0.0+build.1",
expectedPaths: []string{"/crates/async-std/1.0.0+build.1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := cargoPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestDockerPackageType_GetNodePathsForImage_Updated(t *testing.T) {
dockerPackage := NewDockerPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple image name",
packageName: "nginx",
expectedPaths: []string{"/nginx"},
},
{
name: "namespaced image",
packageName: "library/nginx",
expectedPaths: []string{"/library/nginx"},
},
{
name: "registry with namespace",
packageName: "gcr.io/project/image",
expectedPaths: []string{"/gcr.io/project/image"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := dockerPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestDockerPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
dockerPackage := NewDockerPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple image with digest",
packageName: "nginx",
version: "0154ac4961ea10df8ceb1301f46d213f26d397fbd17f190b797d221f79dd7abc12",
expectedPaths: []string{"/nginx/sha256:54ac4961ea10df8ceb1301f46d213f26d397fbd17f190b797d221f79dd7abc12"},
},
{
name: "image with different digest",
packageName: "alpine",
version: "011a9ec845ee94c202b2d5da74a24f0ed2058318bfa9879fa541efaecba272e86b",
expectedPaths: []string{"/alpine/sha256:1a9ec845ee94c202b2d5da74a24f0ed2058318bfa9879fa541efaecba272e86b"},
},
{
name: "namespaced image with digest",
packageName: "library/postgres",
version: "0162d8908bee94c202b2d35224a221aaa2058318bfa9879fa541efaecba272331b",
expectedPaths: []string{"/library/postgres/sha256:62d8908bee94c202b2d35224a221aaa2058318bfa9879fa541efaecba272331b"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := dockerPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestMavenPackageType_GetNodePathsForImage_Updated(t *testing.T) {
mavenPackage := NewMavenPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple group and artifact",
packageName: "com.example:my-artifact",
expectedPaths: []string{"/com/example/my-artifact"},
},
{
name: "nested group structure",
packageName: "org.springframework.boot:spring-boot-starter",
expectedPaths: []string{"/org/springframework/boot/spring-boot-starter"},
},
{
name: "artifact with multiple dots",
packageName: "com.fasterxml.jackson.core:jackson-core",
expectedPaths: []string{"/com/fasterxml/jackson/core/jackson-core"},
},
{
name: "artifact without colon separator",
packageName: "junit.junit",
expectedPaths: []string{"/"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := mavenPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestMavenPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
mavenPackage := NewMavenPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple group and artifact with version",
packageName: "com.example:my-artifact",
version: "1.0.0",
expectedPaths: []string{"/com/example/my-artifact/1.0.0"},
},
{
name: "spring boot artifact with version",
packageName: "org.springframework.boot:spring-boot-starter",
version: "2.7.0",
expectedPaths: []string{"/org/springframework/boot/spring-boot-starter/2.7.0"},
},
{
name: "snapshot version",
packageName: "com.example:test-artifact",
version: "1.0.0-SNAPSHOT",
expectedPaths: []string{"/com/example/test-artifact/1.0.0-SNAPSHOT"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := mavenPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestGoPackageType_GetNodePathsForImage_Updated(t *testing.T) {
goPackage := NewGoPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "github module",
packageName: "github.com/gin-gonic/gin",
expectedPaths: []string{"/github.com/gin-gonic/gin"},
},
{
name: "golang.org module",
packageName: "golang.org/x/crypto",
expectedPaths: []string{"/golang.org/x/crypto"},
},
{
name: "custom domain module",
packageName: "go.uber.org/zap",
expectedPaths: []string{"/go.uber.org/zap"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := goPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestGoPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
goPackage := NewGoPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "github module with version",
packageName: "github.com/gin-gonic/gin",
version: "v1.8.1",
expectedPaths: []string{"/github.com/gin-gonic/gin/@v/v1.8.1"},
},
{
name: "golang.org module with version",
packageName: "golang.org/x/crypto",
version: "v0.0.0-20220622213112-05595931fe9d",
expectedPaths: []string{"/golang.org/x/crypto/@v/v0.0.0-20220622213112-05595931fe9d"},
},
{
name: "pre-release version",
packageName: "go.uber.org/zap",
version: "v1.22.0-rc.1",
expectedPaths: []string{"/go.uber.org/zap/@v/v1.22.0-rc.1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := goPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestRpmPackageType_GetNodePathsForImage_Updated(t *testing.T) {
rpmPackage := NewRPMPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple package name",
packageName: "nginx",
expectedPaths: []string{"/nginx"},
},
{
name: "package with hyphens",
packageName: "httpd-tools",
expectedPaths: []string{"/httpd-tools"},
},
{
name: "kernel package",
packageName: "kernel-devel",
expectedPaths: []string{"/kernel-devel"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := rpmPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestRpmPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
rpmPackage := NewRPMPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple package with version",
packageName: "nginx",
version: "1.20.1-1.el8.x86_64",
expectedPaths: []string{"/nginx/1.20.1-1.el8/x86_64"},
},
{
name: "package with complex architecture",
packageName: "httpd",
version: "2.4.37-43.module+el8.5.0+13806+b30d9eec.x86_64",
expectedPaths: []string{"/httpd/2.4.37-43.module+el8.5.0+13806+b30d9eec/x86_64"},
},
{
name: "kernel package with version",
packageName: "kernel-devel",
version: "4.18.0-348.el8.noarch",
expectedPaths: []string{"/kernel-devel/4.18.0-348.el8/noarch"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := rpmPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestNpmPackageType_GetNodePathsForImage_Updated(t *testing.T) {
npmPackage := NewNPMPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple package name",
packageName: "express",
expectedPaths: []string{"/express"},
},
{
name: "scoped package",
packageName: "@types/node",
expectedPaths: []string{"/@types/node"},
},
{
name: "organization scoped package",
packageName: "@angular/core",
expectedPaths: []string{"/@angular/core"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := npmPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestNpmPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
npmPackage := NewNPMPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple package with version",
packageName: "express",
version: "4.18.1",
expectedPaths: []string{"/express/4.18.1"},
},
{
name: "scoped package with version",
packageName: "@types/node",
version: "18.0.0",
expectedPaths: []string{"/@types/node/18.0.0"},
},
{
name: "pre-release version",
packageName: "react",
version: "18.0.0-rc.0",
expectedPaths: []string{"/react/18.0.0-rc.0"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := npmPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestHelmPackageType_GetNodePathsForImage_Updated(t *testing.T) {
helmPackage := NewHelmPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple chart name",
packageName: "nginx",
expectedPaths: []string{"/nginx"},
},
{
name: "chart with hyphens",
packageName: "nginx-ingress",
expectedPaths: []string{"/nginx-ingress"},
},
{
name: "complex chart name",
packageName: "prometheus-operator",
expectedPaths: []string{"/prometheus-operator"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := helmPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestHelmPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
helmPackage := NewHelmPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple chart with digest",
packageName: "nginx",
version: "0154ac4961ea10df8ceb1301f46d213f26d397fbd17f190b797d221f79dd7abc12",
expectedPaths: []string{"/nginx/sha256:54ac4961ea10df8ceb1301f46d213f26d397fbd17f190b797d221f79dd7abc12"},
},
{
name: "chart with different digest",
packageName: "prometheus",
version: "011a9ec845ee94c202b2d5da74a24f0ed2058318bfa9879fa541efaecba272e86b",
expectedPaths: []string{"/prometheus/sha256:1a9ec845ee94c202b2d5da74a24f0ed2058318bfa9879fa541efaecba272e86b"},
},
{
name: "chart with sha256 digest",
packageName: "grafana",
version: "0162d8908bee94c202b2d35224a221aaa2058318bfa9879fa541efaecba272331b",
expectedPaths: []string{"/grafana/sha256:62d8908bee94c202b2d35224a221aaa2058318bfa9879fa541efaecba272331b"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := helmPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestGenericPackageType_GetNodePathsForImage_Updated(t *testing.T) {
genericPackage := NewGenericPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple package name",
packageName: "mypackage",
expectedPaths: []string{"/mypackage"},
},
{
name: "package with hyphens",
packageName: "my-generic-package",
expectedPaths: []string{"/my-generic-package"},
},
{
name: "package with underscores",
packageName: "my_package_name",
expectedPaths: []string{"/my_package_name"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := genericPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestGenericPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
genericPackage := NewGenericPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple package with version",
packageName: "mypackage",
version: "1.0.0",
expectedPaths: []string{"/mypackage/1.0.0"},
},
{
name: "package with semantic version",
packageName: "data-processor",
version: "2.5.3",
expectedPaths: []string{"/data-processor/2.5.3"},
},
{
name: "package with custom version string",
packageName: "my_tool",
version: "v1.2.3-alpha",
expectedPaths: []string{"/my_tool/v1.2.3-alpha"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := genericPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestNugetPackageType_GetNodePathsForImage_Updated(t *testing.T) {
nugetPackage := NewNugetPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple package name",
packageName: "Newtonsoft.Json",
expectedPaths: []string{"/Newtonsoft.Json"},
},
{
name: "microsoft package",
packageName: "Microsoft.Extensions.Logging",
expectedPaths: []string{"/Microsoft.Extensions.Logging"},
},
{
name: "entity framework package",
packageName: "EntityFramework.Core",
expectedPaths: []string{"/EntityFramework.Core"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := nugetPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestNugetPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
nugetPackage := NewNugetPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple package with version",
packageName: "Newtonsoft.Json",
version: "13.0.1",
expectedPaths: []string{"/Newtonsoft.Json/13.0.1"},
},
{
name: "microsoft package with version",
packageName: "Microsoft.Extensions.Logging",
version: "6.0.0",
expectedPaths: []string{"/Microsoft.Extensions.Logging/6.0.0"},
},
{
name: "pre-release version",
packageName: "EntityFramework.Core",
version: "7.0.0-preview.5",
expectedPaths: []string{"/EntityFramework.Core/7.0.0-preview.5"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := nugetPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestPythonPackageType_GetNodePathsForImage_Updated(t *testing.T) {
pythonPackage := NewPythonPackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple package name",
packageName: "requests",
expectedPaths: []string{"/requests"},
},
{
name: "package with hyphens",
packageName: "django-rest-framework",
expectedPaths: []string{"/django-rest-framework"},
},
{
name: "numpy package",
packageName: "numpy",
expectedPaths: []string{"/numpy"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := pythonPackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestPythonPackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
pythonPackage := NewPythonPackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple package with version",
packageName: "requests",
version: "2.28.1",
expectedPaths: []string{"/requests/2.28.1"},
},
{
name: "django package with version",
packageName: "django",
version: "4.1.0",
expectedPaths: []string{"/django/4.1.0"},
},
{
name: "pre-release version",
packageName: "pytest",
version: "7.2.0rc1",
expectedPaths: []string{"/pytest/7.2.0rc1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := pythonPackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestHuggingFacePackageType_GetNodePathsForImage_Updated(t *testing.T) {
huggingFacePackage := NewHuggingFacePackageType(nil)
tests := []struct {
name string
packageName string
expectedPaths []string
}{
{
name: "simple model name",
packageName: "bert-base-uncased",
expectedPaths: []string{"/bert-base-uncased"},
},
{
name: "namespaced model",
packageName: "facebook/bart-large",
expectedPaths: []string{"/facebook/bart-large"},
},
{
name: "organization model",
packageName: "openai/whisper-base",
expectedPaths: []string{"/openai/whisper-base"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := huggingFacePackage.GetNodePathsForImage(nil, tt.packageName)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
func TestHuggingFacePackageType_GetNodePathsForArtifact_Updated(t *testing.T) {
huggingFacePackage := NewHuggingFacePackageType(nil)
tests := []struct {
name string
packageName string
version string
expectedPaths []string
}{
{
name: "simple model with version",
packageName: "bert-base-uncased",
version: "v1.0",
expectedPaths: []string{"/bert-base-uncased/v1.0"},
},
{
name: "namespaced model with commit hash",
packageName: "facebook/bart-large",
version: "abc123def456",
expectedPaths: []string{"/facebook/bart-large/abc123def456"},
},
{
name: "model with semantic version",
packageName: "openai/whisper-base",
version: "1.2.3",
expectedPaths: []string{"/openai/whisper-base/1.2.3"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
paths, err := huggingFacePackage.GetNodePathsForArtifact(nil, tt.packageName, tt.version)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPaths, paths)
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/helpers/pkg/docker.go | registry/app/helpers/pkg/docker.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"strings"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type DockerPackageType interface {
interfaces.PackageHelper
}
type dockerPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewDockerPackageType(registryHelper interfaces.RegistryHelper) DockerPackageType {
return &dockerPackageType{
packageType: string(artifact.PackageTypeDOCKER),
pathPackageType: string(types.PathPackageTypeDocker),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceDockerhub),
string(artifact.UpstreamConfigSourceAwsEcr),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceDockerhub): {
urlRequired: false,
},
string(artifact.UpstreamConfigSourceAwsEcr): {
urlRequired: true,
},
},
}
}
func (c *dockerPackageType) GetPackageType() string {
return c.packageType
}
func (c *dockerPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *dockerPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *dockerPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *dockerPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *dockerPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *dockerPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *dockerPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *dockerPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *dockerPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *dockerPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *dockerPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *dockerPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *dockerPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *dockerPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *dockerPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *dockerPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *dockerPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *dockerPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *dockerPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *dockerPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *dockerPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *dockerPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *dockerPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *dockerPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
parsedDigest, err := types.Digest(strings.ToLower(version)).Parse()
if err != nil {
return nil, err
}
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + parsedDigest.String()
}
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/helpers/pkg/rpm.go | registry/app/helpers/pkg/rpm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"strings"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type RPMPackageType interface {
interfaces.PackageHelper
}
type rpmPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewRPMPackageType(registryHelper interfaces.RegistryHelper) RPMPackageType {
return &rpmPackageType{
packageType: string(artifact.PackageTypeRPM),
registryHelper: registryHelper,
pathPackageType: string(types.PathPackageTypeRPM),
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
},
}
}
func (c *rpmPackageType) GetPackageType() string {
return c.packageType
}
func (c *rpmPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *rpmPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *rpmPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *rpmPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *rpmPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *rpmPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *rpmPackageType) DeleteVersion(
ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *rpmPackageType) ReportDeleteVersionEvent(
ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *rpmPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *rpmPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *rpmPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *rpmPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *rpmPackageType) GetPackageURL(
_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *rpmPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *rpmPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *rpmPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *rpmPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *rpmPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *rpmPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *rpmPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *rpmPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *rpmPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *rpmPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *rpmPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
lastDotIndex := strings.LastIndex(version, ".")
rpmVersion := version[:lastDotIndex]
rpmArch := version[lastDotIndex+1:]
epochSeparatorDotIndex := strings.LastIndex(version, ":")
if epochSeparatorDotIndex > 0 {
epoch := rpmVersion[:epochSeparatorDotIndex]
rpmVersion = rpmVersion[epochSeparatorDotIndex+1:]
result[i] = path + "/" + rpmVersion + "/" + rpmArch + "/" + epoch
} else {
result[i] = path + "/" + rpmVersion + "/" + rpmArch
}
}
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/helpers/pkg/cargo.go | registry/app/helpers/pkg/cargo.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"encoding/json"
"fmt"
"slices"
"strings"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/app/utils/cargo"
"github.com/harness/gitness/registry/services/webhook"
"github.com/harness/gitness/registry/types"
registryutils "github.com/harness/gitness/registry/utils"
)
type CargoPackageType interface {
interfaces.PackageHelper
}
type UpstreamSourceConfig struct {
urlRequired bool
}
type cargoPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
pathPackageType string
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
cargoRegistryHelper cargo.RegistryHelper
}
func NewCargoPackageType(
registryHelper interfaces.RegistryHelper,
cargoRegistryHelper cargo.RegistryHelper,
) CargoPackageType {
return &cargoPackageType{
packageType: string(artifact.PackageTypeCARGO),
pathPackageType: string(types.PathPackageTypeCargo),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceCrates),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceCrates): {
urlRequired: false,
},
},
cargoRegistryHelper: cargoRegistryHelper,
}
}
func (c *cargoPackageType) GetPackageType() string {
return c.packageType
}
func (c *cargoPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *cargoPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *cargoPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *cargoPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *cargoPackageType) GetPullCommand(_ string, image string, version string) string {
downloadCommand := "cargo add <ARTIFACT>@<VERSION> --registry <REGISTRY>"
// Replace the placeholders with the actual values
replacements := map[string]string{
"<ARTIFACT>": image,
"<VERSION>": version,
}
for placeholder, value := range replacements {
downloadCommand = strings.ReplaceAll(downloadCommand, placeholder, value)
}
return downloadCommand
}
func (c *cargoPackageType) GetDownloadFileCommand(
regURL string,
artifact string,
version string,
isAnonymous bool,
) string {
var authHeader string
if !isAnonymous {
authHeader = " --header '<AUTH_HEADER_PREFIX> <API_KEY>'"
}
downloadCommand := "curl --location '<HOSTNAME>/api/v1/crates/<ARTIFACT>/<VERSION>/download'" + authHeader +
" -J -o '<OUTPUT_FILE_NAME>'"
// Replace the placeholders with the actual values
replacements := map[string]string{
"<HOSTNAME>": regURL,
"<ARTIFACT>": artifact,
"<VERSION>": version,
"<AUTH_HEADER_PREFIX>": c.registryHelper.GetAuthHeaderPrefix(),
}
for placeholder, value := range replacements {
downloadCommand = strings.ReplaceAll(downloadCommand, placeholder, value)
}
return downloadCommand
}
func (c *cargoPackageType) DeleteVersion(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
imageInfo *types.Image,
artifactName string,
versionName string,
) error {
err := c.registryHelper.DeleteVersion(
ctx, regInfo, imageInfo, artifactName, versionName,
c.GetFilePath(artifactName, versionName),
)
if err != nil {
return fmt.Errorf("failed to delete cargo artifact version: %w", err)
}
return nil
}
func (c *cargoPackageType) ReportDeleteVersionEvent(ctx context.Context,
principalID int64,
registryID int64,
artifactName string,
version string,
) {
payload := webhook.GetArtifactDeletedPayloadForCommonArtifacts(
principalID,
registryID,
artifact.PackageTypeCARGO,
artifactName,
version,
)
c.registryHelper.ReportDeleteVersionEvent(ctx, &payload)
}
func (c *cargoPackageType) ReportBuildPackageIndexEvent(ctx context.Context, registryID int64, artifactName string) {
c.registryHelper.ReportBuildPackageIndexEvent(ctx, registryID, artifactName)
}
func (c *cargoPackageType) ReportBuildRegistryIndexEvent(_ context.Context, _ int64, _ []types.SourceRef) {
// no-op for cargo
}
func (c *cargoPackageType) GetFilePath(
artifactName string,
versionName string,
) string {
filePathPrefix := "/crates/" + artifactName
if versionName != "" {
filePathPrefix += "/" + versionName
}
return filePathPrefix
}
func (c *cargoPackageType) DeleteArtifact(ctx context.Context,
regInfo *types.RegistryRequestBaseInfo,
artifactName string,
) error {
filePath := c.GetFilePath(artifactName, "")
err := c.registryHelper.DeleteGenericImage(ctx, regInfo, artifactName, filePath)
if err != nil {
return fmt.Errorf("failed to delete cargo artifact: %w", err)
}
return nil
}
func (c *cargoPackageType) GetPackageURL(ctx context.Context,
rootIdentifier string,
registryIdentifier string,
) string {
return c.registryHelper.GetPackageURL(ctx, rootIdentifier, registryIdentifier, "cargo")
}
func (c *cargoPackageType) GetArtifactMetadata(
artifact types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
pullCommand := c.GetPullCommand("", artifact.Name, artifact.Version)
return c.registryHelper.GetArtifactMetadata(artifact, pullCommand)
}
func (c *cargoPackageType) GetArtifactVersionMetadata(
image string,
tag types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
pullCommand := c.GetPullCommand("", image, tag.Name)
return c.registryHelper.GetArtifactVersionMetadata(tag, pullCommand, c.packageType)
}
func (c *cargoPackageType) GetFileMetadata(
ctx context.Context,
rootIdentifier string,
registryIdentifier string,
artifactName string,
version string,
file types.FileNodeMetadata,
) *artifact.FileDetail {
filePathPrefix := "/crates/" + artifactName + "/" + version + "/"
filename := strings.Replace(file.Path, filePathPrefix, "", 1)
regURL := c.GetPackageURL(ctx, rootIdentifier, registryIdentifier)
session, _ := request.AuthSessionFrom(ctx)
downloadCommand := c.GetDownloadFileCommand(regURL, artifactName, version, auth.IsAnonymousSession(session))
return c.registryHelper.GetFileMetadata(file, filename, downloadCommand)
}
func (c *cargoPackageType) GetArtifactDetail(
img *types.Image,
art *types.Artifact,
downloadCount int64,
) (*artifact.ArtifactDetail, error) {
var result map[string]any
err := json.Unmarshal(art.Metadata, &result)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal metadata: %w", err)
}
artifactDetails := c.registryHelper.GetArtifactDetail(img, art, result, downloadCount)
if artifactDetails == nil {
return nil, fmt.Errorf("failed to get artifact details")
}
err = artifactDetails.FromCargoArtifactDetailConfig(artifact.CargoArtifactDetailConfig{
Metadata: &result,
})
if err != nil {
return nil, fmt.Errorf("failed to get artifact details: %w", err)
}
return artifactDetails, nil
}
func (c *cargoPackageType) GetClientSetupDetails(
ctx context.Context,
regRef string,
image *artifact.ArtifactParam,
tag *artifact.VersionParam,
registryType artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
staticStepType := artifact.ClientSetupStepTypeStatic
generateTokenType := artifact.ClientSetupStepTypeGenerateToken
registryURL := c.GetPackageURL(ctx, regRef, "")
session, _ := request.AuthSessionFrom(ctx)
username := session.Principal.Email
var clientSetupDetails artifact.ClientSetupDetails
if auth.IsAnonymousSession(session) {
clientSetupDetails = c.GetAnonymousClientSetupDetails(
registryType, staticStepType,
)
} else {
clientSetupDetails = c.GetAuthenticatedClientSetupDetails(
registryType, staticStepType, generateTokenType,
)
}
c.registryHelper.ReplacePlaceholders(
ctx, &clientSetupDetails.Sections, username, regRef, image, tag, registryURL, "", "", "")
return &clientSetupDetails, nil
}
func (c *cargoPackageType) GetAuthenticatedClientSetupDetails(
registryType artifact.RegistryType,
staticStepType artifact.ClientSetupStepType,
generateTokenType artifact.ClientSetupStepType,
) artifact.ClientSetupDetails {
// Authentication section
section1 := artifact.ClientSetupSection{
Header: registryutils.StringPtr("Configure Authentication"),
}
_ = section1.FromClientSetupStepConfig(artifact.ClientSetupStepConfig{
Steps: &[]artifact.ClientSetupStep{
{
Header: registryutils.StringPtr("Create or update ~/.cargo/config.toml with the following content:"),
Type: &staticStepType,
Commands: &[]artifact.ClientSetupStepCommand{
{
Value: registryutils.StringPtr("[registry]\n" +
`global-credential-providers = ["cargo:token", "cargo:libsecret", "cargo:macos-keychain", "cargo:wincred"]` +
"\n\n" +
"[registries.harness-<REGISTRY_NAME>]\n" +
`index = "sparse+<REGISTRY_URL>/index/"`),
},
},
},
{
Header: registryutils.StringPtr("Generate an identity token for authentication"),
Type: &generateTokenType,
},
{
Header: registryutils.StringPtr("Create or update ~/.cargo/credentials.toml with the following content:"),
Type: &staticStepType,
Commands: &[]artifact.ClientSetupStepCommand{
{
Value: registryutils.StringPtr(
"[registries.harness-<REGISTRY_NAME>]" + "\n" + `token = "Bearer <token from step 2>"`,
),
},
},
},
},
})
// Publish section
section2 := artifact.ClientSetupSection{
Header: registryutils.StringPtr("Publish Package"),
}
_ = section2.FromClientSetupStepConfig(artifact.ClientSetupStepConfig{
Steps: &[]artifact.ClientSetupStep{
{
Header: registryutils.StringPtr("Publish your package:"),
Type: &staticStepType,
Commands: &[]artifact.ClientSetupStepCommand{
{
Value: registryutils.StringPtr("cargo publish --registry harness-<REGISTRY_NAME>"),
},
},
},
},
})
// Install section
section3 := getInstallPackageClientSetupSection(staticStepType)
sections := []artifact.ClientSetupSection{
section1,
section2,
section3,
}
if registryType == artifact.RegistryTypeUPSTREAM {
sections = []artifact.ClientSetupSection{
section1,
section3,
}
}
clientSetupDetails := artifact.ClientSetupDetails{
MainHeader: "Cargo Client Setup",
SecHeader: "Follow these instructions to install/use cargo packages from this registry.",
Sections: sections,
}
return clientSetupDetails
}
func (c *cargoPackageType) GetAnonymousClientSetupDetails(
registryType artifact.RegistryType,
staticStepType artifact.ClientSetupStepType,
) artifact.ClientSetupDetails {
section1 := artifact.ClientSetupSection{
Header: registryutils.StringPtr("Configure registry"),
}
_ = section1.FromClientSetupStepConfig(artifact.ClientSetupStepConfig{
Steps: &[]artifact.ClientSetupStep{
{
Header: registryutils.StringPtr("Create or update ~/.cargo/config.toml with the following content:"),
Type: &staticStepType,
Commands: &[]artifact.ClientSetupStepCommand{
{
Value: registryutils.StringPtr("[registry]\n" +
`global-credential-providers = ["cargo:token", "cargo:libsecret", "cargo:macos-keychain", "cargo:wincred"]` +
"\n\n" +
"[registries.harness-<REGISTRY_NAME>]\n" +
`index = "sparse+<REGISTRY_URL>/index/"`),
},
},
},
},
})
// Install section
section3 := getInstallPackageClientSetupSection(staticStepType)
sections := []artifact.ClientSetupSection{
section1,
section3,
}
if registryType == artifact.RegistryTypeUPSTREAM {
sections = []artifact.ClientSetupSection{
section1,
section3,
}
}
clientSetupDetails := artifact.ClientSetupDetails{
MainHeader: "Cargo Client Setup",
SecHeader: "Follow these instructions to install/use cargo packages from this registry.",
Sections: sections,
}
return clientSetupDetails
}
func getInstallPackageClientSetupSection(
staticStepType artifact.ClientSetupStepType,
) artifact.ClientSetupSection {
// Install section
section3 := artifact.ClientSetupSection{
Header: registryutils.StringPtr("Install Package"),
}
_ = section3.FromClientSetupStepConfig(artifact.ClientSetupStepConfig{
Steps: &[]artifact.ClientSetupStep{
{
Header: registryutils.StringPtr("Install a package using cargo"),
Type: &staticStepType,
Commands: &[]artifact.ClientSetupStepCommand{
{
Value: registryutils.StringPtr("cargo add <ARTIFACT_NAME>@<VERSION> --registry harness-<REGISTRY_NAME>"),
},
},
},
},
})
return section3
}
func (c *cargoPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *cargoPackageType) BuildPackageIndexAsync(
ctx context.Context,
registry *types.Registry,
payload types.BuildPackageIndexTaskPayload,
) error {
err := c.cargoRegistryHelper.UpdatePackageIndex(
ctx, payload.PrincipalID, registry.RootParentID, registry.ID, payload.Image,
)
if err != nil {
return fmt.Errorf("failed to build CARGO package index for registry [%d] package [%s]: %w",
payload.RegistryID, payload.Image, err)
}
return nil
}
func (c *cargoPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *cargoPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/crates/" + packageName}, nil
}
func (c *cargoPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/gopkg.go | registry/app/helpers/pkg/gopkg.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type GoPackageType interface {
interfaces.PackageHelper
}
type goPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewGoPackageType(registryHelper interfaces.RegistryHelper) GoPackageType {
return &goPackageType{
packageType: string(artifact.PackageTypeGO),
registryHelper: registryHelper,
pathPackageType: string(types.PathPackageTypeGo),
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceGoProxy),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceGoProxy): {
urlRequired: false,
},
},
}
}
func (c *goPackageType) GetPackageType() string {
return c.packageType
}
func (c *goPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *goPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *goPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *goPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *goPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *goPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *goPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *goPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *goPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *goPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *goPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *goPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *goPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *goPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *goPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *goPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *goPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *goPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *goPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *goPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *goPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *goPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *goPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *goPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/@v/" + version
}
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/helpers/pkg/npm.go | registry/app/helpers/pkg/npm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type NPMPackageType interface {
interfaces.PackageHelper
}
type npmPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewNPMPackageType(registryHelper interfaces.RegistryHelper) NPMPackageType {
return &npmPackageType{
packageType: string(artifact.PackageTypeNPM),
registryHelper: registryHelper,
pathPackageType: string(types.PathPackageTypeNpm),
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
string(artifact.UpstreamConfigSourceNpmJs),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
string(artifact.UpstreamConfigSourceNpmJs): {
urlRequired: false,
},
},
}
}
func (c *npmPackageType) GetPackageType() string {
return c.packageType
}
func (c *npmPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *npmPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *npmPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *npmPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *npmPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *npmPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *npmPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *npmPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *npmPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *npmPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *npmPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *npmPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *npmPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *npmPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *npmPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *npmPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *npmPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *npmPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *npmPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *npmPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *npmPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *npmPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *npmPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *npmPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/huggingface.go | registry/app/helpers/pkg/huggingface.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type HuggingFacePackageType interface {
interfaces.PackageHelper
}
type huggingFacePackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewHuggingFacePackageType(registryHelper interfaces.RegistryHelper) HuggingFacePackageType {
return &huggingFacePackageType{
packageType: string(artifact.PackageTypeHUGGINGFACE),
pathPackageType: string(types.PathPackageTypeHuggingFace),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
},
}
}
func (c *huggingFacePackageType) GetPackageType() string {
return c.packageType
}
func (c *huggingFacePackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *huggingFacePackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *huggingFacePackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *huggingFacePackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *huggingFacePackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *huggingFacePackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *huggingFacePackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *huggingFacePackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *huggingFacePackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *huggingFacePackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *huggingFacePackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *huggingFacePackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *huggingFacePackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *huggingFacePackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *huggingFacePackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *huggingFacePackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *huggingFacePackageType) GetNodePathsForImage(
artifactType *string,
packageName string,
) ([]string, error) {
prefix := ""
if artifactType != nil && *artifactType != "" {
prefix = "/" + *artifactType
}
return []string{prefix + "/" + packageName}, nil
}
func (c *huggingFacePackageType) GetNodePathsForArtifact(
artifactType *string,
packageName string,
version string,
) ([]string, error) {
paths, err := c.GetNodePathsForImage(artifactType, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + version
}
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/helpers/pkg/helm.go | registry/app/helpers/pkg/helm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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"
"slices"
"strings"
"github.com/harness/gitness/registry/app/api/interfaces"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
"github.com/rs/zerolog/log"
)
type HelmPackageType interface {
interfaces.PackageHelper
}
type helmPackageType struct {
packageType string
registryHelper interfaces.RegistryHelper
validRepoTypes []string
validUpstreamSources []string
upstreamSourceConfig map[string]UpstreamSourceConfig
pathPackageType string
}
func NewHelmPackageType(registryHelper interfaces.RegistryHelper) HelmPackageType {
return &helmPackageType{
packageType: string(artifact.PackageTypeHELM),
pathPackageType: string(types.PathPackageTypeHelm),
registryHelper: registryHelper,
validRepoTypes: []string{
string(artifact.RegistryTypeUPSTREAM),
string(artifact.RegistryTypeVIRTUAL),
},
validUpstreamSources: []string{
string(artifact.UpstreamConfigSourceCustom),
},
upstreamSourceConfig: map[string]UpstreamSourceConfig{
string(artifact.UpstreamConfigSourceCustom): {
urlRequired: true,
},
},
}
}
func (c *helmPackageType) GetPackageType() string {
return c.packageType
}
func (c *helmPackageType) GetPathPackageType() string {
return c.pathPackageType
}
func (c *helmPackageType) IsValidRepoType(repoType string) bool {
return slices.Contains(c.validRepoTypes, repoType)
}
func (c *helmPackageType) IsValidUpstreamSource(upstreamSource string) bool {
return slices.Contains(c.validUpstreamSources, upstreamSource)
}
func (c *helmPackageType) IsURLRequiredForUpstreamSource(upstreamSource string) bool {
config, ok := c.upstreamSourceConfig[upstreamSource]
if !ok {
return true
}
return config.urlRequired
}
func (c *helmPackageType) GetPullCommand(_ string, _ string, _ string) string {
return ""
}
func (c *helmPackageType) DeleteImage() error {
return fmt.Errorf("not implemented")
}
func (c *helmPackageType) DeleteVersion(ctx context.Context,
_ *types.RegistryRequestBaseInfo,
_ *types.Image,
_ string,
_ string,
) error {
log.Error().Ctx(ctx).Msg("Not implemented")
return fmt.Errorf("not implemented")
}
func (c *helmPackageType) ReportDeleteVersionEvent(ctx context.Context,
_ int64,
_ int64,
_ string,
_ string,
) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *helmPackageType) ReportBuildPackageIndexEvent(ctx context.Context, _ int64, _ string) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *helmPackageType) ReportBuildRegistryIndexEvent(ctx context.Context, _ int64, _ []types.SourceRef) {
log.Error().Ctx(ctx).Msg("Not implemented")
}
func (c *helmPackageType) GetFilePath(
_ string,
_ string,
) string {
return ""
}
func (c *helmPackageType) DeleteArtifact(
_ context.Context,
_ *types.RegistryRequestBaseInfo,
_ string,
) error {
return nil
}
func (c *helmPackageType) GetPackageURL(_ context.Context,
_ string,
_ string,
) string {
return ""
}
func (c *helmPackageType) GetArtifactMetadata(
_ types.ArtifactMetadata,
) *artifact.ArtifactMetadata {
return nil
}
func (c *helmPackageType) GetArtifactVersionMetadata(
_ string,
_ types.NonOCIArtifactMetadata,
) *artifact.ArtifactVersionMetadata {
return nil
}
func (c *helmPackageType) GetDownloadFileCommand(
_ string,
_ string,
_ string,
_ bool,
) string {
return ""
}
func (c *helmPackageType) GetFileMetadata(
_ context.Context,
_ string,
_ string,
_ string,
_ string,
_ types.FileNodeMetadata,
) *artifact.FileDetail {
return nil
}
func (c *helmPackageType) GetArtifactDetail(
_ *types.Image,
_ *types.Artifact,
_ int64,
) (*artifact.ArtifactDetail, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *helmPackageType) GetClientSetupDetails(
_ context.Context,
_ string,
_ *artifact.ArtifactParam,
_ *artifact.VersionParam,
_ artifact.RegistryType,
) (*artifact.ClientSetupDetails, error) {
return nil, fmt.Errorf("not implemented")
}
func (c *helmPackageType) BuildRegistryIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildRegistryIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *helmPackageType) BuildPackageIndexAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageIndexTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *helmPackageType) BuildPackageMetadataAsync(
_ context.Context,
_ *types.Registry,
_ types.BuildPackageMetadataTaskPayload,
) error {
return fmt.Errorf("not implemented")
}
func (c *helmPackageType) GetNodePathsForImage(
_ *string,
packageName string,
) ([]string, error) {
return []string{"/" + packageName}, nil
}
func (c *helmPackageType) GetNodePathsForArtifact(
_ *string,
packageName string,
version string,
) ([]string, error) {
parsedDigest, err := types.Digest(strings.ToLower(version)).Parse()
if err != nil {
return nil, err
}
paths, err := c.GetNodePathsForImage(nil, packageName)
if err != nil {
return nil, err
}
result := make([]string, len(paths))
for i, path := range paths {
result[i] = path + "/" + parsedDigest.String()
}
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/store/cache.go | registry/app/store/cache.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
import (
"github.com/harness/gitness/cache"
"github.com/harness/gitness/registry/types"
)
type (
RegistryIDCache cache.Cache[int64, *types.Registry]
RegistryRootRefCache cache.Cache[types.RegistryRootRefCacheKey, int64]
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database.go | registry/app/store/database.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
import (
"context"
"encoding/json"
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"github.com/harness/gitness/registry/types"
gitnesstypes "github.com/harness/gitness/types"
"github.com/lib/pq"
"github.com/opencontainers/go-digest"
)
type MediaTypesRepository interface {
MapMediaType(ctx context.Context, mediaType string) (int64, error)
MediaTypeExists(ctx context.Context, mediaType string) (bool, error)
GetMediaTypeByID(ctx context.Context, ids int64) (*types.MediaType, error)
}
type BlobRepository interface {
FindByID(ctx context.Context, id int64) (*types.Blob, error)
FindByDigestAndRootParentID(
ctx context.Context, d digest.Digest,
rootParentID int64,
) (*types.Blob, error)
FindByDigestAndRepoID(
ctx context.Context, d digest.Digest, repoID int64,
imageName string,
) (*types.Blob, error)
CreateOrFind(ctx context.Context, b *types.Blob) (*types.Blob, bool, error)
DeleteByID(ctx context.Context, id int64) error
ExistsBlob(
ctx context.Context, repoID int64, d digest.Digest,
image string,
) (bool, error)
TotalSizeByRootParentID(ctx context.Context, id int64) (int64, error)
}
type CleanupPolicyRepository interface {
// GetIDsByRegistryID the CleanupPolicy Ids specified by Registry Key
GetIDsByRegistryID(ctx context.Context, id int64) (ids []int64, err error)
// GetByRegistryID the CleanupPolicy specified by Registry Key
GetByRegistryID(
ctx context.Context,
id int64,
) (cleanupPolicies *[]types.CleanupPolicy, err error)
// Create a CleanupPolicy
Create(
ctx context.Context,
cleanupPolicy *types.CleanupPolicy,
) (id int64, err error)
// Delete the CleanupPolicy specified by repokey and name
Delete(ctx context.Context, id int64) (err error)
// Update the CleanupPolicy.
ModifyCleanupPolicies(
ctx context.Context,
cleanupPolicies *[]types.CleanupPolicy, ids []int64,
) error
}
type ManifestRepository interface {
// FindAll finds all manifests.
FindAll(ctx context.Context) (types.Manifests, error)
// Count counts all manifests.
Count(ctx context.Context) (int, error)
// LayerBlobs finds layer blobs associated with a manifest,
// through the `layers` relationship entity.
LayerBlobs(ctx context.Context, m *types.Manifest) (types.Blobs, error)
// References finds all manifests directly
// referenced by a manifest (if any).
References(ctx context.Context, m *types.Manifest) (types.Manifests, error)
// Create saves a new Manifest. ID value is updated in given request object
Create(ctx context.Context, m *types.Manifest) error
// CreateOrFind attempts to create a manifest. If the manifest already exists
// (same digest in the scope of a given repository)
// that record is loaded from the database into m.
// This is similar to a repositoryStore.FindManifestByDigest followed by
// a Create, but without being prone to race conditions on write
// operations between the corresponding read (FindManifestByDigest2)
// and write (Create) operations.
// Separate Find* and Create method calls should be preferred
// to this when race conditions are not a concern.
CreateOrFind(ctx context.Context, m *types.Manifest) error
AssociateLayerBlob(ctx context.Context, m *types.Manifest, b *types.Blob) error
DissociateLayerBlob(ctx context.Context, m *types.Manifest, b *types.Blob) error
Delete(ctx context.Context, registryID, id int64) error
FindManifestByDigest(
ctx context.Context, repoID int64, imageName string,
digest types.Digest,
) (*types.Manifest, error)
FindManifestByTagName(
ctx context.Context, repoID int64, imageName string,
tag string,
) (*types.Manifest, error)
FindManifestPayloadByTagName(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
version string,
) (*types.Payload, error)
GetManifestPayload(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
digest types.Digest,
) (*types.Payload, error)
FindManifestDigestByTagName(
ctx context.Context, regID int64,
imageName string, tag string,
) (types.Digest, error)
Get(ctx context.Context, manifestID int64) (*types.Manifest, error)
DeleteManifest(
ctx context.Context, repoID int64,
imageName string, d digest.Digest,
) (bool, error)
DeleteManifestByImageName(
ctx context.Context, repoID int64,
imageName string,
) (bool, error)
ListManifestsBySubject(
ctx context.Context, repoID int64,
id int64,
) (types.Manifests, error)
ListManifestsBySubjectDigest(
ctx context.Context, repoID int64,
digest types.Digest,
) (types.Manifests, error)
GetLatestManifest(ctx context.Context, repoID int64, imageName string) (*types.Manifest, error)
CountByImageName(ctx context.Context, repoID int64, imageName string) (int64, error)
}
type ManifestReferenceRepository interface {
AssociateManifest(
ctx context.Context, ml *types.Manifest,
m *types.Manifest,
) error
DissociateManifest(
ctx context.Context, ml *types.Manifest,
m *types.Manifest,
) error
}
type OCIImageIndexMappingRepository interface {
Create(ctx context.Context, ociManifest *types.OCIImageIndexMapping) error
GetAllByChildDigest(ctx context.Context, registryID int64, imageName string, childDigest types.Digest) (
[]*types.OCIImageIndexMapping, error,
)
}
type LayerRepository interface {
AssociateLayerBlob(ctx context.Context, m *types.Manifest, b *types.Blob) error
GetAllLayersByManifestID(ctx context.Context, id int64) (*[]types.Layer, error)
}
type TagRepository interface {
// CreateOrUpdate upsert a tag. A tag with a given name
// on a given repository may not exist (in which case it should be
// inserted), already exist and point to the same manifest
// (in which case nothing needs to be done) or already exist but
// points to a different manifest (in which case it should be updated).
CreateOrUpdate(ctx context.Context, t *types.Tag) error
LockTagByNameForUpdate(
ctx context.Context, repoID int64,
name string,
) (bool, error)
DeleteTagByName(
ctx context.Context, repoID int64,
name string,
) (bool, error)
DeleteTagByManifestID(
ctx context.Context, repoID int64,
manifestID int64,
) (bool, error)
TagsPaginated(
ctx context.Context, repoID int64, image string,
filters types.FilterParams,
) ([]*types.Tag, error)
HasTagsAfterName(
ctx context.Context, repoID int64,
filters types.FilterParams,
) (bool, error)
GetAllArtifactsByParentID(
ctx context.Context, parentID int64,
registryIDs *[]string, sortByField string,
sortByOrder string, limit int, offset int, search string,
latestVersion bool, packageTypes []string,
) (*[]types.ArtifactMetadata, error)
GetAllArtifactsByParentIDUntagged(
ctx context.Context, parentID int64,
registryIDs *[]string, sortByField string,
sortByOrder string, limit int, offset int, search string,
packageTypes []string,
) (*[]types.ArtifactMetadata, error)
CountAllArtifactsByParentID(
ctx context.Context, parentID int64,
registryIDs *[]string, search string,
latestVersion bool, packageTypes []string, untaggedImagesEnabled bool,
) (int64, error)
GetAllArtifactsByRepo(
ctx context.Context, parentID int64, repoKey string,
sortByField string, sortByOrder string,
limit int, offset int, search string, labels []string,
) (*[]types.ArtifactMetadata, error)
GetLatestTagMetadata(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
) (*types.ArtifactMetadata, error)
GetLatestTagName(
ctx context.Context, parentID int64, repoKey string,
imageName string,
) (string, error)
GetTagMetadata(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
name string,
) (*types.OciVersionMetadata, error)
GetOCIVersionMetadata(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
dgst string,
) (*types.OciVersionMetadata, error)
CountAllArtifactsByRepo(
ctx context.Context, parentID int64, repoKey string,
search string, labels []string,
) (int64, error)
GetTagDetail(
ctx context.Context, repoID int64, imageName string,
name string,
) (*types.TagDetail, error)
GetLatestTag(ctx context.Context, repoID int64, imageName string) (*types.Tag, error)
GetAllTagsByRepoAndImage(
ctx context.Context,
parentID int64,
repoKey string,
image string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (*[]types.OciVersionMetadata, error)
GetAllOciVersionsByRepoAndImage(
ctx context.Context,
parentID int64,
repoKey string,
image string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (*[]types.OciVersionMetadata, error)
GetOciTagsInfo(
ctx context.Context, registryID int64,
image string, limit int, offset int,
search string,
) (*[]types.TagInfo, error)
DeleteTag(ctx context.Context, registryID int64, imageName string, name string) (err error)
CountAllTagsByRepoAndImage(
ctx context.Context, parentID int64, repoKey string,
image string, search string,
) (int64, error)
CountOciVersionByRepoAndImage(
ctx context.Context, parentID int64, repoKey string,
image string, search string,
) (int64, error)
FindTag(
ctx context.Context, repoID int64, imageName string,
name string,
) (*types.Tag, error)
GetTagsByManifestID(
ctx context.Context, manifestID int64,
) (*[]string, error)
DeleteTagsByImageName(
ctx context.Context, registryID int64,
imageName string,
) (err error)
GetQuarantineStatusForImages(
ctx context.Context, imageNames []string, registryID int64,
) ([]bool, error)
GetQuarantineInfoForArtifacts(
ctx context.Context, artifacts []types.ArtifactIdentifier, parentID int64,
) (map[types.ArtifactIdentifier]*types.QuarantineInfo, error)
}
// UpstreamProxyConfig holds the record of a config of upstream proxy in DB.
type UpstreamProxyConfig struct {
ID int64
RegistryID int64
Source string
URL string
AuthType string
UserName string
Password string
Token string
CreatedAt time.Time
UpdatedAt time.Time
}
type UpstreamProxyConfigRepository interface {
// Get the upstreamproxy specified by ID
Get(ctx context.Context, id int64) (upstreamProxy *types.UpstreamProxy, err error)
// GetByRepoKey gets the upstreamproxy specified by registry key
GetByRegistryIdentifier(
ctx context.Context,
parentID int64,
repoKey string,
) (upstreamProxy *types.UpstreamProxy, err error)
// GetByParentUniqueId gets the upstreamproxy specified by parent id and parent unique id
GetByParentID(ctx context.Context, parentID string) (
upstreamProxies *[]types.UpstreamProxy,
err error,
)
// Create a upstreamProxyConfig
Create(ctx context.Context, upstreamproxyRecord *types.UpstreamProxyConfig) (
id int64,
err error,
)
// Update updates the upstreamproxy.
Update(ctx context.Context, upstreamproxyRecord *types.UpstreamProxyConfig) (err error)
GetAll(
ctx context.Context,
parentID int64,
packageTypes []string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (upstreamProxies *[]types.UpstreamProxy, err error)
CountAll(
ctx context.Context, parentID string, packageTypes []string,
search string,
) (count int64, err error)
}
type RegistryMetadata struct {
RegUUID string
RegID string
ParentID int64
RegIdentifier string
Description string
PackageType artifact.PackageType
Type artifact.RegistryType
LastModified time.Time
URL string
Labels pq.StringArray
Config *types.RegistryConfig
ArtifactCount int64
DownloadCount int64
Size int64
}
type RegistryRepository interface {
GetByUUID(ctx context.Context, uuid string) (*types.Registry, error)
// Get the repository specified by ID
Get(ctx context.Context, id int64) (repository *types.Registry, err error)
// GetByName gets the repository specified by name
GetByIDIn(
ctx context.Context, ids []int64,
) (registries *[]types.Registry, err error)
// GetByName gets the repository specified by parent id and name
GetByParentIDAndName(
ctx context.Context, parentID int64,
name string,
) (registry *types.Registry, err error)
GetByRootParentIDAndName(
ctx context.Context, parentID int64,
name string,
) (registry *types.Registry, err error)
// Create a repository
Create(ctx context.Context, repository *types.Registry) (id int64, err error)
// Delete the repository specified by ID
Delete(ctx context.Context, parentID int64, name string) (err error)
// Update updates the repository. Only the properties specified by "props" will be updated if it is set
Update(ctx context.Context, repository *types.Registry) (err error)
GetAll(
ctx context.Context,
parentIDs []int64,
packageTypes []string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
repoType string,
) (repos *[]RegistryMetadata, err error)
CountAll(
ctx context.Context, parentIDs []int64, packageTypes []string,
search string, repoType string,
) (count int64, err error)
FetchUpstreamProxyIDs(
ctx context.Context, repokeys []string,
parentID int64,
) (ids []int64, err error)
FetchRegistriesIDByUpstreamProxyID(
ctx context.Context, upstreamProxyID string,
rootParentID int64,
) (ids []int64, err error)
FetchUpstreamProxyKeys(ctx context.Context, ids []int64) (repokeys []string, err error)
Count(ctx context.Context) (int64, error)
}
type RegistryBlobRepository interface {
LinkBlob(
ctx context.Context, imageName string,
registry *types.Registry, blobID int64,
) error
UnlinkBlob(
ctx context.Context, imageName string,
registry *types.Registry, blobID int64,
) (bool, error)
UnlinkBlobByImageName(
ctx context.Context, registryID int64,
imageName string,
) (bool, error)
}
type ImageRepository interface {
GetByUUID(ctx context.Context, uuid string) (*types.Image, error)
// Get an Artifact specified by ID
Get(ctx context.Context, id int64) (*types.Image, error)
// Get an Artifact specified by Artifact Name
GetByName(
ctx context.Context, registryID int64,
name string,
) (*types.Image, error)
GetByNameAndType(
ctx context.Context, registryID int64,
name string, artifactType *artifact.ArtifactType,
) (*types.Image, error)
// Get the Labels specified by Parent ID and Repo
GetLabelsByParentIDAndRepo(
ctx context.Context, parentID int64,
repo string, limit int, offset int,
search string,
) (labels []string, err error)
// Count the Labels specified by Parent ID and Repo
CountLabelsByParentIDAndRepo(
ctx context.Context, parentID int64,
repo, search string,
) (count int64, err error)
// Get an Artifact specified by Artifact Name
GetByRepoAndName(
ctx context.Context, parentID int64,
repo string, name string,
) (*types.Image, error)
// Create an Image
CreateOrUpdate(ctx context.Context, image *types.Image) error
// Update an Image
Update(ctx context.Context, artifact *types.Image) (err error)
UpdateStatus(ctx context.Context, artifact *types.Image) (err error)
DeleteByImageNameAndRegID(ctx context.Context, regID int64, image string) (err error)
DeleteByImageNameIfNoLinkedArtifacts(ctx context.Context, regID int64, image string) (err error)
DuplicateImage(ctx context.Context, sourceImage *types.Image, targetRegistryID int64) (*types.Image, error)
}
type ArtifactRepository interface {
GetByUUID(ctx context.Context, uuid string) (*types.Artifact, error)
Get(ctx context.Context, id int64) (*types.Artifact, error)
// Get an Artifact specified by ID
GetByName(ctx context.Context, imageID int64, version string) (*types.Artifact, error)
// Get an Artifact specified by RegistryID, image name and version
GetByRegistryImageAndVersion(
ctx context.Context, registryID int64, image string, version string,
) (*types.Artifact, error)
// Create an Artifact
CreateOrUpdate(ctx context.Context, artifact *types.Artifact) (int64, error)
Count(ctx context.Context) (int64, error)
GetAllArtifactsByParentID(
ctx context.Context, id int64,
i *[]string, field string, order string,
limit int, offset int, term string,
version bool, packageTypes []string,
) (*[]types.ArtifactMetadata, error)
CountAllArtifactsByParentID(
ctx context.Context, parentID int64,
registryIDs *[]string, search string, latestVersion bool, packageTypes []string,
) (int64, error)
GetArtifactsByRepo(
ctx context.Context, parentID int64, repoKey string, sortByField string, sortByOrder string,
limit int, offset int, search string, labels []string,
artifactType *artifact.ArtifactType,
) (*[]types.ArtifactMetadata, error)
CountArtifactsByRepo(
ctx context.Context, parentID int64, repoKey, search string, labels []string,
artifactType *artifact.ArtifactType,
) (int64, error)
GetLatestArtifactMetadata(
ctx context.Context, id int64, identifier string,
image string,
) (*types.ArtifactMetadata, error)
GetAllVersionsByRepoAndImage(
ctx context.Context, id int64, image string, field string, order string, limit int,
offset int, term string, artifactType *artifact.ArtifactType,
) (*[]types.NonOCIArtifactMetadata, error)
CountAllVersionsByRepoAndImage(
ctx context.Context, parentID int64, repoKey string, image string,
search string, artifactType *artifact.ArtifactType,
) (int64, error)
GetArtifactMetadata(
ctx context.Context, id int64, identifier string, image string, version string,
artifactType *artifact.ArtifactType,
) (*types.ArtifactMetadata, error)
UpdateArtifactMetadata(
ctx context.Context, metadata json.RawMessage,
artifactID int64,
) (err error)
GetByRegistryIDAndImage(ctx context.Context, registryID int64, image string) (
*[]types.Artifact,
error,
)
DeleteByImageNameAndRegistryID(ctx context.Context, regID int64, image string) (err error)
DeleteByVersionAndImageName(ctx context.Context, image string, version string, regID int64) (err error)
GetLatestByImageID(ctx context.Context, imageID int64) (*types.Artifact, error)
// get latest artifacts from all images under repo
GetLatestArtifactsByRepo(
ctx context.Context, registryID int64, batchSize int, artifactID int64,
) (*[]types.ArtifactMetadata, error)
// get all artifacts from all images under repo
GetAllArtifactsByRepo(
ctx context.Context, registryID int64, batchSize int, artifactID int64,
) (*[]types.ArtifactMetadata, error)
GetArtifactsByRepoAndImageBatch(
ctx context.Context, registryID int64, imageName string, batchSize int, artifactID int64,
) (*[]types.ArtifactMetadata, error)
SearchLatestByName(
ctx context.Context, regID int64, name string, limit int, offset int,
) (*[]types.Artifact, error)
CountLatestByName(
ctx context.Context, regID int64, name string,
) (int64, error)
SearchByImageName(
ctx context.Context, regID int64, name string,
limit int, offset int,
) (*[]types.ArtifactMetadata, error)
CountByImageName(
ctx context.Context, regID int64, name string,
) (int64, error)
// DuplicateArtifact creates a copy of an artifact with a different image ID and created by user
DuplicateArtifact(
ctx context.Context, sourceArtifact *types.Artifact, targetImageID int64,
) (*types.Artifact, error)
}
type DownloadStatRepository interface {
Create(ctx context.Context, downloadStat *types.DownloadStat) error
GetTotalDownloadsForImage(ctx context.Context, imageID int64) (int64, error)
GetTotalDownloadsForManifests(
ctx context.Context,
artifactVersion []string,
imageID int64,
) (map[string]int64, error)
CreateByRegistryIDImageAndArtifactName(ctx context.Context, regID int64, image string, artifactName string) error
GetTotalDownloadsForArtifactID(ctx context.Context, artifactID int64) (int64, error)
}
type BandwidthStatRepository interface {
Create(ctx context.Context, bandwidthStat *types.BandwidthStat) error
}
type GCBlobTaskRepository interface {
FindAll(ctx context.Context) ([]*types.GCBlobTask, error)
FindAndLockBefore(
ctx context.Context, blobID int64,
date time.Time,
) (*types.GCBlobTask, error)
Count(ctx context.Context) (int, error)
Next(ctx context.Context) (*types.GCBlobTask, error)
Reschedule(ctx context.Context, b *types.GCBlobTask, d time.Duration) error
Postpone(ctx context.Context, b *types.GCBlobTask, d time.Duration) error
IsDangling(ctx context.Context, b *types.GCBlobTask) (bool, error)
Delete(ctx context.Context, b *types.GCBlobTask) error
}
type GCManifestTaskRepository interface {
FindAndLock(
ctx context.Context, registryID,
manifestID int64,
) (*types.GCManifestTask, error)
FindAndLockBefore(
ctx context.Context, registryID, manifestID int64,
date time.Time,
) (*types.GCManifestTask, error)
FindAndLockNBefore(
ctx context.Context, registryID int64,
manifestIDs []int64, date time.Time,
) ([]*types.GCManifestTask, error)
Next(ctx context.Context) (*types.GCManifestTask, error)
Postpone(ctx context.Context, b *types.GCManifestTask, d time.Duration) error
IsDangling(ctx context.Context, b *types.GCManifestTask) (bool, error)
Delete(ctx context.Context, b *types.GCManifestTask) error
DeleteManifest(ctx context.Context, registryID, id int64) (*digest.Digest, error)
}
type NodesRepository interface {
// Get a node specified by ID
Get(ctx context.Context, id string) (*types.Node, error)
// Get a node specified by node Name and registry id
GetByNameAndRegistryID(
ctx context.Context, registryID int64,
name string,
) (*types.Node, error)
FindByPathAndRegistryID(
ctx context.Context, registryID int64, pathPrefix string, filename string,
) (*types.Node, error)
FindByPathsAndRegistryID(ctx context.Context, paths []string, registryID int64) (*[]string, error)
CountByPathAndRegistryID(
ctx context.Context, registryID int64, path string,
) (int64, error)
// Create a node
Create(ctx context.Context, node *types.Node) error
// delete a node
DeleteByID(ctx context.Context, id int64) (err error)
GetByPathAndRegistryID(
ctx context.Context, registryID int64,
path string,
) (*types.Node, error)
// GetByBlobIDAndRegistryID retrieves a node by its blob ID and registry ID.
GetByBlobIDAndRegistryID(ctx context.Context, blobID string, registryID int64) (*types.Node, error)
GetFilesMetadataByPathAndRegistryID(
ctx context.Context, registryID int64, path string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (*[]types.FileNodeMetadata, error)
GetFileMetadataByPathAndRegistryID(
ctx context.Context,
registryID int64,
path string,
) (*types.FileNodeMetadata, error)
DeleteByNodePathAndRegistryID(ctx context.Context, nodePath string, regID int64) (err error)
DeleteByLeafNodePathAndRegistryID(ctx context.Context, nodePath string, regID int64) (err error)
GetAllFileNodesByPathPrefixAndRegistryID(
ctx context.Context, registryID int64, pathPrefix string,
) (*[]types.Node, error)
}
type GenericBlobRepository interface {
FindByID(ctx context.Context, id string) (*types.GenericBlob, error)
FindBySha256AndRootParentID(
ctx context.Context, sha256 string,
rootParentID int64,
) (*types.GenericBlob, error)
Create(ctx context.Context, gb *types.GenericBlob) (bool, error)
DeleteByID(ctx context.Context, id string) error
TotalSizeByRootParentID(ctx context.Context, id int64) (int64, error)
}
type WebhooksRepository interface {
Create(ctx context.Context, webhook *gitnesstypes.WebhookCore) error
GetByRegistryAndIdentifier(
ctx context.Context,
registryID int64,
webhookIdentifier string,
) (*gitnesstypes.WebhookCore, error)
Find(ctx context.Context, webhookID int64) (*gitnesstypes.WebhookCore, error)
ListByRegistry(
ctx context.Context,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
registryID int64,
) ([]*gitnesstypes.WebhookCore, error)
ListAllByRegistry(
ctx context.Context,
parents []gitnesstypes.WebhookParentInfo,
) ([]*gitnesstypes.WebhookCore, error)
CountAllByRegistry(
ctx context.Context,
registryID int64,
search string,
) (int64, error)
Update(ctx context.Context, webhook *gitnesstypes.WebhookCore) error
DeleteByRegistryAndIdentifier(ctx context.Context, registryID int64, webhookIdentifier string) error
UpdateOptLock(
ctx context.Context, hook *gitnesstypes.WebhookCore,
mutateFn func(hook *gitnesstypes.WebhookCore) error,
) (*gitnesstypes.WebhookCore, error)
}
type WebhooksExecutionRepository interface {
Find(ctx context.Context, id int64) (*gitnesstypes.WebhookExecutionCore, error)
// Create creates a new webhook execution entry.
Create(ctx context.Context, hook *gitnesstypes.WebhookExecutionCore) error
// ListForWebhook lists the webhook executions for a given webhook id.
ListForWebhook(
ctx context.Context,
webhookID int64,
limit int,
page int,
size int,
) ([]*gitnesstypes.WebhookExecutionCore, error)
CountForWebhook(ctx context.Context, webhookID int64) (int64, error)
// ListForTrigger lists the webhook executions for a given trigger id.
ListForTrigger(ctx context.Context, triggerID string) ([]*gitnesstypes.WebhookExecutionCore, error)
}
type PackageTagRepository interface {
FindByImageNameAndRegID(ctx context.Context, image string, regID int64) ([]*types.PackageTagMetadata, error)
Create(ctx context.Context, tag *types.PackageTag) (string, error)
DeleteByTagAndImageName(ctx context.Context, tag string, image string, regID int64) error
DeleteByImageNameAndRegID(ctx context.Context, image string, regID int64) error
}
type TaskRepository interface {
Find(ctx context.Context, key string) (*types.Task, error)
UpsertTask(ctx context.Context, task *types.Task) error
LockForUpdate(ctx context.Context, task *types.Task) (types.TaskStatus, error)
SetRunAgain(ctx context.Context, taskKey string, runAgain bool) error
UpdateStatus(ctx context.Context, taskKey string, status types.TaskStatus) error
CompleteTask(ctx context.Context, key string, status types.TaskStatus) (bool, error)
ListPendingTasks(ctx context.Context, limit int) ([]*types.Task, error)
}
type TaskSourceRepository interface {
FindByTaskKeyAndSourceType(ctx context.Context, key string, sourceType string) (*types.TaskSource, error)
InsertSource(ctx context.Context, key string, source types.SourceRef) error
ClaimSources(ctx context.Context, key string, runID string) error
UpdateSourceStatus(ctx context.Context, runID string, status types.TaskStatus, errMsg string) error
}
type TaskEventRepository interface {
LogTaskEvent(ctx context.Context, key string, event string, payload []byte) error
}
type QuarantineArtifactRepository interface {
Create(ctx context.Context, artifact *types.QuarantineArtifact) error
GetByFilePath(
ctx context.Context, filePath string,
registryID int64,
artifact string,
version string,
artifactType *artifact.ArtifactType,
) ([]*types.QuarantineArtifact, error)
DeleteByRegistryIDArtifactAndFilePath(
ctx context.Context, registryID int64,
artifactID *int64, imageID int64, nodeID *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/store/cache/wire.go | registry/app/store/cache/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 cache
import (
"context"
"time"
"github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/pubsub"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
"github.com/google/wire"
)
const (
registryCacheDuration = 15 * time.Minute
)
const (
pubsubNamespace = "cache-evictor"
pubsubTopicRegCoreUpdate = "reg-core-update"
)
func ProvideEvictorRegistryCore(pubsub pubsub.PubSub) cache.Evictor[*types.Registry] {
return cache.NewEvictor[*types.Registry](pubsubNamespace, pubsubTopicRegCoreUpdate, pubsub)
}
func ProvideRegistryIDCache(
appCtx context.Context,
regSource store.RegistryRepository,
evictorRepo cache.Evictor[*types.Registry],
) store.RegistryIDCache {
return NewRegistryIDCache(appCtx, regSource, evictorRepo, registryCacheDuration)
}
func ProvideRegRootRefCache(
appCtx context.Context,
regSource store.RegistryRepository,
evictorRepo cache.Evictor[*types.Registry],
) store.RegistryRootRefCache {
return NewRegistryRootRefCache(appCtx, regSource, evictorRepo, registryCacheDuration)
}
var WireSet = wire.NewSet(
ProvideEvictorRegistryCore,
ProvideRegRootRefCache,
ProvideRegistryIDCache,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/cache/reg_id.go | registry/app/store/cache/reg_id.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"context"
"fmt"
"time"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/cache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
)
func NewRegistryIDCache(
appCtx context.Context,
regSource store.RegistryRepository,
evictorRepo cache2.Evictor[*types.Registry],
dur time.Duration,
) store.RegistryIDCache {
c := cache.New[int64, *types.Registry](registryIDCacheGetter{regSource: regSource}, dur)
evictorRepo.Subscribe(appCtx, func(repoCore *types.Registry) error {
c.Evict(appCtx, repoCore.ID)
return nil
})
return c
}
type registryIDCacheGetter struct {
regSource store.RegistryRepository
}
func (c registryIDCacheGetter) Find(ctx context.Context, repoID int64) (*types.Registry, error) {
repo, err := c.regSource.Get(ctx, repoID)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
}
return repo, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/cache/reg_root_ref.go | registry/app/store/cache/reg_root_ref.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"context"
"fmt"
"time"
cache2 "github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/cache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
)
func NewRegistryRootRefCache(
appCtx context.Context,
regSource store.RegistryRepository,
evictorReg cache2.Evictor[*types.Registry],
dur time.Duration,
) store.RegistryRootRefCache {
c := cache.New[types.RegistryRootRefCacheKey, int64](registryRootRefCacheGetter{
regSource: regSource,
}, dur)
evictorReg.Subscribe(appCtx, func(key *types.Registry) error {
c.Evict(appCtx, types.RegistryRootRefCacheKey{
RootParentID: key.RootParentID,
RegistryIdentifier: key.Name,
})
return nil
})
return c
}
type registryRootRefCacheGetter struct {
regSource store.RegistryRepository
}
func (c registryRootRefCacheGetter) Find(ctx context.Context, key types.RegistryRootRefCacheKey) (
int64,
error,
) {
repo, err := c.regSource.GetByRootParentIDAndName(ctx, key.RootParentID, key.RegistryIdentifier)
if err != nil {
return -1, fmt.Errorf("failed to find repo by %d:%s %w", key.RootParentID, key.RegistryIdentifier, err)
}
return repo.ID, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/migrations/migrator.go | registry/app/store/migrations/migrator.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrations
import (
"errors"
"fmt"
"strings"
"github.com/golang-migrate/migrate/v4"
"github.com/rs/zerolog/log"
)
// Migrate orchestrates database migrations using golang-migrate.
func Migrate(m *migrate.Migrate) error {
version, dirty, err := m.Version()
if err != nil && !errors.Is(err, migrate.ErrNilVersion) {
log.Info().Msg("failed to fetch schema version from db.")
return err
}
log.Info().Msgf("current version %d", version)
if dirty {
prev := int(version) - 1 //nolint:gosec
//nolint:gosec
log.Info().Msg(fmt.Sprintf("schema is dirty at version = %d. Forcing version to %d", int(version), prev))
err = m.Force(prev)
if err != nil {
log.Error().Stack().Err(err).Msg(fmt.Sprintf("failed to force schema version to %d %s", prev, err))
return err
}
}
err = m.Up()
if errors.Is(err, migrate.ErrNoChange) {
log.Info().Msg("No change to schema. No migrations were run")
return nil
}
if err != nil && strings.Contains(err.Error(), "no migration found") {
// The library throws this error when a give migration file does not exist. Unfortunately, we do not have
// an error constant to compare with
log.Error().Stack().Err(err).Msg("skipping migration because migration file was not found")
return nil
}
if err != nil {
log.Error().Stack().Err(err).Msg("failed to run db migrations")
return fmt.Errorf("error when migration up: %w", err)
}
log.Info().Msg("Migrations successfully completed")
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/store/database/registry_blobs.go | registry/app/store/database/registry_blobs.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
)
type registryBlobDao struct {
db *sqlx.DB
}
func NewRegistryBlobDao(db *sqlx.DB) store.RegistryBlobRepository {
return ®istryBlobDao{
db: db,
}
}
// registryBlobDB holds the record of a registry_blobs in DB.
type registryBlobDB struct {
ID int64 `db:"rblob_id"`
RegistryID int64 `db:"rblob_registry_id"`
BlobID int64 `db:"rblob_blob_id"`
ImageName string `db:"rblob_image_name"`
CreatedAt int64 `db:"rblob_created_at"`
UpdatedAt int64 `db:"rblob_updated_at"`
CreatedBy int64 `db:"rblob_created_by"`
UpdatedBy int64 `db:"rblob_updated_by"`
}
func (r registryBlobDao) LinkBlob(
ctx context.Context, imageName string,
registry *types.Registry, blobID int64,
) error {
sqlQuery := `
INSERT INTO registry_blobs (
rblob_blob_id,
rblob_registry_id,
rblob_image_name,
rblob_created_at,
rblob_updated_at,
rblob_created_by,
rblob_updated_by
) VALUES (
:rblob_blob_id,
:rblob_registry_id,
:rblob_image_name,
:rblob_created_at,
:rblob_updated_at,
:rblob_created_by,
:rblob_updated_by
) ON CONFLICT (
rblob_registry_id, rblob_blob_id, rblob_image_name
) DO NOTHING
RETURNING rblob_registry_id`
rblob := mapToInternalRegistryBlob(ctx, registry.ID, blobID, imageName)
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, rblob)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object")
}
var registryBlobID int64
if err = db.QueryRowContext(ctx, query, arg...).Scan(®istryBlobID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil
}
return databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
log.Ctx(ctx).Info().Msgf("Linking blob to registry %d with id: %d", registry.ID, registryBlobID)
return nil
}
// UnlinkBlob unlinks a blob from a repository. It does nothing if not linked. A boolean is returned to denote whether
// the link was deleted or not. This avoids the need for a separate preceding `SELECT` to find if it exists.
func (r registryBlobDao) UnlinkBlob(
ctx context.Context, imageName string,
registry *types.Registry, blobID int64,
) (bool, error) {
stmt := databaseg.Builder.Delete("registry_blobs").
Where("rblob_registry_id = ? AND rblob_blob_id = ? "+
"AND rblob_image_name = ?", registry.ID, blobID, imageName)
sql, args, err := stmt.ToSql()
if err != nil {
return false, fmt.Errorf("failed to convert purge registry query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, r.db)
result, err := db.ExecContext(ctx, sql, args...)
if err != nil {
return false, databaseg.ProcessSQLErrorf(ctx, err, "error unlinking blobs")
}
affected, err := result.RowsAffected()
return affected == 1, err
}
func (r registryBlobDao) UnlinkBlobByImageName(
ctx context.Context, registryID int64,
imageName string,
) (bool, error) {
stmt := databaseg.Builder.Delete("registry_blobs").
Where("rblob_registry_id = ? AND rblob_image_name = ?",
registryID, imageName)
sql, args, err := stmt.ToSql()
if err != nil {
return false, fmt.Errorf("failed to convert purge registry query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, r.db)
result, err := db.ExecContext(ctx, sql, args...)
if err != nil {
return false, databaseg.ProcessSQLErrorf(ctx, err, "error unlinking blobs")
}
affected, err := result.RowsAffected()
return affected > 0, err
}
func mapToInternalRegistryBlob(
ctx context.Context, registryID int64, blobID int64,
imageName string,
) *registryBlobDB {
creationTime := time.Now().UnixMilli()
session, _ := request.AuthSessionFrom(ctx)
return ®istryBlobDB{
RegistryID: registryID,
BlobID: blobID,
ImageName: imageName,
CreatedAt: creationTime,
UpdatedAt: creationTime,
CreatedBy: session.Principal.ID,
UpdatedBy: session.Principal.ID,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/wire.go | registry/app/store/database/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 database
import (
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/wire"
"github.com/jmoiron/sqlx"
)
func ProvideUpstreamDao(
db *sqlx.DB,
registryDao store.RegistryRepository,
spaceFinder refcache.SpaceFinder,
) store.UpstreamProxyConfigRepository {
return NewUpstreamproxyDao(db, registryDao, spaceFinder)
}
func ProvideMediaTypeDao(db *sqlx.DB) store.MediaTypesRepository {
return NewMediaTypesDao(db)
}
func ProvideBlobDao(db *sqlx.DB, mtRepository store.MediaTypesRepository) store.BlobRepository {
return NewBlobDao(db, mtRepository)
}
func ProvideRegistryBlobDao(db *sqlx.DB) store.RegistryBlobRepository {
return NewRegistryBlobDao(db)
}
func ProvideImageDao(db *sqlx.DB) store.ImageRepository {
return NewImageDao(db)
}
func ProvideArtifactDao(db *sqlx.DB) store.ArtifactRepository {
return NewArtifactDao(db)
}
func ProvideDownloadStatDao(db *sqlx.DB) store.DownloadStatRepository {
return NewDownloadStatDao(db)
}
func ProvideBandwidthStatDao(db *sqlx.DB) store.BandwidthStatRepository {
return NewBandwidthStatDao(db)
}
func ProvideTagDao(db *sqlx.DB) store.TagRepository {
return NewTagDao(db)
}
func ProvideManifestDao(sqlDB *sqlx.DB, mtRepository store.MediaTypesRepository) store.ManifestRepository {
return NewManifestDao(sqlDB, mtRepository)
}
func ProvideWebhookDao(sqlDB *sqlx.DB) store.WebhooksRepository {
return NewWebhookDao(sqlDB)
}
func ProvideWebhookExecutionDao(sqlDB *sqlx.DB) store.WebhooksExecutionRepository {
return NewWebhookExecutionDao(sqlDB)
}
func ProvideManifestRefDao(db *sqlx.DB) store.ManifestReferenceRepository {
return NewManifestReferenceDao(db)
}
func ProvideOCIImageIndexMappingDao(db *sqlx.DB) store.OCIImageIndexMappingRepository {
return NewOCIImageIndexMappingDao(db)
}
func ProvideLayerDao(db *sqlx.DB, mtRepository store.MediaTypesRepository) store.LayerRepository {
return NewLayersDao(db, mtRepository)
}
func ProvideCleanupPolicyDao(db *sqlx.DB, tx dbtx.Transactor) store.CleanupPolicyRepository {
return NewCleanupPolicyDao(db, tx)
}
func ProvideNodeDao(db *sqlx.DB) store.NodesRepository {
return NewNodeDao(db)
}
func ProvideQuarantineArtifactDao(db *sqlx.DB) store.QuarantineArtifactRepository {
return NewQuarantineArtifactDao(db)
}
func ProvidePackageTagDao(db *sqlx.DB) store.PackageTagRepository {
return NewPackageTagDao(db)
}
func ProvideGenericBlobDao(db *sqlx.DB) store.GenericBlobRepository {
return NewGenericBlobDao(db)
}
func ProvideRegistryDao(
db *sqlx.DB, mtRepository store.MediaTypesRepository,
) store.RegistryRepository {
return NewRegistryDao(db, mtRepository)
}
func ProvideTaskRepository(db *sqlx.DB, tx dbtx.Transactor) store.TaskRepository {
return NewTaskStore(db, tx)
}
func ProvideTaskSourceRepository(db *sqlx.DB, tx dbtx.Transactor) store.TaskSourceRepository {
return NewTaskSourceStore(db, tx)
}
func ProvideTaskEventRepository(db *sqlx.DB) store.TaskEventRepository {
return NewTaskEventStore(db)
}
var WireSet = wire.NewSet(
ProvideUpstreamDao,
ProvideRegistryDao,
ProvideMediaTypeDao,
ProvideQuarantineArtifactDao,
ProvideBlobDao,
ProvideRegistryBlobDao,
ProvideTagDao,
ProvideManifestDao,
ProvideCleanupPolicyDao,
ProvideManifestRefDao,
ProvideOCIImageIndexMappingDao,
ProvideLayerDao,
ProvideImageDao,
ProvideArtifactDao,
ProvideDownloadStatDao,
ProvideBandwidthStatDao,
ProvideNodeDao,
ProvideGenericBlobDao,
ProvideWebhookDao,
ProvideWebhookExecutionDao,
ProvidePackageTagDao,
ProvideTaskRepository,
ProvideTaskSourceRepository,
ProvideTaskEventRepository,
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/oci_image_index_mapping.go | registry/app/store/database/oci_image_index_mapping.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"errors"
"fmt"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/types"
store2 "github.com/harness/gitness/store"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
)
type ociImageIndexMappingDao struct {
db *sqlx.DB
}
func NewOCIImageIndexMappingDao(db *sqlx.DB) store.OCIImageIndexMappingRepository {
return &ociImageIndexMappingDao{
db: db,
}
}
type ociImageIndexMappingDB struct {
ID int64 `db:"oci_mapping_id"`
ParentManifestID int64 `db:"oci_mapping_parent_manifest_id"`
ChildDigest []byte `db:"oci_mapping_child_digest"`
CreatedAt int64 `db:"oci_mapping_created_at"`
UpdatedAt int64 `db:"oci_mapping_updated_at"`
CreatedBy int64 `db:"oci_mapping_created_by"`
UpdatedBy int64 `db:"oci_mapping_updated_by"`
}
func (dao *ociImageIndexMappingDao) Create(
ctx context.Context,
ociManifest *types.OCIImageIndexMapping,
) error {
const sqlQuery = `
INSERT INTO oci_image_index_mappings (
oci_mapping_parent_manifest_id,
oci_mapping_child_digest,
oci_mapping_created_at,
oci_mapping_updated_at,
oci_mapping_created_by,
oci_mapping_updated_by
) VALUES (
:oci_mapping_parent_manifest_id,
:oci_mapping_child_digest,
:oci_mapping_created_at,
:oci_mapping_updated_at,
:oci_mapping_created_by,
:oci_mapping_updated_by
) ON CONFLICT (oci_mapping_parent_manifest_id, oci_mapping_child_digest)
DO NOTHING
RETURNING oci_mapping_id`
db := dbtx.GetAccessor(ctx, dao.db)
internalManifest := mapToInternalOCIMapping(ctx, ociManifest)
query, args, err := db.BindNamed(sqlQuery, internalManifest)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Bind query failed")
}
if err = db.QueryRowContext(ctx, query, args...).Scan(&ociManifest.ID); err != nil {
err = databaseg.ProcessSQLErrorf(ctx, err, "QueryRowContext failed")
if errors.Is(err, store2.ErrDuplicate) {
return nil
}
return fmt.Errorf("inserting OCI image index mapping: %w", err)
}
return nil
}
func (dao *ociImageIndexMappingDao) GetAllByChildDigest(
ctx context.Context, registryID int64, imageName string, childDigest types.Digest,
) ([]*types.OCIImageIndexMapping, error) {
digestBytes, err := util.GetHexDecodedBytes(string(childDigest))
if err != nil {
return nil, fmt.Errorf("failed to get digest bytes: %w", err)
}
const sqlQuery = `
SELECT
oci_mapping_id,
oci_mapping_parent_manifest_id,
oci_mapping_child_digest,
oci_mapping_created_at,
oci_mapping_updated_at,
oci_mapping_created_by,
oci_mapping_updated_by
FROM
oci_image_index_mappings
JOIN manifests ON manifests.manifest_id = oci_image_index_mappings.oci_mapping_parent_manifest_id
WHERE
manifest_registry_id = $1 AND
manifest_image_name = $2 AND
oci_mapping_child_digest = $3`
db := dbtx.GetAccessor(ctx, dao.db)
rows, err := db.QueryxContext(ctx, sqlQuery, registryID, imageName, digestBytes)
if err != nil || rows.Err() != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "QueryxContext failed")
}
defer rows.Close()
var manifests []*types.OCIImageIndexMapping
for rows.Next() {
var dbManifest ociImageIndexMappingDB
if err := rows.StructScan(&dbManifest); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "StructScan failed")
}
manifests = append(manifests, mapToExternalOCIManifest(&dbManifest))
}
return manifests, nil
}
func mapToInternalOCIMapping(ctx context.Context, in *types.OCIImageIndexMapping) *ociImageIndexMappingDB {
if in.CreatedAt.IsZero() {
in.CreatedAt = time.Now()
}
in.UpdatedAt = time.Now()
session, _ := request.AuthSessionFrom(ctx)
if in.CreatedBy == 0 {
in.CreatedBy = session.Principal.ID
}
in.UpdatedBy = session.Principal.ID
childBytes, err := types.GetDigestBytes(in.ChildManifestDigest)
if err != nil {
log.Ctx(ctx).Error().Msgf("failed to get digest bytes: %v", err)
}
return &ociImageIndexMappingDB{
ID: in.ID,
ParentManifestID: in.ParentManifestID,
ChildDigest: childBytes,
CreatedAt: in.CreatedAt.UnixMilli(),
UpdatedAt: in.UpdatedAt.UnixMilli(),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}
}
func mapToExternalOCIManifest(in *ociImageIndexMappingDB) *types.OCIImageIndexMapping {
childDgst := types.Digest(util.GetHexEncodedString(in.ChildDigest))
parsedChildDigest, err := childDgst.Parse()
if err != nil {
log.Error().Msgf("failed to child parse digest: %v", err)
}
return &types.OCIImageIndexMapping{
ID: in.ID,
ParentManifestID: in.ParentManifestID,
ChildManifestDigest: parsedChildDigest,
CreatedAt: time.UnixMilli(in.CreatedAt),
UpdatedAt: time.UnixMilli(in.UpdatedAt),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/registry.go | registry/app/store/database/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 database
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
"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/types"
"github.com/harness/gitness/registry/utils"
gitnessstore "github.com/harness/gitness/store"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
sq "github.com/Masterminds/squirrel"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const SQLITE3 = "sqlite3"
type registryDao struct {
db *sqlx.DB
//FIXME: Arvind: Move this to controller layer later
mtRepository store.MediaTypesRepository
}
func NewRegistryDao(db *sqlx.DB, mtRepository store.MediaTypesRepository) store.RegistryRepository {
return ®istryDao{
db: db,
//FIXME: Arvind: Move this to controller layer later
mtRepository: mtRepository,
}
}
// registryDB holds the record of a registry in DB.
type registryDB struct {
ID int64 `db:"registry_id"`
UUID string `db:"registry_uuid"`
Name string `db:"registry_name"`
ParentID int64 `db:"registry_parent_id"`
RootParentID int64 `db:"registry_root_parent_id"`
Description sql.NullString `db:"registry_description"`
Type artifact.RegistryType `db:"registry_type"`
PackageType artifact.PackageType `db:"registry_package_type"`
UpstreamProxies sql.NullString `db:"registry_upstream_proxies"`
AllowedPattern sql.NullString `db:"registry_allowed_pattern"`
BlockedPattern sql.NullString `db:"registry_blocked_pattern"`
Labels sql.NullString `db:"registry_labels"`
Config sql.NullString `db:"registry_config"`
CreatedAt int64 `db:"registry_created_at"`
UpdatedAt int64 `db:"registry_updated_at"`
CreatedBy int64 `db:"registry_created_by"`
UpdatedBy int64 `db:"registry_updated_by"`
}
type registryNameID struct {
ID int64 `db:"registry_id"`
Name string `db:"registry_name"`
}
func (r registryDao) GetByUUID(ctx context.Context, uuid string) (*types.Registry, error) {
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryDB{}), ",")).
From("registries").
Where("registry_uuid = ?", uuid)
db := dbtx.GetAccessor(ctx, r.db)
dst := new(registryDB)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find registry by uuid")
}
return r.mapToRegistry(ctx, dst)
}
func (r registryDao) Get(ctx context.Context, id int64) (*types.Registry, error) {
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryDB{}), ",")).
From("registries").
Where("registry_id = ?", id)
db := dbtx.GetAccessor(ctx, r.db)
dst := new(registryDB)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find repo")
}
return r.mapToRegistry(ctx, dst)
}
func (r registryDao) GetByParentIDAndName(
ctx context.Context, parentID int64,
name string,
) (*types.Registry, error) {
log.Info().Msgf("GetByParentIDAndName: parentID: %d, name: %s", parentID, name)
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryDB{}), ",")).
From("registries").
Where("registry_parent_id = ? AND registry_name = ?", parentID, name)
db := dbtx.GetAccessor(ctx, r.db)
dst := new(registryDB)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find repo")
}
return r.mapToRegistry(ctx, dst)
}
func (r registryDao) GetByRootParentIDAndName(
ctx context.Context, parentID int64,
name string,
) (*types.Registry, error) {
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryDB{}), ",")).
From("registries").
Where("registry_root_parent_id = ? AND registry_name = ?", parentID, name)
db := dbtx.GetAccessor(ctx, r.db)
dst := new(registryDB)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find repo")
}
return r.mapToRegistry(ctx, dst)
}
func (r registryDao) Count(ctx context.Context) (int64, error) {
stmt := databaseg.Builder.Select("COUNT(*)").
From("registries")
sql, args, err := stmt.ToSql()
if err != nil {
return 0, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
var count int64
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query")
}
return count, nil
}
func (r registryDao) FetchUpstreamProxyKeys(
ctx context.Context,
ids []int64,
) (repokeys []string, err error) {
orderedRepoKeys := make([]string, 0)
if commons.IsEmpty(ids) {
return orderedRepoKeys, nil
}
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryNameID{}), ",")).
From("registries").
Where(sq.Eq{"registry_id": ids})
db := dbtx.GetAccessor(ctx, r.db)
dst := []registryNameID{}
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find repo")
}
// Create a map
recordMap := make(map[int64]registryNameID)
for _, record := range dst {
recordMap[record.ID] = record
}
// Reorder the fetched records based on the ID list
for _, id := range ids {
if record, exists := recordMap[id]; exists {
orderedRepoKeys = append(orderedRepoKeys, record.Name)
} else {
log.Ctx(ctx).Error().Msgf("failed to map upstream registry: %d", id)
orderedRepoKeys = append(orderedRepoKeys, "")
}
}
return orderedRepoKeys, nil
}
func (r registryDao) GetByIDIn(ctx context.Context, ids []int64) (*[]types.Registry, error) {
stmt := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(registryDB{}), ",")).
From("registries").
Where(sq.Eq{"registry_id": ids})
db := dbtx.GetAccessor(ctx, r.db)
dst := []*registryDB{}
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find repo")
}
return r.mapToRegistries(ctx, dst)
}
type RegistryMetadataDB struct {
RegUUID string `db:"registry_uuid"`
RegID string `db:"registry_id"`
ParentID int64 `db:"parent_id"`
RegIdentifier string `db:"reg_identifier"`
Description sql.NullString `db:"description"`
PackageType artifact.PackageType `db:"package_type"`
Type artifact.RegistryType `db:"type"`
LastModified int64 `db:"last_modified"`
URL sql.NullString `db:"url"`
ArtifactCount int64 `db:"artifact_count"`
DownloadCount int64 `db:"download_count"`
Size int64 `db:"size"`
Labels sql.NullString `db:"registry_labels"`
Config sql.NullString `db:"registry_config"`
}
func (r registryDao) GetAll(
ctx context.Context,
parentIDs []int64,
packageTypes []string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
repoType string,
) (repos *[]store.RegistryMetadata, err error) {
if limit < 0 || offset < 0 {
return nil, fmt.Errorf("limit and offset must be non-negative")
}
// Step 1: Fetch base registry data.
selectFields := `
r.registry_uuid AS registry_uuid,
r.registry_id AS registry_id,
r.registry_parent_id AS parent_id,
r.registry_name AS reg_identifier,
COALESCE(r.registry_description, '') AS description,
r.registry_package_type AS package_type,
r.registry_type AS type,
r.registry_updated_at AS last_modified,
COALESCE(u.upstream_proxy_config_url, '') AS url,
r.registry_config,
r.registry_labels,
0 AS artifact_count,
0 AS size,
0 AS download_count
`
var query sq.SelectBuilder
query = databaseg.Builder.
Select(selectFields).
From("registries r").
LeftJoin("upstream_proxy_configs u ON r.registry_id = u.upstream_proxy_config_registry_id").
Where(sq.Eq{"r.registry_parent_id": parentIDs})
// Apply search filter
if search != "" {
query = query.Where("r.registry_name LIKE ?", "%"+search+"%")
}
// Apply package types filter
if len(packageTypes) > 0 {
query = query.Where(sq.Eq{"r.registry_package_type": packageTypes})
}
// Apply repository type filter
if repoType != "" {
query = query.Where("r.registry_type = ?", repoType)
}
// Sorting and pagination
validSortFields := map[string]bool{
"artifact_count": true,
"size": true,
"download_count": true,
}
if validSortFields[sortByField] {
query = query.OrderBy(fmt.Sprintf("%s %s", sortByField, sortByOrder))
} else {
query = query.OrderBy(fmt.Sprintf("r.registry_%s %s", sortByField, sortByOrder))
}
query = query.Limit(utils.SafeUint64(limit)).Offset(utils.SafeUint64(offset))
// Convert query to SQL
sql, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to SQL")
}
// Execute main query
db := dbtx.GetAccessor(ctx, r.db)
dst := []*RegistryMetadataDB{}
if err := db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing main registry query")
}
// If no registries found, return empty list
if len(dst) == 0 {
return r.mapToRegistryMetadataList(ctx, dst)
}
// Extract registry IDs for subsequent queries
registryIDs := make([]int64, len(dst))
registryIDStrings := make([]string, len(dst))
for i, reg := range dst {
regID, err := strconv.ParseInt(reg.RegID, 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse registry ID %s: %w", reg.RegID, err)
}
registryIDs[i] = regID
registryIDStrings[i] = reg.RegID
}
// Fetch aggregate data sequentially
artifactCounts, err := r.fetchArtifactCounts(ctx, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to fetch artifact counts: %w", err)
}
ociSizes, err := r.fetchOCIBlobSizes(ctx, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to fetch OCI blob sizes: %w", err)
}
genericSizes, err := r.fetchGenericBlobSizes(ctx, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to fetch generic blob sizes: %w", err)
}
downloadCounts, err := r.fetchDownloadCounts(ctx, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to fetch download counts: %w", err)
}
// Merge aggregate data into registry results
for _, reg := range dst {
regID, _ := strconv.ParseInt(reg.RegID, 10, 64)
// Set artifact count
if count, ok := artifactCounts[regID]; ok {
reg.ArtifactCount = count
}
// Set size (OCI takes precedence, fallback to generic)
if size, ok := ociSizes[regID]; ok && size > 0 {
reg.Size = size
} else if genericSize, ok := genericSizes[regID]; ok && genericSize > 0 {
reg.Size = genericSize
}
// Set download count
if count, ok := downloadCounts[regID]; ok {
reg.DownloadCount = count
}
}
// Map results to response type
return r.mapToRegistryMetadataList(ctx, dst)
}
// fetchArtifactCounts fetches artifact counts for given registry IDs.
func (r registryDao) fetchArtifactCounts(ctx context.Context, registryIDs []int64) (map[int64]int64, error) {
if len(registryIDs) == 0 {
return make(map[int64]int64), nil
}
query := `
SELECT image_registry_id, COUNT(images.image_id) AS count
FROM images
WHERE image_registry_id IN (?) AND image_enabled = TRUE
GROUP BY image_registry_id
`
db := dbtx.GetAccessor(ctx, r.db)
sql, args, err := sqlx.In(query, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to build artifact counts query: %w", err)
}
sql = db.Rebind(sql)
type result struct {
RegistryID int64 `db:"image_registry_id"`
Count int64 `db:"count"`
}
var results []result
if err := db.SelectContext(ctx, &results, sql, args...); err != nil {
return nil, fmt.Errorf("failed to fetch artifact counts: %w", err)
}
counts := make(map[int64]int64, len(results))
for _, r := range results {
counts[r.RegistryID] = r.Count
}
return counts, nil
}
// fetchOCIBlobSizes fetches OCI blob sizes for given registry IDs.
func (r registryDao) fetchOCIBlobSizes(ctx context.Context, registryIDs []int64) (map[int64]int64, error) {
if len(registryIDs) == 0 {
return make(map[int64]int64), nil
}
query := `
SELECT rb.rblob_registry_id, COALESCE(SUM(blobs.blob_size), 0) AS total_size
FROM registry_blobs rb
LEFT JOIN blobs ON rb.rblob_blob_id = blobs.blob_id
WHERE rb.rblob_registry_id IN (?)
GROUP BY rb.rblob_registry_id
`
db := dbtx.GetAccessor(ctx, r.db)
sql, args, err := sqlx.In(query, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to build OCI blob sizes query: %w", err)
}
sql = db.Rebind(sql)
type result struct {
RegistryID int64 `db:"rblob_registry_id"`
TotalSize int64 `db:"total_size"`
}
var results []result
if err := db.SelectContext(ctx, &results, sql, args...); err != nil {
return nil, fmt.Errorf("failed to fetch OCI blob sizes: %w", err)
}
sizes := make(map[int64]int64, len(results))
for _, r := range results {
sizes[r.RegistryID] = r.TotalSize
}
return sizes, nil
}
// fetchGenericBlobSizes fetches generic blob sizes for given registry IDs.
func (r registryDao) fetchGenericBlobSizes(ctx context.Context, registryIDs []int64) (map[int64]int64, error) {
if len(registryIDs) == 0 {
return make(map[int64]int64), nil
}
query := `
SELECT nodes.node_registry_id, COALESCE(SUM(generic_blobs.generic_blob_size), 0) AS total_size
FROM nodes
LEFT JOIN generic_blobs ON generic_blob_id = nodes.node_generic_blob_id
WHERE node_is_file AND generic_blob_id IS NOT NULL
AND node_registry_id IN (?)
GROUP BY nodes.node_registry_id
`
db := dbtx.GetAccessor(ctx, r.db)
sql, args, err := sqlx.In(query, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to build generic blob sizes query: %w", err)
}
sql = db.Rebind(sql)
type result struct {
RegistryID int64 `db:"node_registry_id"`
TotalSize int64 `db:"total_size"`
}
var results []result
if err := db.SelectContext(ctx, &results, sql, args...); err != nil {
return nil, fmt.Errorf("failed to fetch generic blob sizes: %w", err)
}
sizes := make(map[int64]int64, len(results))
for _, r := range results {
sizes[r.RegistryID] = r.TotalSize
}
return sizes, nil
}
// fetchDownloadCounts fetches download counts for given registry IDs.
func (r registryDao) fetchDownloadCounts(ctx context.Context, registryIDs []int64) (map[int64]int64, error) {
if len(registryIDs) == 0 {
return make(map[int64]int64), nil
}
query := `
SELECT i.image_registry_id, COUNT(d.download_stat_id) AS download_count
FROM download_stats d
LEFT JOIN artifacts a ON d.download_stat_artifact_id = a.artifact_id
LEFT JOIN images i ON a.artifact_image_id = i.image_id
WHERE i.image_registry_id IN (?) AND i.image_enabled = TRUE
GROUP BY i.image_registry_id
`
db := dbtx.GetAccessor(ctx, r.db)
sql, args, err := sqlx.In(query, registryIDs)
if err != nil {
return nil, fmt.Errorf("failed to build download counts query: %w", err)
}
sql = db.Rebind(sql)
type result struct {
RegistryID int64 `db:"image_registry_id"`
DownloadCount int64 `db:"download_count"`
}
var results []result
if err := db.SelectContext(ctx, &results, sql, args...); err != nil {
return nil, fmt.Errorf("failed to fetch download counts: %w", err)
}
counts := make(map[int64]int64, len(results))
for _, r := range results {
counts[r.RegistryID] = r.DownloadCount
}
return counts, nil
}
func (r registryDao) CountAll(
ctx context.Context, parentIDs []int64,
packageTypes []string, search string, repoType string,
) (int64, error) {
stmt := databaseg.Builder.Select("COUNT(*)").
From("registries").
Where(sq.Eq{"registry_parent_id": parentIDs})
if !commons.IsEmpty(search) {
stmt = stmt.Where("registry_name LIKE ?", "%"+search+"%")
}
if len(packageTypes) > 0 {
stmt = stmt.Where(sq.Eq{"registry_package_type": packageTypes})
}
if repoType != "" {
stmt = stmt.Where("registry_type = ?", repoType)
}
sql, args, err := stmt.ToSql()
if err != nil {
return -1, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
var count int64
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query")
}
return count, nil
}
func (r registryDao) Create(ctx context.Context, registry *types.Registry) (id int64, err error) {
const sqlQuery = `
INSERT INTO registries (
registry_name
,registry_root_parent_id
,registry_parent_id
,registry_description
,registry_type
,registry_package_type
,registry_upstream_proxies
,registry_allowed_pattern
,registry_blocked_pattern
,registry_created_at
,registry_updated_at
,registry_created_by
,registry_updated_by
,registry_labels
,registry_config
,registry_uuid
) VALUES (
:registry_name
,:registry_root_parent_id
,:registry_parent_id
,:registry_description
,:registry_type
,:registry_package_type
,:registry_upstream_proxies
,:registry_allowed_pattern
,:registry_blocked_pattern
,:registry_created_at
,:registry_updated_at
,:registry_created_by
,:registry_updated_by
,:registry_labels
,:registry_config
,:registry_uuid
) RETURNING registry_id`
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, mapToInternalRegistry(ctx, registry))
if err != nil {
return -1, databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(®istry.ID); err != nil {
return -1, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
return registry.ID, nil
}
func mapToInternalRegistry(ctx context.Context, in *types.Registry) *registryDB {
session, _ := request.AuthSessionFrom(ctx)
if in.CreatedAt.IsZero() {
in.CreatedAt = time.Now()
}
in.UpdatedAt = time.Now()
if in.CreatedBy == 0 {
in.CreatedBy = session.Principal.ID
}
in.UpdatedBy = session.Principal.ID
if in.UUID == "" {
in.UUID = uuid.NewString()
}
// Serialize config to JSON
var configStr string
if in.Config != nil {
configBytes, err := json.Marshal(in.Config)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to marshal registry config")
} else {
configStr = string(configBytes)
}
}
return ®istryDB{
ID: in.ID,
UUID: in.UUID,
Name: in.Name,
ParentID: in.ParentID,
RootParentID: in.RootParentID,
Description: util.GetEmptySQLString(in.Description),
Type: in.Type,
PackageType: in.PackageType,
UpstreamProxies: util.GetEmptySQLString(util.Int64ArrToString(in.UpstreamProxies)),
AllowedPattern: util.GetEmptySQLString(util.ArrToString(in.AllowedPattern)),
BlockedPattern: util.GetEmptySQLString(util.ArrToString(in.BlockedPattern)),
Labels: util.GetEmptySQLString(util.ArrToString(in.Labels)),
Config: util.GetEmptySQLString(configStr),
CreatedAt: in.CreatedAt.UnixMilli(),
UpdatedAt: in.UpdatedAt.UnixMilli(),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}
}
func (r registryDao) Delete(ctx context.Context, parentID int64, name string) (err error) {
stmt := databaseg.Builder.Delete("registries").
Where("registry_parent_id = ? AND registry_name = ?", parentID, name)
sql, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge registry query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, r.db)
_, err = db.ExecContext(ctx, sql, args...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
return nil
}
func (r registryDao) Update(ctx context.Context, registry *types.Registry) (err error) {
var sqlQuery = " UPDATE registries SET " + util.GetSetDBKeys(registryDB{}, "registry_id, registry_uuid") +
" WHERE registry_id = :registry_id "
dbRepo := mapToInternalRegistry(ctx, registry)
// update Version (used for optimistic locking) and Updated time
dbRepo.UpdatedAt = time.Now().UnixMilli()
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, dbRepo)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object")
}
result, err := db.ExecContext(ctx, query, arg...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to update repository")
}
count, err := result.RowsAffected()
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows")
}
if count == 0 {
return gitnessstore.ErrVersionConflict
}
return nil
}
func (r registryDao) FetchUpstreamProxyIDs(
ctx context.Context,
repokeys []string,
parentID int64,
) (ids []int64, err error) {
var repoIDs []int64
stmt := databaseg.Builder.Select("registry_id").
From("registries").
Where("registry_parent_id = ?", parentID).
Where(sq.Eq{"registry_name": repokeys}).
Where("registry_type = ?", artifact.RegistryTypeUPSTREAM)
db := dbtx.GetAccessor(ctx, r.db)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &repoIDs, query, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find registries")
}
return repoIDs, nil
}
func (r registryDao) FetchRegistriesIDByUpstreamProxyID(
ctx context.Context, upstreamProxyID string,
rootParentID int64,
) (ids []int64, err error) {
var registryIDs []int64
stmt := databaseg.Builder.Select("registry_id").
From("registries").
Where("registry_root_parent_id = ?", rootParentID).
Where(
"(registry_upstream_proxies = ? "+
"OR registry_upstream_proxies LIKE ? "+
"OR registry_upstream_proxies LIKE ? "+
"OR registry_upstream_proxies LIKE ?)",
upstreamProxyID,
upstreamProxyID+"^_%",
"%^_"+upstreamProxyID+"^_%",
"%^_"+upstreamProxyID,
).
Where("registry_type = ?", artifact.RegistryTypeVIRTUAL)
db := dbtx.GetAccessor(ctx, r.db)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, ®istryIDs, query, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find registries")
}
return registryIDs, nil
}
func (r registryDao) mapToRegistries(ctx context.Context, dst []*registryDB) (*[]types.Registry, error) {
registries := make([]types.Registry, 0, len(dst))
for _, d := range dst {
repo, err := r.mapToRegistry(ctx, d)
if err != nil {
return nil, err
}
registries = append(registries, *repo)
}
return ®istries, nil
}
func (r registryDao) mapToRegistry(ctx context.Context, dst *registryDB) (*types.Registry, error) {
// Deserialize config from JSON
var config *types.RegistryConfig
if dst.Config.String != "" {
config = &types.RegistryConfig{}
if err := json.Unmarshal([]byte(dst.Config.String), config); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to unmarshal registry config")
config = nil
}
}
return &types.Registry{
ID: dst.ID,
UUID: dst.UUID,
Name: dst.Name,
ParentID: dst.ParentID,
RootParentID: dst.RootParentID,
Description: dst.Description.String,
Type: dst.Type,
PackageType: dst.PackageType,
UpstreamProxies: util.StringToInt64Arr(dst.UpstreamProxies.String),
AllowedPattern: util.StringToArr(dst.AllowedPattern.String),
BlockedPattern: util.StringToArr(dst.BlockedPattern.String),
Labels: util.StringToArr(dst.Labels.String),
Config: config,
CreatedAt: time.UnixMilli(dst.CreatedAt),
UpdatedAt: time.UnixMilli(dst.UpdatedAt),
CreatedBy: dst.CreatedBy,
UpdatedBy: dst.UpdatedBy,
}, nil
}
func (r registryDao) mapToRegistryMetadataList(
ctx context.Context,
dst []*RegistryMetadataDB,
) (*[]store.RegistryMetadata, error) {
repos := make([]store.RegistryMetadata, 0, len(dst))
for _, d := range dst {
repo := r.mapToRegistryMetadata(ctx, d)
repos = append(repos, *repo)
}
return &repos, nil
}
func (r registryDao) mapToRegistryMetadata(ctx context.Context, dst *RegistryMetadataDB) *store.RegistryMetadata {
// Deserialize config from JSON
var config *types.RegistryConfig
if dst.Config.String != "" {
config = &types.RegistryConfig{}
if err := json.Unmarshal([]byte(dst.Config.String), config); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to unmarshal registry config in metadata")
config = nil
}
}
return &store.RegistryMetadata{
RegUUID: dst.RegUUID,
RegID: dst.RegID,
ParentID: dst.ParentID,
RegIdentifier: dst.RegIdentifier,
Description: dst.Description.String,
PackageType: dst.PackageType,
Type: dst.Type,
LastModified: time.UnixMilli(dst.LastModified),
URL: dst.URL.String,
ArtifactCount: dst.ArtifactCount,
DownloadCount: dst.DownloadCount,
Size: dst.Size,
Labels: util.StringToArr(dst.Labels.String),
Config: config,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/package_tag.go | registry/app/store/database/package_tag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/types"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type PackageTagDao struct {
db *sqlx.DB
}
func NewPackageTagDao(db *sqlx.DB) *PackageTagDao {
return &PackageTagDao{
db: db,
}
}
type PackageTagDB struct {
ID string `db:"package_tag_id"`
Name string `db:"package_tag_name"`
ArtifactID int64 `db:"package_tag_artifact_id"`
CreatedAt int64 `db:"package_tag_created_at"`
CreatedBy int64 `db:"package_tag_created_by"`
UpdatedAt int64 `db:"package_tag_updated_at"`
UpdatedBy int64 `db:"package_tag_updated_by"`
}
type PackageTagMetadataDB struct {
ID string `db:"package_tag_id"`
Name string `db:"package_tag_name"`
ImageID int64 `db:"package_tag_image_id"`
Version string `db:"package_tag_version"`
}
func (r PackageTagDao) FindByImageNameAndRegID(ctx context.Context,
image string, regID int64) ([]*types.PackageTagMetadata, error) {
stmt := databaseg.Builder.
Select("p.package_tag_id as package_tag_id, "+
"p.package_tag_name as package_tag_name,"+
"i.image_id as package_tag_image_id,"+
"a.artifact_version as package_tag_version").
From("package_tags as p").
Join("artifacts as a ON p.package_tag_artifact_id = a.artifact_id").
Join("images as i ON a.artifact_image_id = i.image_id").
Join("registries as r ON i.image_registry_id = r.registry_id").
Where("i.image_name = ? AND r.registry_id = ?", image, regID)
db := dbtx.GetAccessor(ctx, r.db)
dst := []PackageTagMetadataDB{}
sql, args, err := stmt.ToSql()
if err != nil {
return nil,
errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil,
databaseg.ProcessSQLErrorf(ctx, err, "Failed to find package tags")
}
return r.mapToPackageTagList(ctx, dst)
}
func (r PackageTagDao) DeleteByTagAndImageName(ctx context.Context,
tag string, image string, regID int64) error {
// TODO: postgres query can be optimised here
stmt := databaseg.Builder.Delete("package_tags").
Where("package_tag_id IN (SELECT p.package_tag_id FROM package_tags p"+
" JOIN artifacts a ON p.package_tag_artifact_id = a.artifact_id "+
"JOIN images i ON a.artifact_image_id = i.image_id "+
" JOIN registries r ON r.registry_id = i.image_registry_id "+
"WHERE i.image_name = ? AND p.package_tag_name = ? AND r.registry_id = ?)", image, tag, regID)
sql, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge package_tag query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, r.db)
_, err = db.ExecContext(ctx, sql, args...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
return nil
}
func (r PackageTagDao) DeleteByImageNameAndRegID(ctx context.Context, image string, regID int64) error {
stmt := databaseg.Builder.Delete("package_tags").
Where("package_tag_id IN (SELECT p.package_tag_id FROM package_tags p "+
"JOIN artifacts a ON p.package_tag_artifact_id = a.artifact_id "+
"JOIN images i ON a.artifact_image_id = i.image_id "+
" JOIN registries r ON r.registry_id = i.image_registry_id "+
"WHERE i.image_name = ? AND r.registry_id = ?)", image, regID)
sql, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge package_tag query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, r.db)
_, err = db.ExecContext(ctx, sql, args...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
return nil
}
func (r PackageTagDao) Create(ctx context.Context, tag *types.PackageTag) (string, error) {
const sqlQuery = `
INSERT INTO package_tags (
package_tag_id,
package_tag_name,
package_tag_artifact_id,
package_tag_created_at,
package_tag_created_by,
package_tag_updated_at,
package_tag_updated_by
) VALUES (
:package_tag_id,
:package_tag_name,
:package_tag_artifact_id,
:package_tag_created_at,
:package_tag_created_by,
:package_tag_updated_at,
:package_tag_updated_by
)
ON CONFLICT (package_tag_name,
package_tag_artifact_id)
DO UPDATE SET
package_tag_artifact_id = :package_tag_artifact_id
RETURNING package_tag_id`
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, mapToInternalPackageTag(ctx, tag))
if err != nil {
return "",
databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&tag.ID); err != nil {
return "", databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
return tag.ID, nil
}
func (r PackageTagDao) mapToPackageTagList(ctx context.Context,
dst []PackageTagMetadataDB) ([]*types.PackageTagMetadata, error) {
tags := make([]*types.PackageTagMetadata, 0, len(dst))
for _, d := range dst {
tag := r.mapToPackageTag(ctx, d)
tags = append(tags, tag)
}
return tags, nil
}
func (r PackageTagDao) mapToPackageTag(_ context.Context, dst PackageTagMetadataDB) *types.PackageTagMetadata {
return &types.PackageTagMetadata{
ID: dst.ID,
Name: dst.Name,
Version: dst.Version}
}
func mapToInternalPackageTag(ctx context.Context, in *types.PackageTag) *PackageTagDB {
session, _ := request.AuthSessionFrom(ctx)
if in.CreatedAt.IsZero() {
in.CreatedAt = time.Now()
}
in.UpdatedAt = time.Now()
if in.CreatedBy == 0 {
in.CreatedBy = session.Principal.ID
}
in.UpdatedBy = session.Principal.ID
return &PackageTagDB{
ID: in.ID,
Name: in.Name,
ArtifactID: in.ArtifactID,
CreatedAt: in.CreatedAt.UnixMilli(),
UpdatedAt: in.UpdatedAt.UnixMilli(),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/webhook.go | registry/app/store/database/webhook.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/harness/gitness/registry/app/pkg/commons"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
gitnessstore "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
gitnesstypes "github.com/harness/gitness/types"
gitnessenum "github.com/harness/gitness/types/enum"
"github.com/Masterminds/squirrel"
"github.com/guregu/null"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
const triggersSeparator = ","
var registryWebhooksFields = []string{
"registry_webhook_id",
"registry_webhook_version",
"registry_webhook_registry_id",
"registry_webhook_space_id",
"registry_webhook_created_by",
"registry_webhook_created",
"registry_webhook_updated",
"registry_webhook_scope",
"registry_webhook_identifier",
"registry_webhook_name",
"registry_webhook_description",
"registry_webhook_url",
"registry_webhook_secret_identifier",
"registry_webhook_secret_space_id",
"registry_webhook_enabled",
"registry_webhook_internal",
"registry_webhook_insecure",
"registry_webhook_triggers",
"registry_webhook_extra_headers",
"registry_webhook_latest_execution_result",
}
func NewWebhookDao(db *sqlx.DB) store.WebhooksRepository {
return &WebhookDao{
db: db,
}
}
type webhookDB struct {
ID int64 `db:"registry_webhook_id"`
Version int64 `db:"registry_webhook_version"`
RegistryID null.Int `db:"registry_webhook_registry_id"`
SpaceID null.Int `db:"registry_webhook_space_id"`
CreatedBy int64 `db:"registry_webhook_created_by"`
Created int64 `db:"registry_webhook_created"`
Updated int64 `db:"registry_webhook_updated"`
Scope int64 `db:"registry_webhook_scope"`
Internal bool `db:"registry_webhook_internal"`
Identifier string `db:"registry_webhook_identifier"`
Name string `db:"registry_webhook_name"`
Description string `db:"registry_webhook_description"`
URL string `db:"registry_webhook_url"`
SecretIdentifier sql.NullString `db:"registry_webhook_secret_identifier"`
SecretSpaceID sql.NullInt64 `db:"registry_webhook_secret_space_id"`
Enabled bool `db:"registry_webhook_enabled"`
Insecure bool `db:"registry_webhook_insecure"`
Triggers string `db:"registry_webhook_triggers"`
ExtraHeaders null.String `db:"registry_webhook_extra_headers"`
LatestExecutionResult null.String `db:"registry_webhook_latest_execution_result"`
}
type WebhookDao struct {
db *sqlx.DB
}
func (w WebhookDao) Create(ctx context.Context, webhook *gitnesstypes.WebhookCore) error {
const sqlQuery = `
INSERT INTO registry_webhooks (
registry_webhook_registry_id
,registry_webhook_space_id
,registry_webhook_created_by
,registry_webhook_created
,registry_webhook_updated
,registry_webhook_identifier
,registry_webhook_name
,registry_webhook_description
,registry_webhook_url
,registry_webhook_secret_identifier
,registry_webhook_secret_space_id
,registry_webhook_enabled
,registry_webhook_internal
,registry_webhook_insecure
,registry_webhook_triggers
,registry_webhook_latest_execution_result
,registry_webhook_extra_headers
,registry_webhook_scope
) values (
:registry_webhook_registry_id
,:registry_webhook_space_id
,:registry_webhook_created_by
,:registry_webhook_created
,:registry_webhook_updated
,:registry_webhook_identifier
,:registry_webhook_name
,:registry_webhook_description
,:registry_webhook_url
,:registry_webhook_secret_identifier
,:registry_webhook_secret_space_id
,:registry_webhook_enabled
,:registry_webhook_internal
,:registry_webhook_insecure
,:registry_webhook_triggers
,:registry_webhook_latest_execution_result
,:registry_webhook_extra_headers
,:registry_webhook_scope
) RETURNING registry_webhook_id`
db := dbtx.GetAccessor(ctx, w.db)
dbwebhook, err := mapToWebhookDB(webhook)
dbwebhook.Created = webhook.Created
dbwebhook.Updated = webhook.Updated
if err != nil {
return fmt.Errorf("failed to map registry webhook to internal db type: %w", err)
}
query, arg, err := db.BindNamed(sqlQuery, dbwebhook)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to registry bind webhook object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&webhook.ID); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
return nil
}
func (w WebhookDao) GetByRegistryAndIdentifier(
ctx context.Context,
registryID int64,
webhookIdentifier string,
) (*gitnesstypes.WebhookCore, error) {
query := database.Builder.Select(registryWebhooksFields...).
From("registry_webhooks").
Where("registry_webhook_registry_id = ? AND registry_webhook_identifier = ?", registryID, webhookIdentifier)
sqlQuery, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, w.db)
dst := new(webhookDB)
if err = db.GetContext(ctx, dst, sqlQuery, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to get webhook detail")
}
return mapToWebhook(dst)
}
func (w WebhookDao) Find(
ctx context.Context, id int64,
) (*gitnesstypes.WebhookCore, error) {
query := database.Builder.Select(registryWebhooksFields...).
From("registry_webhooks").
Where("registry_webhook_id = ?", id)
sqlQuery, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, w.db)
dst := new(webhookDB)
if err = db.GetContext(ctx, dst, sqlQuery, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to get webhook detail")
}
return mapToWebhook(dst)
}
func (w WebhookDao) ListByRegistry(
ctx context.Context,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
registryID int64,
) ([]*gitnesstypes.WebhookCore, error) {
query := database.Builder.Select(registryWebhooksFields...).
From("registry_webhooks").
Where("registry_webhook_registry_id = ?", registryID)
if search != "" {
query = query.Where("registry_webhook_name LIKE ?", "%"+search+"%")
}
validSortFields := map[string]string{
"name": "registry_webhook_name",
}
validSortByField := validSortFields[sortByField]
if validSortByField != "" {
query = query.OrderBy(fmt.Sprintf("%s %s", validSortByField, sortByOrder))
}
query = query.Limit(util.SafeIntToUInt64(limit)).Offset(util.SafeIntToUInt64(offset))
sqlQuery, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, w.db)
var dst []*webhookDB
if err = db.SelectContext(ctx, &dst, sqlQuery, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list webhooks details")
}
return mapToWebhooksList(dst)
}
func (w WebhookDao) ListAllByRegistry(
ctx context.Context,
parents []gitnesstypes.WebhookParentInfo,
) ([]*gitnesstypes.WebhookCore, error) {
query := database.Builder.Select(registryWebhooksFields...).
From("registry_webhooks")
err := selectWebhookParents(parents, &query)
if err != nil {
return nil, fmt.Errorf("failed to select webhook parents: %w", err)
}
sqlQuery, args, err := query.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, w.db)
var dst []*webhookDB
if err = db.SelectContext(ctx, &dst, sqlQuery, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list webhooks details")
}
return mapToWebhooksList(dst)
}
func (w WebhookDao) CountAllByRegistry(
ctx context.Context,
registryID int64,
search string,
) (int64, error) {
stmt := database.Builder.Select("COUNT(*)").
From("registry_webhooks").
Where("registry_webhook_registry_id = ?", registryID)
if !commons.IsEmpty(search) {
stmt = stmt.Where("registry_webhook_name LIKE ?", "%"+search+"%")
}
sqlQuery, args, err := stmt.ToSql()
if err != nil {
return -1, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, w.db)
var count int64
err = db.QueryRowContext(ctx, sqlQuery, args...).Scan(&count)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed executing count query")
}
return count, nil
}
func (w WebhookDao) Update(ctx context.Context, webhook *gitnesstypes.WebhookCore) error {
var sqlQuery = " UPDATE registry_webhooks SET " +
util.GetSetDBKeys(webhookDB{},
"registry_webhook_id",
"registry_webhook_identifier",
"registry_webhook_registry_id",
"registry_webhook_created",
"registry_webhook_created_by",
"registry_webhook_version",
"registry_webhook_internal") +
", registry_webhook_version = registry_webhook_version + 1" +
" WHERE registry_webhook_identifier = :registry_webhook_identifier" +
" AND registry_webhook_registry_id = :registry_webhook_registry_id"
dbWebhook, err := mapToWebhookDB(webhook)
dbWebhook.Updated = webhook.Updated
if err != nil {
return err
}
dbWebhook.Updated = time.Now().UnixMilli()
db := dbtx.GetAccessor(ctx, w.db)
query, arg, err := db.BindNamed(sqlQuery, dbWebhook)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind registry webhook object")
}
result, err := db.ExecContext(ctx, query, arg...)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to update registry webhook")
}
count, err := result.RowsAffected()
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows")
}
if count == 0 {
return gitnessstore.ErrVersionConflict
}
return nil
}
func (w WebhookDao) DeleteByRegistryAndIdentifier(
ctx context.Context,
registryID int64,
webhookIdentifier string,
) error {
sqlQuery := database.Builder.Delete("registry_webhooks").
Where("registry_webhook_identifier = ? AND registry_webhook_registry_id = ?", webhookIdentifier, registryID)
query, args, err := sqlQuery.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge registry_webhooks query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, w.db)
_, err = db.ExecContext(ctx, query, args...)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "the delete registry_webhooks query failed")
}
return nil
}
// UpdateOptLock updates the webhook using the optimistic locking mechanism.
func (w *WebhookDao) UpdateOptLock(
ctx context.Context, hook *gitnesstypes.WebhookCore,
mutateFn func(hook *gitnesstypes.WebhookCore) error,
) (*gitnesstypes.WebhookCore, error) {
for {
dup := *hook
err := mutateFn(&dup)
if err != nil {
return nil, fmt.Errorf("failed to mutate the webhook: %w", err)
}
err = w.Update(ctx, &dup)
if err == nil {
return &dup, nil
}
if !errors.Is(err, gitnessstore.ErrVersionConflict) {
return nil, fmt.Errorf("failed to update the webhook: %w", err)
}
hook, err = w.Find(ctx, hook.ID)
if err != nil {
return nil, fmt.Errorf("failed to find the latst version of the webhook: %w", err)
}
}
}
func mapToWebhookDB(webhook *gitnesstypes.WebhookCore) (*webhookDB, error) {
if webhook.Created < 0 {
webhook.Created = time.Now().UnixMilli()
}
webhook.Updated = time.Now().UnixMilli()
dBWebhook := &webhookDB{
ID: webhook.ID,
Version: webhook.Version,
CreatedBy: webhook.CreatedBy,
Identifier: webhook.Identifier,
Scope: webhook.Scope,
Name: webhook.DisplayName,
Description: webhook.Description,
URL: webhook.URL,
SecretIdentifier: util.GetEmptySQLString(webhook.SecretIdentifier),
SecretSpaceID: util.GetEmptySQLInt64(webhook.SecretSpaceID),
Enabled: webhook.Enabled,
Insecure: webhook.Insecure,
Triggers: triggersToString(webhook.Triggers),
ExtraHeaders: null.StringFrom(structListToString(webhook.ExtraHeaders)),
LatestExecutionResult: null.StringFromPtr((*string)(webhook.LatestExecutionResult)),
}
if webhook.Type == gitnessenum.WebhookTypeInternal {
dBWebhook.Internal = true
}
switch webhook.ParentType {
case gitnessenum.WebhookParentRegistry:
dBWebhook.RegistryID = null.IntFrom(webhook.ParentID)
case gitnessenum.WebhookParentSpace:
dBWebhook.SpaceID = null.IntFrom(webhook.ParentID)
case gitnessenum.WebhookParentRepo:
default:
return nil, fmt.Errorf("webhook parent type %q is not supported", webhook.ParentType)
}
return dBWebhook, nil
}
func mapToWebhook(webhookDB *webhookDB) (*gitnesstypes.WebhookCore, error) {
webhook := &gitnesstypes.WebhookCore{
ID: webhookDB.ID,
Version: webhookDB.Version,
CreatedBy: webhookDB.CreatedBy,
Created: webhookDB.Created,
Updated: webhookDB.Updated,
Scope: webhookDB.Scope,
Identifier: webhookDB.Identifier,
DisplayName: webhookDB.Name,
Description: webhookDB.Description,
URL: webhookDB.URL,
Enabled: webhookDB.Enabled,
Insecure: webhookDB.Insecure,
Triggers: triggersFromString(webhookDB.Triggers),
ExtraHeaders: stringToStructList(webhookDB.ExtraHeaders.String),
LatestExecutionResult: (*gitnessenum.WebhookExecutionResult)(webhookDB.LatestExecutionResult.Ptr()),
}
if webhookDB.SecretIdentifier.Valid {
webhook.SecretIdentifier = webhookDB.SecretIdentifier.String
}
if webhookDB.SecretSpaceID.Valid {
webhook.SecretSpaceID = webhookDB.SecretSpaceID.Int64
}
if webhookDB.Internal {
webhook.Type = gitnessenum.WebhookTypeInternal
} else {
webhook.Type = gitnessenum.WebhookTypeExternal
}
switch {
case webhookDB.RegistryID.Valid && webhookDB.SpaceID.Valid:
return nil, fmt.Errorf("both registryID and spaceID are set for hook %d", webhookDB.ID)
case webhookDB.RegistryID.Valid:
webhook.ParentType = gitnessenum.WebhookParentRegistry
webhook.ParentID = webhookDB.RegistryID.Int64
case webhookDB.SpaceID.Valid:
webhook.ParentType = gitnessenum.WebhookParentSpace
webhook.ParentID = webhookDB.SpaceID.Int64
default:
return nil, fmt.Errorf("neither registryID nor spaceID are set for hook %d", webhookDB.ID)
}
return webhook, nil
}
func selectWebhookParents(
parents []gitnesstypes.WebhookParentInfo,
stmt *squirrel.SelectBuilder,
) error {
var parentSelector squirrel.Or
for _, parent := range parents {
switch parent.Type {
case gitnessenum.WebhookParentRegistry:
parentSelector = append(parentSelector, squirrel.Eq{
"registry_webhook_registry_id": parent.ID,
})
case gitnessenum.WebhookParentSpace:
parentSelector = append(parentSelector, squirrel.Eq{
"registry_webhook_space_id": parent.ID,
})
case gitnessenum.WebhookParentRepo:
default:
return fmt.Errorf("webhook parent type '%s' is not supported", parent.Type)
}
}
*stmt = stmt.Where(parentSelector)
return nil
}
func triggersToString(triggers []gitnessenum.WebhookTrigger) string {
rawTriggers := make([]string, len(triggers))
for i := range triggers {
rawTriggers[i] = string(triggers[i])
}
return strings.Join(rawTriggers, triggersSeparator)
}
func triggersFromString(triggersString string) []gitnessenum.WebhookTrigger {
if triggersString == "" {
return []gitnessenum.WebhookTrigger{}
}
rawTriggers := strings.Split(triggersString, triggersSeparator)
triggers := make([]gitnessenum.WebhookTrigger, len(rawTriggers))
for i, rawTrigger := range rawTriggers {
triggers[i] = gitnessenum.WebhookTrigger(rawTrigger)
}
return triggers
}
// Convert a list of ExtraHeaders structs to a JSON string.
func structListToString(headers []gitnesstypes.ExtraHeader) string {
jsonData, err := json.Marshal(headers)
if err != nil {
return ""
}
return string(jsonData)
}
// Convert a JSON string back to a list of ExtraHeaders structs.
func stringToStructList(jsonStr string) []gitnesstypes.ExtraHeader {
var headers []gitnesstypes.ExtraHeader
err := json.Unmarshal([]byte(jsonStr), &headers)
if err != nil {
return nil
}
return headers
}
func mapToWebhooksList(
dst []*webhookDB,
) ([]*gitnesstypes.WebhookCore, error) {
webhooks := make([]*gitnesstypes.WebhookCore, 0, len(dst))
for _, d := range dst {
webhook, err := mapToWebhook(d)
if err != nil {
return nil, err
}
webhooks = append(webhooks, webhook)
}
return webhooks, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/manifest.go | registry/app/store/database/manifest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/types"
store2 "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/jmoiron/sqlx"
"github.com/opencontainers/go-digest"
errors2 "github.com/pkg/errors"
)
type manifestDao struct {
sqlDB *sqlx.DB
mtRepository store.MediaTypesRepository
}
func NewManifestDao(sqlDB *sqlx.DB, mtRepository store.MediaTypesRepository) store.ManifestRepository {
return &manifestDao{
sqlDB: sqlDB,
mtRepository: mtRepository,
}
}
var (
PrimaryInsertQuery = `
INSERT INTO manifests (
manifest_registry_id,
manifest_schema_version,
manifest_media_type_id,
manifest_artifact_media_type,
manifest_total_size,
manifest_configuration_media_type,
manifest_configuration_payload,
manifest_configuration_blob_id,
manifest_configuration_digest,
manifest_digest,
manifest_payload,
manifest_non_conformant,
manifest_non_distributable_layers,
manifest_subject_id,
manifest_subject_digest,
manifest_annotations,
manifest_image_name,
manifest_created_at,
manifest_created_by,
manifest_updated_at,
manifest_updated_by
) VALUES (
:manifest_registry_id,
:manifest_schema_version,
:manifest_media_type_id,
:manifest_artifact_media_type,
:manifest_total_size,
:manifest_configuration_media_type,
:manifest_configuration_payload,
:manifest_configuration_blob_id,
:manifest_configuration_digest,
:manifest_digest,
:manifest_payload,
:manifest_non_conformant,
:manifest_non_distributable_layers,
:manifest_subject_id,
:manifest_subject_digest,
:manifest_annotations,
:manifest_image_name,
:manifest_created_at,
:manifest_created_by,
:manifest_updated_at,
:manifest_updated_by
) RETURNING manifest_id`
InsertQueryWithConflictHandling = `
INSERT INTO manifests (
manifest_registry_id,
manifest_schema_version,
manifest_media_type_id,
manifest_artifact_media_type,
manifest_total_size,
manifest_configuration_media_type,
manifest_configuration_payload,
manifest_configuration_blob_id,
manifest_configuration_digest,
manifest_digest,
manifest_payload,
manifest_non_conformant,
manifest_non_distributable_layers,
manifest_subject_id,
manifest_subject_digest,
manifest_annotations,
manifest_image_name,
manifest_created_at,
manifest_created_by,
manifest_updated_at,
manifest_updated_by
) VALUES (
:manifest_registry_id,
:manifest_schema_version,
:manifest_media_type_id,
:manifest_artifact_media_type,
:manifest_total_size,
:manifest_configuration_media_type,
:manifest_configuration_payload,
:manifest_configuration_blob_id,
:manifest_configuration_digest,
:manifest_digest,
:manifest_payload,
:manifest_non_conformant,
:manifest_non_distributable_layers,
:manifest_subject_id,
:manifest_subject_digest,
:manifest_annotations,
:manifest_image_name,
:manifest_created_at,
:manifest_created_by,
:manifest_updated_at,
:manifest_updated_by
) ON CONFLICT (manifest_registry_id, manifest_image_name, manifest_digest) DO NOTHING
RETURNING manifest_id`
ReadQuery = database.Builder.Select(
"manifest_id", "manifest_registry_id",
"manifest_total_size", "manifest_schema_version",
"manifest_media_type_id", "mt_media_type", "manifest_artifact_media_type",
"manifest_digest", "manifest_payload",
"manifest_configuration_blob_id", "manifest_configuration_media_type",
"manifest_configuration_digest",
"manifest_configuration_payload", "manifest_non_conformant",
"manifest_non_distributable_layers", "manifest_subject_id",
"manifest_subject_digest", "manifest_annotations", "manifest_created_at",
"manifest_created_by", "manifest_updated_at", "manifest_updated_by", "manifest_image_name",
).
From("manifests").
Join("media_types ON mt_id = manifest_media_type_id")
)
// Manifest holds the record of a manifest in DB.
type manifestDB struct {
ID int64 `db:"manifest_id"`
RegistryID int64 `db:"manifest_registry_id"`
TotalSize int64 `db:"manifest_total_size"`
SchemaVersion int `db:"manifest_schema_version"`
MediaTypeID int64 `db:"manifest_media_type_id"`
ImageName string `db:"manifest_image_name"`
ArtifactMediaType sql.NullString `db:"manifest_artifact_media_type"`
Digest []byte `db:"manifest_digest"`
Payload []byte `db:"manifest_payload"`
ConfigurationMediaType string `db:"manifest_configuration_media_type"`
ConfigurationPayload []byte `db:"manifest_configuration_payload"`
ConfigurationDigest []byte `db:"manifest_configuration_digest"`
ConfigurationBlobID sql.NullInt64 `db:"manifest_configuration_blob_id"`
SubjectID sql.NullInt64 `db:"manifest_subject_id"`
SubjectDigest []byte `db:"manifest_subject_digest"`
NonConformant bool `db:"manifest_non_conformant"`
// NonDistributableLayers identifies whether a manifest
// references foreign/non-distributable layers. For now, we are
// not registering metadata about these layers,
// but we may wish to backfill that metadata in the future by parsing
// the manifest payload.
NonDistributableLayers bool `db:"manifest_non_distributable_layers"`
Annotations []byte `db:"manifest_annotations"`
CreatedAt int64 `db:"manifest_created_at"`
CreatedBy int64 `db:"manifest_created_by"`
UpdatedAt int64 `db:"manifest_updated_at"`
UpdatedBy int64 `db:"manifest_updated_by"`
}
type manifestMetadataDB struct {
manifestDB
MediaType string `db:"mt_media_type"`
}
// FindAll finds all manifests.
func (dao manifestDao) FindAll(_ context.Context) (
types.Manifests, error,
) {
// TODO implement me
panic("implement me")
}
func (dao manifestDao) Count(_ context.Context) (int, error) {
// TODO implement me
panic("implement me")
}
func (dao manifestDao) LayerBlobs(
_ context.Context,
_ *types.Manifest,
) (types.Blobs, error) {
// TODO implement me
panic("implement me")
}
// References finds all manifests directly referenced by a manifest (if any).
func (dao manifestDao) References(
ctx context.Context,
m *types.Manifest,
) (types.Manifests, error) {
stmt := ReadQuery.Join("manifest_references ON manifest_ref_child_id = manifest_id").
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where("manifest_ref_registry_id = ?", m.RegistryID).Where("manifest_ref_parent_id = ?", m.ID)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
dst := []*manifestMetadataDB{}
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, errors2.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifests during references")
return nil, err
}
result, err := dao.mapToManifests(dst)
if err != nil {
return nil, fmt.Errorf("finding referenced manifests: %w", err)
}
return *result, err
}
func (dao manifestDao) Create(ctx context.Context, m *types.Manifest) error {
mediaTypeID, err := dao.mtRepository.MapMediaType(ctx, m.MediaType)
if err != nil {
return fmt.Errorf("mapping manifest media type: %w", err)
}
m.MediaTypeID = mediaTypeID
db := dbtx.GetAccessor(ctx, dao.sqlDB)
manifest, err := mapToInternalManifest(ctx, m)
if err != nil {
return err
}
query, arg, err := db.BindNamed(PrimaryInsertQuery, manifest)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind manifest object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&manifest.ID); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Insert query failed")
if !errors.Is(err, store2.ErrResourceNotFound) {
return err
}
}
m.ID = manifest.ID
return nil
}
func (dao manifestDao) CreateOrFind(ctx context.Context, m *types.Manifest) error {
dgst, err := types.NewDigest(m.Digest)
if err != nil {
return err
}
mediaTypeID, err := dao.mtRepository.MapMediaType(ctx, m.MediaType)
if err != nil {
return fmt.Errorf("mapping manifest media type: %w", err)
}
m.MediaTypeID = mediaTypeID
db := dbtx.GetAccessor(ctx, dao.sqlDB)
manifest, err := mapToInternalManifest(ctx, m)
if err != nil {
return err
}
query, arg, err := db.BindNamed(InsertQueryWithConflictHandling, manifest)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind manifest object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&manifest.ID); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Insert query failed")
if !errors.Is(err, store2.ErrResourceNotFound) {
return err
}
result, err := dao.FindManifestByDigest(ctx, m.RegistryID, m.ImageName, dgst)
if err != nil {
return err
}
m.ID = result.ID
return nil
}
m.ID = manifest.ID
return nil
}
func (dao manifestDao) AssociateLayerBlob(
_ context.Context,
_ *types.Manifest,
_ *types.Blob,
) error {
// TODO implement me
panic("implement me")
}
func (dao manifestDao) DissociateLayerBlob(
_ context.Context,
_ *types.Manifest,
_ *types.Blob,
) error {
// TODO implement me
panic("implement me")
}
func (dao manifestDao) Delete(ctx context.Context, registryID, id int64) error {
_, err := dao.FindManifestByID(ctx, registryID, id)
if err != nil {
if errors.Is(err, store2.ErrResourceNotFound) {
return nil
}
return fmt.Errorf("failed to get the manifest: %w", err)
}
stmt := database.Builder.Delete("manifests").
Where("manifest_registry_id = ? AND manifest_id = ?", registryID, id)
toSQL, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
_, err = db.ExecContext(ctx, toSQL, args...)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
return nil
}
func (dao manifestDao) DeleteManifest(
ctx context.Context, repoID int64,
imageName string, d digest.Digest,
) (bool, error) {
digestBytes, err := types.GetDigestBytes(d)
if err != nil {
return false, err
}
stmt := database.Builder.Delete("manifests").
Where(
"manifest_registry_id = ? AND manifest_image_name = ? AND manifest_digest = ?",
repoID, imageName, digestBytes,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return false, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
r, err := db.ExecContext(ctx, toSQL, args...)
if err != nil {
return false, database.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
count, _ := r.RowsAffected()
return count == 1, nil
}
func (dao manifestDao) DeleteManifestByImageName(
ctx context.Context, repoID int64,
imageName string,
) (bool, error) {
stmt := database.Builder.Delete("manifests").
Where(
"manifest_registry_id = ? AND manifest_image_name = ?",
repoID, imageName,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return false, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
r, err := db.ExecContext(ctx, toSQL, args...)
if err != nil {
return false, database.ProcessSQLErrorf(ctx, err, "the delete query failed")
}
count, _ := r.RowsAffected()
return count > 0, nil
}
func (dao manifestDao) FindManifestByID(
ctx context.Context,
registryID,
id int64,
) (*types.Manifest, error) {
stmt := ReadQuery.Where("manifest_id = ?", id).Where("manifest_registry_id = ?", registryID)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert find manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
return dao.mapToManifest(dst)
}
func (dao manifestDao) FindManifestByDigest(
ctx context.Context, repoID int64,
imageName string, digest types.Digest,
) (*types.Manifest, error) {
digestBytes, err := util.GetHexDecodedBytes(string(digest))
if err != nil {
return nil, err
}
stmt := ReadQuery.
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where(
"manifest_registry_id = ? AND manifest_image_name = ? AND manifest_digest = ?",
repoID, imageName, digestBytes,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
return dao.mapToManifest(dst)
}
func (dao manifestDao) ListManifestsBySubjectDigest(
ctx context.Context, repoID int64,
digest types.Digest,
) (types.Manifests, error) {
digestBytes, err := util.GetHexDecodedBytes(string(digest))
if err != nil {
return nil, err
}
stmt := ReadQuery.
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where(
"manifest_registry_id = ? AND manifest_subject_digest = ?",
repoID, digestBytes,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := []*manifestMetadataDB{}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.SelectContext(ctx, &dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to list manifests")
return nil, err
}
result, err := dao.mapToManifests(dst)
if err != nil {
return nil, fmt.Errorf("finding manifests by subject digest: %w", err)
}
return *result, err
}
// FindManifestByTagName finds a manifest by tag name within a repository.
func (dao manifestDao) FindManifestByTagName(
ctx context.Context, repoID int64,
imageName string, tag string,
) (*types.Manifest, error) {
stmt := ReadQuery.
Join("tags t ON t.tag_registry_id = manifest_registry_id AND t.tag_manifest_id = manifest_id").
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where(
"manifest_registry_id = ? AND manifest_image_name = ? AND t.tag_name = ?",
repoID, imageName, tag,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
return dao.mapToManifest(dst)
}
// FindManifestDigestByTagName finds a manifest digest by tag name within a repository.
func (dao manifestDao) FindManifestDigestByTagName(
ctx context.Context, regID int64,
imageName string, tag string,
) (types.Digest, error) {
stmt := database.Builder.Select("manifest_digest").
From("manifests m").
Join("tags t ON t.tag_manifest_id = m.manifest_id AND "+
"t.tag_registry_id = m.manifest_registry_id AND "+
"t.tag_image_name = m.manifest_image_name").
Where(
"manifest_registry_id = ? AND manifest_image_name = ? AND t.tag_name = ?",
regID, imageName, tag,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return "", fmt.Errorf("failed to convert manifest digest query to sql: %w", err)
}
var manifestDigestBytes []byte
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, &manifestDigestBytes, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest digest")
return "", err
}
// Convert byte digest to hex-encoded string
manifestDigest := types.Digest(util.GetHexEncodedString(manifestDigestBytes))
return manifestDigest, nil
}
func (dao manifestDao) GetManifestPayload(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
digest types.Digest,
) (*types.Payload, error) {
digestBytes, err := util.GetHexDecodedBytes(string(digest))
if err != nil {
return nil, err
}
stmt := ReadQuery.Join("registries r ON r.registry_id = manifest_registry_id").
Where(
"r.registry_parent_id = ? AND r.registry_name = ? AND "+
"manifest_image_name = ? AND manifest_digest = ?",
parentID, repoKey, imageName, digestBytes,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest payload")
return nil, err
}
m, err := dao.mapToManifest(dst)
if err != nil {
return nil, err
}
return &m.Payload, nil
}
func (dao manifestDao) FindManifestPayloadByTagName(
ctx context.Context,
parentID int64,
repoKey string,
imageName string,
version string,
) (*types.Payload, error) {
stmt := ReadQuery.Join("registries r ON r.registry_id = manifest_registry_id").
Join("tags t ON t.tag_manifest_id = manifest_id").
Where(
"r.registry_parent_id = ? AND r.registry_name = ?"+
" AND manifest_image_name = ? AND t.tag_name = ?",
parentID, repoKey, imageName, version,
)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
m, err := dao.mapToManifest(dst)
if err != nil {
return nil, err
}
return &m.Payload, nil
}
func (dao manifestDao) Get(ctx context.Context, manifestID int64) (*types.Manifest, error) {
stmt := ReadQuery.
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where("manifest_id = ?", manifestID)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := new(manifestMetadataDB)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.GetContext(ctx, dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
return dao.mapToManifest(dst)
}
func (dao manifestDao) ListManifestsBySubject(
ctx context.Context,
repoID int64, id int64,
) (types.Manifests, error) {
stmt := ReadQuery.
LeftJoin("blobs ON manifest_configuration_blob_id = blob_id").
Where("manifest_registry_id = ? AND manifest_subject_id = ?", repoID, id)
toSQL, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to convert manifest query to sql: %w", err)
}
dst := []*manifestMetadataDB{}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
if err = db.SelectContext(ctx, &dst, toSQL, args...); err != nil {
err := database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
return nil, err
}
result, err := dao.mapToManifests(dst)
if err != nil {
return nil, err
}
return *result, nil
}
func (dao manifestDao) GetLatestManifest(ctx context.Context, repoID int64, imageName string) (*types.Manifest, error) {
stmt := database.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(manifestDB{}), ",")).
From("manifests").
Where("manifest_registry_id = ? AND manifest_image_name = ?", repoID, imageName).
OrderBy("manifest_created_at DESC").Limit(1)
db := dbtx.GetAccessor(ctx, dao.sqlDB)
dst := new(manifestMetadataDB)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors2.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find manifest")
}
return dao.mapToManifest(dst)
}
func (dao manifestDao) CountByImageName(ctx context.Context, repoID int64, imageName string) (int64, error) {
q := database.Builder.Select("COUNT(*)").
From("manifests").
Where("manifest_registry_id = ? AND manifest_image_name = ?", repoID, imageName)
sql, args, err := q.ToSql()
if err != nil {
return -1, errors2.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, dao.sqlDB)
var count int64
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed executing count query")
}
return count, nil
}
func mapToInternalManifest(ctx context.Context, in *types.Manifest) (*manifestDB, error) {
if in.CreatedAt.IsZero() {
in.CreatedAt = time.Now()
}
in.UpdatedAt = time.Now()
session, _ := request.AuthSessionFrom(ctx)
if in.CreatedBy == 0 {
in.CreatedBy = session.Principal.ID
}
in.UpdatedBy = session.Principal.ID
digestBytes, err := types.GetDigestBytes(in.Digest)
if err != nil {
return nil, err
}
var configBlobID sql.NullInt64
var configPayload types.Payload
var configMediaType string
var cfgDigestBytes []byte
if in.Configuration != nil {
configPayload = in.Configuration.Payload
configMediaType = in.Configuration.MediaType
configBlobID = sql.NullInt64{Int64: in.Configuration.BlobID, Valid: true}
cfgDigestBytes, err = types.GetDigestBytes(in.Configuration.Digest)
if err != nil {
return nil, err
}
}
sbjDigestBytes, err := types.GetDigestBytes(in.SubjectDigest)
if err != nil {
return nil, err
}
annot, err := json.Marshal(in.Annotations)
if err != nil {
return nil, err
}
return &manifestDB{
ID: in.ID,
RegistryID: in.RegistryID,
TotalSize: in.TotalSize,
SchemaVersion: in.SchemaVersion,
MediaTypeID: in.MediaTypeID,
ArtifactMediaType: in.ArtifactType,
Digest: digestBytes,
Payload: in.Payload,
ConfigurationBlobID: configBlobID,
ConfigurationMediaType: configMediaType,
ConfigurationPayload: configPayload,
ConfigurationDigest: cfgDigestBytes,
NonConformant: in.NonConformant,
NonDistributableLayers: in.NonDistributableLayers,
SubjectID: in.SubjectID,
SubjectDigest: sbjDigestBytes,
Annotations: annot,
ImageName: in.ImageName,
CreatedAt: in.CreatedAt.UnixMilli(),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}, nil
}
func (dao manifestDao) mapToManifest(dst *manifestMetadataDB) (*types.Manifest, error) {
// Converting []byte digest into Digest
dgst := types.Digest(util.GetHexEncodedString(dst.Digest))
parsedDigest, err := dgst.Parse()
if err != nil {
return nil, err
}
// Converting Configuration []byte digest into Digest
cfgDigest := types.Digest(util.GetHexEncodedString(dst.ConfigurationDigest))
cfgParsedDigest, err := cfgDigest.Parse()
if err != nil {
return nil, err
}
// Converting Subject []byte digest into Digest
sbjDigest := types.Digest(util.GetHexEncodedString(dst.SubjectDigest))
sbjParsedDigest, err := sbjDigest.Parse()
if err != nil {
return nil, err
}
var annot map[string]string
err = json.Unmarshal(dst.Annotations, &annot)
if err != nil {
return nil, err
}
m := &types.Manifest{
ID: dst.ID,
RegistryID: dst.RegistryID,
TotalSize: dst.TotalSize,
SchemaVersion: dst.SchemaVersion,
MediaTypeID: dst.MediaTypeID,
MediaType: dst.MediaType,
ArtifactType: dst.ArtifactMediaType,
Digest: parsedDigest,
Payload: dst.Payload,
NonConformant: dst.NonConformant,
NonDistributableLayers: dst.NonDistributableLayers,
SubjectID: dst.SubjectID,
SubjectDigest: sbjParsedDigest,
Annotations: annot,
ImageName: dst.ImageName,
CreatedAt: time.UnixMilli(dst.CreatedAt),
}
if dst.ConfigurationBlobID.Valid {
m.Configuration = &types.Configuration{
BlobID: dst.ConfigurationBlobID.Int64,
MediaType: dst.ConfigurationMediaType,
Digest: cfgParsedDigest,
Payload: dst.ConfigurationPayload,
}
}
return m, nil
}
func (dao manifestDao) mapToManifests(dst []*manifestMetadataDB) (*types.Manifests, error) {
mm := make(types.Manifests, 0, len(dst))
for _, d := range dst {
m, err := dao.mapToManifest(d)
if err != nil {
return nil, err
}
mm = append(mm, m)
}
return &mm, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/node.go | registry/app/store/database/node.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/types"
store2 "github.com/harness/gitness/store"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/Masterminds/squirrel"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type NodeDao struct {
sqlDB *sqlx.DB
}
func (n NodeDao) GetByPathAndRegistryID(ctx context.Context, registryID int64, path string) (*types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_path = ? AND node_registry_id = ?", path, registryID)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := new(Nodes)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNode(ctx, dst)
}
func (n NodeDao) FindByPathsAndRegistryID(ctx context.Context, paths []string, registryID int64) (*[]string, error) {
query := databaseg.Builder.
Select("node_id").
From("nodes").
Where(squirrel.Eq{"node_registry_id": registryID}).
Where(squirrel.Eq{"node_path": paths})
sql, args, err := query.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to build query: %w", err)
}
db := dbtx.GetAccessor(ctx, n.sqlDB)
var nodes []string
if err = db.SelectContext(ctx, &nodes, sql, args...); err != nil {
return nil, fmt.Errorf("failed to query nodes: %w", err)
}
return &nodes, nil
}
func (n NodeDao) Get(ctx context.Context, id string) (*types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_id = ?", id)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := new(Nodes)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with id %s", id)
}
return n.mapToNode(ctx, dst)
}
func (n NodeDao) GetByNameAndRegistryID(ctx context.Context, registryID int64, name string) (*types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_name = ? AND node_registry_id = ?", name, registryID)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := new(Nodes)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNode(ctx, dst)
}
func (n NodeDao) GetByBlobIDAndRegistryID(ctx context.Context, blobID string, registryID int64) (*types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_generic_blob_id = ? AND node_registry_id = ?", blobID, registryID).Limit(1)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := new(Nodes)
_sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, _sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNode(ctx, dst)
}
func (n NodeDao) FindByPathAndRegistryID(
ctx context.Context, registryID int64, pathPrefix string, filename string,
) (*types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_registry_id = ? AND node_path LIKE ? AND node_is_file = true AND node_name = ?",
registryID, pathPrefix+"/%", filename).
OrderBy("node_created_at DESC").Limit(1)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := new(Nodes)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNode(ctx, dst)
}
func (n NodeDao) CountByPathAndRegistryID(
ctx context.Context, registryID int64, path string,
) (int64, error) {
q := databaseg.Builder.
Select("COUNT(*)").
From("nodes").
Where("node_is_file = true AND node_path LIKE ? AND node_registry_id = ?", path, registryID)
db := dbtx.GetAccessor(ctx, n.sqlDB)
sql, args, err := q.ToSql()
if err != nil {
return -1, errors.Wrap(err, "Failed to convert query to sql")
}
var count int64
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing node count query")
}
return count, nil
}
func (n NodeDao) Create(ctx context.Context, node *types.Node) error {
const sqlQuery = `
INSERT INTO nodes (
node_id,
node_name
,node_registry_id
,node_parent_id
,node_is_file
,node_path
,node_generic_blob_id
,node_created_at
,node_created_by
) VALUES (
:node_id,
:node_name
,:node_registry_id
,:node_parent_id
,:node_is_file
,:node_path
,:node_generic_blob_id
,:node_created_at
,:node_created_by
) ON CONFLICT (node_registry_id, node_path)
DO UPDATE SET node_id = nodes.node_id,
node_generic_blob_id = :node_generic_blob_id
RETURNING node_id`
db := dbtx.GetAccessor(ctx, n.sqlDB)
query, arg, err := db.BindNamed(sqlQuery, n.mapToInternalNode(node))
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind node object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&node.ID); err != nil && !errors.Is(err, sql.ErrNoRows) {
if errors.Is(err, sql.ErrNoRows) || errors.Is(err, store2.ErrDuplicate) {
return nil
}
return databaseg.ProcessSQLErrorf(ctx, err, "Insert node query failed")
}
return nil
}
func (n NodeDao) DeleteByID(_ context.Context, _ int64) (err error) {
// TODO implement me
panic("implement me")
}
func (n NodeDao) DeleteByNodePathAndRegistryID(ctx context.Context, nodePath string, regID int64) (err error) {
db := dbtx.GetAccessor(ctx, n.sqlDB)
delStmt := databaseg.Builder.Delete("nodes").
Where("(node_path = ? OR node_path LIKE ?)", nodePath, nodePath+"/%").
Where("node_registry_id = ?", regID)
delQuery, delArgs, err := delStmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge query to sql: %w", err)
}
_, err = db.ExecContext(ctx, delQuery, delArgs...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "delete node query failed")
}
return nil
}
func (n NodeDao) DeleteByLeafNodePathAndRegistryID(ctx context.Context, nodePath string, regID int64) (err error) {
db := dbtx.GetAccessor(ctx, n.sqlDB)
delStmt := databaseg.Builder.Delete("nodes").
Where("node_path = ?", nodePath).
Where("node_registry_id = ?", regID).
Where("node_is_file = true")
delQuery, delArgs, err := delStmt.ToSql()
if err != nil {
return fmt.Errorf("failed to convert purge query to sql: %w", err)
}
_, err = db.ExecContext(ctx, delQuery, delArgs...)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil
}
return databaseg.ProcessSQLErrorf(ctx, err, "delete node query failed")
}
return nil
}
func (n NodeDao) GetAllFileNodesByPathPrefixAndRegistryID(
ctx context.Context, registryID int64, pathPrefix string,
) (*[]types.Node, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(Nodes{}), ",")).
From("nodes").
Where("node_registry_id = ? AND node_is_file AND (node_path = ? OR node_path LIKE ?)",
registryID, pathPrefix, pathPrefix+"/%")
db := dbtx.GetAccessor(ctx, n.sqlDB)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
dst := []*Nodes{}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find nodes with registry id %d and path prefix %s",
registryID, pathPrefix)
}
nodes := make([]types.Node, 0, len(dst))
for _, d := range dst {
node, err := n.mapToNode(ctx, d)
if err != nil {
return nil, err
}
nodes = append(nodes, *node)
}
return &nodes, nil
}
func (n NodeDao) mapToNode(_ context.Context, dst *Nodes) (*types.Node, error) {
var blobID, parentNodeID string
if dst.BlobID != nil {
blobID = *dst.BlobID // Dereference the pointer if it's not nil
}
if dst.ParentNodeID != nil {
parentNodeID = *dst.ParentNodeID // Dereference the pointer if it's not nil
}
return &types.Node{
ID: dst.ID,
Name: dst.Name,
RegistryID: dst.RegistryID,
IsFile: dst.IsFile,
NodePath: dst.NodePath,
BlobID: blobID,
ParentNodeID: parentNodeID,
CreatedAt: time.UnixMilli(dst.CreatedAt),
CreatedBy: dst.CreatedBy,
}, nil
}
func (n NodeDao) mapToInternalNode(node *types.Node) any {
if node.CreatedAt.IsZero() {
node.CreatedAt = time.Now()
}
if node.ID == "" {
node.ID = uuid.NewString()
}
var blobID, parentNodeID *string
if node.BlobID != "" {
blobID = &node.BlobID // Store the actual value of BlobID
}
if node.ParentNodeID != "" {
parentNodeID = &node.ParentNodeID // Store the actual value of BlobID
}
return &Nodes{
ID: node.ID,
Name: node.Name,
ParentNodeID: parentNodeID,
RegistryID: node.RegistryID,
IsFile: node.IsFile,
NodePath: node.NodePath,
BlobID: blobID,
CreatedAt: node.CreatedAt.UnixMilli(),
CreatedBy: node.CreatedBy,
}
}
func (n NodeDao) GetFilesMetadataByPathAndRegistryID(
ctx context.Context, registryID int64, path string,
sortByField string,
sortByOrder string,
limit int,
offset int,
search string,
) (*[]types.FileNodeMetadata, error) {
q := databaseg.Builder.
Select(`n.node_name AS name,
n.node_created_at AS created_at,
n.node_path AS path,
gb.generic_blob_sha_1 AS sha1,
gb.generic_blob_sha_256 AS sha256,
gb.generic_blob_sha_512 AS sha512,
gb.generic_blob_md5 AS md5,
gb.generic_blob_size AS size`).
From("nodes n").
Where("n.node_is_file = true").
Join("generic_blobs gb ON gb.generic_blob_id = n.node_generic_blob_id").
Where("n.node_is_file = true AND n.node_path LIKE ? AND n.node_registry_id = ?", path, registryID)
db := dbtx.GetAccessor(ctx, n.sqlDB)
q = q.OrderBy(sortByField + " " + sortByOrder).Limit(uint64(limit)).Offset(uint64(offset)) //nolint:gosec
if search != "" {
q = q.Where("name LIKE ?", sqlPartialMatch(search))
}
dst := []*FileNodeMetadataDB{}
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNodesMetadata(dst)
}
func (n NodeDao) GetFileMetadataByPathAndRegistryID(
ctx context.Context,
registryID int64,
path string,
) (*types.FileNodeMetadata, error) {
q := databaseg.Builder.
Select(`n.node_name AS name,
n.node_created_at AS created_at,
n.node_path AS path,
gb.generic_blob_sha_1 AS sha1,
gb.generic_blob_sha_256 AS sha256,
gb.generic_blob_sha_512 AS sha512,
gb.generic_blob_md5 AS md5,
gb.generic_blob_size AS size`).
From("nodes n").
Where("n.node_is_file = true").
Join("generic_blobs gb ON gb.generic_blob_id = n.node_generic_blob_id").
Where("n.node_is_file = true AND n.node_path LIKE ? AND n.node_registry_id = ?", path, registryID)
db := dbtx.GetAccessor(ctx, n.sqlDB)
dst := FileNodeMetadataDB{}
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find node with registry id %d", registryID)
}
return n.mapToNodeMetadata(&dst), nil
}
func (n NodeDao) mapToNodesMetadata(dst []*FileNodeMetadataDB) (*[]types.FileNodeMetadata, error) {
nodes := make([]types.FileNodeMetadata, 0, len(dst))
for _, d := range dst {
node := n.mapToNodeMetadata(d)
nodes = append(nodes, *node)
}
return &nodes, nil
}
func (n NodeDao) mapToNodeMetadata(d *FileNodeMetadataDB) *types.FileNodeMetadata {
return &types.FileNodeMetadata{
Name: d.Name,
Path: d.Path,
Size: d.Size,
MD5: d.MD5,
Sha1: d.Sha1,
Sha256: d.Sha256,
Sha512: d.Sha512,
CreatedAt: d.CreatedAt,
}
}
func NewNodeDao(sqlDB *sqlx.DB) store.NodesRepository {
return &NodeDao{sqlDB: sqlDB}
}
type Nodes struct {
ID string `db:"node_id"`
Name string `db:"node_name"`
RegistryID int64 `db:"node_registry_id"`
IsFile bool `db:"node_is_file"`
NodePath string `db:"node_path"`
BlobID *string `db:"node_generic_blob_id"`
ParentNodeID *string `db:"node_parent_id"`
CreatedAt int64 `db:"node_created_at"`
CreatedBy int64 `db:"node_created_by"`
}
type FileNodeMetadataDB struct {
Name string `db:"name"`
CreatedAt int64 `db:"created_at"`
Path string `db:"path"`
Sha1 string `db:"sha1"`
Sha256 string `db:"sha256"`
Sha512 string `db:"sha512"`
MD5 string `db:"md5"`
Size int64 `db:"size"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/task_source_store.go | registry/app/store/database/task_source_store.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/types"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/jmoiron/sqlx"
)
type taskSourceStore struct {
db *sqlx.DB
tx dbtx.Transactor
}
// NewTaskSourceStore returns a new TaskSourceRepository implementation.
func NewTaskSourceStore(db *sqlx.DB, tx dbtx.Transactor) store.TaskSourceRepository {
return &taskSourceStore{
db: db,
tx: tx,
}
}
// FindByTaskKeyAndSourceType returns a task source by its task key and source type.
func (s *taskSourceStore) FindByTaskKeyAndSourceType(
ctx context.Context, key string, sourceType string,
) (*types.TaskSource, error) {
stmt := databaseg.Builder.
Select(
"registry_task_source_key", "registry_task_source_type", "registry_task_source_id",
"registry_task_source_error", "registry_task_source_run_id", "registry_task_source_updated_at").
From("registry_task_sources").
Where("registry_task_source_key = ?", key).
Where("registry_task_source_type = ?", sourceType)
query, args, err := stmt.ToSql()
if err != nil {
return nil, fmt.Errorf("failed to build query: %w", err)
}
taskSourceDB := &TaskSourceDB{}
if err := s.db.GetContext(ctx, taskSourceDB, query, args...); err != nil {
return nil, fmt.Errorf("failed to find task with key %s: %w", key, err)
}
return taskSourceDB.ToTaskSource(), nil
}
// InsertSource inserts a source for a task.
func (s *taskSourceStore) InsertSource(ctx context.Context, key string, source types.SourceRef) error {
now := time.Now().UnixMilli()
stmt := databaseg.Builder.
Insert("registry_task_sources").
Columns("registry_task_source_key", "registry_task_source_type",
"registry_task_source_id", "registry_task_source_updated_at").
Values(key, source.Type, source.ID, now).
Suffix("ON CONFLICT (registry_task_source_key, registry_task_source_type, registry_task_source_id) "+
"DO UPDATE SET registry_task_source_status = ? WHERE registry_task_sources.registry_task_source_status = ?",
types.TaskStatusPending, types.TaskStatusFailure)
query, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to build insert source query: %w", err)
}
_, err = s.db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("failed to insert source (type: %s, id: %d) for task key %s: %w",
source.Type, source.ID, key, err)
}
return nil
}
// ClaimSources marks sources as processing for a specific run and returns them.
func (s *taskSourceStore) ClaimSources(ctx context.Context, key string, runID string) error {
now := time.Now().UnixMilli()
stmt := databaseg.Builder.
Update("registry_task_sources").
Set("registry_task_source_status", types.TaskStatusProcessing).
Set("registry_task_source_run_id", runID).
Set("registry_task_source_updated_at", now).
Where("registry_task_source_key = ?", key).
Where("registry_task_source_status = ?", types.TaskStatusPending)
query, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to build claim sources query: %w", err)
}
_, err = s.db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("failed to claim pending sources for task %s: %w", key, err)
}
return nil
}
// UpdateSourceStatus updates the status of sources for a specific run.
func (s *taskSourceStore) UpdateSourceStatus(
ctx context.Context,
runID string,
status types.TaskStatus,
errMsg string,
) error {
now := time.Now().UnixMilli()
stmt := databaseg.Builder.
Update("registry_task_sources").
Set("registry_task_source_status", status).
Set("registry_task_source_updated_at", now)
if errMsg == "" {
stmt = stmt.Set("registry_task_source_error", nil)
} else {
stmt = stmt.Set("registry_task_source_error", errMsg)
}
stmt = stmt.Where("registry_task_source_run_id = ?", runID)
query, args, err := stmt.ToSql()
if err != nil {
return fmt.Errorf("failed to build update source status query: %w", err)
}
_, err = s.db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("failed to update source status for run ID %s to %s: %w", runID, status, err)
}
return nil
}
// TaskSourceDB represents a database entity for task source processing.
type TaskSourceDB struct {
Key string `db:"registry_task_source_key"`
SrcType string `db:"registry_task_source_type"`
SrcID int64 `db:"registry_task_source_id"`
Status string `db:"registry_task_source_status"`
RunID *string `db:"registry_task_source_run_id"`
Error *string `db:"registry_task_source_error"`
UpdatedAt int64 `db:"registry_task_source_updated_at"`
}
// ToTaskSource converts a database task source entity to a DTO.
func (s *TaskSourceDB) ToTaskSource() *types.TaskSource {
return &types.TaskSource{
Key: s.Key,
SrcType: types.SourceType(s.SrcType),
SrcID: s.SrcID,
Status: types.TaskStatus(s.Status),
RunID: s.RunID,
Error: s.Error,
UpdatedAt: time.UnixMilli(s.UpdatedAt),
}
}
// ToSourceRef converts a TaskSourceDB to a SourceRef.
func (s *TaskSourceDB) ToSourceRef() types.SourceRef {
return types.SourceRef{
Type: types.SourceType(s.SrcType),
ID: s.SrcID,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/upstream_proxy.go | registry/app/store/database/upstream_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 database
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"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/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/types"
gitness_store "github.com/harness/gitness/store"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
var (
ulimit = uint64(0)
uoffset = uint64(0)
)
type UpstreamproxyDao struct {
registryDao store.RegistryRepository
db *sqlx.DB
spaceFinder refcache.SpaceFinder
}
func NewUpstreamproxyDao(
db *sqlx.DB, registryDao store.RegistryRepository, spaceFinder refcache.SpaceFinder,
) store.UpstreamProxyConfigRepository {
return &UpstreamproxyDao{
registryDao: registryDao,
db: db,
spaceFinder: spaceFinder,
}
}
// upstreamProxyConfigDB holds the record of an upstream_proxy_config in DB.
type upstreamProxyConfigDB struct {
ID int64 `db:"upstream_proxy_config_id"`
RegistryID int64 `db:"upstream_proxy_config_registry_id"`
Source string `db:"upstream_proxy_config_source"`
URL string `db:"upstream_proxy_config_url"`
AuthType string `db:"upstream_proxy_config_auth_type"`
UserName string `db:"upstream_proxy_config_user_name"`
SecretIdentifier sql.NullString `db:"upstream_proxy_config_secret_identifier"`
SecretSpaceID sql.NullInt64 `db:"upstream_proxy_config_secret_space_id"`
UserNameSecretIdentifier sql.NullString `db:"upstream_proxy_config_user_name_secret_identifier"`
UserNameSecretSpaceID sql.NullInt64 `db:"upstream_proxy_config_user_name_secret_space_id"`
Token string `db:"upstream_proxy_config_token"`
CreatedAt int64 `db:"upstream_proxy_config_created_at"`
UpdatedAt int64 `db:"upstream_proxy_config_updated_at"`
CreatedBy int64 `db:"upstream_proxy_config_created_by"`
UpdatedBy int64 `db:"upstream_proxy_config_updated_by"`
}
type upstreamProxyDB struct {
ID int64 `db:"id"`
RegistryUUID string `db:"registry_uuid"`
RegistryID int64 `db:"registry_id"`
RepoKey string `db:"repo_key"`
ParentID string `db:"parent_id"`
PackageType artifact.PackageType `db:"package_type"`
AllowedPattern sql.NullString `db:"allowed_pattern"`
BlockedPattern sql.NullString `db:"blocked_pattern"`
Config sql.NullString `db:"registry_config"`
Source string `db:"source"`
RepoURL string `db:"repo_url"`
RepoAuthType string `db:"repo_auth_type"`
UserName string `db:"user_name"`
SecretIdentifier sql.NullString `db:"secret_identifier"`
SecretSpaceID sql.NullInt32 `db:"secret_space_id"`
UserNameSecretIdentifier sql.NullString `db:"user_name_secret_identifier"`
UserNameSecretSpaceID sql.NullInt32 `db:"user_name_secret_space_id"`
Token string `db:"token"`
CreatedAt int64 `db:"created_at"`
UpdatedAt int64 `db:"updated_at"`
CreatedBy sql.NullInt64 `db:"created_by"`
UpdatedBy sql.NullInt64 `db:"updated_by"`
}
func getUpstreamProxyQuery() squirrel.SelectBuilder {
return databaseg.Builder.Select(
" u.upstream_proxy_config_id as id," +
" r.registry_uuid as registry_uuid," +
" r.registry_id as registry_id," +
" r.registry_name as repo_key," +
" r.registry_parent_id as parent_id," +
" r.registry_package_type as package_type," +
" r.registry_allowed_pattern as allowed_pattern," +
" r.registry_blocked_pattern as blocked_pattern," +
" r.registry_config as registry_config," +
" u.upstream_proxy_config_url as repo_url," +
" u.upstream_proxy_config_source as source," +
" u.upstream_proxy_config_auth_type as repo_auth_type," +
" u.upstream_proxy_config_user_name as user_name," +
" u.upstream_proxy_config_secret_identifier as secret_identifier," +
" u.upstream_proxy_config_secret_space_id as secret_space_id," +
" u.upstream_proxy_config_user_name_secret_identifier as user_name_secret_identifier," +
" u.upstream_proxy_config_user_name_secret_space_id as user_name_secret_space_id," +
" u.upstream_proxy_config_token as token," +
" r.registry_created_at as created_at," +
" r.registry_updated_at as updated_at ").
From("registries r ").
LeftJoin("upstream_proxy_configs u ON r.registry_id = u.upstream_proxy_config_registry_id ")
}
func (r UpstreamproxyDao) Get(ctx context.Context, id int64) (upstreamProxy *types.UpstreamProxy, err error) {
q := getUpstreamProxyQuery()
q = q.Where("r.registry_id = ? AND r.registry_type = 'UPSTREAM'", id)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
dst := new(upstreamProxyDB)
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get upstream proxy detail")
}
return r.mapToUpstreamProxy(ctx, dst)
}
func (r UpstreamproxyDao) GetByRegistryIdentifier(
ctx context.Context,
parentID int64,
repoKey string,
) (upstreamProxy *types.UpstreamProxy, err error) {
q := getUpstreamProxyQuery()
q = q.Where("r.registry_parent_id = ? AND r.registry_name = ? AND r.registry_type = 'UPSTREAM'",
parentID, repoKey)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
dst := new(upstreamProxyDB)
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get upstream proxy detail")
}
return r.mapToUpstreamProxy(ctx, dst)
}
func (r UpstreamproxyDao) GetByParentID(ctx context.Context, parentID string) (
upstreamProxies *[]types.UpstreamProxy, err error,
) {
q := getUpstreamProxyQuery()
q = q.Where("r.registry_parent_id = ? AND r.registry_type = 'UPSTREAM'",
parentID)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
dst := []*upstreamProxyDB{}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get tag detail")
}
return r.mapToUpstreamProxyList(ctx, dst)
}
func (r UpstreamproxyDao) Create(
ctx context.Context,
upstreamproxyRecord *types.UpstreamProxyConfig,
) (id int64, err error) {
const sqlQuery = `
INSERT INTO upstream_proxy_configs (
upstream_proxy_config_registry_id
,upstream_proxy_config_source
,upstream_proxy_config_url
,upstream_proxy_config_auth_type
,upstream_proxy_config_user_name
,upstream_proxy_config_secret_identifier
,upstream_proxy_config_secret_space_id
,upstream_proxy_config_user_name_secret_identifier
,upstream_proxy_config_user_name_secret_space_id
,upstream_proxy_config_token
,upstream_proxy_config_created_at
,upstream_proxy_config_updated_at
,upstream_proxy_config_created_by
,upstream_proxy_config_updated_by
) VALUES (
:upstream_proxy_config_registry_id
,:upstream_proxy_config_source
,:upstream_proxy_config_url
,:upstream_proxy_config_auth_type
,:upstream_proxy_config_user_name
,:upstream_proxy_config_secret_identifier
,:upstream_proxy_config_secret_space_id
,:upstream_proxy_config_user_name_secret_identifier
,:upstream_proxy_config_user_name_secret_space_id
,:upstream_proxy_config_token
,:upstream_proxy_config_created_at
,:upstream_proxy_config_updated_at
,:upstream_proxy_config_created_by
,:upstream_proxy_config_updated_by
) RETURNING upstream_proxy_config_registry_id`
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, r.mapToInternalUpstreamProxy(ctx, upstreamproxyRecord))
if err != nil {
return -1, databaseg.ProcessSQLErrorf(ctx,
err, "Failed to bind upstream proxy object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&upstreamproxyRecord.ID); err != nil {
return -1, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
return upstreamproxyRecord.ID, nil
}
func (r UpstreamproxyDao) Update(
ctx context.Context,
upstreamProxyRecord *types.UpstreamProxyConfig,
) (err error) {
var sqlQuery = " UPDATE upstream_proxy_configs SET " +
util.GetSetDBKeys(upstreamProxyConfigDB{}, "upstream_proxy_config_id") +
" WHERE upstream_proxy_config_id = :upstream_proxy_config_id "
upstreamProxy := r.mapToInternalUpstreamProxy(ctx, upstreamProxyRecord)
// update Version (used for optimistic locking) and Updated time
upstreamProxy.UpdatedAt = time.Now().UnixMilli()
db := dbtx.GetAccessor(ctx, r.db)
query, arg, err := db.BindNamed(sqlQuery, upstreamProxy)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object")
}
result, err := db.ExecContext(ctx, query, arg...)
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to update repository")
}
count, err := result.RowsAffected()
if err != nil {
return databaseg.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows")
}
if count == 0 {
return gitness_store.ErrVersionConflict
}
return nil
}
func (r UpstreamproxyDao) GetAll(
ctx context.Context, parentID int64,
packageTypes []string, sortByField string, sortByOrder string, limit int,
offset int, search string,
) (upstreamProxies *[]types.UpstreamProxy, err error) {
q := getUpstreamProxyQuery()
q = q.Where("r.registry_parent_id = ? AND r.registry_type = 'UPSTREAM'",
parentID)
if search != "" {
q = q.Where(" r.registry_name LIKE ?", sqlPartialMatch(search))
}
if len(packageTypes) > 0 {
q = q.Where(" AND r.registry_package_type in ? ", packageTypes)
}
if limit > 0 {
ulimit = uint64(limit)
}
if offset > 0 {
uoffset = uint64(offset)
}
q = q.OrderBy(" r.registry_" + sortByField + " " + sortByOrder).
Limit(ulimit).
Offset(uoffset)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
dst := []*upstreamProxyDB{}
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get tag detail")
}
return r.mapToUpstreamProxyList(ctx, dst)
}
func (r UpstreamproxyDao) CountAll(
ctx context.Context, parentID string,
packageTypes []string, search string,
) (count int64, err error) {
q := databaseg.Builder.Select(" COUNT(*) ").
From(" registries r").
LeftJoin(" upstream_proxy_configs u ON r.registry_id = u.upstream_proxy_config_registry_id ").
Where("r.registry_parent_id = ? AND r.registry_type = 'UPSTREAM'",
parentID)
if search != "" {
q = q.Where(" r.registry_name LIKE '%" + search + "%' ")
}
if len(packageTypes) > 0 {
q = q.Where(" AND r.registry_package_type in ? ", packageTypes)
}
sql, args, err := q.ToSql()
if err != nil {
return -1, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, r.db)
var total int64
if err = db.QueryRowContext(ctx, sql, args...).Scan(&total); err != nil {
return -1, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get upstream proxy count")
}
return total, nil
}
func (r UpstreamproxyDao) mapToInternalUpstreamProxy(
ctx context.Context,
in *types.UpstreamProxyConfig,
) *upstreamProxyConfigDB {
if in.CreatedAt.IsZero() {
in.CreatedAt = time.Now()
}
in.UpdatedAt = time.Now()
session, _ := request.AuthSessionFrom(ctx)
if in.CreatedBy == 0 {
in.CreatedBy = session.Principal.ID
}
in.UpdatedBy = session.Principal.ID
return &upstreamProxyConfigDB{
ID: in.ID,
RegistryID: in.RegistryID,
Source: in.Source,
URL: in.URL,
AuthType: in.AuthType,
UserName: in.UserName,
SecretIdentifier: util.GetEmptySQLString(in.SecretIdentifier),
SecretSpaceID: util.GetEmptySQLInt64(in.SecretSpaceID),
UserNameSecretSpaceID: util.GetEmptySQLInt64(in.UserNameSecretSpaceID),
UserNameSecretIdentifier: util.GetEmptySQLString(in.UserNameSecretIdentifier),
Token: in.Token,
CreatedAt: in.CreatedAt.UnixMilli(),
UpdatedAt: in.UpdatedAt.UnixMilli(),
CreatedBy: in.CreatedBy,
UpdatedBy: in.UpdatedBy,
}
}
func (r UpstreamproxyDao) mapToUpstreamProxy(
ctx context.Context,
dst *upstreamProxyDB,
) (*types.UpstreamProxy, error) {
createdBy := int64(-1)
updatedBy := int64(-1)
secretIdentifier := ""
secretSpaceID := int64(-1)
if dst.CreatedBy.Valid {
createdBy = dst.CreatedBy.Int64
}
if dst.UpdatedBy.Valid {
updatedBy = dst.UpdatedBy.Int64
}
if dst.SecretIdentifier.Valid {
secretIdentifier = dst.SecretIdentifier.String
}
if dst.SecretSpaceID.Valid {
secretSpaceID = int64(dst.SecretSpaceID.Int32)
}
secretSpacePath := ""
if dst.SecretSpaceID.Valid {
primary, err := r.spaceFinder.FindByID(ctx, int64(dst.SecretSpaceID.Int32))
if err != nil {
return nil, fmt.Errorf("failed to get secret space path: %w", err)
}
secretSpacePath = primary.Path
}
userNameSecretIdentifier := ""
userNameSecretSpaceID := int64(-1)
if dst.UserNameSecretIdentifier.Valid {
userNameSecretIdentifier = dst.UserNameSecretIdentifier.String
}
if dst.UserNameSecretSpaceID.Valid {
userNameSecretSpaceID = int64(dst.UserNameSecretSpaceID.Int32)
}
userNameSecretSpacePath := ""
if dst.UserNameSecretSpaceID.Valid {
primary, err := r.spaceFinder.FindByID(ctx, int64(dst.UserNameSecretSpaceID.Int32))
if err != nil {
return nil, fmt.Errorf("failed to get secret space path: %w", err)
}
userNameSecretSpacePath = primary.Path
}
// Deserialize config from JSON
var config *types.RegistryConfig
if dst.Config.String != "" {
config = &types.RegistryConfig{}
if err := json.Unmarshal([]byte(dst.Config.String), config); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Failed to unmarshal registry config in upstream proxy")
config = nil
}
}
return &types.UpstreamProxy{
ID: dst.ID,
RegistryUUID: dst.RegistryUUID,
RegistryID: dst.RegistryID,
RepoKey: dst.RepoKey,
ParentID: dst.ParentID,
PackageType: dst.PackageType,
AllowedPattern: util.StringToArr(dst.AllowedPattern.String),
BlockedPattern: util.StringToArr(dst.BlockedPattern.String),
Config: config,
Source: dst.Source,
RepoURL: dst.RepoURL,
RepoAuthType: dst.RepoAuthType,
UserName: dst.UserName,
SecretIdentifier: secretIdentifier,
SecretSpaceID: secretSpaceID,
SecretSpacePath: secretSpacePath,
UserNameSecretIdentifier: userNameSecretIdentifier,
UserNameSecretSpaceID: userNameSecretSpaceID,
UserNameSecretSpacePath: userNameSecretSpacePath,
Token: dst.Token,
CreatedAt: time.UnixMilli(dst.CreatedAt),
UpdatedAt: time.UnixMilli(dst.UpdatedAt),
CreatedBy: createdBy,
UpdatedBy: updatedBy,
}, nil
}
func (r UpstreamproxyDao) mapToUpstreamProxyList(
ctx context.Context,
dst []*upstreamProxyDB,
) (*[]types.UpstreamProxy, error) {
upstreamProxies := make([]types.UpstreamProxy, 0, len(dst))
for _, d := range dst {
upstreamProxy, err := r.mapToUpstreamProxy(ctx, d)
if err != nil {
return nil, err
}
upstreamProxies = append(upstreamProxies, *upstreamProxy)
}
return &upstreamProxies, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/generic_blob.go | registry/app/store/database/generic_blob.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"database/sql"
"time"
"github.com/harness/gitness/registry/app/store"
"github.com/harness/gitness/registry/app/store/database/util"
"github.com/harness/gitness/registry/types"
store2 "github.com/harness/gitness/store"
databaseg "github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type GenericBlobDao struct {
sqlDB *sqlx.DB
}
func (g GenericBlobDao) FindByID(ctx context.Context, id string) (*types.GenericBlob, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(GenericBlob{}), ",")).
From("generic_blobs").
Where("generic_blob_id = ?", id)
db := dbtx.GetAccessor(ctx, g.sqlDB)
dst := new(GenericBlob)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find generic blob with id %s", id)
}
return g.mapToGenericBlob(ctx, dst)
}
func (g GenericBlobDao) TotalSizeByRootParentID(ctx context.Context, rootID int64) (int64, error) {
q := databaseg.Builder.
Select("COALESCE(SUM(generic_blob_size), 0) AS size").
From("generic_blobs").
Where("generic_blob_root_parent_id = ?", rootID)
db := dbtx.GetAccessor(ctx, g.sqlDB)
var size int64
sqlQuery, args, err := q.ToSql()
if err != nil {
return 0, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.QueryRowContext(ctx, sqlQuery, args...).Scan(&size); err != nil &&
!errors.Is(err, sql.ErrNoRows) {
return 0,
databaseg.ProcessSQLErrorf(ctx, err, "Failed to find total blob size for root parent with id %d", rootID)
}
return size, nil
}
func (g GenericBlobDao) FindBySha256AndRootParentID(
ctx context.Context,
sha256 string, rootParentID int64,
) (
*types.GenericBlob, error) {
q := databaseg.Builder.
Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(GenericBlob{}), ",")).
From("generic_blobs").
Where("generic_blob_root_parent_id = ? AND generic_blob_sha_256 = ?", rootParentID, sha256)
db := dbtx.GetAccessor(ctx, g.sqlDB)
dst := new(GenericBlob)
sql, args, err := q.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
if err = db.GetContext(ctx, dst, sql, args...); err != nil {
return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find generic blob with sha256 %s", sha256)
}
return g.mapToGenericBlob(ctx, dst)
}
func (g GenericBlobDao) Create(ctx context.Context, gb *types.GenericBlob) (bool, error) {
const sqlQuery = `
INSERT INTO generic_blobs (
generic_blob_id,
generic_blob_root_parent_id,
generic_blob_sha_1,
generic_blob_sha_256,
generic_blob_sha_512,
generic_blob_md5,
generic_blob_size,
generic_blob_created_at,
generic_blob_created_by
) VALUES (
:generic_blob_id,
:generic_blob_root_parent_id,
:generic_blob_sha_1,
:generic_blob_sha_256,
:generic_blob_sha_512,
:generic_blob_md5,
:generic_blob_size,
:generic_blob_created_at,
:generic_blob_created_by
) ON CONFLICT (generic_blob_root_parent_id, generic_blob_sha_256)
DO UPDATE SET generic_blob_id = generic_blobs.generic_blob_id
RETURNING generic_blob_id`
db := dbtx.GetAccessor(ctx, g.sqlDB)
query, arg, err := db.BindNamed(sqlQuery, g.mapToInternalGenericBlob(gb))
if err != nil {
return false, databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind generic blob object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&gb.ID); err != nil {
if errors.Is(err, sql.ErrNoRows) || errors.Is(err, store2.ErrDuplicate) {
return false, nil
}
return false, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed")
}
return true, nil
}
func (g GenericBlobDao) DeleteByID(_ context.Context, _ string) error {
// TODO implement me
panic("implement me")
}
func (g GenericBlobDao) mapToGenericBlob(_ context.Context, dst *GenericBlob) (*types.GenericBlob, error) {
return &types.GenericBlob{
ID: dst.ID,
RootParentID: dst.RootParentID,
Sha256: dst.Sha256,
Sha1: dst.Sha1,
Sha512: dst.Sha512,
MD5: dst.MD5,
Size: dst.Size,
CreatedAt: time.UnixMilli(dst.CreatedAt),
CreatedBy: dst.CreatedBy,
}, nil
}
func (g GenericBlobDao) mapToInternalGenericBlob(gb *types.GenericBlob) any {
if gb.CreatedAt.IsZero() {
gb.CreatedAt = time.Now()
}
if gb.ID == "" {
gb.ID = uuid.NewString()
}
return &GenericBlob{
ID: gb.ID,
Sha256: gb.Sha256,
Sha1: gb.Sha1,
Sha512: gb.Sha512,
MD5: gb.MD5,
Size: gb.Size,
RootParentID: gb.RootParentID,
CreatedAt: gb.CreatedAt.UnixMilli(),
CreatedBy: gb.CreatedBy,
}
}
func NewGenericBlobDao(sqlDB *sqlx.DB) store.GenericBlobRepository {
return &GenericBlobDao{
sqlDB: sqlDB,
}
}
type GenericBlob struct {
ID string `db:"generic_blob_id"`
RootParentID int64 `db:"generic_blob_root_parent_id"`
Sha1 string `db:"generic_blob_sha_1"`
Sha256 string `db:"generic_blob_sha_256"`
Sha512 string `db:"generic_blob_sha_512"`
MD5 string `db:"generic_blob_md5"`
Size int64 `db:"generic_blob_size"`
CreatedAt int64 `db:"generic_blob_created_at"`
CreatedBy int64 `db:"generic_blob_created_by"`
}
| 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.