// Package assets resolves virtual asset paths against an ordered list of // sources (embedded folder, ZIP, embedded ZIP, explicit directory root). package assets import ( "archive/zip" "bytes" "context" "errors" "fmt" "io" "io/fs" "os" "strings" ) // DefaultMaxSize bounds a single resolved resource (also the uncompressed // budget for a ZIP entry). const DefaultMaxSize = 32 << 20 // Resource is one resolved asset. type Resource struct { Name string // canonical virtual path MIME string Bytes []byte Source string // name of the source that served it } // Source is one place assets can come from. Open must return an error // wrapping fs.ErrNotExist for a missing file; any other error is a real // failure and stops the lookup. type Source interface { Name() string ReadFile(name string, max int64) ([]byte, error) Close() error } // Resolver looks a path up in its sources in order. It falls back to the // next source only on "not found". type Resolver struct { sources []Source max int64 } // NewResolver builds a resolver over sources (at least one). func NewResolver(sources ...Source) (*Resolver, error) { if len(sources) == 0 { return nil, errors.New("assets: no sources configured") } return &Resolver{sources: sources, max: DefaultMaxSize}, nil } // Sources lists the source names in lookup order (for the diagnostic report). func (r *Resolver) Sources() []string { out := make([]string, len(r.sources)) for i, s := range r.sources { out[i] = s.Name() } return out } // Resolve returns the resource for a canonical virtual path. func (r *Resolver) Resolve(ctx context.Context, name string) (*Resource, error) { if err := ValidatePath(name); err != nil { return nil, err } for _, s := range r.sources { if err := ctx.Err(); err != nil { return nil, err } data, err := s.ReadFile(name, r.max) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err) } m, err := DetectMIME(name, data) if err != nil { return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err) } return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil } return nil, fmt.Errorf("asset %q: %w (searched %s)", name, fs.ErrNotExist, strings.Join(r.Sources(), ", ")) } // ResolveIn returns the resource from one named source only (diagnostics: // "same bytes from every source"). func (r *Resolver) ResolveIn(name, source string) (*Resource, error) { if err := ValidatePath(name); err != nil { return nil, err } for _, s := range r.sources { if s.Name() != source { continue } data, err := s.ReadFile(name, r.max) if err != nil { return nil, err } m, err := DetectMIME(name, data) if err != nil { return nil, err } return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil } return nil, fmt.Errorf("no source %q", source) } // Close closes all sources (ZIP archives, directory roots). func (r *Resolver) Close() error { var errs []error for _, s := range r.sources { errs = append(errs, s.Close()) } return errors.Join(errs...) } func readLimited(rd io.Reader, max int64, name string) ([]byte, error) { data, err := io.ReadAll(io.LimitReader(rd, max+1)) if err != nil { return nil, err } if int64(len(data)) > max { return nil, fmt.Errorf("%s exceeds size limit of %d bytes", name, max) } return data, nil } // --- fs.FS source (embed.FS, or any fs.FS) ------------------------------- type fsSource struct { name string fsys fs.FS } // NewFSSource wraps an fs.FS whose root is the asset root (for embed.FS use // fs.Sub(efs, "assets") first). func NewFSSource(name string, fsys fs.FS) Source { return &fsSource{name: name, fsys: fsys} } func (s *fsSource) Name() string { return s.name } func (s *fsSource) Close() error { return nil } func (s *fsSource) ReadFile(name string, max int64) ([]byte, error) { f, err := s.fsys.Open(name) if err != nil { return nil, err } defer f.Close() st, err := f.Stat() if err != nil { return nil, err } if st.IsDir() { return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist) } return readLimited(f, max, name) } // --- directory source ---------------------------------------------------- type dirSource struct { name string root *os.Root } // NewDirSource opens dir as an explicit asset root. os.Root keeps every // lookup (including symlinks) inside dir. func NewDirSource(dir string) (Source, error) { root, err := os.OpenRoot(dir) if err != nil { return nil, fmt.Errorf("asset dir %s: %w", dir, err) } return &dirSource{name: "dir:" + dir, root: root}, nil } func (s *dirSource) Name() string { return s.name } func (s *dirSource) Close() error { return s.root.Close() } func (s *dirSource) ReadFile(name string, max int64) ([]byte, error) { f, err := s.root.Open(name) if err != nil { return nil, err } defer f.Close() st, err := f.Stat() if err != nil { return nil, err } if st.IsDir() { return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist) } return readLimited(f, max, name) } // --- ZIP source ---------------------------------------------------------- type zipSource struct { name string zr *zip.Reader prefix string closer io.Closer files map[string]*zip.File } // NewZipFileSource opens a ZIP file on disk (never extracted). prefix is the // directory inside the archive that is the asset root ("" = archive root). func NewZipFileSource(file, prefix string) (Source, error) { rc, err := zip.OpenReader(file) if err != nil { return nil, fmt.Errorf("asset zip %s: %w", file, err) } s, err := newZipSource("zip:"+file, &rc.Reader, prefix, rc) if err != nil { rc.Close() return nil, err } return s, nil } // NewZipBytesSource reads a ZIP held in memory (e.g. an embedded assets.zip). func NewZipBytesSource(name string, data []byte, prefix string) (Source, error) { zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { return nil, fmt.Errorf("asset zip %s: %w", name, err) } return newZipSource(name, zr, prefix, nil) } func newZipSource(name string, zr *zip.Reader, prefix string, closer io.Closer) (*zipSource, error) { if prefix != "" { if err := ValidatePath(prefix); err != nil { return nil, fmt.Errorf("zip root: %w", err) } prefix += "/" } s := &zipSource{name: name, zr: zr, prefix: prefix, closer: closer, files: map[string]*zip.File{}} for _, f := range zr.File { if !strings.HasPrefix(f.Name, prefix) || strings.HasSuffix(f.Name, "/") { continue } rel := f.Name[len(prefix):] // Entries with unsafe names ("../x", "/etc/x", "a\\b") are never // reachable: they simply do not get an identity. if ValidatePath(rel) != nil { continue } s.files[rel] = f } return s, nil } func (s *zipSource) Name() string { return s.name } func (s *zipSource) Close() error { if s.closer != nil { return s.closer.Close() } return nil } func (s *zipSource) ReadFile(name string, max int64) ([]byte, error) { f, ok := s.files[name] if !ok { return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist) } if f.UncompressedSize64 > uint64(max) { return nil, fmt.Errorf("%s: uncompressed size %d exceeds budget %d", name, f.UncompressedSize64, max) } rc, err := f.Open() if err != nil { return nil, err } defer rc.Close() return readLimited(rc, max, name) }