Skip to content

Docker Compose Validator — Go source

Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package composevalidator is the Go twin of CosmoDev's
// src/lib/compose-validator.ts (dual source: the web lib is TypeScript, the
// CLI lib is Go — kept in lock-step). Pure + deterministic, never panics.
// The table-driven tests in compose-validator_test.go share vectors with
// src/lib/compose-validator.test.ts so the two implementations are held to
// the same contract.
//
// The validator parses a compose file with gopkg.in/yaml.v3 (the TS lib uses
// the npm `yaml` package with { merge: true }) and checks structural rules:
// services mapping with image or build, port syntax, environment shape (map
// or K=V list), volumes lists, depends_on references and acyclicity. Not
// checked (by design, as documented in the TS lib): image tag validity,
// build context paths, top-level version field semantics, profiles,
// extensions.
//
// Document order is observable through the contract — issue order follows
// service order, and the depends_on cycle message names the chain starting
// from the first service in document order — so the parser walks the
// yaml.Node tree into an ordered ynode tree (Go maps lose insertion order).
// << merge keys expand (explicit keys win over merged ones, earlier merge
// sources win over later ones) and aliases resolve, mirroring the npm yaml
// parser the TS lib relies on.
package composevalidator

import (
	"encoding/json"
	"fmt"
	"math"
	"strconv"
	"strings"
	"time"

	"gopkg.in/yaml.v3"
)

// ComposeIssue is one structural finding at one YAML path. Mirrors the
// ComposeIssue interface in compose-validator.ts.
type ComposeIssue struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

// ComposeValidateResult mirrors the ComposeValidateResult union of
// compose-validator.ts: a checked document carries Valid plus Issues with a
// nil Error (TS: error: null); a document that could not be parsed carries
// Valid=false, no Issues, and the parser's message in Error.
type ComposeValidateResult struct {
	Valid  bool           `json:"valid"`
	Issues []ComposeIssue `json:"issues"`
	Error  *string        `json:"error"` // nil unless parsing failed (TS: error: null)
}

// strptr returns a pointer to s; it builds the nullable Error field.
func strptr(s string) *string { return &s }

// ---------------------------------------------------------------------------
// Ordered value tree — the parsed document, remembering key order.
// ---------------------------------------------------------------------------

type ykind int

const (
	yScalar ykind = iota // null / bool / int / float / string
	ySeq
	yMap
)

type yscalarKind int

const (
	yNull yscalarKind = iota
	yBool
	yInt
	yFloat
	yStr
)

// ynode is one parsed YAML value in document order. text holds the TS
// String(value) form of a scalar (used in messages and depends_on name
// coercion); num holds the numeric value of int/float scalars.
type ynode struct {
	kind   ykind
	scalar yscalarKind // valid when kind == yScalar
	text   string      // TS String(value) canonical form
	num    float64     // yInt / yFloat numeric value
	items  []*ynode    // ySeq entries, document order
	keys   []string    // yMap keys, document order
	vals   []*ynode    // yMap values, parallel to keys
}

// isMap mirrors isMap() in the TS lib: an object that is not an array.
func isMap(v *ynode) bool { return v != nil && v.kind == yMap }

// mapGet looks a key up in an ordered map node, preserving the "in" operator
// semantics of the TS lib (presence check independent of value).
func mapGet(v *ynode, key string) (*ynode, bool) {
	if !isMap(v) {
		return nil, false
	}
	for i, k := range v.keys {
		if k == key {
			return v.vals[i], true
		}
	}
	return nil, false
}

// ---------------------------------------------------------------------------
// YAML → ordered tree
// ---------------------------------------------------------------------------

// yamlThrowNonError mirrors the TS suite's hoisted yamlThrow.nonError mock:
// when set, the yaml seam reports a thrown non-Error value so the
// 'Invalid YAML' fallback in ValidateCompose can be exercised. It exists so
// the Go and TS suites share that vector byte-for-byte; nothing in production
// code ever sets it.
var yamlThrowNonError = false

// errNonError stands in for a non-Error value thrown by the parser — a
// JavaScript-only situation the TS lib guards with `e instanceof Error`.
// ValidateCompose maps it to 'Invalid YAML'.
type errNonError struct{}

func (errNonError) Error() string { return "not an Error" }

// parseCompose parses raw into the ordered ynode tree. It is the seam around
// yaml.Unmarshal, the analogue of the TS lib's `parse` import.
func parseCompose(raw string) (*ynode, error) {
	if yamlThrowNonError {
		return nil, errNonError{}
	}
	var doc yaml.Node
	if err := yaml.Unmarshal([]byte(raw), &doc); err != nil {
		return nil, err
	}
	return toNode(&doc, nil)
}

// toNode converts a yaml.Node subtree into the ordered ynode tree. path holds
// the nodes on the current DFS route for alias-cycle detection.
func toNode(n *yaml.Node, path []*yaml.Node) (*ynode, error) {
	if n == nil {
		return nullNode(), nil
	}
	switch n.Kind {
	case yaml.DocumentNode:
		if len(n.Content) == 0 {
			return nullNode(), nil // bare "---" parses to null
		}
		return toNode(n.Content[0], path)
	case yaml.AliasNode:
		if n.Alias == nil {
			return nil, fmt.Errorf("yaml: unresolved alias")
		}
		return toNode(n.Alias, path)
	case yaml.MappingNode:
		if onPath(path, n) {
			return nil, fmt.Errorf("yaml: circular reference through anchors")
		}
		return mappingToNode(n, append(path, n))
	case yaml.SequenceNode:
		if onPath(path, n) {
			return nil, fmt.Errorf("yaml: circular reference through anchors")
		}
		path = append(path, n)
		out := &ynode{kind: ySeq}
		for _, c := range n.Content {
			item, err := toNode(c, path)
			if err != nil {
				return nil, err
			}
			out.items = append(out.items, item)
		}
		return out, nil
	case yaml.ScalarNode:
		return scalarToNode(n), nil
	default:
		return nil, fmt.Errorf("yaml: unsupported node kind %d", n.Kind)
	}
}

// mappingToNode walks a mapping's key/value pairs in document order, expanding
// merge keys in place: an explicit key overrides a merged value at the merged
// key's position, and a later merge source never clobbers an earlier one.
func mappingToNode(n *yaml.Node, path []*yaml.Node) (*ynode, error) {
	out := &ynode{kind: yMap}
	index := map[string]int{} // key → position in out.keys/vals
	for i := 0; i+1 < len(n.Content); i += 2 {
		kn, vn := n.Content[i], n.Content[i+1]
		if isMergeKey(kn) {
			sources, err := mergeSources(vn, path)
			if err != nil {
				return nil, err
			}
			for _, src := range sources {
				flat, err := mappingToNode(src, append(path, src))
				if err != nil {
					return nil, err
				}
				for j, k := range flat.keys {
					if _, ok := index[k]; !ok {
						index[k] = len(out.keys)
						out.keys = append(out.keys, k)
						out.vals = append(out.vals, flat.vals[j])
					}
				}
			}
			continue
		}
		key, err := keyText(kn)
		if err != nil {
			return nil, err
		}
		val, err := toNode(vn, path)
		if err != nil {
			return nil, err
		}
		if idx, ok := index[key]; ok {
			out.vals[idx] = val // explicit key overrides merged value in place
		} else {
			index[key] = len(out.keys)
			out.keys = append(out.keys, key)
			out.vals = append(out.vals, val)
		}
	}
	return out, nil
}

// isMergeKey reports whether kn is the YAML merge key. yaml.v3 resolves a
// plain "<<" to the !!merge tag; quoted "<<" keeps !!str and stays a plain
// key — the same semantics the npm yaml parser gives the TS lib.
func isMergeKey(kn *yaml.Node) bool {
	return kn.Kind == yaml.ScalarNode && kn.Tag == "!!merge"
}

// mergeSources dereferences a merge value into the list of mappings to merge,
// in precedence order: a mapping, an alias, or a sequence of those. A null
// merge value merges nothing.
func mergeSources(vn *yaml.Node, path []*yaml.Node) ([]*yaml.Node, error) {
	deref := func(x *yaml.Node) (*yaml.Node, error) {
		if x.Kind == yaml.AliasNode {
			if x.Alias == nil {
				return nil, fmt.Errorf("yaml: unresolved alias in merge key")
			}
			x = x.Alias
		}
		return x, nil
	}
	appendSource := func(x *yaml.Node) ([]*yaml.Node, error) {
		x, err := deref(x)
		if err != nil {
			return nil, err
		}
		if x.Kind != yaml.MappingNode {
			return nil, fmt.Errorf("yaml: merge sources must be mappings")
		}
		if onPath(path, x) {
			return nil, fmt.Errorf("yaml: circular reference through merge key")
		}
		return []*yaml.Node{x}, nil
	}
	switch vn.Kind {
	case yaml.ScalarNode:
		if vn.Tag == "!!null" {
			return nil, nil
		}
		return nil, fmt.Errorf("yaml: merge value must be a mapping, sequence, or null")
	case yaml.AliasNode, yaml.MappingNode:
		return appendSource(vn)
	case yaml.SequenceNode:
		var out []*yaml.Node
		for _, c := range vn.Content {
			src, err := appendSource(c)
			if err != nil {
				return nil, err
			}
			out = append(out, src[0])
		}
		return out, nil
	default:
		return nil, fmt.Errorf("yaml: merge value must be a mapping, sequence, or null")
	}
}

// scalarToNode resolves a YAML scalar. yaml.v3 has already tagged the node
// (plain scalars resolve per the core schema; quoted scalars stay !!str), so
// decoding into interface{} yields what the npm yaml parser would — except
// !!timestamp, which yaml.v3 decodes to time.Time while the npm yaml default
// schema keeps dates as strings; the original literal is restored so both
// twins agree.
func scalarToNode(n *yaml.Node) *ynode {
	if n.Tag == "!!null" {
		return nullNode()
	}
	var v any
	if err := n.Decode(&v); err != nil {
		// Decode cannot fail for a tagged scalar in practice; fall back to
		// the literal text rather than panicking (the twin never panics).
		return &ynode{kind: yScalar, scalar: yStr, text: n.Value}
	}
	if _, ok := v.(time.Time); ok {
		return &ynode{kind: yScalar, scalar: yStr, text: n.Value}
	}
	switch x := v.(type) {
	case string:
		return &ynode{kind: yScalar, scalar: yStr, text: x}
	case bool:
		return &ynode{kind: yScalar, scalar: yBool, text: strconv.FormatBool(x)}
	case int:
		return intNode(float64(x))
	case int64:
		return intNode(float64(x))
	case uint64:
		return intNode(float64(x))
	case float64:
		return &ynode{kind: yScalar, scalar: yFloat, text: jsonNumberText(x), num: x}
	case []byte: // !!binary — base64 text, the closest string form
		return &ynode{kind: yScalar, scalar: yStr, text: string(x)}
	default:
		return &ynode{kind: yScalar, scalar: yStr, text: n.Value}
	}
}

// intNode builds an integer scalar whose text is canonical decimal (the TS
// String(number) form) and whose num carries the value for range checks.
func intNode(f float64) *ynode {
	return &ynode{kind: yScalar, scalar: yInt, text: jsonNumberText(f), num: f}
}

// nullNode builds the TS null value (String(null) is "null").
func nullNode() *ynode {
	return &ynode{kind: yScalar, scalar: yNull, text: "null"}
}

// jsonNumberText renders f the way JavaScript String(number) / JSON
// numberification does (the npm yaml parser yields plain JS numbers).
func jsonNumberText(f float64) string {
	if math.IsNaN(f) || math.IsInf(f, 0) {
		return "null"
	}
	b, err := json.Marshal(f)
	if err != nil {
		return "null"
	}
	return string(b)
}

// keyText renders a mapping key as its string form (TS implicitly does
// String(key) inside Object.keys / member access).
func keyText(kn *yaml.Node) (string, error) {
	if kn.Kind != yaml.ScalarNode {
		return "", fmt.Errorf("yaml: mapping keys must be scalars")
	}
	return scalarToNode(kn).text, nil
}

// onPath reports whether target is on the current traversal path.
func onPath(path []*yaml.Node, target *yaml.Node) bool {
	for _, p := range path {
		if p == target {
			return true
		}
	}
	return false
}

// ---------------------------------------------------------------------------
// Structural checks — mirrors check() in compose-validator.ts.
// ---------------------------------------------------------------------------

// check walks the document and appends issues in TS order: root, services,
// per-service findings in document order, then depends_on cycle detection.
func check(root *ynode, out *[]ComposeIssue) {
	push := func(path, message string) {
		*out = append(*out, ComposeIssue{Path: path, Message: message})
	}
	if !isMap(root) {
		push("$", "compose root must be a mapping")
		return
	}
	services, hasServices := mapGet(root, "services")
	if !hasServices || !isMap(services) {
		push("$.services", `missing or invalid "services" mapping`)
		return
	}
	ids := services.keys
	if len(ids) == 0 {
		push("$.services", "services must not be empty")
	}

	for _, id := range ids {
		svc, _ := mapGet(services, id)
		at := "$.services." + id
		if !isMap(svc) {
			push(at, "service must be a mapping")
			continue
		}
		_, hasImage := mapGet(svc, "image")
		_, hasBuild := mapGet(svc, "build")
		if !hasImage && !hasBuild {
			push(at, "service needs image or build")
		}
		if ports, has := mapGet(svc, "ports"); has {
			if ports.kind != ySeq {
				push(at+".ports", "ports must be a list")
			} else {
				for i, p := range ports.items {
					if msg := portIssue(p); msg != "" {
						push(fmt.Sprintf("%s.ports[%d]", at, i), msg)
					}
				}
			}
		}
		if env, has := mapGet(svc, "environment"); has {
			switch {
			case isMap(env):
				for i, k := range env.keys {
					if v := env.vals[i]; v.kind != yScalar {
						push(at+".environment."+k, "environment values must be scalars")
					}
				}
			case env.kind == ySeq:
				for i, e := range env.items {
					if e.kind != yScalar || e.scalar != yStr || strings.IndexByte(e.text, '=') <= 0 {
						push(fmt.Sprintf("%s.environment[%d]", at, i), "list environment entries must look like KEY=value")
					}
				}
			default:
				push(at+".environment", "environment must be a mapping or a list")
			}
		}
		if volumes, has := mapGet(svc, "volumes"); has && volumes.kind != ySeq {
			push(at+".volumes", "volumes must be a list")
		}
		if dep, has := mapGet(svc, "depends_on"); has {
			if dep.kind != ySeq && !(dep.kind == yScalar && dep.scalar == yStr) && !isMap(dep) {
				push(at+".depends_on", "depends_on must be a string, list or mapping")
			} else {
				var names []string
				switch {
				case isMap(dep):
					names = dep.keys
				case dep.kind == ySeq:
					for _, e := range dep.items {
						names = append(names, e.text) // TS: deps.map(String)
					}
				default: // string
					names = []string{dep.text}
				}
				for i, n := range names {
					if _, ok := mapGet(services, n); !ok {
						push(fmt.Sprintf("%s.depends_on[%d]", at, i), fmt.Sprintf("unknown service \"%s\"", n))
					}
				}
			}
		}
	}

	// depends_on cycle detection (map-form conditions do not affect the
	// graph). color: 1 = on stack, 2 = done — mirrors the TS Map.
	color := map[string]int{}
	var visit func(id string, stack []string)
	visit = func(id string, stack []string) {
		if color[id] == 2 {
			return
		}
		if color[id] == 1 {
			from := 0
			for i, s := range stack {
				if s == id {
					from = i
					break
				}
			}
			chain := append(append([]string{}, stack[from:]...), id)
			push("$.services", "depends_on cycle: "+strings.Join(chain, " -> "))
			return
		}
		color[id] = 1
		if svc, ok := mapGet(services, id); ok && isMap(svc) {
			if raw, has := mapGet(svc, "depends_on"); has {
				var names []string
				switch {
				case raw.kind == yScalar && raw.scalar == yStr:
					names = []string{raw.text}
				case raw.kind == ySeq:
					// TS: for (const n of names) if (typeof n === 'string' && n in services)
					for _, e := range raw.items {
						if e.kind == yScalar && e.scalar == yStr {
							names = append(names, e.text)
						}
					}
				case isMap(raw):
					names = raw.keys
				}
				for _, n := range names {
					if _, ok := mapGet(services, n); ok {
						visit(n, append(append([]string{}, stack...), id))
					}
				}
			}
		}
		color[id] = 2
	}
	for _, id := range ids {
		visit(id, nil)
	}
}

// portIssue validates one ports entry. Port forms: "8080", "80:8080",
// "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp". It mirrors portIssue()
// in compose-validator.ts and returns "" when the entry is acceptable.
func portIssue(entry *ynode) string {
	if entry.kind != yScalar {
		return "port must be a string or integer"
	}
	switch entry.scalar {
	case yInt, yFloat:
		// TS Number.isInteger: NaN/Infinity and fractional values are not
		// integers; integer-valued floats pass and get range-checked.
		if entry.scalar == yFloat && (math.IsNaN(entry.num) || math.IsInf(entry.num, 0) || entry.num != math.Trunc(entry.num)) {
			return "port must be a string or integer"
		}
		if entry.num < 0 || entry.num > 65535 {
			return fmt.Sprintf("port %s out of range 0-65535", entry.text)
		}
		return ""
	case yStr:
		s := entry.text
		proto := ""
		if i := strings.IndexByte(s, '/'); i >= 0 {
			proto = s[i+1:]
		}
		if proto != "" && proto != "tcp" && proto != "udp" {
			return fmt.Sprintf("unknown protocol \"%s\" (use tcp or udp)", proto)
		}
		body := s
		if i := strings.IndexByte(s, '/'); i >= 0 {
			body = s[:i]
		}
		parts := strings.Split(body, ":")
		// Host forms (localhost, IPv6 like ::1) carry non-numeric parts
		// anywhere and are accepted without further checks.
		if !allDigitsEach(parts) {
			return ""
		}
		if len(parts) > 3 { // TS checks length < 1 too, unreachable after split
			return "port must have 1-3 colon-separated parts"
		}
		for _, p := range parts {
			n, err := strconv.ParseInt(p, 10, 64)
			if err != nil || n < 0 || n > 65535 {
				return fmt.Sprintf("port %s out of range 0-65535", p)
			}
		}
		return ""
	default: // null, bool
		return "port must be a string or integer"
	}
}

// allDigitsEach reports whether every part matches /^\d+$/ (ASCII digits,
// at least one) — the same test as parts.every(p => /^\d+$/.test(p)).
func allDigitsEach(parts []string) bool {
	for _, p := range parts {
		if p == "" {
			return false
		}
		for i := 0; i < len(p); i++ {
			if p[i] < '0' || p[i] > '9' {
				return false
			}
		}
	}
	return true
}

// ---------------------------------------------------------------------------
// Public surface
// ---------------------------------------------------------------------------

// ValidateCompose validates a Docker Compose file. It is the Go twin of
// validateCompose() in src/lib/compose-validator.ts and must agree with it
// on every shared vector.
func ValidateCompose(raw string) ComposeValidateResult {
	if strings.TrimSpace(raw) == "" {
		return ComposeValidateResult{Valid: false, Issues: []ComposeIssue{}, Error: strptr("A compose document is required")}
	}
	root, err := parseCompose(raw)
	if err != nil {
		msg := err.Error()
		if _, thrown := err.(errNonError); thrown {
			msg = "Invalid YAML" // TS: e instanceof Error ? e.message : 'Invalid YAML'
		}
		return ComposeValidateResult{Valid: false, Issues: []ComposeIssue{}, Error: strptr(msg)}
	}
	issues := []ComposeIssue{}
	check(root, &issues)
	if len(issues) == 0 {
		return ComposeValidateResult{Valid: true, Issues: []ComposeIssue{}, Error: nil}
	}
	return ComposeValidateResult{Valid: false, Issues: issues, Error: nil}
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →