Files
tiny-forge/internal/docker/image.go
T
alexei.dolgolyov be6ad15efc fix: comprehensive security, performance, and quality hardening
Security: apply AdminOnly middleware to mutating routes, require
ENCRYPTION_KEY and ADMIN_PASSWORD (no insecure defaults), restrict
CORS to same-origin, fix OIDC token delivery via cookie instead of
URL query param, add rate limiting on login, add MaxBytesReader,
validate volume paths against traversal, add security headers,
validate user roles, add Secure flag to OIDC cookie.

Performance: set SQLite MaxOpenConns(1) to prevent SQLITE_BUSY,
add FK indexes on 8 columns, track notifier goroutines with
WaitGroup for graceful shutdown, use GetRegistryByName instead of
GetAllRegistries in deployer, pass basePath param to avoid redundant
settings query, return empty slices from store to remove reflection.

Quality: refactor TriggerDeploy to delegate to runDeploy (~100 lines
removed), consolidate duplicated utilities (extractPort, boolToInt,
now, isTerminalStatus) into shared exports, migrate all log.Printf
to slog structured logging, use consistent webhook response envelope,
remove dead code (parseEnvVars, duplicate auth types).

UX: clean up NPM proxy on instance removal via API, add README with
quickstart guide, add .env.example, require ADMIN_PASSWORD in
docker-compose, document staging-net prerequisite.
2026-03-29 12:49:24 +03:00

120 lines
3.3 KiB
Go

package docker
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/moby/moby/api/types/registry"
"github.com/moby/moby/client"
)
// ExtractPort parses the first exposed port from Docker EXPOSE entries.
// Entries are in the form "8080/tcp" or "8080". Returns 0 if none found.
func ExtractPort(exposedPorts []string) int {
if len(exposedPorts) == 0 {
return 0
}
raw := exposedPorts[0]
if idx := strings.Index(raw, "/"); idx != -1 {
raw = raw[:idx]
}
port, _ := strconv.Atoi(raw)
return port
}
// ImageInfo holds metadata extracted from a Docker image inspection.
type ImageInfo struct {
// ExposedPorts lists the ports declared via EXPOSE in the Dockerfile (e.g. ["8080/tcp"]).
ExposedPorts []string
// Healthcheck is the CMD string from the image's HEALTHCHECK instruction, if any.
Healthcheck string
// Labels are the key-value pairs defined in the image metadata.
Labels map[string]string
}
// PullImage pulls an image from a registry. If authConfig is non-empty, it is
// used as the base64-encoded JSON auth payload for private registries.
// The image reference should be in the form "repository:tag".
func (c *Client) PullImage(ctx context.Context, imageRef string, tag string, authConfig string) error {
ref := imageRef
if tag != "" {
ref = imageRef + ":" + tag
}
opts := client.ImagePullOptions{}
if authConfig != "" {
opts.RegistryAuth = authConfig
}
reader, err := c.api.ImagePull(ctx, ref, opts)
if err != nil {
return fmt.Errorf("pull image %s: %w", ref, err)
}
// Wait for the pull to complete.
if err := reader.Wait(ctx); err != nil {
return fmt.Errorf("wait for pull of %s: %w", ref, err)
}
return nil
}
// InspectImage retrieves metadata from a local image.
func (c *Client) InspectImage(ctx context.Context, imageRef string) (ImageInfo, error) {
inspectResult, err := c.api.ImageInspect(ctx, imageRef)
if err != nil {
return ImageInfo{}, fmt.Errorf("inspect image %s: %w", imageRef, err)
}
info := ImageInfo{}
// Extract labels from Config if available.
if inspectResult.Config != nil {
info.Labels = inspectResult.Config.Labels
// Extract exposed ports from OCI config (map[string]struct{}).
for port := range inspectResult.Config.ExposedPorts {
info.ExposedPorts = append(info.ExposedPorts, port)
}
// Extract healthcheck command.
if inspectResult.Config.Healthcheck != nil && len(inspectResult.Config.Healthcheck.Test) > 0 {
// The Test slice is ["CMD", "arg1", "arg2", ...] or ["CMD-SHELL", "cmd string"].
// Join all parts after the first element for a readable representation.
if len(inspectResult.Config.Healthcheck.Test) > 1 {
info.Healthcheck = joinArgs(inspectResult.Config.Healthcheck.Test[1:])
}
}
}
return info, nil
}
// EncodeRegistryAuth builds a base64-encoded JSON auth string suitable for
// Docker API calls. Pass empty strings for anonymous access.
func EncodeRegistryAuth(username, password, serverAddress string) (string, error) {
cfg := registry.AuthConfig{
Username: username,
Password: password,
ServerAddress: serverAddress,
}
data, err := json.Marshal(cfg)
if err != nil {
return "", fmt.Errorf("encode registry auth: %w", err)
}
return base64.URLEncoding.EncodeToString(data), nil
}
// joinArgs joins string arguments with spaces.
func joinArgs(args []string) string {
return strings.Join(args, " ")
}