Skip to content

Modern Docker Management, Designed for Everyone

chore: add backend unit tests and implement registry utility tests

Kyle Mendell9e6bdfc2f2d7
diff --git a/.github/workflows/backend-tests.yml b/.github/workflows/backend-tests.yml
new file mode 100644
index 000000000..b5fd79086
--- /dev/null
+++ b/.github/workflows/backend-tests.yml
@@ -0,0 +1,42 @@
+name: Backend Unit Tests
+
+on:
+ push:
+ paths:
+ - 'backend/**'
+ - '.github/workflows/backend-tests.yml'
+ pull_request:
+ paths:
+ - 'backend/**'
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: backend
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Setup Go
+ uses: actions/setup-go@v5
+ with:
+ go-version-file: backend/go.mod
+ cache: true
+
+ - name: Download modules
+ run: go mod download
+
+ - name: Run unit tests
+ env:
+ CGO_ENABLED: '0'
+ run: go test ./... -race -coverprofile=coverage.out -covermode=atomic -v
+
+ - name: Upload coverage artifact
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: backend-coverage
+ path: backend/coverage.out
diff --git a/backend/internal/dto/auto_update_dto.go b/backend/internal/dto/auto_update_dto.go
index 75d125859..dfdb12742 100644
--- a/backend/internal/dto/auto_update_dto.go
+++ b/backend/internal/dto/auto_update_dto.go
@@ -1,10 +1,10 @@
package dto
type AutoUpdateCheckDto struct {
- Type string `json:"type,omitempty"` // "containers", "stacks", or "all"
- ResourceIds []string `json:"resourceIds,omitempty"` // Specific resources to check
- ForceUpdate bool `json:"forceUpdate,omitempty"` // Force update even if no changes
- DryRun bool `json:"dryRun,omitempty"` // Check only, don't apply updates
+ Type string `json:"type,omitempty"`
+ ResourceIds []string `json:"resourceIds,omitempty"`
+ ForceUpdate bool `json:"forceUpdate,omitempty"`
+ DryRun bool `json:"dryRun,omitempty"`
}
type AutoUpdateResultDto struct {
diff --git a/backend/internal/dto/container_dto.go b/backend/internal/dto/container_dto.go
index e1c78de36..1dca90d36 100644
--- a/backend/internal/dto/container_dto.go
+++ b/backend/internal/dto/container_dto.go
@@ -8,14 +8,14 @@ type CreateContainerDto struct {
WorkingDir string `json:"workingDir,omitempty"`
User string `json:"user,omitempty"`
Environment []string `json:"environment,omitempty"`
- Ports map[string]string `json:"ports,omitempty"` // "80/tcp": "8080"
- Volumes []string `json:"volumes,omitempty"` // ["/host/path:/container/path"]
+ Ports map[string]string `json:"ports,omitempty"`
+ Volumes []string `json:"volumes,omitempty"`
Networks []string `json:"networks,omitempty"`
- RestartPolicy string `json:"restartPolicy,omitempty"` // "no", "always", "unless-stopped", "on-failure"
+ RestartPolicy string `json:"restartPolicy,omitempty"`
Privileged bool `json:"privileged,omitempty"`
AutoRemove bool `json:"autoRemove,omitempty"`
- Memory int64 `json:"memory,omitempty"` // Memory limit in bytes
- CPUs float64 `json:"cpus,omitempty"` // CPU limit
+ Memory int64 `json:"memory,omitempty"`
+ CPUs float64 `json:"cpus,omitempty"`
}
type ContainerActionResult struct {
diff --git a/backend/internal/dto/template.go b/backend/internal/dto/template.go
index b9492a89a..aac99811c 100644
--- a/backend/internal/dto/template.go
+++ b/backend/internal/dto/template.go
@@ -6,16 +6,16 @@ type RemoteTemplate struct {
Description string `json:"description"`
Version string `json:"version"`
Author string `json:"author"`
- Tags []string `json:"tags"`
+ Tags []string `json:"tags,omitempty"`
ComposeURL string `json:"composeUrl"`
- EnvURL string `json:"envUrl"`
- DocsURL string `json:"docsUrl"`
- IconURL string `json:"iconUrl"`
- UpdatedAt string `json:"updatedAt"`
+ EnvURL string `json:"envUrl,omitempty"`
+ DocsURL string `json:"docsUrl,omitempty"`
+ IconURL string `json:"iconUrl,omitempty"`
+ UpdatedAt string `json:"updatedAt,omitempty"`
}
type RemoteRegistry struct {
Name string `json:"name"`
- Description string `json:"description"`
+ Description string `json:"description,omitempty"`
Templates []RemoteTemplate `json:"templates"`
}
diff --git a/backend/internal/utils/registry_utils.go b/backend/internal/utils/registry_utils.go
index 1e527ca43..f7f774ddf 100644
--- a/backend/internal/utils/registry_utils.go
+++ b/backend/internal/utils/registry_utils.go
@@ -12,7 +12,11 @@ import (
const DEFAULT_REGISTRY = "registry-1.docker.io"
-type RegistryUtils struct{}
+// RegistryUtils provides helper methods for Docker/OCI registries.
+// A shared HTTP client is used; per-method timeouts are enforced via context.
+type RegistryUtils struct {
+ client *http.Client
+}
var (
SemanticVersionRegex = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)(?:-.*)?$`)
@@ -37,9 +41,13 @@ type RegistryTestResult struct {
}
func NewRegistryUtils() *RegistryUtils {
- return &RegistryUtils{}
+ return &RegistryUtils{
+ client: &http.Client{}, // timeouts applied via context per request below
+ }
}
+// SplitImageReference splits an image reference into registry, repository, and tag.
+// Defaults: registry=docker hub, tag=latest. Strips any digest suffix.
func (r *RegistryUtils) SplitImageReference(reference string) (string, string, string, error) {
if reference == "" {
return "", "", "", fmt.Errorf("empty reference provided")
@@ -66,6 +74,7 @@ func (r *RegistryUtils) SplitImageReference(reference string) (string, string, s
}
}
+ // strip any digest suffix
repositoryAndTag = strings.Split(repositoryAndTag, "@")[0]
tagSplits := strings.Split(repositoryAndTag, ":")
@@ -102,16 +111,19 @@ func (r *RegistryUtils) GetRegistryURL(registry string) string {
}
}
+// CheckAuth pings the v2 endpoint and returns the auth realm URL if auth is required.
func (r *RegistryUtils) CheckAuth(ctx context.Context, registry string) (string, error) {
url := fmt.Sprintf("%s/v2/", r.GetRegistryURL(registry))
- client := &http.Client{Timeout: 10 * time.Second}
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
- resp, err := client.Do(req)
+ resp, err := r.client.Do(req)
if err != nil {
return "", err
}
@@ -154,11 +166,14 @@ func (r *RegistryUtils) getServiceName(authURL string) string {
return "registry"
}
+// GetToken fetches a Bearer token for the given repository scope.
func (r *RegistryUtils) GetToken(ctx context.Context, authURL, repository string, credentials *RegistryCredentials) (string, error) {
serviceName := r.getServiceName(authURL)
tokenURL := fmt.Sprintf("%s?service=%s&scope=repository:%s:pull", authURL, serviceName, repository)
- client := &http.Client{Timeout: 30 * time.Second}
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)
if err != nil {
return "", err
@@ -168,7 +183,7 @@ func (r *RegistryUtils) GetToken(ctx context.Context, authURL, repository string
req.SetBasicAuth(credentials.Username, credentials.Token)
}
- resp, err := client.Do(req)
+ resp, err := r.client.Do(req)
if err != nil {
return "", err
}
@@ -189,10 +204,13 @@ func (r *RegistryUtils) GetToken(ctx context.Context, authURL, repository string
return tokenResp.Token, nil
}
+// GetLatestDigest returns the current manifest digest for the given repository:tag.
func (r *RegistryUtils) GetLatestDigest(ctx context.Context, registry, repository, tag string, token string) (string, error) {
url := fmt.Sprintf("%s/v2/%s/manifests/%s", r.GetRegistryURL(registry), repository, tag)
- client := &http.Client{Timeout: 30 * time.Second}
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
if err != nil {
return "", err
@@ -204,7 +222,7 @@ func (r *RegistryUtils) GetLatestDigest(ctx context.Context, registry, repositor
req.Header.Set("Authorization", "Bearer "+token)
}
- resp, err := client.Do(req)
+ resp, err := r.client.Do(req)
if err != nil {
return "", err
}
@@ -232,6 +250,7 @@ func (r *RegistryUtils) GetLatestDigest(ctx context.Context, registry, repositor
return digest, nil
}
+// GetImageTags returns all tags for the given repository, following pagination.
func (r *RegistryUtils) GetImageTags(ctx context.Context, registry, repository string, token string) ([]string, error) {
url := fmt.Sprintf("%s/v2/%s/tags/list", r.GetRegistryURL(registry), repository)
@@ -239,8 +258,10 @@ func (r *RegistryUtils) GetImageTags(ctx context.Context, registry, repository s
nextURL := url
for nextURL != "" {
- client := &http.Client{Timeout: 30 * time.Second}
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, nextURL, nil)
+ ctxReq, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctxReq, http.MethodGet, nextURL, nil)
if err != nil {
return nil, err
}
@@ -251,7 +272,7 @@ func (r *RegistryUtils) GetImageTags(ctx context.Context, registry, repository s
req.Header.Set("Authorization", "Bearer "+token)
}
- resp, err := client.Do(req)
+ resp, err := r.client.Do(req)
if err != nil {
return nil, err
}
@@ -271,13 +292,13 @@ func (r *RegistryUtils) GetImageTags(ctx context.Context, registry, repository s
allTags = append(allTags, tagsResp.Tags...)
linkHeader := resp.Header.Get("Link")
- nextURL = r.parseLinkHeader(linkHeader, url)
+ nextURL = r.parseLinkHeader(linkHeader)
}
return allTags, nil
}
-func (r *RegistryUtils) parseLinkHeader(linkHeader, baseURL string) string {
+func (r *RegistryUtils) parseLinkHeader(linkHeader string) string {
if linkHeader == "" {
return ""
}
@@ -297,6 +318,7 @@ func (r *RegistryUtils) parseLinkHeader(linkHeader, baseURL string) string {
return ""
}
+// TestRegistryConnection runs a simple ping/auth/tags check against a registry.
func TestRegistryConnection(ctx context.Context, registryURL string, credentials *RegistryCredentials) (*RegistryTestResult, error) {
registryUtils := NewRegistryUtils()
@@ -345,6 +367,7 @@ func TestRegistryConnection(ctx context.Context, registryURL string, credentials
return result, nil
}
+// ExtractRegistryDomain normalizes the image ref to a registry domain (docker.io for hub).
func ExtractRegistryDomain(imageRef string) (string, error) {
registryUtils := NewRegistryUtils()
registry, _, _, err := registryUtils.SplitImageReference(imageRef)
diff --git a/backend/internal/utils/registry_utils_test.go b/backend/internal/utils/registry_utils_test.go
new file mode 100644
index 000000000..073c57db9
--- /dev/null
+++ b/backend/internal/utils/registry_utils_test.go
@@ -0,0 +1,264 @@
+package utils
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestSplitImageReference(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ ref string
+ wantReg string
+ wantRepo string
+ wantTag string
+ wantError bool
+ }{
+ {
+ name: "docker hub short name adds library and latest",
+ ref: "nginx",
+ wantReg: DEFAULT_REGISTRY,
+ wantRepo: "library/nginx",
+ wantTag: "latest",
+ },
+ {
+ name: "docker hub explicit tag",
+ ref: "nginx:alpine",
+ wantReg: DEFAULT_REGISTRY,
+ wantRepo: "library/nginx",
+ wantTag: "alpine",
+ },
+ {
+ name: "docker.io prefix normalizes to default",
+ ref: "docker.io/library/redis:7",
+ wantReg: DEFAULT_REGISTRY,
+ wantRepo: "library/redis",
+ wantTag: "7",
+ },
+ {
+ name: "ghcr with org/repo:tag",
+ ref: "ghcr.io/acme/api:1.2.3",
+ wantReg: "ghcr.io",
+ wantRepo: "acme/api",
+ wantTag: "1.2.3",
+ },
+ {
+ name: "ghcr default tag latest",
+ ref: "ghcr.io/owner/repo",
+ wantReg: "ghcr.io",
+ wantRepo: "owner/repo",
+ wantTag: "latest",
+ },
+ {
+ name: "localhost registry with port",
+ ref: "localhost:5000/myrepo:dev",
+ wantReg: "localhost:5000",
+ wantRepo: "myrepo",
+ wantTag: "dev",
+ },
+ {
+ name: "strip digest suffix",
+ ref: "ghcr.io/acme/api:1.2.3@sha256:deadbeef",
+ wantReg: "ghcr.io",
+ wantRepo: "acme/api",
+ wantTag: "1.2.3",
+ },
+ }
+
+ r := NewRegistryUtils()
+ for _, tc := range tests {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ reg, repo, tag, err := r.SplitImageReference(tc.ref)
+ if tc.wantError {
+ if err == nil {
+ t.Fatalf("expected error, got nil")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if reg != tc.wantReg || repo != tc.wantRepo || tag != tc.wantTag {
+ t.Fatalf("got (%q,%q,%q), want (%q,%q,%q)", reg, repo, tag, tc.wantReg, tc.wantRepo, tc.wantTag)
+ }
+ })
+ }
+}
+
+func TestGetRegistryURL(t *testing.T) {
+ t.Parallel()
+
+ r := NewRegistryUtils()
+ if got := r.GetRegistryURL("docker.io"); got != "https://index.docker.io" {
+ t.Fatalf("docker.io mapped to %q, want https://index.docker.io", got)
+ }
+ if got := r.GetRegistryURL(DEFAULT_REGISTRY); got != "https://index.docker.io" {
+ t.Fatalf("DEFAULT_REGISTRY mapped to %q, want https://index.docker.io", got)
+ }
+ if got := r.GetRegistryURL("ghcr.io"); got != "https://ghcr.io" {
+ t.Fatalf("ghcr.io mapped to %q, want https://ghcr.io", got)
+ }
+ if got := r.GetRegistryURL("https://custom.registry:8443"); got != "https://custom.registry:8443" {
+ t.Fatalf("https url changed to %q", got)
+ }
+}
+
+func TestExtractRegistryDomain(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ ref string
+ want string
+ }{
+ {"nginx:alpine", "docker.io"},
+ {"docker.io/library/redis:7", "docker.io"},
+ {"ghcr.io/acme/api:1.2.3", "ghcr.io"},
+ {"localhost:5000/repo:dev", "localhost:5000"},
+ }
+
+ for _, tc := range tests {
+ tc := tc
+ t.Run(tc.ref, func(t *testing.T) {
+ got, err := ExtractRegistryDomain(tc.ref)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestCheckAuthParsesRealm(t *testing.T) {
+ t.Parallel()
+
+ realm := "https://auth.example/token"
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v2/" {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="`+realm+`",service="example.org"`)
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ utils := NewRegistryUtils()
+ // Pass full server URL so GetRegistryURL returns it unchanged
+ got, err := utils.CheckAuth(context.Background(), srv.URL)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != realm {
+ t.Fatalf("realm = %q, want %q", got, realm)
+ }
+}
+
+func TestGetToken(t *testing.T) {
+ t.Parallel()
+
+ // Fake auth server returning a token
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // verify optional basic auth presence if provided
+ if ah := r.Header.Get("Authorization"); ah != "" {
+ if !strings.HasPrefix(ah, "Basic ") {
+ t.Fatalf("expected Basic auth header, got %q", ah)
+ }
+ // ensure decodes without error
+ if _, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(ah, "Basic ")); err != nil {
+ t.Fatalf("bad basic auth header: %v", err)
+ }
+ }
+
+ _ = r.ParseForm()
+ _ = r.Form.Get("service")
+ _ = r.Form.Get("scope")
+
+ _ = json.NewEncoder(w).Encode(map[string]string{"token": "abc123"})
+ }))
+ defer srv.Close()
+
+ utils := NewRegistryUtils()
+ // authURL points to our test server
+ token, err := utils.GetToken(context.Background(), srv.URL, "library/hello-world", &RegistryCredentials{
+ Username: "user",
+ Token: "pass",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if token != "abc123" {
+ t.Fatalf("token = %q, want abc123", token)
+ }
+}
+
+func TestGetLatestDigest(t *testing.T) {
+ t.Parallel()
+
+ // Fake registry returning a digest header on HEAD
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodHead {
+ t.Fatalf("expected HEAD, got %s", r.Method)
+ }
+ if !strings.Contains(r.Header.Get("Accept"), "manifest") {
+ t.Fatalf("missing Accept header for manifests")
+ }
+ w.Header().Set("Docker-Content-Digest", "sha256:deadbeef")
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ utils := NewRegistryUtils()
+ digest, err := utils.GetLatestDigest(context.Background(), srv.URL, "org/repo", "latest", "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if digest != "sha256:deadbeef" {
+ t.Fatalf("digest = %q, want sha256:deadbeef", digest)
+ }
+}
+
+func TestGetImageTagsPagination(t *testing.T) {
+ t.Parallel()
+
+ var server *httptest.Server
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/v2/org/repo/tags/list" && (r.URL.RawQuery == "" || r.URL.RawQuery == "page=1"):
+ page2URL := server.URL + "/v2/org/repo/tags/list?page=2"
+ w.Header().Set("Link", `<`+page2URL+`>; rel="next"`)
+ _ = json.NewEncoder(w).Encode(map[string]any{"tags": []string{"a", "b"}})
+ case r.URL.Path == "/v2/org/repo/tags/list" && r.URL.RawQuery == "page=2":
+ _ = json.NewEncoder(w).Encode(map[string]any{"tags": []string{"c"}})
+ default:
+ http.NotFound(w, r)
+ }
+ })
+
+ server = httptest.NewServer(handler)
+ defer server.Close()
+
+ utils := NewRegistryUtils()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ tags, err := utils.GetImageTags(ctx, server.URL, "org/repo", "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ got := strings.Join(tags, ",")
+ if got != "a,b,c" {
+ t.Fatalf("tags = %q, want %q", got, "a,b,c")
+ }
+}