package catalog import ( "bytes" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "io/fs" "os" "path" "path/filepath" "sort" "strings" "gopkg.in/yaml.v3" ) // Limits protect against hostile catalogs (SEC-03). const ( MaxFileSize = 4 << 20 MaxFiles = 10000 MaxQuestions = 500 MaxRules = 1000 ) // Entity fields shared by all loaded manifests. type Entity struct { Kind string `json:"kind"` Meta Meta `json:"metadata"` File string `json:"file"` // relative to the catalog root (or "bigpicture:...") Line int `json:"line"` Hash string `json:"hash"` // sha256 of the document's source } // Package is a loaded Package manifest. type Package struct { Entity Spec PackageSpec `json:"spec"` } // Module returns the module with that ID. func (p *Package) Module(id string) *Module { for i := range p.Spec.Modules { if p.Spec.Modules[i].ID == id { return &p.Spec.Modules[i] } } return nil } // Profile is a loaded Profile manifest. type Profile struct { Entity Spec ProfileSpec `json:"spec"` } // Key is "/". func (p *Profile) Key() string { return p.Meta.Package + "/" + p.Meta.ID } // Solution is a loaded Solution or Task manifest. type Solution struct { Entity Spec SolutionSpec `json:"spec"` } // IsTask reports whether this is a Task. func (s *Solution) IsTask() bool { return s.Kind == KindTask } // Question returns the question with that ID and its index. func (s *Solution) Question(id string) (*Question, int) { for i := range s.Spec.Questions { if s.Spec.Questions[i].ID == id { return &s.Spec.Questions[i], i } } return nil, -1 } // Example is a loaded Example manifest. type Example struct { Entity Spec ExampleSpec `json:"spec"` } // Key is "/". func (e *Example) Key() string { return e.Spec.Solution + "/" + e.Meta.ID } // KnowledgeSource is a loaded KnowledgeSource manifest. type KnowledgeSource struct { Entity Spec KnowledgeSourceSpec `json:"spec"` } // Catalog is everything loaded from one catalog root. type Catalog struct { Root string `json:"-"` Meta Meta `json:"metadata"` Spec CatalogSpec `json:"spec"` Capabilities map[string]*Capability `json:"capabilities"` Packages map[string]*Package `json:"packages"` Profiles map[string]*Profile `json:"profiles"` Solutions map[string]*Solution `json:"solutions"` Tasks map[string]*Solution `json:"tasks"` Examples map[string]*Example `json:"examples"` Sources map[string]*KnowledgeSource `json:"sources"` BigPicture *BigPicture `json:"bigpicture"` // Files are all source files with their hashes, sorted (for locks). Files []FileHash `json:"files"` // Issues found while loading (fatal ones make Load fail). Issues []Issue `json:"-"` capFile map[string]string } // FileHash is one source file and its sha256. type FileHash struct { Path string `json:"path"` Hash string `json:"sha256"` } // Issue is a problem in a catalog (load, validation or lint). type Issue struct { Severity string `json:"severity"` // error | warning File string `json:"file,omitempty"` Line int `json:"line,omitempty"` ID string `json:"id,omitempty"` Code string `json:"code"` Message string `json:"message"` } func (i Issue) String() string { loc := i.File if i.Line > 0 { loc = fmt.Sprintf("%s:%d", i.File, i.Line) } if loc != "" { loc += ": " } id := "" if i.ID != "" { id = i.ID + ": " } return fmt.Sprintf("%s%s%s (%s)", loc, id, i.Message, i.Code) } // ErrInvalid wraps load errors. var ErrInvalid = errors.New("invalid catalog") // Load reads a catalog root directory (the one with catalog.yaml). func Load(root string) (*Catalog, error) { return LoadFS(os.DirFS(root), root) } // LoadFS reads a catalog from fsys (root is only used for messages and // to find the Big Picture relative to it, when fsys is a directory). func LoadFS(fsys fs.FS, root string) (*Catalog, error) { return LoadFSWith(fsys, root, nil) } // LoadFSWith is LoadFS with the Big Picture read from bigPicture instead // of the directory catalog.yaml names -- for a catalog without a disk // (embedded in a program, or in the browser as WebAssembly). nil: as // LoadFS. func LoadFSWith(fsys fs.FS, root string, bigPicture fs.FS) (*Catalog, error) { c := &Catalog{ Root: root, Capabilities: map[string]*Capability{}, Packages: map[string]*Package{}, Profiles: map[string]*Profile{}, Solutions: map[string]*Solution{}, Tasks: map[string]*Solution{}, Examples: map[string]*Example{}, Sources: map[string]*KnowledgeSource{}, capFile: map[string]string{}, } var files []string err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error { if err != nil { return err } name := d.Name() if d.IsDir() { if p != "." && (strings.HasPrefix(name, ".") || name == "schema" || name == "testdata" || name == "golden") { return fs.SkipDir } return nil } if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") { files = append(files, p) if len(files) > MaxFiles { return fmt.Errorf("more than %d files", MaxFiles) } } return nil }) if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalid, err) } sort.Strings(files) sawRoot := false for _, f := range files { b, err := readLimited(fsys, f) if err != nil { c.add("error", f, 0, "", "read", err.Error()) continue } c.Files = append(c.Files, FileHash{Path: f, Hash: sha(b)}) if c.loadFile(f, b) { sawRoot = true } } if !sawRoot { c.add("error", "catalog.yaml", 0, "", "no-root", "no Catalog manifest (catalog.yaml) found") } if c.Spec.BigPicture != "" && bigPicture != nil { bp, err := LoadBigPictureFS(bigPicture, c.Spec.BigPicture) if err != nil { c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error()) } else { c.BigPicture = bp c.Files = append(c.Files, bp.Files...) } } else if c.Spec.BigPicture != "" { bpDir := c.Spec.BigPicture if !filepath.IsAbs(bpDir) { bpDir = filepath.Join(root, bpDir) } bp, err := LoadBigPicture(bpDir) if err != nil { c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error()) } else { c.BigPicture = bp c.Files = append(c.Files, bp.Files...) } } sort.Slice(c.Files, func(i, j int) bool { return c.Files[i].Path < c.Files[j].Path }) if errs := c.Errors(); len(errs) > 0 { return c, fmt.Errorf("%w: %d error(s), first: %s", ErrInvalid, len(errs), errs[0]) } return c, nil } func readLimited(fsys fs.FS, p string) ([]byte, error) { f, err := fsys.Open(p) if err != nil { return nil, err } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1)) if err != nil { return nil, err } if len(b) > MaxFileSize { return nil, fmt.Errorf("larger than %d bytes", MaxFileSize) } return b, nil } func sha(b []byte) string { h := sha256.Sum256(b) return hex.EncodeToString(h[:]) } func (c *Catalog) add(sev, file string, line int, id, code, msg string) { c.Issues = append(c.Issues, Issue{Severity: sev, File: file, Line: line, ID: id, Code: code, Message: msg}) } // Errors returns the issues with severity error. func (c *Catalog) Errors() []Issue { var out []Issue for _, i := range c.Issues { if i.Severity == "error" { out = append(out, i) } } return out } // loadFile decodes all documents of one file; reports whether it held the root. func (c *Catalog) loadFile(file string, b []byte) bool { dec := yaml.NewDecoder(bytes.NewReader(b)) root := false for { var doc yaml.Node err := dec.Decode(&doc) if errors.Is(err, io.EOF) { break } if err != nil { c.add("error", file, 0, "", "yaml", err.Error()) return root } if len(doc.Content) == 0 { continue } raw, _ := yaml.Marshal(&doc) var h Header if err := strictDecode(raw, &h); err != nil { c.add("error", file, doc.Line, "", "header", err.Error()) continue } line := doc.Content[0].Line if h.APIVersion != APIVersion { c.add("error", file, line, h.Metadata.ID, "api-version", fmt.Sprintf("apiVersion %q, want %q", h.APIVersion, APIVersion)) continue } ent := Entity{Kind: h.Kind, Meta: h.Metadata, File: file, Line: line, Hash: sha(raw)} specRaw, _ := yaml.Marshal(&h.Spec) if h.Spec.Kind == 0 { specRaw = []byte("{}") } if err := c.addEntity(ent, specRaw); err != nil { c.add("error", file, line, h.Metadata.ID, "spec", err.Error()) continue } if h.Kind == KindCatalog { root = true } } return root } func strictDecode(b []byte, v any) error { d := yaml.NewDecoder(bytes.NewReader(b)) d.KnownFields(true) if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) { return err } return nil } func (c *Catalog) addEntity(e Entity, spec []byte) error { dup := func(kind, id, other string) error { return fmt.Errorf("duplicate %s %q (also in %s)", kind, id, other) } switch e.Kind { case KindCatalog: if c.Meta.ID != "" { return fmt.Errorf("more than one Catalog manifest") } if err := strictDecode(spec, &c.Spec); err != nil { return err } c.Meta = e.Meta case KindCapabilities: var s CapabilitiesSpec if err := strictDecode(spec, &s); err != nil { return err } for i := range s.Capabilities { cp := s.Capabilities[i] if other, ok := c.capFile[cp.ID]; ok { return dup("capability", cp.ID, other) } c.Capabilities[cp.ID] = &cp c.capFile[cp.ID] = e.File } case KindPackage: p := &Package{Entity: e} if err := strictDecode(spec, &p.Spec); err != nil { return err } if o, ok := c.Packages[e.Meta.ID]; ok { return dup("package", e.Meta.ID, o.File) } c.Packages[e.Meta.ID] = p case KindProfile: p := &Profile{Entity: e} if err := strictDecode(spec, &p.Spec); err != nil { return err } if e.Meta.Package == "" { return fmt.Errorf("profile %q: metadata.package is required", e.Meta.ID) } if o, ok := c.Profiles[p.Key()]; ok { return dup("profile", p.Key(), o.File) } c.Profiles[p.Key()] = p case KindSolution, KindTask: s := &Solution{Entity: e} if err := strictDecode(spec, &s.Spec); err != nil { return err } if len(s.Spec.Questions) > MaxQuestions || len(s.Spec.Rules) > MaxRules { return fmt.Errorf("more than %d questions or %d rules", MaxQuestions, MaxRules) } m := c.Solutions if e.Kind == KindTask { m = c.Tasks } if o, ok := m[e.Meta.ID]; ok { return dup(strings.ToLower(e.Kind), e.Meta.ID, o.File) } m[e.Meta.ID] = s case KindExample: x := &Example{Entity: e} if err := strictDecode(spec, &x.Spec); err != nil { return err } if x.Spec.Solution == "" { // default: the solution directory the example lives in x.Spec.Solution = solutionDirOf(e.File) } if o, ok := c.Examples[x.Key()]; ok { return dup("example", x.Key(), o.File) } c.Examples[x.Key()] = x case KindKnowledgeSource: k := &KnowledgeSource{Entity: e} if err := strictDecode(spec, &k.Spec); err != nil { return err } if o, ok := c.Sources[e.Meta.ID]; ok { return dup("knowledge source", e.Meta.ID, o.File) } c.Sources[e.Meta.ID] = k default: return fmt.Errorf("unknown kind %q", e.Kind) } return nil } // solutionDirOf: solutions///examples/x.yaml -> . func solutionDirOf(file string) string { dir := path.Dir(path.Dir(file)) return path.Base(dir) } // SortedIDs returns the keys of a map in order. func SortedIDs[V any](m map[string]V) []string { out := make([]string, 0, len(m)) for k := range m { out = append(out, k) } sort.Strings(out) return out } // Lookup finds a solution or task by ID (solutions first). func (c *Catalog) Lookup(id string) *Solution { if s, ok := c.Solutions[id]; ok { return s } if s, ok := c.Tasks[id]; ok { return s } for _, m := range []map[string]*Solution{c.Solutions, c.Tasks} { for _, s := range m { for _, a := range s.Meta.Aliases { if a == id { return s } } } } return nil } // ProvidersOf lists package modules providing a capability, best first. func (c *Catalog) ProvidersOf(capID string) []ModuleRef { var out []ModuleRef for _, pid := range SortedIDs(c.Packages) { p := c.Packages[pid] for _, m := range p.Spec.Modules { for _, pr := range m.Provides { if pr == capID { out = append(out, ModuleRef{Package: pid, Module: m.ID, Priority: m.Priority, Support: m.Support}) } } } } sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority }) return out } // ModuleRef points at one module of one package. type ModuleRef struct { Package string `json:"package"` Module string `json:"module"` Priority int `json:"priority,omitempty"` Support Support `json:"support,omitempty"` } func (m ModuleRef) String() string { return m.Package + "/" + m.Module } // ProfileChain returns the profile and its ancestors, base first; it // fails on unknown profiles and cycles (PROF-03). func (c *Catalog) ProfileChain(pkg, id string) ([]*Profile, error) { var chain []*Profile seen := map[string]bool{} for cur := id; cur != ""; { key := pkg + "/" + cur if seen[key] { return nil, fmt.Errorf("profile %s: inheritance cycle", key) } seen[key] = true p, ok := c.Profiles[key] if !ok { return nil, fmt.Errorf("unknown profile %s", key) } chain = append(chain, p) cur = p.Spec.Extends } for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 { chain[i], chain[j] = chain[j], chain[i] } return chain, nil } // Hash is a digest over all catalog files (catalog version for locks). func (c *Catalog) Hash() string { h := sha256.New() for _, f := range c.Files { fmt.Fprintf(h, "%s %s\n", f.Path, f.Hash) } return hex.EncodeToString(h.Sum(nil)) }