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/tests/maven/02_upload_test.go | registry/tests/maven/02_upload_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 mavenconformance
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test02Upload = func() {
ginkgo.Context("Upload", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestUpload) {
ginkgo.Skip("Upload tests are disabled")
}
})
ginkgo.It("should upload an artifact", func() {
// Use a unique artifact name and version for this test
artifactName := GetUniqueArtifactName("upload", 1)
version := GetUniqueVersion(1)
filename := fmt.Sprintf("%s-%s.jar", artifactName, version)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, artifactName, version, filename)
req := client.NewRequest("PUT", path)
req.SetHeader("Content-Type", "application/java-archive")
req.SetBody([]byte("mock jar content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/01_download_test.go | registry/tests/maven/01_download_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 mavenconformance
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test01Download = func() {
ginkgo.Context("Download", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestDownload) {
ginkgo.Skip("Download tests are disabled")
}
})
ginkgo.It("should download an artifact", func() {
// Upload an artifact first.
path := fmt.Sprintf("/maven/%s/%s/com/example/test-artifact/1.0/test-artifact-1.0.jar",
TestConfig.Namespace, TestConfig.RegistryName)
req := client.NewRequest("PUT", path)
req.SetHeader("Content-Type", "application/java-archive")
req.SetBody([]byte("mock jar content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
// Now download it.
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("application/java-archive"))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock jar content"))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/05_error_test.go | registry/tests/maven/05_error_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 mavenconformance
import (
"fmt"
"log"
"time"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test05ErrorHandling = func() {
ginkgo.Context("Error Handling", func() {
ginkgo.Context("Invalid Requests", func() {
ginkgo.It("should reject invalid artifact path", func() {
path := fmt.Sprintf("/maven/%s/%s/invalid/path",
TestConfig.Namespace,
TestConfig.RegistryName)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
log.Printf("Response for invalid path: %d %s\n",
resp.StatusCode, string(resp.Body))
log.Printf("Response Headers: %v\n", resp.Headers)
// The server returns 500 with a text/plain error response.
gomega.Expect(resp.StatusCode).To(gomega.Equal(500))
gomega.Expect(resp.Headers.Get("Content-Type")).To(
gomega.Equal("text/plain; charset=utf-8"))
gomega.Expect(string(resp.Body)).To(gomega.ContainSubstring("invalid path format"))
})
ginkgo.It("should reject invalid version format", func() {
path := fmt.Sprintf("/maven/%s/%s/com/example/test-artifact/invalid-version/test-artifact.jar",
TestConfig.Namespace,
TestConfig.RegistryName)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
ginkgo.It("should reject invalid groupId", func() {
path := fmt.Sprintf("/maven/%s/%s/com/example/../test-artifact/1.0/test-artifact-1.0.jar",
TestConfig.Namespace,
TestConfig.RegistryName)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
})
ginkgo.Context("Authentication", func() {
ginkgo.It("should reject unauthorized access", func() {
// Create a new client with invalid credentials.
invalidClient := conformanceutils.NewClient(TestConfig.RootURL, "invalid", TestConfig.Debug)
path := fmt.Sprintf("/maven/%s/%s/com/example/test-artifact/1.0/test-artifact-1.0.jar",
TestConfig.Namespace,
TestConfig.RegistryName)
req := invalidClient.NewRequest("GET", path)
resp, err := invalidClient.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(401))
})
ginkgo.It("should reject access to non-existent space", func() {
path := fmt.Sprintf("/maven/nonexistent/%s/com/example/test-artifact/1.0/test-artifact-1.0.jar",
TestConfig.RegistryName)
log.Printf("Testing path: %s\n", path)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
// The server returns 500 with a text/plain error response.
gomega.Expect(resp.StatusCode).To(gomega.Equal(500))
gomega.Expect(resp.Headers.Get("Content-Type")).To(
gomega.Equal("text/plain; charset=utf-8"))
gomega.Expect(string(resp.Body)).To(gomega.ContainSubstring("ROOT_NOT_FOUND"))
})
})
ginkgo.Context("Content Validation", ginkgo.Ordered, func() {
// Define variables at the context level so they're accessible to all tests.
var errorArtifact string
var errorVersion string
// Use BeforeAll to set up artifacts just once for all tests in this context.
ginkgo.BeforeAll(func() {
// Define a unique artifact name and version for error handling tests with random component.
errorArtifact = GetUniqueArtifactName("error", int(time.Now().UnixNano()%1000))
errorVersion = GetUniqueVersion(50)
// Create test artifact directory with unique name and version.
filename := fmt.Sprintf("%s-%s.jar", errorArtifact, errorVersion)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
errorArtifact,
errorVersion,
filename)
req := client.NewRequest("PUT", path)
req.SetHeader("Content-Type", "application/java-archive")
req.SetBody([]byte("mock jar content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
})
ginkgo.It("should handle invalid POM XML", func() {
// Use a completely different artifact name with timestamp to ensure uniqueness.
timestamp := time.Now().UnixNano()
pomArtifact := fmt.Sprintf("pom-artifact-%d", timestamp)
pomVersion := fmt.Sprintf("3.0.%d", timestamp)
filename := fmt.Sprintf("%s-%s.pom", pomArtifact, pomVersion)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
pomArtifact,
pomVersion,
filename)
req := client.NewRequest("PUT", path)
req.SetHeader("Content-Type", "text/xml")
req.SetBody([]byte("invalid xml content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
// The server accepts invalid XML as it's just stored as bytes.
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
})
ginkgo.It("should handle mismatched content type", func() {
// Use a completely different artifact name with timestamp to ensure uniqueness.
timestamp := time.Now().UnixNano()
mismatchArtifact := fmt.Sprintf("mismatch-artifact-%d", timestamp)
mismatchVersion := fmt.Sprintf("2.0.%d", timestamp)
filename := fmt.Sprintf("%s-%s.jar", mismatchArtifact, mismatchVersion)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
mismatchArtifact,
mismatchVersion,
filename)
req := client.NewRequest("PUT", path)
req.SetHeader("Content-Type", "text/plain")
req.SetBody([]byte("invalid jar content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
// The server accepts any content type as it's just stored as bytes.
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/config.go | registry/tests/maven/config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mavenconformance
import (
"fmt"
"os"
"time"
)
// Config holds the test configuration.
type Config struct {
RootURL string
Username string
Password string
Namespace string
RegistryName string
Debug bool
DisabledTests map[string]bool
StartTime int64 // Used to generate unique versions.
}
// TestCategory represents different test categories.
type TestCategory string
const (
TestDownload TestCategory = "download"
TestUpload TestCategory = "upload"
TestContentDiscovery TestCategory = "content_discovery"
TestErrorHandling TestCategory = "error_handling"
)
var (
// TestConfig holds the global test configuration.
TestConfig Config
)
// InitConfig initializes the test configuration.
func InitConfig() {
// For Gitness integration, we need to ensure values are properly set.
// to work with the Gitness server structure.
TestConfig = Config{
// Base URL for the Gitness server.
RootURL: getEnv("REGISTRY_ROOT_URL", "http://localhost:3000"),
// Use admin@gitness.io as per .local.env configuration.
Username: getEnv("REGISTRY_USERNAME", "admin@gitness.io"),
// Password will be filled by setup_test.sh via token authentication
Password: getEnv("REGISTRY_PASSWORD", ""),
// These values come from setup_test.sh.
Namespace: getEnv("REGISTRY_NAMESPACE", ""),
RegistryName: getEnv("REGISTRY_NAME", ""),
// Enable debug to see detailed logs.
Debug: getEnv("DEBUG", "true") == "true",
// Store start time for unique version generation.
StartTime: time.Now().Unix(),
// All tests are now enabled
DisabledTests: map[string]bool{},
}
}
// IsTestEnabled checks if a test category is enabled.
func IsTestEnabled(category TestCategory) bool {
return !TestConfig.DisabledTests[string(category)]
}
func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
// GetUniqueVersion generates a unique version string for tests.
// Each test should call this with a different test ID to ensure uniqueness.
func GetUniqueVersion(testID int) string {
return fmt.Sprintf("1.0.%d-%d", TestConfig.StartTime, testID)
}
// GetUniqueArtifactName generates a unique artifact name for tests.
// This ensures that different test contexts don't conflict with each other.
func GetUniqueArtifactName(testContext string, testID int) string {
return fmt.Sprintf("test-artifact-%s-%d-%d", testContext, TestConfig.StartTime, testID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/03_content_discovery_test.go | registry/tests/maven/03_content_discovery_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 mavenconformance
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test03ContentDiscovery = func() {
ginkgo.Context("Content Discovery", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestContentDiscovery) {
ginkgo.Skip("Content discovery tests are disabled")
}
})
ginkgo.Context("Basic Content Discovery", ginkgo.Ordered, func() {
// Define variables at the context level so they're accessible to all tests.
var artifactName string
var version1, version2 string
// Use BeforeAll to set up artifacts just once for all tests in this context.
ginkgo.BeforeAll(func() {
// Define unique artifact name for this test context with random component
artifactName = GetUniqueArtifactName("discovery", int(time.Now().UnixNano()%1000))
// Define test versions that will be used across all tests in this context.
version1 = GetUniqueVersion(10)
version2 = GetUniqueVersion(11)
// Upload test artifacts with unique names and versions.
artifacts := []struct {
version string
filename string
fileType string
}{
{version: version1, filename: fmt.Sprintf("%s-%s.jar", artifactName, version1), fileType: "jar"},
{version: version1, filename: fmt.Sprintf("%s-%s.pom", artifactName, version1), fileType: "pom"},
{version: version2, filename: fmt.Sprintf("%s-%s.jar", artifactName, version2), fileType: "jar"},
{version: version2, filename: fmt.Sprintf("%s-%s.pom", artifactName, version2), fileType: "pom"},
}
for _, artifact := range artifacts {
artifactPath := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
artifactName,
artifact.version,
artifact.filename,
)
contentType := "application/octet-stream"
switch artifact.fileType {
case "jar":
contentType = "application/java-archive"
case "pom":
contentType = "application/xml"
}
req := client.NewRequest("PUT", artifactPath)
req.SetHeader("Content-Type", contentType)
req.SetBody([]byte("mock content"))
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
}
})
ginkgo.It("should find artifacts by version", func() {
// Use the unique artifact name and version defined earlier.
filename := fmt.Sprintf("%s-%s.jar", artifactName, version1)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
artifactName,
version1,
filename,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock content"))
})
ginkgo.It("should find POM files", func() {
// Use the unique artifact name and version defined earlier.
filename := fmt.Sprintf("%s-%s.pom", artifactName, version1)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
artifactName,
version1,
filename,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock content"))
})
ginkgo.It("should handle non-existent artifacts", func() {
// Use a completely different artifact name and version for non-existent artifact.
nonExistentArtifact := GetUniqueArtifactName("nonexistent", 99)
nonExistentVersion := GetUniqueVersion(99)
filename := fmt.Sprintf("%s-%s.jar", nonExistentArtifact, nonExistentVersion)
path := fmt.Sprintf("/maven/%s/%s/com/example/%s/%s/%s",
TestConfig.Namespace,
TestConfig.RegistryName,
nonExistentArtifact,
nonExistentVersion,
filename,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/reporter.go | registry/tests/maven/reporter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mavenconformance
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/onsi/ginkgo/v2/types"
)
// Status constants for test results.
const (
StatusPassed = "passed"
StatusFailed = "failed"
StatusSkipped = "skipped"
StatusPending = "pending"
)
// TestResult represents a single test result.
type TestResult struct {
Name string `json:"name"`
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
// TestReport represents the overall test report.
type TestReport struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
TestResults []TestResult `json:"test_results"`
Summary struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Skipped int `json:"skipped"`
Total int `json:"total"`
} `json:"summary"`
}
var (
report = TestReport{
StartTime: time.Now(),
TestResults: make([]TestResult, 0),
}
)
// ReportTest adds a test result to the report.
func ReportTest(name string, status string, err error) {
// Create detailed output with available information.
detailedOutput := fmt.Sprintf("Test: %s\nStatus: %s\n", name, status)
detailedOutput += fmt.Sprintf("Time: %s\n", time.Now().Format(time.RFC3339))
// Add more context based on test status.
switch status {
case StatusPassed:
detailedOutput += "Result: Test completed successfully\n"
case StatusFailed:
detailedOutput += "Result: Test failed with errors\n"
case StatusSkipped:
detailedOutput += "Result: Test was skipped\n"
case StatusPending:
detailedOutput += "Result: Test is pending implementation\n"
}
// Create a new test result with detailed information.
result := TestResult{
Name: name,
Status: status,
StartTime: time.Now(),
EndTime: time.Now(),
Output: detailedOutput,
}
// Capture error information if available.
if err != nil {
result.Error = err.Error()
result.Output += fmt.Sprintf("Error: %v\n", err)
// Add stack trace or additional context if available.
log.Printf("Test failed: %s - %v", name, err)
}
// Add the result to the report.
report.TestResults = append(report.TestResults, result)
}
// SaveReport saves the test report to a file.
// If logSummary is true, a summary of test results will be logged to stdout.
func SaveReport(filename string, logSummary bool) error {
// Update summary statistics.
report.EndTime = time.Now()
report.Summary.Passed = 0
report.Summary.Failed = 0
report.Summary.Skipped = 0
report.Summary.Pending = 0
report.Summary.Total = len(report.TestResults)
// Count test results by status.
for _, result := range report.TestResults {
switch result.Status {
case StatusPassed:
report.Summary.Passed++
case StatusFailed:
report.Summary.Failed++
case StatusSkipped:
report.Summary.Skipped++
case StatusPending:
report.Summary.Pending++
}
}
// Generate JSON report.
data, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal report: %w", err)
}
// Write the JSON report to file.
if err := os.WriteFile(filename, data, 0600); err != nil {
return err
}
// Log the summary only if requested.
if logSummary {
log.Printf("Maven test results: %d passed, %d failed, %d pending, %d skipped (total: %d)",
report.Summary.Passed, report.Summary.Failed, report.Summary.Pending,
report.Summary.Skipped, report.Summary.Total)
}
return nil
}
// ReporterHook implements ginkgo's Reporter interface.
type ReporterHook struct{}
func (r *ReporterHook) SuiteWillBegin() {
report.StartTime = time.Now()
}
func (r *ReporterHook) SuiteDidEnd() {
report.EndTime = time.Now()
// Pass true to log summary in the ReporterHook context.
if err := SaveReport("maven_conformance_report.json", true); err != nil {
log.Printf("Failed to save report: %v\n", err)
}
}
func (r *ReporterHook) SpecDidComplete(text string, state types.SpecState, failure error) {
// Determine test status.
var status string
switch state {
case types.SpecStateSkipped:
status = StatusSkipped
case types.SpecStateFailed:
status = StatusFailed
case types.SpecStatePending:
status = StatusPending
case types.SpecStatePassed:
status = StatusPassed
case types.SpecStateInvalid, types.SpecStateAborted, types.SpecStatePanicked,
types.SpecStateInterrupted, types.SpecStateTimedout:
status = StatusFailed
}
// Log detailed test information.
log.Printf("Test completed: %s - %s", text, status)
// Report the test with detailed information.
ReportTest(text, status, failure)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/reporter_init.go | registry/tests/maven/reporter_init.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mavenconformance
import (
"log"
"github.com/onsi/ginkgo/v2"
)
func init() {
// Register a reporter hook with Ginkgo.
ginkgo.ReportAfterSuite("Maven Conformance Report", func(_ ginkgo.Report) {
// Save the report when the suite is done.
// Pass false to avoid duplicate logging from the shell script.
if err := SaveReport("maven_conformance_report.json", false); err != nil {
// Log error but don't fail the test.
log.Printf("Failed to save report: %v", err)
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/maven/00_conformance_suite_test.go | registry/tests/maven/00_conformance_suite_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 mavenconformance
import (
"fmt"
"testing"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var (
client *conformanceutils.Client
)
func TestMavenConformance(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "Maven Registry Conformance Test Suite")
}
var _ = ginkgo.BeforeSuite(func() {
InitConfig()
// Log authentication details for debugging
ginkgo.By("Initializing Maven client with configuration")
ginkgo.By(fmt.Sprintf("RootURL: %s", TestConfig.RootURL))
ginkgo.By(fmt.Sprintf("Username: %s", TestConfig.Username))
ginkgo.By(fmt.Sprintf("Namespace: %s", TestConfig.Namespace))
ginkgo.By(fmt.Sprintf("RegistryName: %s", TestConfig.RegistryName))
ginkgo.By(fmt.Sprintf("Password/Token available: %t", TestConfig.Password != ""))
// Ensure we have a valid token.
if TestConfig.Password == "" {
ginkgo.Skip("Skipping integration tests: REGISTRY_PASSWORD environment variable not set")
}
// Initialize client with auth token.
client = conformanceutils.NewClient(TestConfig.RootURL, TestConfig.Password, TestConfig.Debug)
})
var _ = ginkgo.Describe("Maven Registry Conformance Tests", func() {
// Test categories will be defined in separate files.
test01Download()
test02Upload()
test03ContentDiscovery()
test05ErrorHandling()
})
// SkipIfDisabled skips the test if the category is disabled.
func SkipIfDisabled(category TestCategory) {
if !IsTestEnabled(category) {
ginkgo.Skip(string(category) + " tests are disabled")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/05_scoped_packages_test.go | registry/tests/npm/05_scoped_packages_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 npmconformance
import (
"encoding/json"
"fmt"
npm2 "github.com/harness/gitness/registry/app/metadata/npm"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test05ScopedPackages = func() {
ginkgo.Context("Scoped Packages", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestScopedPackages)
})
ginkgo.It("should handle complete lifecycle of scoped packages", func() {
scope := "harness"
packageName := "test-lifecycle"
version := GetUniqueVersion(1)
fullName := fmt.Sprintf("@%s/%s", scope, packageName)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// 1. Upload scoped package
packageData := generateNpmPackagePayload(packageName, version, true, scope)
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// 2. Retrieve metadata
metadataReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
metadataResp, err := client.Do(metadataReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadataResp.StatusCode).To(gomega.Equal(200))
var metadata npm2.PackageMetadata
err = json.Unmarshal(metadataResp.Body, &metadata)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadata.Name).To(gomega.Equal(fullName))
// 3. Download package file
downloadReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/-/@%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName, scope, filename,
),
)
downloadResp, err := client.Do(downloadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(downloadResp.StatusCode).To(gomega.Equal(200))
// 4. Add custom tag
customTag := "rc"
addTagReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/@%s/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName, customTag,
),
)
addTagReq.SetHeader("Content-Type", "application/json")
addTagReq.SetBody(fmt.Sprintf(`"%s"`, version))
addTagResp, err := client.Do(addTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(addTagResp.StatusCode).To(gomega.Equal(200))
// 5. Verify tag was added
tagsReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/@%s/%s/dist-tags/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
tagsResp, err := client.Do(tagsReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tagsResp.StatusCode).To(gomega.Equal(200))
var tags map[string]string
err = json.Unmarshal(tagsResp.Body, &tags)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tags).To(gomega.HaveKeyWithValue(customTag, version))
})
ginkgo.It("should handle multiple versions of scoped packages", func() {
scope := "multiversion"
packageName := "test-versions"
version1 := GetUniqueVersion(2)
version2 := GetUniqueVersion(3)
fullName := fmt.Sprintf("@%s/%s", scope, packageName)
// Upload first version
packageData1 := generateNpmPackagePayload(packageName, version1, true, scope)
uploadReq1 := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq1.SetHeader("Content-Type", "application/json")
uploadReq1.SetBody(packageData1)
uploadResp1, err := client.Do(uploadReq1)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp1.StatusCode).To(gomega.Equal(200))
// Upload second version
packageData2 := generateNpmPackagePayload(packageName, version2, true, scope)
uploadReq2 := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq2.SetHeader("Content-Type", "application/json")
uploadReq2.SetBody(packageData2)
uploadResp2, err := client.Do(uploadReq2)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp2.StatusCode).To(gomega.Equal(200))
// Retrieve metadata and verify both versions exist
metadataReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
metadataResp, err := client.Do(metadataReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadataResp.StatusCode).To(gomega.Equal(200))
var metadata npm2.PackageMetadata
err = json.Unmarshal(metadataResp.Body, &metadata)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadata.Name).To(gomega.Equal(fullName))
gomega.Expect(metadata.Versions).To(gomega.HaveKey(version1))
gomega.Expect(metadata.Versions).To(gomega.HaveKey(version2))
})
ginkgo.It("should handle HEAD requests for scoped package files", func() {
scope := "headtest"
packageName := "test-head"
version := GetUniqueVersion(4)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// Upload scoped package
packageData := generateNpmPackagePayload(packageName, version, true, scope)
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Perform HEAD request
headReq := client.NewRequest(
"HEAD",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/-/@%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName, scope, filename,
),
)
headResp, err := client.Do(headReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(headResp.StatusCode).To(gomega.Equal(200))
gomega.Expect(len(headResp.Body)).To(gomega.Equal(0)) // HEAD should not return body
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/01_upload_test.go | registry/tests/npm/01_upload_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 npmconformance
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test01Upload = func() {
ginkgo.Context("Upload", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestUpload)
})
ginkgo.It("should upload a non-scoped NPM package", func() {
packageName := GetUniquePackageName("upload", 1)
version := GetUniqueVersion(1)
// Generate the package payload
packageData := generateNpmPackagePayload(packageName, version, false, "")
// Set up the upload request
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
req.SetHeader("Content-Type", "application/json")
req.SetBody(packageData)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
})
ginkgo.It("should upload a scoped NPM package", func() {
scope := TestScope
packageName := "test-scoped-package"
version := GetUniqueVersion(2)
// Generate the scoped package payload
packageData := generateNpmPackagePayload(packageName, version, true, scope)
// Set up the upload request for scoped package
req := client.NewRequest(
"PUT",
fmt.Sprintf("/npm/%s/%s/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
req.SetHeader("Content-Type", "application/json")
req.SetBody(packageData)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/06_error_handling_test.go | registry/tests/npm/06_error_handling_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 npmconformance
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test06ErrorHandling = func() {
ginkgo.Context("Error Handling", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestErrorHandling)
})
ginkgo.It("should return 404 for non-existent package metadata", func() {
nonExistentPackage := "non-existent-package-12345"
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, nonExistentPackage,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
ginkgo.It("should return 404 for non-existent package file download", func() {
nonExistentPackage := "non-existent-package-54321"
version := "1.0.0"
filename := fmt.Sprintf("%s-%s.tgz", nonExistentPackage, version)
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/%s/-/%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, nonExistentPackage, version, filename,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
ginkgo.It("should return 404 for non-existent scoped package", func() {
scope := "nonexistent"
packageName := "test-package"
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
ginkgo.It("should return empty object for non-existent package tags", func() {
nonExistentPackage := "non-existent-tags-package"
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/",
TestConfig.Namespace, TestConfig.RegistryName, nonExistentPackage,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
// Verify response body is empty object
body := resp.Body
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(string(body)).To(gomega.Equal("{}"))
})
ginkgo.It("should return 404 when trying to delete non-existent tag", func() {
packageName := GetUniquePackageName("delete-nonexistent-tag", 2)
version := GetUniqueVersion(2)
nonExistentTag := "nonexistent-tag"
// First upload a package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Try to delete non-existent tag
deleteTagReq := client.NewRequest(
"DELETE",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, nonExistentTag,
),
)
_, err = client.Do(deleteTagReq)
gomega.Expect(err).To(gomega.BeNil())
})
ginkgo.It("should handle invalid version format in tag operations", func() {
packageName := GetUniquePackageName("invalid-version", 3)
version := GetUniqueVersion(3)
invalidVersion := "not-a-valid-version"
// First upload a package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Try to add tag with invalid version
addTagReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/beta",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
addTagReq.SetHeader("Content-Type", "application/json")
addTagReq.SetBody(fmt.Sprintf(`"%s"`, invalidVersion))
addTagResp, err := client.Do(addTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(addTagResp.StatusCode).To(gomega.Equal(404)) // Bad Request, Not Found, or Unprocessable Entity
})
ginkgo.It("should return 404 for HEAD request on non-existent file", func() {
nonExistentPackage := "non-existent-head-test"
filename := "nonexistent-file.tgz"
req := client.NewRequest(
"HEAD",
fmt.Sprintf("/pkg/%s/%s/npm/%s/-/%s",
TestConfig.Namespace, TestConfig.RegistryName, nonExistentPackage, filename,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(string(resp.Body)).To(gomega.Equal(""))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/config.go | registry/tests/npm/config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmconformance
import (
"fmt"
"os"
"time"
)
// Config holds the test configuration.
type Config struct {
RootURL string
Username string
Password string
Namespace string
RegistryName string
Debug bool
DisabledTests map[string]bool
StartTime int64 // Used to generate unique versions.
}
// TestCategory represents different test categories.
type TestCategory string
const (
TestUpload TestCategory = "upload"
TestDownload TestCategory = "download"
TestMetadata TestCategory = "metadata"
TestTagOperations TestCategory = "tag_operations"
TestScopedPackages TestCategory = "scoped_packages"
TestErrorHandling TestCategory = "error_handling"
TestSearch TestCategory = "search"
)
var (
// TestConfig holds the global test configuration.
TestConfig Config
)
// InitConfig initializes the test configuration.
func InitConfig() {
// For Gitness integration, we need to ensure values are properly set.
// to work with the Gitness server structure.
TestConfig = Config{
// Base URL for the Gitness server.
RootURL: getEnv("REGISTRY_ROOT_URL", ""),
// Use admin@gitness.io as per .local.env configuration.
Username: getEnv("REGISTRY_USERNAME", ""),
// Password will be filled by setup_test.sh via token authentication
Password: getEnv("REGISTRY_PASSWORD", ""),
// These values come from setup_test.sh.
Namespace: getEnv("REGISTRY_NAMESPACE", ""),
RegistryName: getEnv("REGISTRY_NAME", ""),
// Enable debug to see detailed logs.
Debug: getEnv("DEBUG", "true") == "true",
// Store start time for unique version generation.
StartTime: time.Now().Unix(),
// All tests are now enabled
DisabledTests: map[string]bool{},
}
}
// IsTestEnabled checks if a test category is enabled.
func IsTestEnabled(category TestCategory) bool {
return !TestConfig.DisabledTests[string(category)]
}
func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
// GetUniqueVersion generates a unique version string for tests.
// Each test should call this with a different test ID to ensure uniqueness.
func GetUniqueVersion(testID int) string {
return fmt.Sprintf("1.0.%d-%d", TestConfig.StartTime, testID)
}
// GetUniquePackageName generates a unique package name for tests.
// This ensures that different test contexts don't conflict with each other.
func GetUniquePackageName(testContext string, testID int) string {
return fmt.Sprintf("test-npm-package-%s-%d-%d", testContext, TestConfig.StartTime, testID)
}
// GetUniqueScopedPackageName generates a unique scoped package name for tests.
func GetUniqueScopedPackageName(scope, testContext string, testID int) string {
return fmt.Sprintf("@%s/test-npm-package-%s-%d-%d", scope, testContext, TestConfig.StartTime, testID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/02_download_test.go | registry/tests/npm/02_download_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 npmconformance
import (
"encoding/base64"
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test02Download = func() {
ginkgo.Context("Download", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestDownload)
})
ginkgo.It("should download a non-scoped NPM package file", func() {
packageName := GetUniquePackageName("download", 1)
version := GetUniqueVersion(1)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// Generate expected tarball content for validation
expectedTarballContent := fmt.Sprintf(`{"name":"%s","version":"%s","main":"index.js"}`, packageName, version)
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now download the package file
downloadReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/%s/-/%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version, filename,
),
)
downloadResp, err := client.Do(downloadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(downloadResp.StatusCode).To(gomega.Equal(200))
gomega.Expect(downloadResp.Headers.Get("Content-Disposition")).To(
gomega.ContainSubstring(fmt.Sprintf("filename=%s", filename)))
// Validate file content
gomega.Expect(downloadResp.Body).ToNot(gomega.BeEmpty(), "Downloaded file should not be empty")
// The downloaded content should be the base64-decoded tarball content
// Since we're mocking the tarball as JSON content, we can validate it directly
downloadedContent := string(downloadResp.Body)
// Try to decode as base64 first (in case the server returns base64-encoded content)
if decodedContent, err := base64.StdEncoding.DecodeString(downloadedContent); err == nil {
downloadedContent = string(decodedContent)
}
// Validate that the downloaded content matches what we uploaded
gomega.Expect(downloadedContent).To(gomega.Equal(expectedTarballContent),
"Downloaded file content should match the uploaded tarball content")
// Validate Content-Disposition header contains the correct filename
gomega.Expect(downloadResp.Headers.Get("Content-Disposition")).To(
gomega.ContainSubstring(fmt.Sprintf("filename=%s", filename)))
})
ginkgo.It("should download a scoped NPM package file", func() {
scope := TestScope
packageName := "test-scoped-download"
version := GetUniqueVersion(2)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// First upload the scoped package
packageData := generateNpmPackagePayload(packageName, version, true, scope)
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now download the scoped package file
downloadReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/-/%s/@%s/%s",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName, version, scope, filename,
),
)
downloadResp, err := client.Do(downloadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(downloadResp.StatusCode).To(gomega.Equal(200))
expectedFilename := fmt.Sprintf("filename=%s", "@"+scope+"/"+filename)
gomega.Expect(downloadResp.Headers.Get("Content-Disposition")).To(
gomega.ContainSubstring(expectedFilename))
})
ginkgo.It("should download package file by name", func() {
packageName := GetUniquePackageName("download-by-name", 3)
version := GetUniqueVersion(3)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now download the package file by name
downloadReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/%s/-/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, filename,
),
)
downloadResp, err := client.Do(downloadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(downloadResp.StatusCode).To(gomega.Equal(200))
gomega.Expect(downloadResp.Headers.Get("Content-Disposition")).To(
gomega.ContainSubstring(fmt.Sprintf("filename=%s", filename)))
})
ginkgo.It("should perform HEAD request on package file", func() {
packageName := GetUniquePackageName("head-test", 4)
version := GetUniqueVersion(4)
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now perform HEAD request
headReq := client.NewRequest(
"HEAD",
fmt.Sprintf("/pkg/%s/%s/npm/%s/-/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, filename,
),
)
headResp, err := client.Do(headReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(headResp.StatusCode).To(gomega.Equal(200))
gomega.Expect(len(headResp.Body)).To(gomega.Equal(0)) // HEAD should not return body
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/reporter.go | registry/tests/npm/reporter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmconformance
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/onsi/ginkgo/v2/types"
)
// Status constants for test results.
const (
StatusPassed = "passed"
StatusFailed = "failed"
StatusSkipped = "skipped"
StatusPending = "pending"
)
// TestResult represents a single test result.
type TestResult struct {
Name string `json:"name"`
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
// TestReport represents the overall test report.
type TestReport struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
TestResults []TestResult `json:"test_results"`
Summary struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Skipped int `json:"skipped"`
Total int `json:"total"`
} `json:"summary"`
}
var (
report = TestReport{
StartTime: time.Now(),
TestResults: make([]TestResult, 0),
}
)
// ReportTest adds a test result to the report.
func ReportTest(name string, status string, err error) {
// Create detailed output with available information.
detailedOutput := fmt.Sprintf("Test: %s\nStatus: %s\n", name, status)
detailedOutput += fmt.Sprintf("Time: %s\n", time.Now().Format(time.RFC3339))
// Add more context based on test status.
switch status {
case StatusPassed:
detailedOutput += "Result: Test completed successfully\n"
case StatusFailed:
detailedOutput += "Result: Test failed with errors\n"
case StatusSkipped:
detailedOutput += "Result: Test was skipped\n"
case StatusPending:
detailedOutput += "Result: Test is pending implementation\n"
}
// Create a new test result with detailed information.
result := TestResult{
Name: name,
Status: status,
StartTime: time.Now(),
EndTime: time.Now(),
Output: detailedOutput,
}
// Capture error information if available.
if err != nil {
result.Error = err.Error()
result.Output += fmt.Sprintf("Error: %v\n", err)
// Add stack trace or additional context if available.
log.Printf("Test failed: %s - %v", name, err)
}
// Add the result to the report.
report.TestResults = append(report.TestResults, result)
}
// SaveReport saves the test report to a file.
// If logSummary is true, a summary of test results will be logged to stdout.
func SaveReport(filename string, logSummary bool) error {
// Update summary statistics.
report.EndTime = time.Now()
report.Summary.Passed = 0
report.Summary.Failed = 0
report.Summary.Skipped = 0
report.Summary.Pending = 0
report.Summary.Total = len(report.TestResults)
// Count test results by status.
for _, result := range report.TestResults {
switch result.Status {
case StatusPassed:
report.Summary.Passed++
case StatusFailed:
report.Summary.Failed++
case StatusSkipped:
report.Summary.Skipped++
case StatusPending:
report.Summary.Pending++
}
}
// Generate JSON report.
data, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal report: %w", err)
}
// Write the JSON report to file.
if err := os.WriteFile(filename, data, 0600); err != nil {
return err
}
// Log the summary only if requested.
if logSummary {
log.Printf("NPM test results: %d passed, %d failed, %d pending, %d skipped (total: %d)",
report.Summary.Passed, report.Summary.Failed, report.Summary.Pending,
report.Summary.Skipped, report.Summary.Total)
}
return nil
}
// ReporterHook implements ginkgo's Reporter interface.
type ReporterHook struct{}
func (r *ReporterHook) SuiteWillBegin() {
report.StartTime = time.Now()
}
func (r *ReporterHook) SuiteDidEnd() {
report.EndTime = time.Now()
// Pass true to log summary in the ReporterHook context.
if err := SaveReport("npm_conformance_report.json", true); err != nil {
log.Printf("Failed to save report: %v\n", err)
}
}
func (r *ReporterHook) SpecDidComplete(text string, state types.SpecState, failure error) {
// Determine test status.
var status string
switch state {
case types.SpecStateSkipped:
status = StatusSkipped
case types.SpecStateFailed:
status = StatusFailed
case types.SpecStatePending:
status = StatusPending
case types.SpecStatePassed:
status = StatusPassed
case types.SpecStateInvalid, types.SpecStateAborted, types.SpecStatePanicked,
types.SpecStateInterrupted, types.SpecStateTimedout:
status = StatusFailed
}
// Log detailed test information.
log.Printf("Test completed: %s - %s", text, status)
// Report the test with detailed information.
ReportTest(text, status, failure)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/04_tag_operations_test.go | registry/tests/npm/04_tag_operations_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 npmconformance
import (
"encoding/json"
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test04TagOperations = func() {
ginkgo.Context("Tag Operations", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestTagOperations)
})
ginkgo.It("should list package tags for non-scoped package", func() {
packageName := GetUniquePackageName("tags", 1)
version := GetUniqueVersion(1)
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now list tags
tagsReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
tagsResp, err := client.Do(tagsReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tagsResp.StatusCode).To(gomega.Equal(200))
// Verify tags structure
var tags map[string]string
err = json.Unmarshal(tagsResp.Body, &tags)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tags).To(gomega.HaveKeyWithValue("latest", version))
})
ginkgo.It("should add a new tag to non-scoped package", func() {
packageName := GetUniquePackageName("add-tag", 2)
version := GetUniqueVersion(2)
newTag := "beta"
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Add new tag
addTagReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, newTag,
),
)
addTagReq.SetHeader("Content-Type", "application/json")
addTagReq.SetBody(fmt.Sprintf(`"%s"`, version))
addTagResp, err := client.Do(addTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(addTagResp.StatusCode).To(gomega.Equal(200))
// Verify tag was added
tagsReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
tagsResp, err := client.Do(tagsReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tagsResp.StatusCode).To(gomega.Equal(200))
var tags map[string]string
err = json.Unmarshal(tagsResp.Body, &tags)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tags).To(gomega.HaveKeyWithValue(newTag, version))
})
ginkgo.It("should delete a tag from non-scoped package", func() {
packageName := GetUniquePackageName("delete-tag", 3)
version := GetUniqueVersion(3)
tagToDelete := "beta"
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Add tag first
addTagReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, tagToDelete,
),
)
addTagReq.SetHeader("Content-Type", "application/json")
addTagReq.SetBody(fmt.Sprintf(`"%s"`, version))
addTagResp, err := client.Do(addTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(addTagResp.StatusCode).To(gomega.Equal(200))
// Now delete the tag
deleteTagReq := client.NewRequest(
"DELETE",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, packageName, tagToDelete,
),
)
deleteTagResp, err := client.Do(deleteTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(deleteTagResp.StatusCode).To(gomega.Equal(200))
// Verify tag was deleted
tagsReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/%s/dist-tags/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
tagsResp, err := client.Do(tagsReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tagsResp.StatusCode).To(gomega.Equal(200))
var tags map[string]string
err = json.Unmarshal(tagsResp.Body, &tags)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tags).ToNot(gomega.HaveKey(tagToDelete))
})
ginkgo.It("should handle tag operations for scoped packages", func() {
scope := TestScope
packageName := "test-scoped-tags"
version := GetUniqueVersion(4)
newTag := "alpha"
// First upload the scoped package
packageData := generateNpmPackagePayload(packageName, version, true, scope)
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// List tags for scoped package
tagsReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/@%s/%s/dist-tags/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
tagsResp, err := client.Do(tagsReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tagsResp.StatusCode).To(gomega.Equal(200))
var tags map[string]string
err = json.Unmarshal(tagsResp.Body, &tags)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(tags).To(gomega.HaveKeyWithValue("latest", version))
// Add new tag to scoped package
addTagReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/-/package/@%s/%s/dist-tags/%s",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName, newTag,
),
)
addTagReq.SetHeader("Content-Type", "application/json")
addTagReq.SetBody(fmt.Sprintf(`"%s"`, version))
addTagResp, err := client.Do(addTagReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(addTagResp.StatusCode).To(gomega.Equal(200))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/03_metadata_test.go | registry/tests/npm/03_metadata_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 npmconformance
import (
"encoding/json"
"fmt"
"github.com/harness/gitness/registry/app/metadata/npm"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test03Metadata = func() {
ginkgo.Context("Metadata", func() {
ginkgo.BeforeEach(func() {
SkipIfDisabled(TestMetadata)
})
ginkgo.It("should retrieve package metadata for non-scoped package", func() {
packageName := GetUniquePackageName("metadata", 1)
version := GetUniqueVersion(1)
// First upload the package
packageData := generateNpmPackagePayload(packageName, version, false, "")
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now retrieve metadata
metadataReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/%s/",
TestConfig.Namespace, TestConfig.RegistryName, packageName,
),
)
metadataResp, err := client.Do(metadataReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadataResp.StatusCode).To(gomega.Equal(200))
// Verify metadata structure
var metadata npm.PackageMetadata
err = json.Unmarshal(metadataResp.Body, &metadata)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadata.Name).To(gomega.Equal(packageName))
gomega.Expect(metadata.Versions).To(gomega.HaveKey(version))
gomega.Expect(metadata.DistTags).To(gomega.HaveKeyWithValue("latest", version))
})
ginkgo.It("should retrieve package metadata for scoped package", func() {
scope := TestScope
packageName := "test-scoped-metadata"
version := GetUniqueVersion(2)
fullName := fmt.Sprintf("@%s/%s", scope, packageName)
// First upload the scoped package
packageData := generateNpmPackagePayload(packageName, version, true, scope)
uploadReq := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
uploadReq.SetHeader("Content-Type", "application/json")
uploadReq.SetBody(packageData)
uploadResp, err := client.Do(uploadReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(uploadResp.StatusCode).To(gomega.Equal(200))
// Now retrieve metadata
metadataReq := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/npm/@%s/%s/",
TestConfig.Namespace, TestConfig.RegistryName, scope, packageName,
),
)
metadataResp, err := client.Do(metadataReq)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadataResp.StatusCode).To(gomega.Equal(200))
// Verify metadata structure
var metadata npm.PackageMetadata
err = json.Unmarshal(metadataResp.Body, &metadata)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(metadata.Name).To(gomega.Equal(fullName))
gomega.Expect(metadata.Versions).To(gomega.HaveKey(version))
gomega.Expect(metadata.DistTags).To(gomega.HaveKeyWithValue("latest", version))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/reporter_init.go | registry/tests/npm/reporter_init.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmconformance
import (
"log"
"github.com/onsi/ginkgo/v2"
)
func init() {
// Register a reporter hook with Ginkgo.
ginkgo.ReportAfterSuite("NPM Conformance Report", func(_ ginkgo.Report) {
// Save the report when the suite is done.
// Pass false to avoid duplicate logging from the shell script.
if err := SaveReport("npm_conformance_report.json", false); err != nil {
// Log error but don't fail the test.
log.Printf("Failed to save report: %v", err)
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/00_conformance_suite_test.go | registry/tests/npm/00_conformance_suite_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 npmconformance
import (
"fmt"
"testing"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var (
client *conformanceutils.Client
)
func TestNpmConformance(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "NPM Registry Conformance Test Suite")
}
var _ = ginkgo.BeforeSuite(func() {
InitConfig()
// Log authentication details for debugging
ginkgo.By("Initializing NPM client with configuration")
ginkgo.By(fmt.Sprintf("RootURL: %s", TestConfig.RootURL))
ginkgo.By(fmt.Sprintf("Username: %s", TestConfig.Username))
ginkgo.By(fmt.Sprintf("Namespace: %s", TestConfig.Namespace))
ginkgo.By(fmt.Sprintf("RegistryName: %s", TestConfig.RegistryName))
ginkgo.By(fmt.Sprintf("Password/Token available: %t", TestConfig.Password != ""))
// Ensure we have a valid token.
if TestConfig.Password == "" {
ginkgo.Skip("Skipping integration tests: REGISTRY_PASSWORD environment variable not set")
}
// Initialize client with auth token.
client = conformanceutils.NewClient(TestConfig.RootURL, TestConfig.Password, TestConfig.Debug)
// Create registry if it doesn't exist
ginkgo.By("Creating NPM registry for conformance tests")
})
var _ = ginkgo.Describe("NPM Registry Conformance Tests", func() {
// Test categories will be defined in separate files.
test01Upload()
test02Download()
test03Metadata()
test04TagOperations()
test05ScopedPackages()
test06ErrorHandling()
})
// SkipIfDisabled skips the test if the category is disabled.
func SkipIfDisabled(category TestCategory) {
if !IsTestEnabled(category) {
ginkgo.Skip(string(category) + " tests are disabled")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/npm/helpers.go | registry/tests/npm/helpers.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package npmconformance
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/harness/gitness/registry/app/metadata/npm"
)
// TestScope is the default scope used for scoped package testing.
const TestScope = "testscope"
// generateNpmPackagePayload creates a mock NPM package payload for testing.
func generateNpmPackagePayload(packageName, version string, isScoped bool, scope string) string {
var fullName string
if isScoped {
fullName = fmt.Sprintf("@%s/%s", scope, packageName)
} else {
fullName = packageName
}
// Create mock tarball content
tarballContent := fmt.Sprintf(`{"name":"%s","version":"%s","main":"index.js"}`, fullName, version)
encodedTarball := base64.StdEncoding.EncodeToString([]byte(tarballContent))
filename := fmt.Sprintf("%s-%s.tgz", packageName, version)
if isScoped {
filename = fmt.Sprintf("%s-%s.tgz", packageName, version)
}
payload := npm.PackageUpload{
PackageMetadata: npm.PackageMetadata{
ID: fullName,
Name: fullName,
Description: "Test package for conformance testing",
DistTags: map[string]string{
"latest": version,
},
Versions: map[string]*npm.PackageMetadataVersion{
version: {
Name: fullName,
Version: version,
Description: "Test package for conformance testing",
Keywords: []string{"test", "conformance"},
Author: "Harness Test Suite",
License: "MIT",
Dist: npm.PackageDistribution{
Integrity: "sha512-test",
Shasum: "testsha",
Tarball: fmt.Sprintf("http://localhost/%s/-/%s", fullName, filename),
},
},
},
},
Attachments: map[string]*npm.PackageAttachment{
filename: {
ContentType: "application/octet-stream",
Data: encodedTarball,
Length: len(tarballContent),
},
},
}
jsonData, _ := json.Marshal(payload)
return string(jsonData)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/04_error_test.go | registry/tests/gopkg/04_error_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 gopkgconformance
import (
"fmt"
"log"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test04ErrorHandling = func() {
ginkgo.Context("Error Handling", func() {
ginkgo.Context("Invalid Requests", func() {
ginkgo.It("should reject invalid artifact path", func() {
path := fmt.Sprintf("/pkg/%s/%s/go/invalid/path",
TestConfig.Namespace,
TestConfig.RegistryName)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
log.Printf("Response for invalid path: %d %s\n",
resp.StatusCode, string(resp.Body))
log.Printf("Response Headers: %v\n", resp.Headers)
gomega.Expect(resp.StatusCode).To(gomega.Equal(404)) // bad request for invalid path
})
})
ginkgo.Context("Authentication", func() {
ginkgo.It("should reject unauthorized access", func() {
// Create a new client with invalid credentials.
invalidClient := conformanceutils.NewClient(TestConfig.RootURL, "invalid", TestConfig.Debug)
path := fmt.Sprintf("/pkg/%s/%s/go/example.com/test/@v/v1.0.0.zip",
TestConfig.Namespace,
TestConfig.RegistryName)
req := invalidClient.NewRequest("GET", path)
resp, err := invalidClient.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(401))
})
ginkgo.It("should reject access to non-existent space", func() {
path := fmt.Sprintf("/pkg/nonexistent/%s/go/example.com/test/@v/v1.0.0.zip",
TestConfig.RegistryName)
log.Printf("Testing path: %s\n", path)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
gomega.Expect(resp.Headers.Get("Content-Type")).To(
gomega.Equal("application/json; charset=utf-8"))
gomega.Expect(string(resp.Body)).To(gomega.ContainSubstring("Root not found: nonexistent"))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/02_upload_test.go | registry/tests/gopkg/02_upload_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.
// registry/tests/gopkg/02_upload_test.go
package gopkgconformance
import (
"bytes"
"fmt"
"mime/multipart"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
type UploadFormData struct {
body []byte
contentType string
}
type PackageInfo struct {
Version string `json:"version"`
Time string `json:"time"`
}
var test02Upload = func() {
ginkgo.Context("Upload", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestUpload) {
ginkgo.Skip("Upload tests are disabled")
}
})
ginkgo.It("should upload a Go package", func() {
// Use a unique package name and version for this test
packageName := GetUniqueArtifactName("go", 2)
version := GetUniqueVersion(2)
// Generate the package payload
formData := generateGoPackagePayload(packageName, version)
// Set up the upload request
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/go/upload",
TestConfig.Namespace, TestConfig.RegistryName,
),
)
req.SetHeader("Content-Type", formData.contentType)
req.SetBody(formData.body)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
})
})
}
func generateGoPackagePayload(packageName string, version string) *UploadFormData {
// create form and add 3 files with form keys mod, info and .zip
// Buffer to hold multipart body
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// Add dummy .mod file
addFile(writer, "mod", version+".mod", "module "+packageName+"\n")
// Add dummy .info file
addFile(writer, "info", version+".info", `{"Version":"`+version+`","Time":"2023-01-01T00:00:00Z"}`)
// Add dummy .zip file
addFile(writer, "zip", version+".zip", "mock package content") // Zip header or dummy content
// Close the multipart writer to set final boundary
writer.Close()
return &UploadFormData{
body: body.Bytes(),
contentType: writer.FormDataContentType(),
}
}
// Helper to add a form file with string content.
func addFile(writer *multipart.Writer, fieldName, fileName, content string) {
part, err := writer.CreateFormFile(fieldName, fileName)
gomega.Expect(err).To(gomega.BeNil())
_, err = part.Write([]byte(content))
gomega.Expect(err).To(gomega.BeNil())
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/01_download_test.go | registry/tests/gopkg/01_download_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 gopkgconformance
import (
"encoding/json"
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test01Download = func() {
ginkgo.Context("Download", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestDownload) {
ginkgo.Skip("Download tests are disabled")
}
})
ginkgo.It("should download an artifact", func() {
// Upload an artifact first.
// Use a unique package name and version for this test
packageName := GetUniqueArtifactName("go", 1)
version := GetUniqueVersion(1)
// Generate the package payload
formData := generateGoPackagePayload(packageName, version)
// Set up the upload request
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/go/upload",
TestConfig.Namespace, TestConfig.RegistryName,
),
)
req.SetHeader("Content-Type", formData.contentType)
req.SetBody(formData.body)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
// Now download mod file.
path := fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.mod",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(string(resp.Body)).To(gomega.Equal("module " + packageName + "\n"))
// Now download info file.
path = fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.info",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
var response PackageInfo
err = json.Unmarshal(resp.Body, &response)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(response.Version).To(gomega.Equal(version))
gomega.Expect(response.Time).To(gomega.Equal("2023-01-01T00:00:00Z"))
// Now download zip file.
path = fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.zip",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("application/zip"))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock package content"))
})
ginkgo.It("should download an artifact from upstream", func() {
packageName := "golang.org/x/time"
version := "v0.9.0"
// get package index
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.mod",
TestConfig.Namespace, TestConfig.RegistryName,
packageName, version,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
gomega.Expect(err).To(gomega.BeNil())
// Now download info file.
path := fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.info",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
// Now download zip file.
path = fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.zip",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("application/zip"))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/config.go | registry/tests/gopkg/config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopkgconformance
import (
"fmt"
"os"
"time"
)
// Config holds the test configuration.
type Config struct {
RootURL string
Username string
Password string
Namespace string
RegistryName string
Debug bool
DisabledTests map[string]bool
StartTime int64 // Used to generate unique versions.
}
// TestCategory represents different test categories.
type TestCategory string
const (
TestDownload TestCategory = "download"
TestUpload TestCategory = "upload"
TestContentDiscovery TestCategory = "content_discovery"
TestErrorHandling TestCategory = "error_handling"
)
var (
// TestConfig holds the global test configuration.
TestConfig Config
)
// InitConfig initializes the test configuration.
func InitConfig() {
// For Gitness integration, we need to ensure values are properly set.
// to work with the Gitness server structure.
TestConfig = Config{
// Base URL for the Gitness server.
RootURL: getEnv("REGISTRY_ROOT_URL", "http://localhost:3000"),
// Use admin@gitness.io as per .local.env configuration.
Username: getEnv("REGISTRY_USERNAME", "admin@gitness.io"),
// Password will be filled by setup_test.sh via token authentication
Password: getEnv("REGISTRY_PASSWORD", ""),
// These values come from setup_test.sh.
Namespace: getEnv("REGISTRY_NAMESPACE", ""),
RegistryName: getEnv("REGISTRY_NAME", ""),
// Enable debug to see detailed logs.
Debug: getEnv("DEBUG", "true") == "true",
// Store start time for unique version generation.
StartTime: time.Now().Unix(),
// All tests are now enabled
DisabledTests: map[string]bool{},
}
}
// IsTestEnabled checks if a test category is enabled.
func IsTestEnabled(category TestCategory) bool {
return !TestConfig.DisabledTests[string(category)]
}
func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
// GetUniqueVersion generates a unique version string for tests.
// Each test should call this with a different test ID to ensure uniqueness.
func GetUniqueVersion(testID int) string {
return fmt.Sprintf("1.0.%d-%d", TestConfig.StartTime, testID)
}
// GetUniqueArtifactName generates a unique artifact name for tests.
// This ensures that different test contexts don't conflict with each other.
func GetUniqueArtifactName(testContext string, testID int) string {
return fmt.Sprintf("test-artifact-%s-%d-%d", testContext, TestConfig.StartTime, testID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/03_content_discovery_test.go | registry/tests/gopkg/03_content_discovery_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 gopkgconformance
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test03ContentDiscovery = func() {
ginkgo.Context("Content Discovery", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestContentDiscovery) {
ginkgo.Skip("Content discovery tests are disabled")
}
})
ginkgo.Context("Basic Content Discovery", ginkgo.Ordered, func() {
// Define variables at the context level so they're accessible to all tests.
var artifactName string
var version1, version2 string
// Use BeforeAll to set up artifacts just once for all tests in this context.
ginkgo.BeforeAll(func() {
// Define unique artifact name for this test context with random component
artifactName = GetUniqueArtifactName("discovery", int(time.Now().UnixNano()%1000))
// Define test versions that will be used across all tests in this context.
version1 = GetUniqueVersion(10)
version2 = GetUniqueVersion(11)
// Upload test artifacts with unique names and versions.
artifacts := []*UploadFormData{
generateGoPackagePayload(artifactName, version1),
generateGoPackagePayload(artifactName, version2),
}
for _, artifact := range artifacts {
artifactPath := fmt.Sprintf("/pkg/%s/%s/go/upload",
TestConfig.Namespace, TestConfig.RegistryName,
)
req := client.NewRequest("PUT", artifactPath)
req.SetHeader("Content-Type", artifact.contentType)
req.SetBody(artifact.body)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
}
time.Sleep(2 * time.Second)
})
ginkgo.It("should find all versions in package index", func() {
// Use the unique artifact name and version defined earlier.
path := fmt.Sprintf("/pkg/%s/%s/go/%s/@v/list",
TestConfig.Namespace,
TestConfig.RegistryName,
artifactName,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(string(resp.Body)).Should(gomega.ContainSubstring(version1))
gomega.Expect(string(resp.Body)).Should(gomega.ContainSubstring(version2))
})
ginkgo.It("should handle non-existent artifacts", func() {
// Use a completely different artifact name and version for non-existent artifact.
nonExistentArtifact := GetUniqueArtifactName("nonexistent", 99)
nonExistentVersion := GetUniqueVersion(99)
// verify package index
path := fmt.Sprintf("/pkg/%s/%s/go/%s/@v/%s.mod",
TestConfig.Namespace, TestConfig.RegistryName,
nonExistentArtifact, nonExistentVersion,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/reporter.go | registry/tests/gopkg/reporter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopkgconformance
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/onsi/ginkgo/v2/types"
)
// Status constants for test results.
const (
StatusPassed = "passed"
StatusFailed = "failed"
StatusSkipped = "skipped"
StatusPending = "pending"
)
// TestResult represents a single test result.
type TestResult struct {
Name string `json:"name"`
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
// TestReport represents the overall test report.
type TestReport struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
TestResults []TestResult `json:"test_results"`
Summary struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Skipped int `json:"skipped"`
Total int `json:"total"`
} `json:"summary"`
}
var (
report = TestReport{
StartTime: time.Now(),
TestResults: make([]TestResult, 0),
}
)
// ReportTest adds a test result to the report.
func ReportTest(name string, status string, err error) {
// Create detailed output with available information.
detailedOutput := fmt.Sprintf("Test: %s\nStatus: %s\n", name, status)
detailedOutput += fmt.Sprintf("Time: %s\n", time.Now().Format(time.RFC3339))
// Add more context based on test status.
switch status {
case StatusPassed:
detailedOutput += "Result: Test completed successfully\n"
case StatusFailed:
detailedOutput += "Result: Test failed with errors\n"
case StatusSkipped:
detailedOutput += "Result: Test was skipped\n"
case StatusPending:
detailedOutput += "Result: Test is pending implementation\n"
}
// Create a new test result with detailed information.
result := TestResult{
Name: name,
Status: status,
StartTime: time.Now(),
EndTime: time.Now(),
Output: detailedOutput,
}
// Capture error information if available.
if err != nil {
result.Error = err.Error()
result.Output += fmt.Sprintf("Error: %v\n", err)
// Add stack trace or additional context if available.
log.Printf("Test failed: %s - %v", name, err)
}
// Add the result to the report.
report.TestResults = append(report.TestResults, result)
}
// SaveReport saves the test report to a file.
// If logSummary is true, a summary of test results will be logged to stdout.
func SaveReport(filename string, logSummary bool) error {
// Update summary statistics.
report.EndTime = time.Now()
report.Summary.Passed = 0
report.Summary.Failed = 0
report.Summary.Skipped = 0
report.Summary.Pending = 0
report.Summary.Total = len(report.TestResults)
// Count test results by status.
for _, result := range report.TestResults {
switch result.Status {
case StatusPassed:
report.Summary.Passed++
case StatusFailed:
report.Summary.Failed++
case StatusSkipped:
report.Summary.Skipped++
case StatusPending:
report.Summary.Pending++
}
}
// Generate JSON report.
data, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal report: %w", err)
}
// Write the JSON report to file.
if err := os.WriteFile(filename, data, 0600); err != nil {
return err
}
// Log the summary only if requested.
if logSummary {
log.Printf("Go test results: %d passed, %d failed, %d pending, %d skipped (total: %d)",
report.Summary.Passed, report.Summary.Failed, report.Summary.Pending,
report.Summary.Skipped, report.Summary.Total)
}
return nil
}
// ReporterHook implements ginkgo's Reporter interface.
type ReporterHook struct{}
func (r *ReporterHook) SuiteWillBegin() {
report.StartTime = time.Now()
}
func (r *ReporterHook) SuiteDidEnd() {
report.EndTime = time.Now()
// Pass true to log summary in the ReporterHook context.
if err := SaveReport("go_conformance_report.json", true); err != nil {
log.Printf("Failed to save report: %v\n", err)
}
}
func (r *ReporterHook) SpecDidComplete(text string, state types.SpecState, failure error) {
// Determine test status.
var status string
switch state {
case types.SpecStateSkipped:
status = StatusSkipped
case types.SpecStateFailed:
status = StatusFailed
case types.SpecStatePending:
status = StatusPending
case types.SpecStatePassed:
status = StatusPassed
case types.SpecStateInvalid, types.SpecStateAborted, types.SpecStatePanicked,
types.SpecStateInterrupted, types.SpecStateTimedout:
status = StatusFailed
}
// Log detailed test information.
log.Printf("Test completed: %s - %s", text, status)
// Report the test with detailed information.
ReportTest(text, status, failure)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/reporter_init.go | registry/tests/gopkg/reporter_init.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gopkgconformance
import (
"log"
"github.com/onsi/ginkgo/v2"
)
func init() {
// Register a reporter hook with Ginkgo.
ginkgo.ReportAfterSuite("Go Conformance Report", func(_ ginkgo.Report) {
// Save the report when the suite is done.
// Pass false to avoid duplicate logging from the shell script.
if err := SaveReport("go_conformance_report.json", false); err != nil {
// Log error but don't fail the test.
log.Printf("Failed to save report: %v", err)
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/gopkg/00_conformance_suite_test.go | registry/tests/gopkg/00_conformance_suite_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 gopkgconformance
import (
"fmt"
"testing"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var (
client *conformanceutils.Client
)
func TestGoPkgConformance(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "Go Package Registry Conformance Test Suite")
}
var _ = ginkgo.BeforeSuite(func() {
InitConfig()
// Log authentication details for debugging
ginkgo.By("Initializing Go Package client with configuration")
ginkgo.By(fmt.Sprintf("RootURL: %s", TestConfig.RootURL))
ginkgo.By(fmt.Sprintf("Username: %s", TestConfig.Username))
ginkgo.By(fmt.Sprintf("Namespace: %s", TestConfig.Namespace))
ginkgo.By(fmt.Sprintf("RegistryName: %s", TestConfig.RegistryName))
ginkgo.By(fmt.Sprintf("Password/Token available: %t", TestConfig.Password != ""))
// Ensure we have a valid token.
if TestConfig.Password == "" {
ginkgo.Skip("Skipping integration tests: REGISTRY_PASSWORD environment variable not set")
}
// Initialize client with auth token.
client = conformanceutils.NewClient(TestConfig.RootURL, TestConfig.Password, TestConfig.Debug)
})
var _ = ginkgo.Describe("Go Package Registry Conformance Tests", func() {
// Test categories will be defined in separate files.
test01Download()
test02Upload()
test03ContentDiscovery()
test04ErrorHandling()
})
// SkipIfDisabled skips the test if the category is disabled.
func SkipIfDisabled(category TestCategory) {
if !IsTestEnabled(category) {
ginkgo.Skip(string(category) + " tests are disabled")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/02_upload_test.go | registry/tests/cargo/02_upload_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.
// registry/tests/cargo/02_upload_test.go
package cargoconformance
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
type packageIndexMetadata struct {
Name string `json:"name"`
Version string `json:"vers"`
Cksum string `json:"cksum"`
Yanked bool `json:"yanked"`
}
var test02Upload = func() {
ginkgo.Context("Upload", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestUpload) {
ginkgo.Skip("Upload tests are disabled")
}
})
ginkgo.It("should upload a Cargo package", func() {
// Use a unique package name and version for this test
packageName := GetUniqueArtifactName("cargo", 2)
version := GetUniqueVersion(2)
// get package index
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
// Generate the package payload
body := generateCargoPackagePayload(packageName, version)
// Set up the upload request
req = client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/new",
TestConfig.Namespace, TestConfig.RegistryName,
),
)
req.SetHeader("Content-Type", "application/crate")
req.SetBody(body)
// Send the request and verify the response
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
time.Sleep(2 * time.Second)
// get package index
var indexArr []packageIndexMetadata
req = client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(http.StatusOK))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err = getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(len(indexArr)).To(gomega.Equal(1))
gomega.Expect(indexArr[0].Name).To(gomega.Equal(packageName))
gomega.Expect(indexArr[0].Version).To(gomega.Equal(version))
gomega.Expect(indexArr[0].Yanked).To(gomega.Equal(false))
})
})
}
func generateCargoPackagePayload(packageName string, version string) []byte {
// Create a test package file
packageBytes := []byte("mock package content")
// Create metadata for the package
metadata := map[string]string{
"name": packageName,
"vers": version,
}
metadataBytes, err := json.Marshal(metadata)
gomega.Expect(err).To(gomega.BeNil())
metadataLen := uint32(len(metadataBytes)) // #nosec G115
packageLen := uint32(len(packageBytes)) // #nosec G115
// Construct the request body according to the Cargo package upload format
body := make([]byte, 4+metadataLen+4+packageLen)
binary.LittleEndian.PutUint32(body[:4], metadataLen)
copy(body[4:], metadataBytes)
binary.LittleEndian.PutUint32(body[4+metadataLen:4+metadataLen+4], packageLen)
copy(body[4+metadataLen+4:], packageBytes)
return body
}
func getIndexFilePathFromImageName(imageName string) string {
length := len(imageName)
switch length {
case 0:
return imageName
case 1:
return fmt.Sprintf("index/1/%s", imageName)
case 2:
return fmt.Sprintf("index/2/%s", imageName)
case 3:
return fmt.Sprintf("index/3/%c/%s", imageName[0], imageName)
default:
return fmt.Sprintf("index/%s/%s/%s", imageName[0:2], imageName[2:4], imageName)
}
}
func getPackageIndexContentFromText(text string) ([]packageIndexMetadata, error) {
result := []packageIndexMetadata{}
for line := range strings.SplitSeq(text, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
var index packageIndexMetadata
err := json.Unmarshal([]byte(line), &index)
if err != nil {
return nil, fmt.Errorf("failed to parse line: %q, error: %w", line, err)
}
result = append(result, index)
}
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/tests/cargo/01_download_test.go | registry/tests/cargo/01_download_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 cargoconformance
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test01Download = func() {
ginkgo.Context("Download", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestDownload) {
ginkgo.Skip("Download tests are disabled")
}
})
ginkgo.It("should download an artifact", func() {
// Upload an artifact first.
// Use a unique package name and version for this test
packageName := GetUniqueArtifactName("cargo", 1)
version := GetUniqueVersion(1)
// Generate the package payload
body := generateCargoPackagePayload(packageName, version)
// Set up the upload request
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/new",
TestConfig.Namespace, TestConfig.RegistryName,
),
)
req.SetHeader("Content-Type", "application/crate")
req.SetBody(body)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
// Now download it.
path := fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/download",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock package content"))
})
ginkgo.It("should download an artifact from upstream", func() {
packageName := "quote"
version := "1.0.40"
// get package index
req := client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err := getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
// find package in indexArr with version
var packageInfo packageIndexMetadata
for _, pkg := range indexArr {
if pkg.Name == packageName && pkg.Version == version {
packageInfo = pkg
break
}
}
// check if packageInfo is empty
if packageInfo == (packageIndexMetadata{}) {
ginkgo.Fail("Package not found in index")
}
// Now download it.
path := fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/download",
TestConfig.Namespace, TestConfig.RegistryName, packageName, version,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("application/x-gzip"))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/03_update_yank_test.go | registry/tests/cargo/03_update_yank_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.
// registry/tests/cargo/02_upload_test.go
package cargoconformance
import (
"fmt"
"net/http"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test03UpdateYank = func() {
ginkgo.Context("Update Yank", func() {
var packageName string
var version string
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestUpdateYank) {
ginkgo.Skip("Update Yank tests are disabled")
}
})
ginkgo.It("should update yank to true for a Cargo package", func() {
// Use a unique package name and version for this test
packageName = GetUniqueArtifactName("cargo", 3)
version = GetUniqueVersion(3)
// Generate the package payload
body := generateCargoPackagePayload(packageName, version)
// Set up the upload request
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/new",
TestConfig.Namespace, TestConfig.RegistryName,
),
)
req.SetHeader("Content-Type", "application/crate")
req.SetBody(body)
// Send the request and verify the response
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
time.Sleep(2 * time.Second)
// get package index
var indexArr []packageIndexMetadata
req = client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(http.StatusOK))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err = getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(len(indexArr)).To(gomega.Equal(1))
gomega.Expect(indexArr[0].Name).To(gomega.Equal(packageName))
gomega.Expect(indexArr[0].Version).To(gomega.Equal(version))
gomega.Expect(indexArr[0].Yanked).To(gomega.Equal(false))
// update yank to true
req = client.NewRequest(
"DELETE",
fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/yank",
TestConfig.Namespace, TestConfig.RegistryName,
packageName, version,
),
)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
time.Sleep(2 * time.Second)
// get package index
req = client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err = getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(len(indexArr)).To(gomega.Equal(1))
gomega.Expect(indexArr[0].Name).To(gomega.Equal(packageName))
gomega.Expect(indexArr[0].Version).To(gomega.Equal(version))
gomega.Expect(indexArr[0].Yanked).To(gomega.Equal(true))
})
ginkgo.It("should update yank to false for a Cargo package", func() {
// update yank to false
req := client.NewRequest(
"PUT",
fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/unyank",
TestConfig.Namespace, TestConfig.RegistryName,
packageName, version,
),
)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
time.Sleep(2 * time.Second)
// get package index
req = client.NewRequest(
"GET",
fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(packageName),
),
)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err := getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(len(indexArr)).To(gomega.Equal(1))
gomega.Expect(indexArr[0].Name).To(gomega.Equal(packageName))
gomega.Expect(indexArr[0].Version).To(gomega.Equal(version))
gomega.Expect(indexArr[0].Yanked).To(gomega.Equal(false))
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/05_error_test.go | registry/tests/cargo/05_error_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 cargoconformance
import (
"fmt"
"log"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test05ErrorHandling = func() {
ginkgo.Context("Error Handling", func() {
ginkgo.Context("Invalid Requests", func() {
ginkgo.It("should reject invalid artifact path", func() {
path := fmt.Sprintf("/pkg/%s/%s/cargo/invalid/path",
TestConfig.Namespace,
TestConfig.RegistryName)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
log.Printf("Response for invalid path: %d %s\n",
resp.StatusCode, string(resp.Body))
log.Printf("Response Headers: %v\n", resp.Headers)
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
})
})
ginkgo.Context("Authentication", func() {
ginkgo.It("should reject unauthorized access", func() {
// Create a new client with invalid credentials.
invalidClient := conformanceutils.NewClient(TestConfig.RootURL, "invalid", TestConfig.Debug)
path := fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/test/1.0.0/download",
TestConfig.Namespace,
TestConfig.RegistryName)
req := invalidClient.NewRequest("GET", path)
resp, err := invalidClient.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(401))
})
ginkgo.It("should reject access to non-existent space", func() {
path := fmt.Sprintf("/pkg/nonexistent/%s/cargo/api/v1/crates/test/1.0.0/download",
TestConfig.RegistryName)
log.Printf("Testing path: %s\n", path)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
gomega.Expect(resp.Headers.Get("Content-Type")).To(
gomega.Equal("application/json; charset=utf-8"))
gomega.Expect(string(resp.Body)).To(gomega.ContainSubstring("Root not found: nonexistent"))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/config.go | registry/tests/cargo/config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargoconformance
import (
"fmt"
"os"
"time"
)
// Config holds the test configuration.
type Config struct {
RootURL string
Username string
Password string
Namespace string
RegistryName string
Debug bool
DisabledTests map[string]bool
StartTime int64 // Used to generate unique versions.
}
// TestCategory represents different test categories.
type TestCategory string
const (
TestDownload TestCategory = "download"
TestUpload TestCategory = "upload"
TestUpdateYank TestCategory = "update_yank"
TestContentDiscovery TestCategory = "content_discovery"
TestErrorHandling TestCategory = "error_handling"
)
var (
// TestConfig holds the global test configuration.
TestConfig Config
)
// InitConfig initializes the test configuration.
func InitConfig() {
// For Gitness integration, we need to ensure values are properly set.
// to work with the Gitness server structure.
TestConfig = Config{
// Base URL for the Gitness server.
RootURL: getEnv("REGISTRY_ROOT_URL", "http://localhost:3000"),
// Use admin@gitness.io as per .local.env configuration.
Username: getEnv("REGISTRY_USERNAME", "admin@gitness.io"),
// Password will be filled by setup_test.sh via token authentication
Password: getEnv("REGISTRY_PASSWORD", ""),
// These values come from setup_test.sh.
Namespace: getEnv("REGISTRY_NAMESPACE", ""),
RegistryName: getEnv("REGISTRY_NAME", ""),
// Enable debug to see detailed logs.
Debug: getEnv("DEBUG", "true") == "true",
// Store start time for unique version generation.
StartTime: time.Now().Unix(),
// All tests are now enabled
DisabledTests: map[string]bool{},
}
}
// IsTestEnabled checks if a test category is enabled.
func IsTestEnabled(category TestCategory) bool {
return !TestConfig.DisabledTests[string(category)]
}
func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
// GetUniqueVersion generates a unique version string for tests.
// Each test should call this with a different test ID to ensure uniqueness.
func GetUniqueVersion(testID int) string {
return fmt.Sprintf("1.0.%d-%d", TestConfig.StartTime, testID)
}
// GetUniqueArtifactName generates a unique artifact name for tests.
// This ensures that different test contexts don't conflict with each other.
func GetUniqueArtifactName(testContext string, testID int) string {
return fmt.Sprintf("test-artifact-%s-%d-%d", testContext, TestConfig.StartTime, testID)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/reporter.go | registry/tests/cargo/reporter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargoconformance
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/onsi/ginkgo/v2/types"
)
// Status constants for test results.
const (
StatusPassed = "passed"
StatusFailed = "failed"
StatusSkipped = "skipped"
StatusPending = "pending"
)
// TestResult represents a single test result.
type TestResult struct {
Name string `json:"name"`
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
// TestReport represents the overall test report.
type TestReport struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
TestResults []TestResult `json:"test_results"`
Summary struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Skipped int `json:"skipped"`
Total int `json:"total"`
} `json:"summary"`
}
var (
report = TestReport{
StartTime: time.Now(),
TestResults: make([]TestResult, 0),
}
)
// ReportTest adds a test result to the report.
func ReportTest(name string, status string, err error) {
// Create detailed output with available information.
detailedOutput := fmt.Sprintf("Test: %s\nStatus: %s\n", name, status)
detailedOutput += fmt.Sprintf("Time: %s\n", time.Now().Format(time.RFC3339))
// Add more context based on test status.
switch status {
case StatusPassed:
detailedOutput += "Result: Test completed successfully\n"
case StatusFailed:
detailedOutput += "Result: Test failed with errors\n"
case StatusSkipped:
detailedOutput += "Result: Test was skipped\n"
case StatusPending:
detailedOutput += "Result: Test is pending implementation\n"
}
// Create a new test result with detailed information.
result := TestResult{
Name: name,
Status: status,
StartTime: time.Now(),
EndTime: time.Now(),
Output: detailedOutput,
}
// Capture error information if available.
if err != nil {
result.Error = err.Error()
result.Output += fmt.Sprintf("Error: %v\n", err)
// Add stack trace or additional context if available.
log.Printf("Test failed: %s - %v", name, err)
}
// Add the result to the report.
report.TestResults = append(report.TestResults, result)
}
// SaveReport saves the test report to a file.
// If logSummary is true, a summary of test results will be logged to stdout.
func SaveReport(filename string, logSummary bool) error {
// Update summary statistics.
report.EndTime = time.Now()
report.Summary.Passed = 0
report.Summary.Failed = 0
report.Summary.Skipped = 0
report.Summary.Pending = 0
report.Summary.Total = len(report.TestResults)
// Count test results by status.
for _, result := range report.TestResults {
switch result.Status {
case StatusPassed:
report.Summary.Passed++
case StatusFailed:
report.Summary.Failed++
case StatusSkipped:
report.Summary.Skipped++
case StatusPending:
report.Summary.Pending++
}
}
// Generate JSON report.
data, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal report: %w", err)
}
// Write the JSON report to file.
if err := os.WriteFile(filename, data, 0600); err != nil {
return err
}
// Log the summary only if requested.
if logSummary {
log.Printf("Cargo test results: %d passed, %d failed, %d pending, %d skipped (total: %d)",
report.Summary.Passed, report.Summary.Failed, report.Summary.Pending,
report.Summary.Skipped, report.Summary.Total)
}
return nil
}
// ReporterHook implements ginkgo's Reporter interface.
type ReporterHook struct{}
func (r *ReporterHook) SuiteWillBegin() {
report.StartTime = time.Now()
}
func (r *ReporterHook) SuiteDidEnd() {
report.EndTime = time.Now()
// Pass true to log summary in the ReporterHook context.
if err := SaveReport("cargo_conformance_report.json", true); err != nil {
log.Printf("Failed to save report: %v\n", err)
}
}
func (r *ReporterHook) SpecDidComplete(text string, state types.SpecState, failure error) {
// Determine test status.
var status string
switch state {
case types.SpecStateSkipped:
status = StatusSkipped
case types.SpecStateFailed:
status = StatusFailed
case types.SpecStatePending:
status = StatusPending
case types.SpecStatePassed:
status = StatusPassed
case types.SpecStateInvalid, types.SpecStateAborted, types.SpecStatePanicked,
types.SpecStateInterrupted, types.SpecStateTimedout:
status = StatusFailed
}
// Log detailed test information.
log.Printf("Test completed: %s - %s", text, status)
// Report the test with detailed information.
ReportTest(text, status, failure)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/reporter_init.go | registry/tests/cargo/reporter_init.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cargoconformance
import (
"log"
"github.com/onsi/ginkgo/v2"
)
func init() {
// Register a reporter hook with Ginkgo.
ginkgo.ReportAfterSuite("Cargo Conformance Report", func(_ ginkgo.Report) {
// Save the report when the suite is done.
// Pass false to avoid duplicate logging from the shell script.
if err := SaveReport("cargo_conformance_report.json", false); err != nil {
// Log error but don't fail the test.
log.Printf("Failed to save report: %v", err)
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/00_conformance_suite_test.go | registry/tests/cargo/00_conformance_suite_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 cargoconformance
import (
"fmt"
"testing"
conformanceutils "github.com/harness/gitness/registry/tests/utils"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var (
client *conformanceutils.Client
)
func TestCargoConformance(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "Cargo Registry Conformance Test Suite")
}
var _ = ginkgo.BeforeSuite(func() {
InitConfig()
// Log authentication details for debugging
ginkgo.By("Initializing Cargo client with configuration")
ginkgo.By(fmt.Sprintf("RootURL: %s", TestConfig.RootURL))
ginkgo.By(fmt.Sprintf("Username: %s", TestConfig.Username))
ginkgo.By(fmt.Sprintf("Namespace: %s", TestConfig.Namespace))
ginkgo.By(fmt.Sprintf("RegistryName: %s", TestConfig.RegistryName))
ginkgo.By(fmt.Sprintf("Password/Token available: %t", TestConfig.Password != ""))
// Ensure we have a valid token.
if TestConfig.Password == "" {
ginkgo.Skip("Skipping integration tests: REGISTRY_PASSWORD environment variable not set")
}
// Initialize client with auth token.
client = conformanceutils.NewClient(TestConfig.RootURL, TestConfig.Password, TestConfig.Debug)
})
var _ = ginkgo.Describe("Cargo Registry Conformance Tests", func() {
// Test categories will be defined in separate files.
test01Download()
test02Upload()
test03UpdateYank()
test04ContentDiscovery()
test05ErrorHandling()
})
// SkipIfDisabled skips the test if the category is disabled.
func SkipIfDisabled(category TestCategory) {
if !IsTestEnabled(category) {
ginkgo.Skip(string(category) + " tests are disabled")
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/tests/cargo/04_content_discovery_test.go | registry/tests/cargo/04_content_discovery_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 cargoconformance
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
var test04ContentDiscovery = func() {
ginkgo.Context("Content Discovery", func() {
ginkgo.BeforeEach(func() {
if !IsTestEnabled(TestContentDiscovery) {
ginkgo.Skip("Content discovery tests are disabled")
}
})
ginkgo.Context("Basic Content Discovery", ginkgo.Ordered, func() {
// Define variables at the context level so they're accessible to all tests.
var artifactName string
var version1, version2 string
// Use BeforeAll to set up artifacts just once for all tests in this context.
ginkgo.BeforeAll(func() {
// Define unique artifact name for this test context with random component
artifactName = GetUniqueArtifactName("discovery", int(time.Now().UnixNano()%1000))
// Define test versions that will be used across all tests in this context.
version1 = GetUniqueVersion(10)
version2 = GetUniqueVersion(11)
// Upload test artifacts with unique names and versions.
artifacts := [][]byte{
generateCargoPackagePayload(artifactName, version1),
generateCargoPackagePayload(artifactName, version2),
}
for _, artifact := range artifacts {
artifactPath := fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/new",
TestConfig.Namespace, TestConfig.RegistryName,
)
contentType := "application/crate"
req := client.NewRequest("PUT", artifactPath)
req.SetHeader("Content-Type", contentType)
req.SetBody(artifact)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(201))
}
})
ginkgo.It("should find artifacts by version", func() {
// Use the unique artifact name and version defined earlier.
path := fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/download",
TestConfig.Namespace,
TestConfig.RegistryName,
artifactName,
version1,
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(string(resp.Body)).To(gomega.Equal("mock package content"))
})
ginkgo.It("should find all versions in package index", func() {
// Use the unique artifact name and version defined earlier.
time.Sleep(2 * time.Second)
var indexArr []packageIndexMetadata
path := fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(artifactName),
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(200))
gomega.Expect(resp.Headers.Get("Content-Type")).To(gomega.Equal("text/plain; charset=utf-8"))
indexArr, err = getPackageIndexContentFromText(string(resp.Body))
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(len(indexArr)).To(gomega.Equal(2))
gomega.Expect(indexArr[0].Name).To(gomega.Equal(artifactName))
gomega.Expect(indexArr[0].Version).To(gomega.Equal(version1))
gomega.Expect(indexArr[0].Yanked).To(gomega.Equal(false))
gomega.Expect(indexArr[1].Name).To(gomega.Equal(artifactName))
gomega.Expect(indexArr[1].Version).To(gomega.Equal(version2))
gomega.Expect(indexArr[1].Yanked).To(gomega.Equal(false))
})
ginkgo.It("should handle non-existent artifacts", func() {
// Use a completely different artifact name and version for non-existent artifact.
nonExistentArtifact := GetUniqueArtifactName("nonexistent", 99)
nonExistentVersion := GetUniqueVersion(99)
// verify package index
path := fmt.Sprintf("/pkg/%s/%s/cargo/%s",
TestConfig.Namespace, TestConfig.RegistryName,
getIndexFilePathFromImageName(nonExistentArtifact),
)
req := client.NewRequest("GET", path)
resp, err := client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
gomega.Expect(resp.StatusCode).To(gomega.Equal(404))
// verify download package file
path = fmt.Sprintf("/pkg/%s/%s/cargo/api/v1/crates/%s/%s/download",
TestConfig.Namespace,
TestConfig.RegistryName,
nonExistentArtifact,
nonExistentVersion,
)
req = client.NewRequest("GET", path)
resp, err = client.Do(req)
gomega.Expect(err).To(gomega.BeNil())
// ideally this should return 404 but giving 403 because upstream proxy gives 403 if file not found
gomega.Expect(resp.StatusCode).To(gomega.Equal(403))
})
})
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/utils/pointer_helpers.go | registry/utils/pointer_helpers.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// Helper functions for creating pointers.
func StringPtr(s string) *string { return &s }
func Int64Ptr(i int64) *int64 { return &i }
func IntPtr(i int) *int { return &i }
func BoolPtr(b bool) *bool { return &b }
func Int32Ptr(i int32) *int32 { return &i }
func WebhookExecResultPtr(r api.WebhookExecResult) *api.WebhookExecResult { return &r }
func WebhookTriggerPtr(t api.Trigger) *api.Trigger { return &t }
func PageSizePtr(i int32) *api.PageSize { size := api.PageSize(i); return &size }
func PageNumberPtr(i int32) *api.PageNumber { num := api.PageNumber(i); return &num }
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/utils/utils.go | registry/utils/utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"reflect"
"strings"
"github.com/harness/gitness/registry/types"
goDigest "github.com/opencontainers/go-digest"
)
func HasAnyPrefix(s string, prefixes []string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(s, prefix) {
return true
}
}
return false
}
func HasAnySuffix(s string, prefixes []string) bool {
for _, prefix := range prefixes {
if strings.HasSuffix(s, prefix) {
return true
}
}
return false
}
func SafeUint64(n int) uint64 {
if n < 0 {
return 0
}
return uint64(n)
}
func IsEmpty(slice any) bool {
if slice == nil {
return true
}
val := reflect.ValueOf(slice)
// Check if the input is a pointer
if val.Kind() == reflect.Ptr {
// Dereference the pointer
val = val.Elem()
}
// Check if the dereferenced value is nil
if !val.IsValid() {
return true
}
return val.Len() == 0
}
func GetParsedDigest(digest string) (string, error) {
parsedDigest, err := goDigest.Parse(digest)
if err != nil {
return "", err
}
typesDigest, err := types.NewDigest(parsedDigest)
if err != nil {
return "", err
}
return typesDigest.String(), err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/request.go | registry/types/request.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
api "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// RegistryRequestBaseInfo represents base information about a registry request.
type RegistryRequestBaseInfo struct {
RootIdentifier string
RootIdentifierID int64
RegistryRef string
RegistryIdentifier string
RegistryID int64
ParentRef string
ParentID int64
RegistryType api.RegistryType
PackageType api.PackageType
}
// ArtifactFilesRequestInfo represents base information about an artifact files request.
type ArtifactFilesRequestInfo struct {
RegistryRequestBaseInfo
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/gc.go | registry/types/gc.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type GCBlobTask struct {
BlobID int64
ReviewAfter int64
ReviewCount int
CreatedAt int64
Event string
}
// GCManifestTask represents a row in the gc_manifest_review_queue table.
type GCManifestTask struct {
RegistryID int64
ManifestID int64
ReviewAfter int64
ReviewCount int
CreatedAt int64
Event string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/registry_root_ref_key.go | registry/types/registry_root_ref_key.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type RegistryRootRefCacheKey struct {
RootParentID int64
RegistryIdentifier string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/registry.go | registry/types/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 types
import (
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// RegistryConfig holds configuration settings for a registry.
type RegistryConfig struct {
// RemoteUrlSuffix is the suffix to append to remote URLs for this registry
// keeping it Url instead of URL coz body param with Url is cleaner
RemoteUrlSuffix string `json:"remoteUrlSuffix,omitempty"` //nolint:staticcheck,revive,tagliatelle
}
// Registry DTO object.
type Registry struct {
ID int64
UUID string
Name string
ParentID int64
RootParentID int64
Description string
Type artifact.RegistryType
PackageType artifact.PackageType
UpstreamProxies []int64
AllowedPattern []string
BlockedPattern []string
Labels []string
Config *RegistryConfig
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
IsPublic bool
}
func (r Registry) Identifier() int64 { return r.ID }
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/oci_Image_index_mapping.go | registry/types/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 types
import (
"time"
"github.com/opencontainers/go-digest"
)
type OCIImageIndexMapping struct {
ID int64
ParentManifestID int64
ChildManifestDigest digest.Digest
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/filter_params.go | registry/types/filter_params.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
type SortOrder string
type FilterParams struct {
SortOrder SortOrder
OrderBy string
Name string
BeforeEntry string
LastEntry string
PublishedAt string
MaxEntries int
IncludeReferrers bool
ReferrerTypes []string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/manifest.go | registry/types/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 types
import (
"database/sql"
"time"
"github.com/opencontainers/go-digest"
)
// Manifest DTO object.
type Manifest struct {
ID int64
RegistryID int64
TotalSize int64
SchemaVersion int
MediaType string
MediaTypeID int64
ImageName string
ArtifactType sql.NullString
Digest digest.Digest
Payload Payload
Configuration *Configuration
SubjectID sql.NullInt64
SubjectDigest digest.Digest
NonConformant bool
// 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
Annotations JSONB
CreatedAt time.Time
CreatedBy int64
UpdatedAt time.Time
UpdatedBy int64
}
// Manifests is a slice of Manifest pointers.
type Manifests []*Manifest
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/cleanuppolicy.go | registry/types/cleanuppolicy.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
"github.com/harness/gitness/registry/types/enum"
)
// CleanupPolicy DTO object.
type CleanupPolicy struct {
ID int64
RegistryID int64
Name string
VersionPrefix []string
PackagePrefix []string
ExpiryTime int64
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
// CleanupPolicyPrefix DTO object.
type CleanupPolicyPrefix struct {
ID int64
CleanupPolicyID int64
Prefix string
PrefixType enum.PrefixType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/node.go | registry/types/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 types
import "time"
type Node struct {
ID string
Name string
ParentNodeID string
RegistryID int64
IsFile bool
NodePath string
BlobID string
CreatedAt time.Time
CreatedBy int64
}
type FileNodeMetadata struct {
Name string
Path string
Size int64
Sha1 string
Sha256 string
Sha512 string
MD5 string
CreatedAt int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/generic_blob.go | registry/types/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 types
import "time"
type GenericBlob struct {
ID string
RootParentID int64
Sha1 string
Sha256 string
Sha512 string
MD5 string
Size int64
CreatedAt time.Time
CreatedBy int64
}
type FileInfo struct {
Size int64
Sha1 string
Sha256 string
Sha512 string
MD5 string
Filename string
CreatedAt time.Time
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/image.go | registry/types/image.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// Image DTO object.
type Image struct {
ID int64
UUID string
Name string
ArtifactType *artifact.ArtifactType
RegistryID int64
Enabled bool
Labels []string
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/PackageTag.go | registry/types/PackageTag.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "time"
type PackageTag struct {
ID string
Name string
ArtifactID int64
CreatedAt time.Time
CreatedBy int64
UpdatedAt time.Time
UpdatedBy int64
}
type PackageTagMetadata struct {
ID string
Name string
Version string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/configuration.go | registry/types/configuration.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "github.com/opencontainers/go-digest"
type Configuration struct {
MediaType string
BlobID int64
Digest digest.Digest
// Payload is the JSON payload of a manifest configuration.
// For operational safety reasons,
// a payload is only saved in this attribute if its size
// does not exceed a predefined
// limit (see handlers.dbConfigSizeLimit).
Payload Payload
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/download_stat.go | registry/types/download_stat.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
)
// DownloadStat DTO object.
type DownloadStat struct {
ID int64
ArtifactID int64
Timestamp time.Time
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/upstream_proxy_config.go | registry/types/upstream_proxy_config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// UpstreamProxyConfig DTO object.
type UpstreamProxyConfig struct {
ID int64
RegistryID int64
Source string
URL string
AuthType string
UserName string
UserNameSecretIdentifier string
UserNameSecretSpaceID int64
Password string
SecretIdentifier string
SecretSpaceID int64
Token string
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
type UpstreamProxy struct {
ID int64
RegistryUUID string
RegistryID int64
RepoKey string
ParentID string
PackageType artifact.PackageType
AllowedPattern []string
BlockedPattern []string
Config *RegistryConfig
Source string
RepoURL string
RepoAuthType string
UserName string
UserNameSecretIdentifier string
UserNameSecretSpaceID int64
UserNameSecretSpacePath string
SecretIdentifier string
SecretSpaceID int64
SecretSpacePath string
Token string
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/path_package_types.go | registry/types/path_package_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 types
type PathPackageType string
const (
PathPackageTypeDocker PathPackageType = "docker"
PathPackageTypeHelm PathPackageType = "helm"
PathPackageTypeGeneric PathPackageType = "generic"
PathPackageTypeMaven PathPackageType = "maven"
PathPackageTypePython PathPackageType = "python"
PathPackageTypeNuget PathPackageType = "nuget"
PathPackageTypeNpm PathPackageType = "npm"
PathPackageTypeRPM PathPackageType = "rpm"
PathPackageTypeCargo PathPackageType = "cargo"
PathPackageTypeGo PathPackageType = "go"
PathPackageTypeHuggingFace PathPackageType = "huggingface"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/payload.go | registry/types/payload.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
)
type Payload json.RawMessage
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/bandwidth_stat.go | registry/types/bandwidth_stat.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
)
// Defines values for BandwidthType.
const (
BandwidthTypeUPLOAD BandwidthType = "UPLOAD"
BandwidthTypeDOWNLOAD BandwidthType = "DOWNLOAD"
)
// BandwidthStat DTO object.
type BandwidthStat struct {
ID int64
ImageID int64
Timestamp time.Time
Type BandwidthType
Bytes int64
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
type BandwidthType string
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/media_type.go | registry/types/media_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
)
// Manifest DTO object.
type MediaType struct {
ID int64
MediaType string
CreatedAt time.Time
IsRunnable bool
}
// Manifests is a slice of Manifest pointers.
type MediaTypes []*MediaType
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/tag.go | registry/types/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 types
import (
"encoding/json"
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// Tag DTO object.
type Tag struct {
ID int64
Name string
ImageName string
RegistryID int64
ManifestID int64
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
type ArtifactMetadata struct {
ID int64
UUID string
RegistryUUID string
Name string
RepoName string
DownloadCount int64
PackageType artifact.PackageType
Labels []string
LatestVersion string
CreatedAt time.Time
ModifiedAt time.Time
Version string
Metadata json.RawMessage
IsQuarantined bool
QuarantineReason *string
ArtifactType *artifact.ArtifactType
Tags []string
}
type ImageMetadata struct {
Name string
RegistryUUID string
UUID string
RepoName string
DownloadCount int64
PackageType artifact.PackageType
ArtifactType *artifact.ArtifactType
LatestVersion string
CreatedAt time.Time
ModifiedAt time.Time
}
type OciVersionMetadata struct {
Name string
Size string
PackageType artifact.PackageType
DigestCount int
ModifiedAt time.Time
SchemaVersion int
NonConformant bool
Payload Payload
MediaType string
Digest string
DownloadCount int64
Tags []string
IsQuarantined bool
QuarantineReason string
}
type TagDetail struct {
ID int64
Name string
ImageName string
CreatedAt time.Time
UpdatedAt time.Time
Size string
DownloadCount int64
}
type TagInfo struct {
Name string
Digest string
}
type QuarantineInfo struct {
Reason string
CreatedAt int64
}
// ArtifactIdentifier represents an artifact by name, version, and registry ID.
type ArtifactIdentifier struct {
Name string
Version string
RegistryName string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/jsonb.go | registry/types/jsonb.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"errors"
"fmt"
)
type JSONB map[string]string
// Scan implements the sql.Scanner interface for JSONB.
func (j *JSONB) Scan(value any) error {
if value == nil {
*j = nil
return nil
}
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint(
"Failed to unmarshal JSONB value:", value))
}
var m map[string]string
if err := json.Unmarshal(bytes, &m); err != nil {
return err
}
*j = m
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/digest.go | registry/types/digest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/hex"
"errors"
"fmt"
"github.com/opencontainers/go-digest"
)
// Digest is the database representation of a digest, stored in the format `<algorithm prefix><hex>`.
type Digest string
const (
// Algorithm prefixes are sequences of two digits. These should never change, only additions are allowed.
sha256DigestAlgorithmPrefix = "01"
sha512DigestAlgorithmPrefix = "02"
)
func GetDigestBytes(dgst digest.Digest) ([]byte, error) {
if len(dgst.String()) == 0 {
return nil, nil
}
newDigest, err := NewDigest(dgst)
if err != nil {
return nil, err
}
digestBytes, err := GetHexDecodedBytes(string(newDigest))
if err != nil {
return nil, err
}
return digestBytes, nil
}
func GetHexDecodedBytes(s string) ([]byte, error) {
return hex.DecodeString(s)
}
// String implements the Stringer interface.
func (d Digest) String() string {
return string(d)
}
// NewDigest builds a Digest based on a digest.Digest.
func NewDigest(d digest.Digest) (Digest, error) {
if err := d.Validate(); err != nil {
return "", err
}
var algPrefix string
switch d.Algorithm() {
case digest.SHA256:
algPrefix = sha256DigestAlgorithmPrefix
case digest.SHA512:
algPrefix = sha512DigestAlgorithmPrefix
case digest.SHA384:
return "", fmt.Errorf("unimplemented algorithm %q", digest.SHA384)
default:
return "", fmt.Errorf("unknown algorithm %q", d.Algorithm())
}
return Digest(fmt.Sprintf("%s%s", algPrefix, d.Hex())), nil
}
// Parse maps a Digest to a digest.Digest.
func (d Digest) Parse() (digest.Digest, error) {
str := d.String()
valid, err := d.validate(str)
if !valid {
return "", err
}
algPrefix := str[:2]
if len(str) == 2 {
return "", errors.New("no checksum")
}
var alg digest.Algorithm
switch algPrefix {
case sha256DigestAlgorithmPrefix:
alg = digest.SHA256
case sha512DigestAlgorithmPrefix:
alg = digest.SHA512
default:
return "", fmt.Errorf("unknown algorithm prefix %q", algPrefix)
}
dgst := digest.NewDigestFromHex(alg.String(), str[2:])
if err := dgst.Validate(); err != nil {
return "", err
}
return dgst, nil
}
func (d Digest) validate(str string) (bool, error) {
if len(str) == 0 {
return false, nil
}
if len(str) < 2 {
return false, errors.New("invalid digest length")
}
return true, nil
}
// HexDecode decodes binary data from a textual representation.
// The output is equivalent to the PostgreSQL binary `decode` function with the hex textual format. See
// https://www.postgresql.org/docs/14/functions-binarystring.html.
func (d Digest) HexDecode() string {
return fmt.Sprintf("\\x%s", d.String())
}
func (d Digest) Validate() string {
return fmt.Sprintf("\\x%s", d.String())
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/task.go | registry/types/task.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"time"
)
type TaskStatus string
const (
TaskStatusPending TaskStatus = "pending"
TaskStatusProcessing TaskStatus = "processing"
TaskStatusSuccess TaskStatus = "success"
TaskStatusFailure TaskStatus = "failure"
)
type TaskKind string
const (
TaskKindBuildRegistryIndex TaskKind = "build_registry_index"
TaskKindBuildPackageIndex TaskKind = "build_package_index"
TaskKindBuildPackageMetadata TaskKind = "build_package_metadata"
)
type SourceType string
const (
SourceTypeRegistry SourceType = "Registry"
SourceTypeArtifact SourceType = "Artifact"
)
type Task struct {
Key string
Kind TaskKind
Payload json.RawMessage
Status TaskStatus
RunAgain bool
UpdatedAt time.Time
}
type TaskSource struct {
Key string
SrcType SourceType
SrcID int64
Status TaskStatus
RunID *string
Error *string
UpdatedAt time.Time
}
type TaskEvent struct {
ID string
Key string
Event string
Payload *json.RawMessage
At time.Time
}
type SourceRef struct {
Type SourceType `json:"type"`
ID int64 `json:"id"`
}
type BuildRegistryIndexTaskPayload struct {
Key string `json:"key"`
RegistryID int64 `json:"registry_id"` //nolint:tagliatelle
PrincipalID int64 `json:"principal_id"` //nolint:tagliatelle // TODO: setting service principal ID to run the task
}
type BuildPackageIndexTaskPayload struct {
Key string `json:"key"`
RegistryID int64 `json:"registry_id"` //nolint:tagliatelle
Image string `json:"image"`
PrincipalID int64 `json:"principal_id"` //nolint:tagliatelle // TODO: setting service principal ID to run the task
}
type BuildPackageMetadataTaskPayload struct {
Key string `json:"key"`
RegistryID int64 `json:"registry_id"` //nolint:tagliatelle
Image string `json:"image"`
Version string `json:"version"`
PrincipalID int64 `json:"principal_id"` //nolint:tagliatelle // TODO: setting service principal ID to run the task
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/layer.go | registry/types/layer.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "time"
// Layer DTO object.
type Layer struct {
ID int64
RegistryID int64
ManifestID int64
MediaTypeID int64
BlobID int64
Size int64
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/quarantine_artifact.go | registry/types/quarantine_artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"time"
)
// QuarantineArtifact DTO object.
type QuarantineArtifact struct {
ID string
NodeID *string
Reason string
RegistryID int64
ArtifactID int64
ImageID int64
CreatedAt time.Time
CreatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/manifest_reference.go | registry/types/manifest_reference.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "time"
// ManifestReference DTO object.
type ManifestReference struct {
ID int64
RegistryID int64
ParentID int64
ChildID int64
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/blob.go | registry/types/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 types
import (
"time"
"github.com/opencontainers/go-digest"
)
// Blob DTO object.
type Blob struct {
ID int64
RootParentID int64
// This media type is for S3. The caller should look this up
// and override the value for the specific repository.
MediaType string
MediaTypeID int64
Digest digest.Digest
Size int64
CreatedAt time.Time
CreatedBy int64
}
// Blobs is a slice of Blob pointers.
type Blobs []*Blob
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/artifact.go | registry/types/artifact.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"encoding/json"
"time"
"github.com/harness/gitness/registry/app/api/openapi/contracts/artifact"
)
// Artifact DTO object.
type Artifact struct {
ID int64
UUID string
Version string
ImageID int64
Metadata json.RawMessage
CreatedAt time.Time
UpdatedAt time.Time
CreatedBy int64
UpdatedBy int64
}
type NonOCIArtifactMetadata struct {
ID string
UUID string
Name string
Size string
PackageType artifact.PackageType
FileCount int64
ModifiedAt time.Time
DownloadCount int64
IsQuarantined bool
QuarantineReason *string
ArtifactType *artifact.ArtifactType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/enum/prefix_type.go | registry/types/enum/prefix_type.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type PrefixType string
const (
PrefixTypeVersion PrefixType = "version"
PrefixTypePackage PrefixType = "package"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/types/enum/common.go | registry/types/enum/common.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
import (
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
)
func Sanitize[E constraints.Ordered](element E, all func() ([]E, E)) (E, bool) {
allValues, defValue := all()
var empty E
if element == empty && defValue != empty {
return defValue, true
}
idx, exists := slices.BinarySearch(allValues, element)
if exists {
return allValues[idx], true
}
return defValue, false
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/docs/docs.go | registry/docs/docs.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package docs Code generated by swaggo/swag. DO NOT EDIT
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/v1/healthz": {
"get": {
"description": "Health API for Artifact-Registry Service",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Health API for Artifact-Registry Service",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "1.0",
Host: "localhost:9091",
BasePath: "/",
Schemes: []string{"http"},
Title: "Swagger Doc- Artifact-Registry",
Description: "Client to connect to artifact-registry APIs.",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/gc/wire.go | registry/gc/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 gc
import (
storagedriver "github.com/harness/gitness/registry/app/driver"
"github.com/google/wire"
)
func StorageDeleterProvider(driver storagedriver.StorageDriver) storagedriver.StorageDeleter {
return driver
}
func ServiceProvider() Service {
return New()
}
var WireSet = wire.NewSet(StorageDeleterProvider, ServiceProvider)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/gc/interface.go | registry/gc/interface.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gc
import (
"context"
"time"
corestore "github.com/harness/gitness/app/store"
storagedriver "github.com/harness/gitness/registry/app/driver"
"github.com/harness/gitness/registry/app/store"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/types"
)
type Service interface {
Start(
ctx context.Context, spaceStore corestore.SpaceStore,
blobRepo store.BlobRepository, storageDeleter storagedriver.StorageDeleter,
config *types.Config,
)
BlobFindAndLockBefore(ctx context.Context, blobID int64, date time.Time) (*registrytypes.GCBlobTask, error)
BlobReschedule(ctx context.Context, b *registrytypes.GCBlobTask, d time.Duration) error
ManifestFindAndLockBefore(
ctx context.Context, registryID, manifestID int64,
date time.Time,
) (*registrytypes.GCManifestTask, error)
ManifestFindAndLockNBefore(
ctx context.Context, registryID int64, manifestIDs []int64,
date time.Time,
) ([]*registrytypes.GCManifestTask, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/gc/garbagecollector.go | registry/gc/garbagecollector.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gc
import (
"context"
"time"
corestore "github.com/harness/gitness/app/store"
storagedriver "github.com/harness/gitness/registry/app/driver"
"github.com/harness/gitness/registry/app/store"
registrytypes "github.com/harness/gitness/registry/types"
"github.com/harness/gitness/types"
)
type Noop struct{}
func New() Service {
return &Noop{}
}
func (s *Noop) Start(
context.Context, corestore.SpaceStore,
store.BlobRepository, storagedriver.StorageDeleter,
*types.Config,
) {
// NOOP
}
func (s *Noop) BlobFindAndLockBefore(context.Context, int64, time.Time) (*registrytypes.GCBlobTask, error) {
// NOOP
//nolint:nilnil
return nil, nil
}
func (s *Noop) BlobReschedule(context.Context, *registrytypes.GCBlobTask, time.Duration) error {
// NOOP
return nil
}
func (s *Noop) ManifestFindAndLockBefore(context.Context, int64, int64, time.Time) (
*registrytypes.GCManifestTask, error,
) {
// NOOP
//nolint:nilnil
return nil, nil
}
func (s *Noop) ManifestFindAndLockNBefore(context.Context, int64, []int64, time.Time) (
[]*registrytypes.GCManifestTask, error,
) {
// NOOP
return nil, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/config/helper.go | registry/config/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 config
import "github.com/harness/gitness/types"
func GetS3StorageParameters(c *types.Config) map[string]any {
s3Properties := make(map[string]any)
s3Properties["accesskey"] = c.Registry.Storage.S3Storage.AccessKey
s3Properties["secretkey"] = c.Registry.Storage.S3Storage.SecretKey
s3Properties["region"] = c.Registry.Storage.S3Storage.Region
s3Properties["regionendpoint"] = c.Registry.Storage.S3Storage.RegionEndpoint
s3Properties["forcepathstyle"] = c.Registry.Storage.S3Storage.ForcePathStyle
s3Properties["accelerate"] = c.Registry.Storage.S3Storage.Accelerate
s3Properties["bucket"] = c.Registry.Storage.S3Storage.Bucket
s3Properties["encrypt"] = c.Registry.Storage.S3Storage.Encrypt
s3Properties["keyid"] = c.Registry.Storage.S3Storage.KeyID
s3Properties["secure"] = c.Registry.Storage.S3Storage.Secure
s3Properties["v4auth"] = c.Registry.Storage.S3Storage.V4Auth
s3Properties["chunksize"] = c.Registry.Storage.S3Storage.ChunkSize
s3Properties["multipartcopychunksize"] = c.Registry.Storage.S3Storage.MultipartCopyChunkSize
s3Properties["multipartcopymaxconcurrency"] = c.Registry.Storage.S3Storage.MultipartCopyMaxConcurrency
s3Properties["multipartcopythresholdsize"] = c.Registry.Storage.S3Storage.MultipartCopyThresholdSize
s3Properties["rootdirectory"] = c.Registry.Storage.S3Storage.RootDirectory
s3Properties["usedualstack"] = c.Registry.Storage.S3Storage.UseDualStack
s3Properties["loglevel"] = c.Registry.Storage.S3Storage.LogLevel
return s3Properties
}
func GetFilesystemParams(c *types.Config) map[string]any {
props := make(map[string]any)
props["maxthreads"] = c.Registry.Storage.FileSystemStorage.MaxThreads
props["rootdirectory"] = c.Registry.Storage.FileSystemStorage.RootDirectory
return props
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/config/const.go | registry/config/const.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
type contextKey string
// const variables.
const (
PostgresqlDatabase = "postgres"
Sqlite = "sqlite3"
GoRoutineKey contextKey = "goRoutine"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/request/context.go | registry/request/context.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package request
import (
"context"
"github.com/harness/gitness/registry/app/pkg"
"github.com/rs/zerolog/log"
)
type contextKey string
const OriginalPathKey contextKey = "originalPath"
const OriginalURLKey contextKey = "originalURL"
const ArtifactInfoKey contextKey = "artifactInfo"
// Functions for original PATH.
func OriginalPathFrom(ctx context.Context) string {
originalPath, ok := ctx.Value(OriginalPathKey).(string)
if !ok {
log.Ctx(ctx).Warn().Msg("Original path not found in context")
}
return originalPath
}
func WithOriginalPath(parent context.Context, originalPath string) context.Context {
return context.WithValue(parent, OriginalPathKey, originalPath)
}
// Functions for original FULL URL.
func OriginalURLFrom(ctx context.Context) string {
originalURL, ok := ctx.Value(OriginalURLKey).(string)
if !ok {
log.Ctx(ctx).Warn().Msg("Original URL not found in context")
}
return originalURL
}
func WithOriginalURL(parent context.Context, originalURL string) context.Context {
return context.WithValue(parent, OriginalURLKey, originalURL)
}
func ArtifactInfoFrom(ctx context.Context) pkg.PackageArtifactInfo {
baseInfo, ok := ctx.Value(ArtifactInfoKey).(pkg.PackageArtifactInfo)
if !ok {
log.Ctx(ctx).Warn().Msg("Failed to get artifact info")
}
return baseInfo
}
func WithArtifactInfo(parent context.Context, artifactInfo pkg.PackageArtifactInfo) context.Context {
return context.WithValue(parent, ArtifactInfoKey, artifactInfo)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/job/wire.go | registry/job/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 job
import (
"github.com/harness/gitness/job"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/job/handler"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideJobRpmRegistryIndex,
)
func ProvideJobRpmRegistryIndex(
postProcessingReporter *registrypostprocessingevents.Reporter,
executor *job.Executor,
) (*handler.JobRpmRegistryIndex, error) {
return handler.NewJobRpmRegistryIndex(postProcessingReporter, executor)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/job/handler/rpm_registry_index.go | registry/job/handler/rpm_registry_index.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package handler
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/harness/gitness/job"
registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing"
"github.com/harness/gitness/registry/types"
)
const JobType = "rpm_registry_index"
type JobRpmRegistryIndex struct {
postProcessingReporter *registrypostprocessingevents.Reporter
}
func NewJobRpmRegistryIndex(
postProcessingReporter *registrypostprocessingevents.Reporter,
executor *job.Executor,
) (*JobRpmRegistryIndex, error) {
j := JobRpmRegistryIndex{
postProcessingReporter: postProcessingReporter,
}
err := executor.Register(JobType, &j)
if err != nil {
return nil, err
}
return &j, nil
}
func (j *JobRpmRegistryIndex) Handle(ctx context.Context, data string, _ job.ProgressReporter) (string, error) {
input, err := j.getJobInput(data)
if err != nil {
return "", err
}
for _, id := range input.RegistryIDs {
j.postProcessingReporter.BuildRegistryIndexWithPrincipal(
ctx, id, make([]types.SourceRef, 0), 0,
)
}
return "", nil
}
func (j *JobRpmRegistryIndex) getJobInput(data string) (RegistrySyncInput, error) {
var input RegistrySyncInput
err := json.NewDecoder(strings.NewReader(data)).Decode(&input)
if err != nil {
return RegistrySyncInput{}, fmt.Errorf("failed to unmarshal rpm registry sync job input json: %w", err)
}
return input, nil
}
type RegistrySyncInput struct {
RegistryIDs []int64 `json:"registry_ids"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/crypto/crypto_test.go | crypto/crypto_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 crypto
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strings"
"testing"
)
func TestGenerateHMACSHA256(t *testing.T) {
tests := []struct {
name string
data []byte
key []byte
expected string
}{
{
name: "simple data and key",
data: []byte("hello world"),
key: []byte("secret"),
expected: "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a",
},
{
name: "empty data",
data: []byte(""),
key: []byte("secret"),
expected: "f9e66e179b6747ae54108f82f8ade8b3c25d76fd30afde6c395822c530196169",
},
{
name: "empty key",
data: []byte("hello world"),
key: []byte(""),
expected: "", // We'll calculate this dynamically
},
{
name: "both empty",
data: []byte(""),
key: []byte(""),
expected: "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad",
},
{
name: "long data",
data: []byte(strings.Repeat("a", 1000)),
key: []byte("secret"),
expected: "", // We'll calculate this dynamically
},
{
name: "long key",
data: []byte("hello"),
key: []byte(strings.Repeat("k", 100)),
expected: "", // We'll calculate this dynamically
},
{
name: "binary data",
data: []byte{0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD},
key: []byte("binary"),
expected: "", // We'll calculate this dynamically
},
{
name: "unicode data",
data: []byte("Hello 世界 🌍"),
key: []byte("unicode"),
expected: "", // We'll calculate this dynamically
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := GenerateHMACSHA256(tt.data, tt.key)
if err != nil {
t.Errorf("GenerateHMACSHA256() error = %v", err)
return
}
// For cases where we don't have pre-calculated expected values,
// verify the result by computing it manually
if tt.expected == "" {
h := hmac.New(sha256.New, tt.key)
h.Write(tt.data)
expected := hex.EncodeToString(h.Sum(nil))
if result != expected {
t.Errorf("GenerateHMACSHA256() = %v, want %v", result, expected)
}
} else if result != tt.expected {
t.Errorf("GenerateHMACSHA256() = %v, want %v", result, tt.expected)
}
// Verify the result is valid hex
_, err = hex.DecodeString(result)
if err != nil {
t.Errorf("GenerateHMACSHA256() returned invalid hex: %v", err)
}
// Verify the result has the correct length for SHA256 (64 hex characters)
if len(result) != 64 {
t.Errorf("GenerateHMACSHA256() returned wrong length: got %d, want 64", len(result))
}
})
}
}
func TestGenerateHMACSHA256Consistency(t *testing.T) {
// Test that the same input always produces the same output
data := []byte("test data")
key := []byte("test key")
result1, err1 := GenerateHMACSHA256(data, key)
if err1 != nil {
t.Fatalf("First call failed: %v", err1)
}
result2, err2 := GenerateHMACSHA256(data, key)
if err2 != nil {
t.Fatalf("Second call failed: %v", err2)
}
if result1 != result2 {
t.Errorf("GenerateHMACSHA256() is not consistent: %v != %v", result1, result2)
}
}
func TestGenerateHMACSHA256DifferentInputs(t *testing.T) {
// Test that different inputs produce different outputs
key := []byte("secret")
result1, _ := GenerateHMACSHA256([]byte("data1"), key)
result2, _ := GenerateHMACSHA256([]byte("data2"), key)
if result1 == result2 {
t.Error("GenerateHMACSHA256() should produce different results for different inputs")
}
// Test different keys
data := []byte("same data")
result3, _ := GenerateHMACSHA256(data, []byte("key1"))
result4, _ := GenerateHMACSHA256(data, []byte("key2"))
if result3 == result4 {
t.Error("GenerateHMACSHA256() should produce different results for different keys")
}
}
func TestIsShaEqual(t *testing.T) {
tests := []struct {
name string
key1 string
key2 string
expected bool
}{
{
name: "identical strings",
key1: "hello",
key2: "hello",
expected: true,
},
{
name: "different strings",
key1: "hello",
key2: "world",
expected: false,
},
{
name: "empty strings",
key1: "",
key2: "",
expected: true,
},
{
name: "one empty string",
key1: "hello",
key2: "",
expected: false,
},
{
name: "case sensitive",
key1: "Hello",
key2: "hello",
expected: false,
},
{
name: "whitespace differences",
key1: "hello ",
key2: "hello",
expected: false,
},
{
name: "long identical strings",
key1: strings.Repeat("a", 1000),
key2: strings.Repeat("a", 1000),
expected: true,
},
{
name: "long different strings",
key1: strings.Repeat("a", 1000),
key2: strings.Repeat("b", 1000),
expected: false,
},
{
name: "unicode strings identical",
key1: "Hello 世界 🌍",
key2: "Hello 世界 🌍",
expected: true,
},
{
name: "unicode strings different",
key1: "Hello 世界 🌍",
key2: "Hello 世界 🌎",
expected: false,
},
{
name: "hex strings identical",
key1: "deadbeef",
key2: "deadbeef",
expected: true,
},
{
name: "hex strings different",
key1: "deadbeef",
key2: "deadbeee",
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := IsShaEqual(tt.key1, tt.key2)
if result != tt.expected {
t.Errorf("IsShaEqual(%q, %q) = %v, want %v", tt.key1, tt.key2, result, tt.expected)
}
})
}
}
func TestIsShaEqualTimingSafety(t *testing.T) {
// Test that IsShaEqual uses constant-time comparison
// This is important for security to prevent timing attacks
// Create two strings that differ only in the last character
base := strings.Repeat("a", 100)
key1 := base + "1"
key2 := base + "2"
// The function should return false
result := IsShaEqual(key1, key2)
if result {
t.Error("IsShaEqual() should return false for different strings")
}
// Test with strings of different lengths
result2 := IsShaEqual("short", "much longer string")
if result2 {
t.Error("IsShaEqual() should return false for strings of different lengths")
}
}
func TestGenerateHMACSHA256WithRealWorldData(t *testing.T) {
// Test with realistic data that might be used in practice
tests := []struct {
name string
data []byte
key []byte
}{
{
name: "JSON payload",
data: []byte(`{"user_id": 123, "action": "login", "timestamp": "2023-01-01T00:00:00Z"}`),
key: []byte("webhook-secret-key"),
},
{
name: "URL parameters",
data: []byte("user=john&action=login×tamp=1672531200"),
key: []byte("api-secret"),
},
{
name: "Base64 data",
data: []byte("SGVsbG8gV29ybGQ="),
key: []byte("base64-key"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := GenerateHMACSHA256(tt.data, tt.key)
if err != nil {
t.Errorf("GenerateHMACSHA256() error = %v", err)
return
}
// Verify the result is a valid SHA256 hash
if len(result) != 64 {
t.Errorf("Expected 64 character hash, got %d", len(result))
}
// Verify it's valid hex
_, err = hex.DecodeString(result)
if err != nil {
t.Errorf("Result is not valid hex: %v", err)
}
})
}
}
// Benchmark tests.
func BenchmarkGenerateHMACSHA256(b *testing.B) {
data := []byte("benchmark data")
key := []byte("benchmark key")
for b.Loop() {
_, err := GenerateHMACSHA256(data, key)
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkGenerateHMACSHA256LargeData(b *testing.B) {
data := []byte(strings.Repeat("a", 10000))
key := []byte("benchmark key")
for b.Loop() {
_, err := GenerateHMACSHA256(data, key)
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkIsShaEqual(b *testing.B) {
key1 := "benchmark string for comparison"
key2 := "benchmark string for comparison"
for b.Loop() {
IsShaEqual(key1, key2)
}
}
func BenchmarkIsShaEqualLarge(b *testing.B) {
key1 := strings.Repeat("a", 1000)
key2 := strings.Repeat("a", 1000)
for b.Loop() {
IsShaEqual(key1, key2)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/crypto/crypto.go | crypto/crypto.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package crypto
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
// GenerateHMACSHA256 generates a new HMAC using SHA256 as hash function.
func GenerateHMACSHA256(data []byte, key []byte) (string, error) {
h := hmac.New(sha256.New, key)
// write all data into hash
_, err := h.Write(data)
if err != nil {
return "", fmt.Errorf("failed to write data into hash: %w", err)
}
// sum hash to final value
macBytes := h.Sum(nil)
// encode MAC as hexadecimal
return hex.EncodeToString(macBytes), nil
}
func IsShaEqual(key1, key2 string) bool {
return hmac.Equal([]byte(key1), []byte(key2))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/resources/embed.go | resources/embed.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resources
import (
"embed"
"fmt"
"strings"
)
var (
//go:embed gitignore
gitignore embed.FS
//go:embed license
licence embed.FS
)
// Licenses returns map of licences in license folder.
func Licenses() ([]byte, error) {
return licence.ReadFile("license/index.json")
}
// ReadLicense reads licence from license folder.
func ReadLicense(name string) ([]byte, error) {
content, err := licence.ReadFile(fmt.Sprintf("license/%s.txt", name))
if err != nil {
return nil, err
}
return content, err
}
// GitIgnores lists all files in gitignore folder and return file names.
func GitIgnores() ([]string, error) {
entries, err := gitignore.ReadDir("gitignore")
files := make([]string, len(entries))
if err != nil {
return []string{}, err
}
for i, filename := range entries {
files[i] = strings.ReplaceAll(filename.Name(), ".gitignore", "")
}
return files, nil
}
// ReadGitIgnore reads gitignore file from license folder.
func ReadGitIgnore(name string) ([]byte, error) {
return gitignore.ReadFile(fmt.Sprintf("gitignore/%s.gitignore", name))
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/resources/embed_test.go | resources/embed_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 resources
import (
"strings"
"testing"
)
func TestLicenses(t *testing.T) {
content, err := Licenses()
if err != nil {
t.Fatalf("Licenses() returned error: %v", err)
}
if len(content) == 0 {
t.Errorf("Licenses() returned empty content")
}
// Verify it's JSON content
contentStr := string(content)
if !strings.HasPrefix(contentStr, "[") && !strings.HasPrefix(contentStr, "{") {
t.Errorf("Licenses() content doesn't appear to be JSON")
}
}
func TestReadLicense(t *testing.T) {
// Test reading a common license (MIT is usually available)
tests := []struct {
name string
licenseName string
expectError bool
}{
{
name: "read MIT license",
licenseName: "mit",
expectError: false,
},
{
name: "read non-existent license",
licenseName: "nonexistent-license-xyz",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
content, err := ReadLicense(tt.licenseName)
if tt.expectError {
if err == nil {
t.Errorf("ReadLicense(%q) expected error but got none", tt.licenseName)
}
} else {
if err != nil {
t.Fatalf("ReadLicense(%q) returned error: %v", tt.licenseName, err)
}
if len(content) == 0 {
t.Errorf("ReadLicense(%q) returned empty content", tt.licenseName)
}
}
})
}
}
func TestGitIgnores(t *testing.T) {
files, err := GitIgnores()
if err != nil {
t.Fatalf("GitIgnores() returned error: %v", err)
}
if len(files) == 0 {
t.Errorf("GitIgnores() returned empty list")
}
// Verify files don't have .gitignore extension
for _, file := range files {
if strings.HasSuffix(file, ".gitignore") {
t.Errorf("GitIgnores() returned file with .gitignore extension: %s", file)
}
}
// Verify we have some common gitignore templates
hasCommon := false
commonTemplates := []string{"Go", "Node", "Python", "Java"}
for _, file := range files {
for _, common := range commonTemplates {
if strings.EqualFold(file, common) {
hasCommon = true
break
}
}
if hasCommon {
break
}
}
if !hasCommon {
t.Logf("Warning: No common gitignore templates found. Available: %v", files)
}
}
func TestReadGitIgnore(t *testing.T) {
// First get the list of available gitignores
files, err := GitIgnores()
if err != nil {
t.Fatalf("GitIgnores() returned error: %v", err)
}
if len(files) == 0 {
t.Skip("No gitignore files available to test")
}
// Test reading the first available gitignore
t.Run("read existing gitignore", func(t *testing.T) {
content, err := ReadGitIgnore(files[0])
if err != nil {
t.Fatalf("ReadGitIgnore(%q) returned error: %v", files[0], err)
}
if len(content) == 0 {
t.Errorf("ReadGitIgnore(%q) returned empty content", files[0])
}
})
// Test reading non-existent gitignore
t.Run("read non-existent gitignore", func(t *testing.T) {
_, err := ReadGitIgnore("nonexistent-gitignore-xyz")
if err == nil {
t.Errorf("ReadGitIgnore(nonexistent) expected error but got none")
}
})
}
func TestReadGitIgnoreContent(t *testing.T) {
// Get available gitignores
files, err := GitIgnores()
if err != nil {
t.Fatalf("GitIgnores() returned error: %v", err)
}
if len(files) == 0 {
t.Skip("No gitignore files available to test")
}
// Test that content is valid gitignore format
for _, file := range files[:minInt(5, len(files))] { // Test first 5 files
t.Run(file, func(t *testing.T) {
content, err := ReadGitIgnore(file)
if err != nil {
t.Fatalf("ReadGitIgnore(%q) returned error: %v", file, err)
}
// Verify content is not empty
if len(content) == 0 {
t.Errorf("ReadGitIgnore(%q) returned empty content", file)
}
// Verify content is text (not binary)
contentStr := string(content)
if len(contentStr) == 0 {
t.Errorf("ReadGitIgnore(%q) content is not valid text", file)
}
})
}
}
func TestLicensesNotEmpty(t *testing.T) {
content, err := Licenses()
if err != nil {
t.Fatalf("Licenses() returned error: %v", err)
}
// Verify content has reasonable size
if len(content) < 10 {
t.Errorf("Licenses() content seems too small: %d bytes", len(content))
}
}
func TestReadLicenseFormat(t *testing.T) {
// Try to read MIT license and verify it has expected content
content, err := ReadLicense("mit")
if err != nil {
t.Skip("MIT license not available, skipping format test")
}
contentStr := string(content)
// MIT license should contain certain keywords
keywords := []string{"MIT", "Permission", "Copyright"}
foundKeywords := 0
for _, keyword := range keywords {
if strings.Contains(contentStr, keyword) {
foundKeywords++
}
}
if foundKeywords == 0 {
t.Errorf("MIT license content doesn't contain expected keywords")
}
}
func TestGitIgnoresUnique(t *testing.T) {
files, err := GitIgnores()
if err != nil {
t.Fatalf("GitIgnores() returned error: %v", err)
}
// Verify all files are unique
seen := make(map[string]bool)
for _, file := range files {
if seen[file] {
t.Errorf("GitIgnores() returned duplicate file: %s", file)
}
seen[file] = true
}
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/wire.go | job/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 job
import (
"github.com/harness/gitness/lock"
"github.com/harness/gitness/pubsub"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideExecutor,
ProvideScheduler,
)
func ProvideExecutor(
store Store,
pubsubService pubsub.PubSub,
) *Executor {
return NewExecutor(
store,
pubsubService,
)
}
func ProvideScheduler(
store Store,
executor *Executor,
mutexManager lock.MutexManager,
pubsubService pubsub.PubSub,
config Config,
) (*Scheduler, error) {
return NewScheduler(
store,
executor,
mutexManager,
pubsubService,
config.InstanceID,
config.BackgroundJobsMaxRunning,
config.BackgroundJobsRetentionTime,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/types.go | job/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 job
type Job struct {
UID string `db:"job_uid"`
Created int64 `db:"job_created"`
Updated int64 `db:"job_updated"`
Type string `db:"job_type"`
Priority Priority `db:"job_priority"`
Data string `db:"job_data"`
Result string `db:"job_result"`
MaxDurationSeconds int `db:"job_max_duration_seconds"`
MaxRetries int `db:"job_max_retries"`
State State `db:"job_state"`
Scheduled int64 `db:"job_scheduled"`
TotalExecutions int `db:"job_total_executions"`
RunBy string `db:"job_run_by"`
RunDeadline int64 `db:"job_run_deadline"`
RunProgress int `db:"job_run_progress"`
LastExecuted int64 `db:"job_last_executed"`
IsRecurring bool `db:"job_is_recurring"`
RecurringCron string `db:"job_recurring_cron"`
ConsecutiveFailures int `db:"job_consecutive_failures"`
LastFailureError string `db:"job_last_failure_error"`
GroupID string `db:"job_group_id"`
}
type StateChange struct {
UID string `json:"uid"`
Type string `json:"type"`
State State `json:"state"`
Progress int `json:"progress"`
Result string `json:"result"`
Failure string `json:"failure"`
}
type Progress struct {
State State `json:"state"`
Progress int `json:"progress"`
Result string `json:"result,omitempty"`
Failure string `json:"failure,omitempty"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/pubsub.go | job/pubsub.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"github.com/harness/gitness/pubsub"
)
const (
PubSubTopicCancelJob = "gitness:job:cancel_job"
PubSubTopicStateChange = "gitness:job:state_change"
)
func encodeStateChange(job *Job) ([]byte, error) {
stateChange := &StateChange{
UID: job.UID,
Type: job.Type,
State: job.State,
Progress: job.RunProgress,
Result: job.Result,
Failure: job.LastFailureError,
}
buffer := bytes.NewBuffer(nil)
if err := gob.NewEncoder(buffer).Encode(stateChange); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func DecodeStateChange(payload []byte) (*StateChange, error) {
stateChange := &StateChange{}
if err := gob.NewDecoder(bytes.NewReader(payload)).Decode(stateChange); err != nil {
return nil, err
}
return stateChange, nil
}
func publishStateChange(ctx context.Context, publisher pubsub.Publisher, job *Job) error {
payload, err := encodeStateChange(job)
if err != nil {
return fmt.Errorf("failed to gob encode StateChange: %w", err)
}
err = publisher.Publish(ctx, PubSubTopicStateChange, payload)
if err != nil {
return fmt.Errorf("failed to publish StateChange: %w", err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/timer.go | job/timer.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"time"
)
const timerMaxDur = 30 * time.Minute
const timerMinDur = time.Nanosecond
type schedulerTimer struct {
timerAt time.Time
timer *time.Timer
edgy bool // if true, the next RescheduleEarlier call will trigger the timer immediately.
}
// newSchedulerTimer created new timer for the Scheduler. It is created to fire immediately.
func newSchedulerTimer() *schedulerTimer {
return &schedulerTimer{
timerAt: time.Now().Add(timerMinDur),
timer: time.NewTimer(timerMinDur),
}
}
// ResetAt resets the internal timer to trigger at the provided time.
// If the provided time is zero, it will schedule it to after the max duration.
func (t *schedulerTimer) ResetAt(next time.Time, edgy bool) time.Duration {
return t.resetAt(time.Now(), next, edgy)
}
func (t *schedulerTimer) resetAt(now, next time.Time, edgy bool) time.Duration {
var dur time.Duration
dur = next.Sub(now)
if dur < timerMinDur {
dur = timerMinDur
next = now.Add(dur)
} else if dur > timerMaxDur {
dur = timerMaxDur
next = now.Add(dur)
}
t.Stop()
t.edgy = edgy
t.timerAt = next
t.timer.Reset(dur)
return dur
}
// RescheduleEarlier will reset the timer if the new time is earlier than the previous time.
// Otherwise, the function does nothing and returns 0.
// Providing zero time triggers the timer if it's edgy, otherwise does nothing.
func (t *schedulerTimer) RescheduleEarlier(next time.Time) time.Duration {
return t.rescheduleEarlier(time.Now(), next)
}
func (t *schedulerTimer) rescheduleEarlier(now, next time.Time) time.Duration {
var dur time.Duration
switch {
case t.edgy:
// if the timer is edgy trigger it immediately
dur = timerMinDur
case next.IsZero():
// if the provided time is zero: trigger the timer if it's edgy otherwise do nothing
if !t.edgy {
return 0
}
dur = timerMinDur
case !next.Before(t.timerAt):
// do nothing if the timer is already scheduled to run sooner than the provided time
return 0
default:
dur = max(next.Sub(now), timerMinDur)
}
next = now.Add(dur)
t.Stop()
t.timerAt = next
t.timer.Reset(dur)
return dur
}
func (t *schedulerTimer) Ch() <-chan time.Time {
return t.timer.C
}
func (t *schedulerTimer) Stop() {
// stop the timer
t.timer.Stop()
// consume the timer's tick if any
select {
case <-t.timer.C:
default:
}
t.timerAt = time.Time{}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/uid.go | job/uid.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"crypto/rand"
"encoding/base32"
)
// UID returns unique random string with length equal to 16.
func UID() (string, error) {
const uidSizeBytes = 10 // must be divisible by 5, the resulting string length will be uidSizeBytes/5*8
var buf [uidSizeBytes]byte
_, err := rand.Read(buf[:])
if err != nil {
return "", err
}
uid := base32.StdEncoding.EncodeToString(buf[:])
return uid, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/config.go | job/config.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import "time"
type Config struct {
// InstanceID specifis the ID of the instance.
InstanceID string `envconfig:"INSTANCE_ID"`
// MaxRunning is maximum number of jobs that can be running at once.
BackgroundJobsMaxRunning int `envconfig:"JOBS_MAX_RUNNING" default:"10"`
// RetentionTime is the duration after which non-recurring,
// finished and failed jobs will be purged from the DB.
BackgroundJobsRetentionTime time.Duration `envconfig:"JOBS_RETENTION_TIME" default:"120h"` // 5 days
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/lock.go | job/lock.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"context"
"github.com/harness/gitness/lock"
)
func globalLock(ctx context.Context, manager lock.MutexManager) (lock.Mutex, error) {
const lockKey = "jobs"
mx, err := manager.NewMutex(lockKey)
if err != nil {
return nil, err
}
err = mx.Lock(ctx)
return mx, err
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/job_overdue.go | job/job_overdue.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/lock"
"github.com/rs/zerolog/log"
)
const (
jobUIDOverdue = "gitness:jobs:overdue"
jobTypeOverdue = "gitness:jobs:overdue"
jobCronOverdue = "*/20 * * * *" // every 20 min
)
type jobOverdue struct {
store Store
mxManager lock.MutexManager
scheduler *Scheduler
}
func newJobOverdue(store Store, mxManager lock.MutexManager, scheduler *Scheduler) *jobOverdue {
return &jobOverdue{
store: store,
mxManager: mxManager,
scheduler: scheduler,
}
}
// Handle reclaims overdue jobs. Normally this shouldn't happen.
// But, it can occur if DB update after a job execution fails,
// or the server suddenly terminates while the job is still running.
func (j *jobOverdue) Handle(ctx context.Context, _ string, _ ProgressReporter) (string, error) {
mx, err := globalLock(ctx, j.mxManager)
if err != nil {
return "", fmt.Errorf("failed to obtain the lock to reclaim overdue jobs")
}
defer func() {
if err := mx.Unlock(ctx); err != nil {
log.Err(err).Msg("failed to release global lock after reclaiming overdue jobs")
}
}()
overdueJobs, err := j.store.ListDeadlineExceeded(ctx, time.Now())
if err != nil {
return "", fmt.Errorf("failed to list overdue jobs")
}
if len(overdueJobs) == 0 {
return "", nil
}
var minScheduled time.Time
for _, job := range overdueJobs {
const errorMessage = "deadline exceeded"
postExec(job, "", errorMessage)
err = j.store.UpdateExecution(ctx, job)
if err != nil {
return "", fmt.Errorf("failed update overdue job")
}
if job.State == JobStateScheduled {
scheduled := time.UnixMilli(job.Scheduled)
if minScheduled.IsZero() || minScheduled.After(scheduled) {
minScheduled = scheduled
}
}
}
if !minScheduled.IsZero() {
j.scheduler.scheduleProcessing(minScheduled)
}
result := fmt.Sprintf("found %d overdue jobs", len(overdueJobs))
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/store.go | job/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 job
import (
"context"
"time"
)
type Store interface {
// Find fetches a job by its unique identifier.
Find(ctx context.Context, uid string) (*Job, error)
// ListByGroupID fetches all jobs for a group id
ListByGroupID(ctx context.Context, groupID string) ([]*Job, error)
// DeleteByGroupID deletes all jobs for a group id
DeleteByGroupID(ctx context.Context, groupID string) (int64, error)
// Create is used to create a new job.
Create(ctx context.Context, job *Job) error
// Upsert will insert the job in the database if the job didn't already exist,
// or it will update the existing one but only if its definition has changed.
Upsert(ctx context.Context, job *Job) error
// UpdateDefinition is used to update a job definition.
UpdateDefinition(ctx context.Context, job *Job) error
// UpdateExecution is used to update a job before and after execution.
UpdateExecution(ctx context.Context, job *Job) error
// UpdateProgress is used to update a job progress data.
UpdateProgress(ctx context.Context, job *Job) error
// CountRunning returns number of jobs that are currently being run.
CountRunning(ctx context.Context) (int, error)
// ListReady returns a list of jobs that are ready for execution.
ListReady(ctx context.Context, now time.Time, limit int) ([]*Job, error)
// ListDeadlineExceeded returns a list of jobs that have exceeded their execution deadline.
ListDeadlineExceeded(ctx context.Context, now time.Time) ([]*Job, error)
// NextScheduledTime returns a scheduled time of the next ready job.
NextScheduledTime(ctx context.Context, now time.Time) (time.Time, error)
// DeleteOld removes non-recurring jobs that have finished execution or have failed.
DeleteOld(ctx context.Context, olderThan time.Time) (int64, error)
// DeleteByUID deletes a job by its unique identifier.
DeleteByUID(ctx context.Context, jobUID string) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/timer_test.go | job/timer_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 job
import (
"testing"
"time"
)
func TestSchedulerTimer_ResetAt(t *testing.T) {
now := time.Now()
tests := []struct {
name string
at time.Time
exp time.Duration
}{
{
name: "zero",
at: time.Time{},
exp: timerMinDur,
},
{
name: "immediate",
at: now,
exp: timerMinDur,
},
{
name: "30s",
at: now.Add(30 * time.Second),
exp: 30 * time.Second,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
timer := newSchedulerTimer()
dur := timer.resetAt(now, test.at, false)
if want, got := test.exp, dur; want != dur {
t.Errorf("want: %s, got: %s", want.String(), got.String())
}
})
}
}
func TestSchedulerTimer_TryResetAt(t *testing.T) {
now := time.Now()
tests := []struct {
name string
at time.Time
edgy bool
exp time.Duration
}{
{
name: "past",
at: now.Add(-time.Second),
exp: timerMinDur,
},
{
name: "30s",
at: now.Add(30 * time.Second),
exp: 30 * time.Second,
},
{
name: "90s",
at: now.Add(90 * time.Second),
exp: 0,
},
{
name: "30s-edgy",
at: now.Add(30 * time.Second),
edgy: true,
exp: timerMinDur,
},
{
name: "90s-edgy",
at: now.Add(90 * time.Second),
edgy: true,
exp: timerMinDur,
},
{
name: "zero",
at: time.Time{},
exp: 0,
},
{
name: "zero-edgy",
at: time.Time{},
edgy: true,
exp: timerMinDur,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
timer := newSchedulerTimer()
timer.resetAt(now, now.Add(time.Minute), test.edgy)
dur := timer.rescheduleEarlier(now, test.at)
if want, got := test.exp, dur; want != dur {
t.Errorf("want: %s, got: %s", want.String(), got.String())
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/scheduler.go | job/scheduler.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"context"
"errors"
"fmt"
"runtime/debug"
"sync"
"time"
"github.com/harness/gitness/lock"
"github.com/harness/gitness/pubsub"
"github.com/harness/gitness/store"
"github.com/gorhill/cronexpr"
"github.com/rs/zerolog/log"
)
// Scheduler controls execution of background jobs.
type Scheduler struct {
// dependencies
store Store
executor *Executor
mxManager lock.MutexManager
pubsubService pubsub.PubSub
// configuration fields
instanceID string
maxRunning int
retentionTime time.Duration
// synchronization stuff
signal chan time.Time
done chan struct{}
wgRunning sync.WaitGroup
cancelJobMx sync.Mutex
cancelJobMap map[string]context.CancelFunc
}
func NewScheduler(
store Store,
executor *Executor,
mxManager lock.MutexManager,
pubsubService pubsub.PubSub,
instanceID string,
maxRunning int,
retentionTime time.Duration,
) (*Scheduler, error) {
if maxRunning < 1 {
maxRunning = 1
}
return &Scheduler{
store: store,
executor: executor,
mxManager: mxManager,
pubsubService: pubsubService,
instanceID: instanceID,
maxRunning: maxRunning,
retentionTime: retentionTime,
cancelJobMap: map[string]context.CancelFunc{},
}, nil
}
// Run runs the background job scheduler.
// It's a blocking call. It blocks until the provided context is done.
//
//nolint:gocognit // refactor if needed.
func (s *Scheduler) Run(ctx context.Context) error {
if s.done != nil {
return errors.New("already started")
}
consumer := s.pubsubService.Subscribe(ctx, PubSubTopicCancelJob, s.handleCancelJob)
defer func() {
err := consumer.Close()
if err != nil {
log.Ctx(ctx).Err(err).
Msg("job scheduler: failed to close pubsub cancel job consumer")
}
}()
if err := s.createNecessaryJobs(ctx); err != nil {
return fmt.Errorf("failed to create necessary jobs: %w", err)
}
if err := s.registerNecessaryJobs(); err != nil {
return fmt.Errorf("failed to register scheduler's internal jobs: %w", err)
}
s.executor.finishRegistration()
log.Ctx(ctx).Debug().Msg("job scheduler: starting")
s.done = make(chan struct{})
defer close(s.done)
s.signal = make(chan time.Time, 1)
timer := newSchedulerTimer()
defer timer.Stop()
for {
err := func() error {
defer func() {
if r := recover(); r != nil {
stack := string(debug.Stack())
log.Ctx(ctx).Error().
Str("panic", fmt.Sprintf("[%T] job scheduler panic: %v", r, r)).
Msg(stack)
}
}()
select {
case <-ctx.Done():
return ctx.Err()
case newTime := <-s.signal:
dur := timer.RescheduleEarlier(newTime)
if dur > 0 {
log.Ctx(ctx).Trace().
Msgf("job scheduler: update of scheduled job processing time... runs in %s", dur)
}
return nil
case now := <-timer.Ch():
count, nextExec, gotAllJobs, err := s.processReadyJobs(ctx, now)
// If the next processing time isn't known use the default.
if nextExec.IsZero() {
const period = time.Minute
nextExec = now.Add(period)
}
// Reset the timer. Make the timer edgy if there are more jobs available.
dur := timer.ResetAt(nextExec, !gotAllJobs)
if err != nil {
log.Ctx(ctx).Err(err).
Msgf("job scheduler: failed to process jobs; next iteration in %s", dur)
} else {
log.Ctx(ctx).Trace().
Msgf("job scheduler: started %d jobs; next iteration in %s", count, dur)
}
return nil
}
}()
if err != nil {
return err
}
}
}
// WaitJobsDone waits until execution of all jobs has finished.
// It is intended to be used for graceful shutdown, after the Run method has finished.
func (s *Scheduler) WaitJobsDone(ctx context.Context) {
log.Ctx(ctx).Debug().Msg("job scheduler: stopping... waiting for the currently running jobs to finish")
ch := make(chan struct{})
go func() {
s.wgRunning.Wait()
close(ch)
}()
select {
case <-ctx.Done():
log.Ctx(ctx).Warn().Msg("job scheduler: stop interrupted")
case <-ch:
log.Ctx(ctx).Info().Msg("job scheduler: gracefully stopped")
}
}
// CancelJob cancels a currently running or scheduled job.
func (s *Scheduler) CancelJob(ctx context.Context, jobUID string) error {
mx, err := globalLock(ctx, s.mxManager)
if err != nil {
return fmt.Errorf("failed to obtain global lock to cancel a job: %w", err)
}
defer func() {
if err := mx.Unlock(ctx); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to release global lock after canceling a job")
}
}()
job, err := s.store.Find(ctx, jobUID)
if errors.Is(err, store.ErrResourceNotFound) {
return nil // ensure consistent response for completed jobs
}
if err != nil {
return fmt.Errorf("failed to find job to cancel: %w", err)
}
if job.IsRecurring {
return errors.New("can't cancel recurring jobs")
}
if job.State != JobStateScheduled && job.State != JobStateRunning {
return nil // return no error if the job is already canceled or has finished or failed.
}
// first we update the job in the database...
job.Updated = time.Now().UnixMilli()
job.State = JobStateCanceled
err = s.store.UpdateExecution(ctx, job)
if err != nil {
return fmt.Errorf("failed to update job to cancel it: %w", err)
}
// ... and then we cancel its context.
s.cancelJobMx.Lock()
cancelFn, ok := s.cancelJobMap[jobUID]
s.cancelJobMx.Unlock()
if ok {
cancelFn()
return nil
}
return s.pubsubService.Publish(ctx, PubSubTopicCancelJob, []byte(jobUID))
}
func (s *Scheduler) handleCancelJob(payload []byte) error {
jobUID := string(payload)
if jobUID == "" {
return nil
}
s.cancelJobMx.Lock()
cancelFn, ok := s.cancelJobMap[jobUID]
s.cancelJobMx.Unlock()
if ok {
cancelFn()
}
return nil
}
// scheduleProcessing triggers processing of ready jobs.
// This should be run after adding new jobs to the database.
func (s *Scheduler) scheduleProcessing(scheduled time.Time) {
go func() {
select {
case <-s.done:
case s.signal <- scheduled:
}
}()
}
// scheduleIfHaveMoreJobs triggers processing of ready jobs if the timer is edgy.
// The timer would be edgy if the previous iteration found more jobs that it could start (full capacity).
// This should be run after a non-recurring job has finished.
func (s *Scheduler) scheduleIfHaveMoreJobs() {
s.scheduleProcessing(time.Time{}) // zero time will trigger the timer if it's edgy
}
// RunJob runs a single job of the type Definition.Type.
// All parameters a job Handler receives must be inside the Definition.Data string
// (as JSON or whatever the job Handler can interpret).
func (s *Scheduler) RunJob(ctx context.Context, def Definition) error {
if err := def.Validate(); err != nil {
return err
}
job := def.toNewJob()
if err := s.store.Create(ctx, job); err != nil {
return fmt.Errorf("failed to add new job to the database: %w", err)
}
s.scheduleProcessing(time.UnixMilli(job.Scheduled))
return nil
}
// RunJobs runs a several jobs. It's more efficient than calling RunJob several times
// because it locks the DB only once.
func (s *Scheduler) RunJobs(ctx context.Context, groupID string, defs []Definition) error {
if len(defs) == 0 {
return nil
}
jobs := make([]*Job, len(defs))
for i, def := range defs {
if err := def.Validate(); err != nil {
return err
}
jobs[i] = def.toNewJob()
jobs[i].GroupID = groupID
}
for _, job := range jobs {
if err := s.store.Create(ctx, job); err != nil {
return fmt.Errorf("failed to add new job to the database: %w", err)
}
}
s.scheduleProcessing(time.Now())
return nil
}
// processReadyJobs executes jobs that are ready to run. This function is periodically run by the Scheduler.
// The function returns the number of jobs it has is started, the next scheduled execution time (of this function)
// and a bool value if all currently available ready jobs were started.
// Internally the Scheduler uses an "edgy" timer to reschedule calls of this function.
// The edgy option of the timer will be on if this function hasn't been able to start all job that are ready to run.
// If the timer has the edgy option turned on it will trigger the timer (and thus this function will be called)
// when any currently running job finishes successfully or fails.
func (s *Scheduler) processReadyJobs(ctx context.Context, now time.Time) (int, time.Time, bool, error) {
mx, err := globalLock(ctx, s.mxManager)
if err != nil {
return 0, time.Time{}, false,
fmt.Errorf("failed to obtain global lock to periodically process ready jobs: %w", err)
}
defer func() {
if err := mx.Unlock(ctx); err != nil {
log.Ctx(ctx).Err(err).
Msg("failed to release global lock after periodic processing of ready jobs")
}
}()
availableCount, err := s.availableSlots(ctx)
if err != nil {
return 0, time.Time{}, false,
fmt.Errorf("failed to count available slots for job execution: %w", err)
}
// get one over the limit to check if all ready jobs are fetched
jobs, err := s.store.ListReady(ctx, now, availableCount+1)
if err != nil {
return 0, time.Time{}, false,
fmt.Errorf("failed to load scheduled jobs: %w", err)
}
var (
countExecuted int
knownNextExecTime time.Time
gotAllJobs bool
)
if len(jobs) > availableCount {
// More jobs are ready than we are able to run.
jobs = jobs[:availableCount]
} else {
gotAllJobs = true
knownNextExecTime, err = s.store.NextScheduledTime(ctx, now)
if err != nil {
return 0, time.Time{}, false,
fmt.Errorf("failed to read next scheduled time: %w", err)
}
}
for _, job := range jobs {
jobCtx := log.Ctx(ctx).With().
Str("job.UID", job.UID).
Str("job.Type", job.Type).
Logger().WithContext(ctx)
// Update the job fields for the new execution
s.preExec(job)
if err := s.store.UpdateExecution(ctx, job); err != nil {
knownNextExecTime = time.Time{}
gotAllJobs = false
log.Ctx(jobCtx).Err(err).Msg("failed to update job to mark it as running")
continue
}
// tell everybody that a job has started
if err := publishStateChange(ctx, s.pubsubService, job); err != nil {
log.Ctx(jobCtx).Err(err).Msg("failed to publish job state change")
}
s.runJob(jobCtx, job)
countExecuted++
}
return countExecuted, knownNextExecTime, gotAllJobs, nil
}
func (s *Scheduler) availableSlots(ctx context.Context) (int, error) {
countRunning, err := s.store.CountRunning(ctx)
if err != nil {
return 0, err
}
availableCount := s.maxRunning - countRunning
if availableCount < 0 {
return 0, nil
}
return availableCount, nil
}
// runJob updates the job in the database and starts it in a separate goroutine.
// The function will also log the execution.
func (s *Scheduler) runJob(ctx context.Context, j *Job) {
s.wgRunning.Add(1)
go func(ctx context.Context,
jobUID, jobType, jobData string,
jobRunDeadline int64,
) {
defer s.wgRunning.Done()
log.Ctx(ctx).Debug().Msg("started job")
timeStart := time.Now()
// Run the job
execResult, execFailure := s.doExec(ctx, jobUID, jobType, jobData, jobRunDeadline)
// Use the context.Background() because we want to update the job even if the job's context is done.
// The context can be done because the job exceeded its deadline or the server is shutting down.
backgroundCtx := context.Background()
//nolint: contextcheck
if mx, err := globalLock(backgroundCtx, s.mxManager); err != nil {
// If locking failed, just log the error and proceed to update the DB anyway.
log.Ctx(ctx).Err(err).Msg("failed to obtain global lock to update job after execution")
} else {
defer func() {
if err := mx.Unlock(backgroundCtx); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to release global lock to update job after execution")
}
}()
}
//nolint: contextcheck
job, err := s.store.Find(backgroundCtx, jobUID)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to find job after execution")
return
}
// Update the job fields, reschedule if necessary.
postExec(job, execResult, execFailure)
//nolint: contextcheck
err = s.store.UpdateExecution(backgroundCtx, job)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to update job after execution")
return
}
logInfo := log.Ctx(ctx).Info().Str("duration", time.Since(timeStart).String())
if job.IsRecurring {
logInfo = logInfo.Bool("job.IsRecurring", true)
}
if job.Result != "" {
logInfo = logInfo.Str("job.Result", job.Result)
}
if job.LastFailureError != "" {
logInfo = logInfo.Str("job.Failure", job.LastFailureError)
}
switch job.State {
case JobStateFinished:
logInfo.Msg("job successfully finished")
s.scheduleIfHaveMoreJobs()
case JobStateFailed:
logInfo.Msg("job failed")
s.scheduleIfHaveMoreJobs()
case JobStateCanceled:
log.Ctx(ctx).Error().Msg("job canceled")
s.scheduleIfHaveMoreJobs()
case JobStateScheduled:
scheduledTime := time.UnixMilli(job.Scheduled)
logInfo.
Str("job.Scheduled", scheduledTime.Format(time.RFC3339Nano)).
Msg("job finished and rescheduled")
s.scheduleProcessing(scheduledTime)
case JobStateRunning:
log.Ctx(ctx).Error().Msg("should not happen; job still has state=running after finishing")
}
// tell everybody that a job has finished execution
//nolint: contextcheck
if err := publishStateChange(backgroundCtx, s.pubsubService, job); err != nil {
log.Ctx(ctx).Err(err).Msg("failed to publish job state change")
}
}(ctx, j.UID, j.Type, j.Data, j.RunDeadline)
}
// preExec updates the provided Job before execution.
func (s *Scheduler) preExec(job *Job) {
if job.MaxDurationSeconds < 1 {
job.MaxDurationSeconds = 1
}
now := time.Now()
nowMilli := now.UnixMilli()
execDuration := time.Duration(job.MaxDurationSeconds) * time.Second
execDeadline := now.Add(execDuration)
job.Updated = nowMilli
job.LastExecuted = nowMilli
job.State = JobStateRunning
job.RunDeadline = execDeadline.UnixMilli()
job.RunBy = s.instanceID
job.RunProgress = ProgressMin
job.TotalExecutions++
job.Result = ""
job.LastFailureError = ""
}
// doExec executes the provided Job.
func (s *Scheduler) doExec(ctx context.Context,
jobUID, jobType, jobData string,
jobRunDeadline int64,
) (execResult, execError string) {
execDeadline := time.UnixMilli(jobRunDeadline)
jobCtx, done := context.WithDeadline(ctx, execDeadline)
defer done()
s.cancelJobMx.Lock()
if _, ok := s.cancelJobMap[jobUID]; ok {
// should not happen: jobs have unique UIDs!
s.cancelJobMx.Unlock()
return "", "failed to start: already running"
}
s.cancelJobMap[jobUID] = done
s.cancelJobMx.Unlock()
defer func() {
s.cancelJobMx.Lock()
delete(s.cancelJobMap, jobUID)
s.cancelJobMx.Unlock()
}()
execResult, err := s.executor.exec(jobCtx, jobUID, jobType, jobData)
if err != nil {
execError = err.Error()
}
return
}
// postExec updates the provided Job after execution and reschedules it if necessary.
//
//nolint:gocognit // refactor if needed.
func postExec(job *Job, resultData, resultErr string) {
// Proceed with the update of the job if it's in the running state or
// if it's marked as canceled but has succeeded nonetheless.
// Other states should not happen, but if they do, just leave the job as it is.
if job.State != JobStateRunning && (job.State != JobStateCanceled || resultErr != "") {
return
}
now := time.Now()
nowMilli := now.UnixMilli()
job.Updated = nowMilli
job.Result = resultData
job.RunBy = ""
if resultErr != "" {
job.ConsecutiveFailures++
job.State = JobStateFailed
job.LastFailureError = resultErr
} else {
job.State = JobStateFinished
job.RunProgress = ProgressMax
}
// Reschedule recurring jobs
//nolint:nestif // refactor if needed
if job.IsRecurring {
if resultErr == "" {
job.ConsecutiveFailures = 0
}
exp, err := cronexpr.Parse(job.RecurringCron)
if err != nil {
job.State = JobStateFailed
messages := fmt.Sprintf("failed to parse cron string: %s", err.Error())
if job.LastFailureError != "" {
messages = messages + "; " + job.LastFailureError
}
job.LastFailureError = messages
} else {
job.State = JobStateScheduled
job.Scheduled = exp.Next(now).UnixMilli()
}
return
}
// Reschedule the failed job if retrying is allowed
if job.State == JobStateFailed && job.ConsecutiveFailures <= job.MaxRetries {
const retryDelay = 15 * time.Second
job.State = JobStateScheduled
job.Scheduled = now.Add(retryDelay).UnixMilli()
job.RunProgress = ProgressMin
}
}
func (s *Scheduler) GetJobProgress(ctx context.Context, jobUID string) (Progress, error) {
job, err := s.store.Find(ctx, jobUID)
if err != nil {
return Progress{}, err
}
return mapToProgress(job), nil
}
func (s *Scheduler) GetJobProgressForGroup(ctx context.Context, jobGroupUID string) ([]Progress, error) {
job, err := s.store.ListByGroupID(ctx, jobGroupUID)
if err != nil {
return nil, err
}
return mapToProgressMany(job), nil
}
func (s *Scheduler) PurgeJobsByGroupID(ctx context.Context, jobGroupID string) (int64, error) {
n, err := s.store.DeleteByGroupID(ctx, jobGroupID)
if err != nil {
return 0, fmt.Errorf("failed to delete jobs by group id=%s: %w", jobGroupID, err)
}
return n, nil
}
func (s *Scheduler) PurgeJobByUID(ctx context.Context, jobUID string) error {
err := s.store.DeleteByUID(ctx, jobUID)
if err != nil {
return fmt.Errorf("failed to delete job with id=%s: %w", jobUID, err)
}
return nil
}
func mapToProgressMany(jobs []*Job) []Progress {
if jobs == nil {
return nil
}
j := make([]Progress, len(jobs))
for i, job := range jobs {
j[i] = mapToProgress(job)
}
return j
}
func mapToProgress(job *Job) Progress {
return Progress{
State: job.State,
Progress: job.RunProgress,
Result: job.Result,
Failure: job.LastFailureError,
}
}
func (s *Scheduler) AddRecurring(
ctx context.Context,
jobUID,
jobType,
cronDef string,
maxDur time.Duration,
) error {
cronExp, err := cronexpr.Parse(cronDef)
if err != nil {
return fmt.Errorf("invalid cron definition string for job type=%s: %w", jobType, err)
}
now := time.Now()
nowMilli := now.UnixMilli()
nextExec := cronExp.Next(now)
job := &Job{
UID: jobUID,
Created: nowMilli,
Updated: nowMilli,
Type: jobType,
Priority: JobPriorityElevated,
Data: "",
Result: "",
MaxDurationSeconds: int(maxDur / time.Second),
MaxRetries: 0,
State: JobStateScheduled,
Scheduled: nextExec.UnixMilli(),
TotalExecutions: 0,
RunBy: "",
RunDeadline: 0,
RunProgress: 0,
LastExecuted: 0,
IsRecurring: true,
RecurringCron: cronDef,
ConsecutiveFailures: 0,
LastFailureError: "",
}
err = s.store.Upsert(ctx, job)
if err != nil {
return fmt.Errorf("failed to upsert job id=%s type=%s: %w", jobUID, jobType, err)
}
return nil
}
func (s *Scheduler) createNecessaryJobs(ctx context.Context) error {
mx, err := globalLock(ctx, s.mxManager)
if err != nil {
return fmt.Errorf("failed to obtain global lock to create necessary jobs: %w", err)
}
defer func() {
if err := mx.Unlock(ctx); err != nil {
log.Ctx(ctx).Err(err).
Msg("failed to release global lock after creating necessary jobs")
}
}()
err = s.AddRecurring(ctx, jobUIDPurge, jobTypePurge, jobCronPurge, 5*time.Second)
if err != nil {
return err
}
err = s.AddRecurring(ctx, jobUIDOverdue, jobTypeOverdue, jobCronOverdue, 5*time.Second)
if err != nil {
return err
}
return nil
}
// registerNecessaryJobs registers two jobs: overdue job recovery and purge old finished jobs.
// These two jobs types are integral part of the job scheduler.
func (s *Scheduler) registerNecessaryJobs() error {
handlerOverdue := newJobOverdue(s.store, s.mxManager, s)
err := s.executor.Register(jobTypeOverdue, handlerOverdue)
if err != nil {
return err
}
handlerPurge := newJobPurge(s.store, s.mxManager, s.retentionTime)
err = s.executor.Register(jobTypePurge, handlerPurge)
if err != nil {
return err
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/enum.go | job/enum.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
)
// State represents state of a background job.
type State string
// State enumeration.
const (
JobStateScheduled State = "scheduled"
JobStateRunning State = "running"
JobStateFinished State = "finished"
JobStateFailed State = "failed"
JobStateCanceled State = "canceled"
)
var jobStates = sortEnum([]State{
JobStateScheduled,
JobStateRunning,
JobStateFinished,
JobStateFailed,
JobStateCanceled,
})
func (State) Enum() []any { return toInterfaceSlice(jobStates) }
func (s State) Sanitize() (State, bool) {
return Sanitize(s, GetAllJobStates)
}
func GetAllJobStates() ([]State, State) {
return jobStates, ""
}
// Priority represents priority of a background job.
type Priority int
// JobPriority enumeration.
const (
JobPriorityNormal Priority = 0
JobPriorityElevated Priority = 1
)
func (s State) IsCompleted() bool {
return s == JobStateFinished || s == JobStateFailed || s == JobStateCanceled
}
func sortEnum[T constraints.Ordered](slice []T) []T {
slices.Sort(slice)
return slice
}
func toInterfaceSlice[T any](vals []T) []any {
res := make([]any, len(vals))
for i := range vals {
res[i] = vals[i]
}
return res
}
func Sanitize[E constraints.Ordered](element E, all func() ([]E, E)) (E, bool) {
allValues, defValue := all()
var empty E
if element == empty && defValue != empty {
return defValue, true
}
idx, exists := slices.BinarySearch(allValues, element)
if exists {
return allValues[idx], true
}
return defValue, false
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/uid_test.go | job/uid_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 job
import (
"testing"
)
func TestUID(t *testing.T) {
uid, err := UID()
if err != nil {
t.Fatalf("UID() returned error: %v", err)
}
// Verify UID is not empty
if uid == "" {
t.Errorf("UID() returned empty string")
}
// Verify UID has expected length (10 bytes / 5 * 8 = 16 characters)
expectedLength := 16
if len(uid) != expectedLength {
t.Errorf("UID() length = %d, expected %d", len(uid), expectedLength)
}
// Verify UID contains only valid base32 characters
validChars := "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="
for _, c := range uid {
found := false
for _, valid := range validChars {
if c == valid {
found = true
break
}
}
if !found {
t.Errorf("UID() contains invalid character: %c", c)
}
}
}
func TestUIDUniqueness(t *testing.T) {
// Generate multiple UIDs and verify they are unique
const numUIDs = 1000
uids := make(map[string]bool)
for i := range numUIDs {
uid, err := UID()
if err != nil {
t.Fatalf("UID() returned error on iteration %d: %v", i, err)
}
if uids[uid] {
t.Errorf("UID() generated duplicate: %s", uid)
}
uids[uid] = true
}
// Verify we generated the expected number of unique UIDs
if len(uids) != numUIDs {
t.Errorf("Generated %d unique UIDs, expected %d", len(uids), numUIDs)
}
}
func TestUIDConsistentLength(t *testing.T) {
// Generate multiple UIDs and verify they all have the same length
const numUIDs = 100
expectedLength := 16
for i := range numUIDs {
uid, err := UID()
if err != nil {
t.Fatalf("UID() returned error on iteration %d: %v", i, err)
}
if len(uid) != expectedLength {
t.Errorf("UID() iteration %d: length = %d, expected %d", i, len(uid), expectedLength)
}
}
}
func TestUIDBase32Encoding(t *testing.T) {
// Generate a UID and verify it's valid base32
uid, err := UID()
if err != nil {
t.Fatalf("UID() returned error: %v", err)
}
// Try to decode it as base32 - should not error
// Note: We don't need to import encoding/base32 again as it's already in uid.go
// Just verify the format is correct by checking characters
for i, c := range uid {
if (c < 'A' || c > 'Z') && (c < '2' || c > '7') && c != '=' {
t.Errorf("UID() character at position %d (%c) is not valid base32", i, c)
}
}
}
func TestUIDNoPadding(t *testing.T) {
// Generate multiple UIDs and verify they don't have padding
// (10 bytes encodes to exactly 16 characters without padding)
const numUIDs = 100
for i := range numUIDs {
uid, err := UID()
if err != nil {
t.Fatalf("UID() returned error on iteration %d: %v", i, err)
}
// Check if UID contains padding character '='
for j, c := range uid {
if c == '=' {
t.Errorf("UID() iteration %d: contains padding at position %d", i, j)
}
}
}
}
func BenchmarkUID(b *testing.B) {
for b.Loop() {
_, err := UID()
if err != nil {
b.Fatalf("UID() returned error: %v", err)
}
}
}
func BenchmarkUIDParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := UID()
if err != nil {
b.Fatalf("UID() returned error: %v", err)
}
}
})
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/executor.go | job/executor.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"context"
"errors"
"fmt"
"runtime/debug"
"time"
"github.com/harness/gitness/pubsub"
"github.com/rs/zerolog/log"
)
// Executor holds map of Handler objects per each job type registered.
// The Scheduler uses the Executor to start execution of jobs.
type Executor struct {
handlerMap map[string]Handler
handlerComplete bool
store Store
publisher pubsub.Publisher
}
const (
ProgressMin = 0
ProgressMax = 100
)
// ProgressReporter can be used by a job Handler to report back the execution progress.
type ProgressReporter func(progress int, result string) error
// Handler is a job executor for a specific job type.
// An implementation should try to honor the context and
// try to abort the execution as soon as the context is done.
type Handler interface {
Handle(ctx context.Context, input string, fn ProgressReporter) (result string, err error)
}
var errNoHandlerDefined = errors.New("no handler registered for the job type")
// NewExecutor creates new Executor.
func NewExecutor(store Store, publisher pubsub.Publisher) *Executor {
return &Executor{
handlerMap: make(map[string]Handler),
handlerComplete: false,
store: store,
publisher: publisher,
}
}
// Register registers a job Handler for the provided job type.
// This function is not thread safe. All calls are expected to be made
// in a single thread during the application boot time.
func (e *Executor) Register(jobType string, exec Handler) error {
if jobType == "" {
return errors.New("jobType must not be empty")
}
if e.handlerComplete {
return errors.New("job handler registration is complete")
}
if exec == nil {
return errors.New("provided Handler is nil")
}
if _, ok := e.handlerMap[jobType]; ok {
return fmt.Errorf("a Handler is already defined to run the '%s' job types", jobType)
}
e.handlerMap[jobType] = exec
return nil
}
// finishRegistration forbids further registration of job types.
// It is called by the Scheduler when it starts.
func (e *Executor) finishRegistration() {
e.handlerComplete = true
}
// exec runs a single job. This function is synchronous,
// so the caller is responsible to run it in a separate go-routine.
func (e *Executor) exec(
ctx context.Context,
jobUID, jobType string,
input string,
) (result string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf(
"panic while processing job=%s type=%s: %v\n%s",
jobUID, jobType, r, debug.Stack())
}
}()
exec, ok := e.handlerMap[jobType]
if !ok {
return "", errNoHandlerDefined
}
// progressReporter is the function with which the job can update its progress.
// This function will be executed in the job executor's Go-routine.
// It uses the job's context.
progressReporter := func(progress int, result string) error {
if progress < ProgressMin || progress > ProgressMax {
return errors.New("progress must be between 0 and 100")
}
jobDummy := &Job{
UID: jobUID,
Type: jobType,
Updated: time.Now().UnixMilli(),
Result: result,
State: JobStateRunning,
RunProgress: progress,
}
// This doesn't need to be behind the global lock because it only updates the single row.
// While a job is running no other process should touch it.
// Even this call will fail if the context deadline has been exceeded.
// The job parameter is a dummy Job object that just holds fields that should be updated.
if err := e.store.UpdateProgress(ctx, jobDummy); err != nil {
return err
}
// tell everybody that a job progress has been updated
if err := publishStateChange(ctx, e.publisher, jobDummy); err != nil {
log.Err(err).Msg("failed to publish job state change")
}
return nil
}
return exec.Handle(ctx, input, progressReporter) // runs the job
}
func FailProgress() Progress {
return Progress{
State: JobStateFailed,
Progress: ProgressMax,
Result: "",
Failure: "",
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/definition.go | job/definition.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"errors"
"time"
)
type Definition struct {
UID string
Type string
MaxRetries int
Timeout time.Duration
Data string
}
func (def *Definition) Validate() error {
if def.Type == "" {
return errors.New("job Type must not be empty")
}
if def.UID == "" {
return errors.New("job must have unique identifier")
}
if def.MaxRetries < 0 {
return errors.New("job MaxRetries must be positive")
}
if def.Timeout < time.Second {
return errors.New("job Timeout too short")
}
return nil
}
func (def *Definition) toNewJob() *Job {
nowMilli := time.Now().UnixMilli()
return &Job{
UID: def.UID,
Created: nowMilli,
Updated: nowMilli,
Type: def.Type,
Priority: JobPriorityNormal,
Data: def.Data,
Result: "",
MaxDurationSeconds: int(def.Timeout / time.Second),
MaxRetries: def.MaxRetries,
State: JobStateScheduled,
Scheduled: nowMilli,
TotalExecutions: 0,
RunBy: "",
RunDeadline: nowMilli,
RunProgress: ProgressMin,
LastExecuted: 0, // never executed
IsRecurring: false,
RecurringCron: "",
ConsecutiveFailures: 0,
LastFailureError: "",
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/job/job_purge.go | job/job_purge.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package job
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/lock"
"github.com/rs/zerolog/log"
)
const (
jobUIDPurge = "gitness:jobs:purge"
jobTypePurge = "gitness:jobs:purge"
jobCronPurge = "15 */4 * * *" // every 4 hours at 15 minutes
)
type jobPurge struct {
store Store
mxManager lock.MutexManager
minOldAge time.Duration
}
func newJobPurge(store Store, mxManager lock.MutexManager, minOldAge time.Duration) *jobPurge {
if minOldAge < 0 {
minOldAge = 0
}
return &jobPurge{
store: store,
mxManager: mxManager,
minOldAge: minOldAge,
}
}
func (j *jobPurge) Handle(ctx context.Context, _ string, _ ProgressReporter) (string, error) {
mx, err := globalLock(ctx, j.mxManager)
if err != nil {
return "", fmt.Errorf("failed to obtain the lock to clean up old jobs")
}
defer func() {
if err := mx.Unlock(ctx); err != nil {
log.Err(err).Msg("failed to release global lock after cleaning up old jobs")
}
}()
olderThan := time.Now().Add(-j.minOldAge)
n, err := j.store.DeleteOld(ctx, olderThan)
if err != nil {
return "", fmt.Errorf("failed to purge old jobs")
}
result := "no old jobs found"
if n > 0 {
result = fmt.Sprintf("deleted %d old jobs", n)
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/web/dist.go | web/dist.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package dist embeds the static web server content.
package web
import (
"bytes"
"context"
"embed"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"time"
"github.com/rs/zerolog/log"
)
//go:embed dist/*
var EmbeddedUIFS embed.FS
const (
distPath = "dist"
remoteEntryJS = "remoteEntry.js"
remoteEntryJSFullPath = "/" + remoteEntryJS
)
// Handler returns an http.HandlerFunc that servers the
// static content from the embedded file system.
//
//nolint:gocognit // refactor if required.
func Handler(uiSourceOverride string) http.HandlerFunc {
fs, err := fs.Sub(EmbeddedUIFS, distPath)
if err != nil {
panic(fmt.Errorf("failed to load embedded files: %w", err))
}
// override UI source if provided (for local development)
if uiSourceOverride != "" {
log.Info().Msgf("Starting with alternate UI located at %q", uiSourceOverride)
fs = os.DirFS(uiSourceOverride)
}
remoteEntryContent, remoteEntryExists, err := readRemoteEntryJSContent(fs)
if err != nil {
panic(fmt.Errorf("failed to read remote entry JS content: %w", err))
}
fileMap, err := createFileMapForDistFolder(fs)
if err != nil {
panic(fmt.Errorf("failed to create file map for dist folder: %w", err))
}
publicIndexFileExists := fileMap["index_public.html"]
// Create an http.FileServer to serve the contents of the files subdiretory.
handler := http.FileServer(http.FS(fs))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the file base path
basePath := path.Base(r.URL.Path)
// fallback to root in case the file doesn't exist so /index.html is served
if !fileMap[basePath] {
r.URL.Path = "/"
} else {
r.URL.Path = "/" + basePath
}
// handle public access
if publicIndexFileExists &&
RenderPublicAccessFrom(r.Context()) &&
(r.URL.Path == "/" || r.URL.Path == "/index.html") {
r.URL.Path = "/index_public.html"
}
const (
maxAgeOneYear = 31536000 // 1 year in seconds
)
// Disable caching and sniffing via HTTP headers for UI main entry resources
if r.URL.Path == "/" ||
r.URL.Path == remoteEntryJSFullPath ||
r.URL.Path == "/index.html" ||
r.URL.Path == "/index_public.html" {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0")
w.Header().Set("pragma", "no-cache")
w.Header().Set("X-Content-Type-Options", "nosniff")
} else {
// Apply long-term caching for static assets
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d, immutable", maxAgeOneYear))
}
// Serve /remoteEntry.js from memory
if remoteEntryExists && r.URL.Path == remoteEntryJSFullPath {
http.ServeContent(w, r, r.URL.Path, time.Now(), bytes.NewReader(remoteEntryContent))
} else {
handler.ServeHTTP(w, r)
}
})
}
func readRemoteEntryJSContent(fileSystem fs.FS) ([]byte, bool, error) {
file, err := fileSystem.Open(remoteEntryJS)
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
}
if err != nil {
return nil, false, fmt.Errorf("failed to open remoteEntry.js: %w", err)
}
defer file.Close()
buf, err := io.ReadAll(file)
if err != nil {
return nil, false, fmt.Errorf("failed to read remoteEntry.js: %w", err)
}
enableCDN := os.Getenv("ENABLE_CDN")
if len(enableCDN) == 0 {
enableCDN = "false"
}
return bytes.Replace(buf, []byte("__ENABLE_CDN__"), []byte(enableCDN), 1), true, nil
}
func createFileMapForDistFolder(fileSystem fs.FS) (map[string]bool, error) {
fileMap := make(map[string]bool)
err := fs.WalkDir(fileSystem, ".", func(path string, _ fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("failed to read file info for %q: %w", path, err)
}
if path != "." {
fileMap[path] = true
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to build file map: %w", err)
}
return fileMap, nil
}
// renderPublicAccessKey is the context key for storing and retrieving whether public access should be rendered.
type renderPublicAccessKey struct{}
// RenderPublicAccessFrom retrieves the public access rendering config from the context.
// If true, the UI should be rendered for public access.
func RenderPublicAccessFrom(ctx context.Context) bool {
if v, ok := ctx.Value(renderPublicAccessKey{}).(bool); ok {
return v
}
return false
}
// WithRenderPublicAccess returns a copy of parent in which the public access rendering is set to the provided value.
func WithRenderPublicAccess(parent context.Context, v bool) context.Context {
return context.WithValue(parent, renderPublicAccessKey{}, v)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/http/server.go | http/server.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package http
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"
"strings"
"time"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/sync/errgroup"
)
const (
// DefaultReadHeaderTimeout defines the default timeout for reading headers.
DefaultReadHeaderTimeout = 2 * time.Second
)
// Config defines the config of an http server.
// TODO: expose via options?
type Config struct {
Acme bool
Host string
Port int
Cert string
Key string
AcmeHost string
ReadHeaderTimeout time.Duration
}
// Server is a wrapper around http.Server that exposes different async ListenAndServe methods
// that return corresponding ShutdownFunctions.
type Server struct {
config Config
handler http.Handler
}
// ShutdownFunction defines a function that is called to shutdown the server.
type ShutdownFunction func(context.Context) error
func NewServer(config Config, handler http.Handler) *Server {
if config.ReadHeaderTimeout == 0 {
config.ReadHeaderTimeout = DefaultReadHeaderTimeout
}
return &Server{
config: config,
handler: handler,
}
}
// ListenAndServe initializes a server to respond to HTTP network requests.
func (s *Server) ListenAndServe() (*errgroup.Group, ShutdownFunction) {
if s.config.Acme {
return s.listenAndServeAcme()
} else if s.config.Key != "" {
return s.listenAndServeTLS(false)
}
return s.listenAndServe()
}
func (s *Server) listenAndServe() (*errgroup.Group, ShutdownFunction) {
var g errgroup.Group
s1 := &http.Server{
Addr: fmt.Sprintf("%s:%d", s.config.Host, s.config.Port),
ReadHeaderTimeout: s.config.ReadHeaderTimeout,
Handler: s.handler,
}
g.Go(func() error {
return s1.ListenAndServe()
})
return &g, s1.Shutdown
}
func (s *Server) ListenAndServeMTLS() (*errgroup.Group, ShutdownFunction) {
return s.listenAndServeTLS(true)
}
func (s *Server) listenAndServeTLS(enableMtls bool) (*errgroup.Group, ShutdownFunction) {
var g errgroup.Group
s1 := &http.Server{
Addr: ":http",
ReadHeaderTimeout: s.config.ReadHeaderTimeout,
Handler: http.HandlerFunc(redirect),
}
var tlsConfig *tls.Config
if enableMtls {
caCert, err := os.ReadFile(s.config.Cert)
if err != nil {
panic(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Create the TLS Config with the CA pool and enable Client certificate validation
tlsConfig = &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
MinVersion: tls.VersionTLS13,
}
}
s2 := &http.Server{
Addr: ":https",
ReadHeaderTimeout: s.config.ReadHeaderTimeout,
Handler: s.handler,
TLSConfig: tlsConfig,
}
g.Go(func() error {
return s1.ListenAndServe()
})
g.Go(func() error {
return s2.ListenAndServeTLS(
s.config.Cert,
s.config.Key,
)
})
return &g, func(ctx context.Context) error {
var sg errgroup.Group
sg.Go(func() error {
return s1.Shutdown(ctx)
})
sg.Go(func() error {
return s2.Shutdown(ctx)
})
return sg.Wait()
}
}
func (s Server) listenAndServeAcme() (*errgroup.Group, ShutdownFunction) {
var g errgroup.Group
m := &autocert.Manager{
Cache: autocert.DirCache(".cache"),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(s.config.AcmeHost),
}
s1 := &http.Server{
Addr: ":http",
ReadHeaderTimeout: s.config.ReadHeaderTimeout,
Handler: m.HTTPHandler(nil),
}
s2 := &http.Server{
Addr: ":https",
Handler: s.handler,
ReadHeaderTimeout: s.config.ReadHeaderTimeout,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: m.GetCertificate,
NextProtos: []string{"h2", "http/1.1"},
},
}
g.Go(func() error {
return s1.ListenAndServe()
})
g.Go(func() error {
return s2.ListenAndServeTLS("", "")
})
return &g, func(ctx context.Context) error {
var sg errgroup.Group
sg.Go(func() error {
return s1.Shutdown(ctx)
})
sg.Go(func() error {
return s2.Shutdown(ctx)
})
return sg.Wait()
}
}
func redirect(w http.ResponseWriter, req *http.Request) {
// TODO: in case of reverse-proxy the host might be not the external host.
target := "https://" + req.Host + "/" + strings.TrimPrefix(req.URL.Path, "/")
http.Redirect(w, req, target, http.StatusTemporaryRedirect)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
gohugoio/hugo | https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/main_withdeploy_test.go | main_withdeploy_test.go | // Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build withdeploy
package main
import (
"testing"
"github.com/rogpeppe/go-internal/testscript"
)
func TestWithdeploy(t *testing.T) {
p := commonTestScriptsParam
p.Dir = "testscripts/withdeploy"
testscript.Run(t, p)
}
| go | Apache-2.0 | 5ea3e13db6e436904ee8154bba77af8247b7e534 | 2026-01-07T08:35:43.452707Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.