Documentation
¶
Overview ¶
Package apk builds, reads, verifies and signs Alpine Linux packages (.apk, the v2 format of apk-tools) and repository indexes, and fetches them from repositories. It is pure Go and needs neither abuild nor apk.
Packages ¶
An .apk file is two or three concatenated gzip members: an optional signature segment (a tar whose entry is named .SIGN.RSA.<key> or .SIGN.RSA256.<key>), the control segment (a tar that starts with .PKGINFO, followed by the install scripts) and the data segment (the files, each regular file with its SHA-1 in a PAX record). abuild leaves the end-of-archive blocks off the signature and control tars so a client reads the three segments as one tar stream.
WritePackage writes a package from a Spec of plain structs: the metadata (Info), the Scripts and the File entries; FilesFromDir lists a staged directory tree. ParsePackage reads one back under explicit limits, SignPackage adds a signature and VerifyPackage checks it.
Signatures ¶
Alpine signs with RSA and PKCS#1 v1.5, either over a SHA-1 digest (.SIGN.RSA.) or a SHA-256 digest (.SIGN.RSA256.). The type is always an explicit choice: a Signer is made for one SigAlgorithm, and VerifyOptions lists the types a verifier accepts, with the trusted keys in a Keyring (LoadKeyring reads an apk keys directory). Nothing defaults to SHA-1.
The installed database ¶
OpenInstalled and NewInstalledDB read /lib/apk/db/installed, read-only: an InstalledPackage per record, with the index fields and the directories and files it owns, their checksums, owners and modes. A record that is not valid is skipped. InstalledDB.InstalledNames and InstalledDB.InstalledProvides list the installed names and capabilities.
Indexes ¶
BuildIndex and RenderIndex write an APKINDEX.tar.gz or its text, ParseIndex reads one and VerifyIndex checks its signature.
Repositories ¶
ParseRepositories reads a repositories file. A Client fetches the index of each repository, requires a valid signature by a trusted key (unless the caller opts out), and downloads packages, checking each against its index entry. The Index it returns resolves package names, provided capabilities and dependencies (Index.ResolveDeps).
Everything that reads untrusted bytes has explicit size and entry limits and returns typed errors; none of it panics on malformed input.
Example ¶
package main
import (
"bytes"
"fmt"
"io/fs"
"log"
"time"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
// Describe the package.
spec := &apk.Spec{
Info: apk.Info{
Name: "hello", Version: "1.0-r0", Arch: "x86_64",
Description: "Prints a greeting", License: "MIT",
BuildDate: time.Unix(1700000000, 0),
Depends: []string{"busybox"},
},
Scripts: apk.Scripts{PostInstall: "#!/bin/sh\necho installed\n"},
Files: []apk.File{
{Name: "usr", Mode: fs.ModeDir | 0o755, Uname: "root", Gname: "root"},
{Name: "usr/bin", Mode: fs.ModeDir | 0o755, Uname: "root", Gname: "root"},
apk.MemFile("usr/bin/hello", 0o755, []byte("#!/bin/sh\necho hello\n")),
},
}
// Sign it with a key of your own.
key, err := apk.GenerateKey(2048)
if err != nil {
log.Fatal(err)
}
signer, err := apk.NewSigner("me@example.org-5f0a1b2c.rsa.pub", key, apk.SigRSASHA256)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
pkg, err := apk.WritePackage(&out, spec, apk.WriteOptions{Signer: signer})
if err != nil {
log.Fatal(err)
}
// Verify it against the keys you trust.
keys := apk.NewKeyring()
if err := keys.Add(signer.KeyName(), signer.PublicKey()); err != nil {
log.Fatal(err)
}
verified, err := apk.VerifyPackage(bytes.NewReader(out.Bytes()), int64(out.Len()), apk.VerifyOptions{
Keys: keys, Algorithms: []apk.SigAlgorithm{apk.SigRSASHA256},
})
if err != nil {
log.Fatal(err)
}
// Put it in a signed repository index.
index, err := apk.BuildIndex([]apk.Package{*pkg}, "example repository", signer)
if err != nil {
log.Fatal(err)
}
entries, err := apk.VerifyIndex(index, apk.VerifyOptions{
Keys: keys, Algorithms: []apk.SigAlgorithm{apk.SigRSASHA256},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(verified.FileName(), verified.Signed, len(entries), entries[0].Checksum == pkg.Checksum)
}
Output: hello-1.0-r0.apk true 1 true
Index ¶
- Constants
- Variables
- func BuildIndex(pkgs []Package, description string, s *Signer) ([]byte, error)
- func DependencyName(spec string) string
- func FindInstalled(root string) (string, error)
- func GenerateKey(bits int) (*rsa.PrivateKey, error)
- func MarshalPrivateKeyPEM(k *rsa.PrivateKey) []byte
- func ParseFileName(s string) (string, string, bool)
- func ParsePrivateKeyPEM(data []byte) (*rsa.PrivateKey, error)
- func ParsePublicKeyPEM(data []byte) (*rsa.PublicKey, error)
- func RenderIndex(pkgs []Package) []byte
- func SignPackage(w io.Writer, ra io.ReaderAt, size int64, s *Signer) error
- func ValidSegment(s string) bool
- type Client
- type ClientOptions
- type File
- type Index
- func (idx *Index) Add(repo Repo, indexArch string, pkgs []Package)
- func (idx *Index) Find(name string) (*RepoPackage, bool)
- func (idx *Index) Lookup(name string) (*RepoPackage, bool)
- func (idx *Index) ResolveDeps(names []string) (*Resolution, error)
- func (idx *Index) ResolveVirtual(name string) (*RepoPackage, bool)
- func (idx *Index) Stats() (packages, capabilities int)
- type Info
- type InstalledDB
- func (db *InstalledDB) Close() error
- func (db *InstalledDB) InstalledNames(ctx context.Context) ([]string, error)
- func (db *InstalledDB) InstalledProvides(ctx context.Context) ([]string, error)
- func (db *InstalledDB) List(ctx context.Context) ([]*InstalledPackage, error)
- func (db *InstalledDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]
- type InstalledFile
- type InstalledOptions
- type InstalledPackage
- type Keyring
- type Package
- func ParseIndex(r io.Reader) ([]Package, error)
- func ParsePackage(r io.ReaderAt, size int64) (*Package, error)
- func VerifyIndex(data []byte, opts VerifyOptions) ([]Package, error)
- func VerifyPackage(ra io.ReaderAt, size int64, opts VerifyOptions) (*Package, error)
- func WritePackage(w io.Writer, spec *Spec, opts WriteOptions) (*Package, error)
- type Repo
- type RepoError
- type RepoPackage
- type Resolution
- type Scripts
- type SigAlgorithm
- type Signature
- type Signer
- type Spec
- type UpdatedIndex
- type VerifyOptions
- type WriteOptions
Examples ¶
Constants ¶
const ( // DefaultMaxInstalledPackages bounds the package records of a database. DefaultMaxInstalledPackages = 1 << 20 // DefaultMaxInstalledFiles bounds the file and directory records of one // package. DefaultMaxInstalledFiles = 1 << 21 // DefaultMaxInstalledBytes bounds the size of the database file. A system // with a thousand packages has a few megabytes. DefaultMaxInstalledBytes int64 = 1 << 30 )
Default limits of the installed-database reader, applied where an InstalledOptions field is zero.
Variables ¶
var ( // ErrInvalidOptions is wrapped by the errors of [NewClient] for options it // refuses. ErrInvalidOptions = errors.New("apk: invalid client options") // ErrNoIndex is returned by [Client.Update] when no repository index could // be loaded. It wraps the failure of each repository. ErrNoIndex = errors.New("apk: no repository index could be loaded") // ErrPackageMismatch means a downloaded package is not the one its index // entry describes: another size, checksum, name or version. ErrPackageMismatch = errors.New("apk: downloaded package does not match the index") )
var ( // ErrInstalledNotFound means [FindInstalled] met no installed database // under the root. ErrInstalledNotFound = errors.New("apk: no installed database found") // ErrInvalidInstalled means a file is not an installed database, or cannot // be read as one. ErrInvalidInstalled = errors.New("apk: invalid installed database") // ErrInstalledTooLarge means an installed database is over one of the // limits of [InstalledOptions]. ErrInstalledTooLarge = errors.New("apk: installed database exceeds a limit") )
Errors of the installed-database reader. Test with errors.Is.
var ( // ErrNoKeyring is returned when verifying without trusted keys. ErrNoKeyring = errors.New("apk: no trusted keys") // ErrUnsigned means the package or index carries no signature. ErrUnsigned = errors.New("apk: not signed") // ErrUntrusted means there are signatures, but none by a trusted key in an // accepted signature type. ErrUntrusted = errors.New("apk: no signature by a trusted key") // ErrBadSignature means a signature by a trusted key does not match. ErrBadSignature = errors.New("apk: signature does not verify") )
Errors of signature verification.
var ErrAlreadySigned = errors.New("apk: package is already signed")
ErrAlreadySigned is returned by SignPackage for a package that already starts with a signature segment.
var ErrInvalidIndex = errors.New("invalid apk index")
ErrInvalidIndex is wrapped by every error ParseIndex and BuildIndex return for malformed or over-limit input.
var ErrInvalidPackage = errors.New("invalid apk package")
ErrInvalidPackage is wrapped by every error ParsePackage returns.
var ErrInvalidRepositories = errors.New("apk: invalid repositories file")
ErrInvalidRepositories is wrapped by every error ParseRepositories returns.
var ErrInvalidSpec = errors.New("apk: invalid package spec")
ErrInvalidSpec is wrapped by every error WritePackage returns for a Spec it refuses.
var ErrNoAlgorithm = errors.New("apk: no signature algorithm chosen")
ErrNoAlgorithm is returned when a signer, a verifier or a client is used without choosing a SigAlgorithm.
var ErrPackageNotFound = errors.New("apk: package not found")
ErrPackageNotFound is wrapped by the errors of a lookup that finds neither a package nor a provider of the name.
Functions ¶
func BuildIndex ¶
BuildIndex builds a deterministic APKINDEX.tar.gz for pkgs: a gzip member with the tar entries DESCRIPTION and APKINDEX, ended like apk's own index tars. With a signer it is preceded by the signature member, a gzip member whose tar (no end-of-archive blocks, so that apk reads on into the next member) holds the entry .SIGN.RSA.<key name> or .SIGN.RSA256.<key name>, as the signer's SigAlgorithm says: the RSA PKCS#1 v1.5 signature of the complete bytes of the index member. Every package must be valid (see Package), carrying at least the Checksum; errors wrap ErrInvalidIndex.
func DependencyName ¶
DependencyName returns the package or capability name of a dependency entry, without its version constraint: "musl-dev>=1.2" gives "musl-dev".
func FindInstalled ¶ added in v0.3.1
FindInstalled looks for the installed database under root, the directory that holds the system's /lib: "/" for the running host, or the root of an image or an install directory. Symbolic links are followed only inside root. It returns ErrInstalledNotFound when there is no regular file.
func GenerateKey ¶
func GenerateKey(bits int) (*rsa.PrivateKey, error)
GenerateKey generates an RSA key of bits bits, which must be between 2048 and 16384.
func MarshalPrivateKeyPEM ¶
func MarshalPrivateKeyPEM(k *rsa.PrivateKey) []byte
MarshalPrivateKeyPEM encodes k as a PKCS#8 "PRIVATE KEY" PEM block. It returns nil for a key that cannot be encoded.
func ParseFileName ¶
ParseFileName is the inverse of Package.FileName. The version starts at the last '-' that is followed by a digit and whose prefix is a valid package name; both halves must be valid. It returns the name, the version and whether s is a valid package file name. For every valid name and version, ParseFileName(name + "-" + version + ".apk") returns them again.
func ParsePrivateKeyPEM ¶
func ParsePrivateKeyPEM(data []byte) (*rsa.PrivateKey, error)
ParsePrivateKeyPEM decodes the first PEM block of data as an unencrypted RSA private key of 2048 to 16384 bits: PKCS#8 ("PRIVATE KEY") or PKCS#1 ("RSA PRIVATE KEY", what abuild-keygen writes).
func ParsePublicKeyPEM ¶
ParsePublicKeyPEM decodes the first PEM block of data as an RSA public key of 2048 to 16384 bits: "PUBLIC KEY" (SubjectPublicKeyInfo, what apk keeps in its keys directory) or "RSA PUBLIC KEY" (PKCS#1).
func RenderIndex ¶
RenderIndex renders packages as APKINDEX text: one stanza per package, in the order given, each ending with a blank line. Fields that are empty or zero are left out, except the mandatory C, P, V and A. Control characters in a value are replaced by a space so that a value can never start a new line or field; BuildIndex refuses such packages outright instead.
func SignPackage ¶
SignPackage writes the unsigned .apk of size bytes to w with a signature segment of s in front of it: the signature covers the control segment, as abuild-sign does. A package that is already signed is ErrAlreadySigned. The package is parsed first and must be valid.
func ValidSegment ¶
ValidSegment reports whether s may be used as a branch, repository or architecture path segment: ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$. Because the first byte must be alphanumeric, "." and ".." never pass.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client fetches and verifies repository indexes and downloads packages. It is safe for concurrent use.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
client, err := apk.NewClient(apk.ClientOptions{
Repos: []apk.Repo{{URL: "https://dl-cdn.alpinelinux.org/alpine/v3.21/main"}},
Arch: "x86_64",
KeysDir: "/etc/apk/keys",
Algorithms: []apk.SigAlgorithm{apk.SigRSASHA1}, // what Alpine's own repositories use
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
index, err := client.Update(ctx)
if err != nil {
log.Fatal(err)
}
res, err := index.ResolveDeps([]string{"curl"})
if err != nil {
log.Fatal(err)
}
paths, err := client.Download(ctx, "/var/cache/apk", res.Packages...)
if err != nil {
log.Fatal(err)
}
fmt.Println(paths)
}
Output:
func NewClient ¶
func NewClient(opts ClientOptions) (*Client, error)
NewClient validates opts and loads the trusted keys.
func (*Client) Download ¶
func (c *Client) Download(ctx context.Context, destDir string, pkgs ...*RepoPackage) ([]string, error)
Download fetches the package files of pkgs into destDir, which must exist, and returns their paths in the order given. Transfers resume after a partial download and are retried by the client's policy. Each file is checked against its index entry before it is kept: it must be a valid package of the size, checksum, name and version the index lists, otherwise it is deleted and the error wraps ErrPackageMismatch or ErrInvalidPackage. The index checksum is the trust anchor, as in apk itself: when the index was verified, so is every package it lists.
func (*Client) FetchIndex ¶
FetchIndex downloads, verifies (when the client has keys) and parses the index of one repository.
func (*Client) Update ¶
func (c *Client) Update(ctx context.Context) (*UpdatedIndex, error)
Update fetches the index of every repository (a few in parallel) and returns them as one Index in the order of the repositories. A repository that cannot be fetched, verified or parsed is left out and reported by [Client.Failures] of the result; Update fails with ErrNoIndex only when no repository loads.
type ClientOptions ¶
type ClientOptions struct {
// Repos are the repositories, in order of preference.
Repos []Repo
// Arch is the architecture directory of every repository, for example
// x86_64.
Arch string
// KeysDir is the directory of trusted public keys (the keys directory of
// /etc/apk) the index signatures are checked against. An index without a
// valid signature by one of them is refused.
KeysDir string
// Algorithms are the signature types accepted when KeysDir is set. There
// is no default: a caller that accepts SHA-1 signatures says so.
Algorithms []SigAlgorithm
// InsecureSkipVerify accepts indexes without checking their signature. It
// excludes KeysDir. The downloaded packages are still checked against the
// index entries.
InsecureSkipVerify bool
// HTTP fetches the indexes and the packages. Nil builds a client with the
// default retry policy.
HTTP *httpclient.Client
// CacheDir, when set, receives a copy of each verified index tarball, named
// APKINDEX.<sha1 of the URL>.tar.gz. The directory is created.
CacheDir string
// Concurrency bounds the parallel package downloads; zero selects the
// download package's default.
Concurrency int
// Logger receives one line per repository and package. Nil is silent.
Logger *slog.Logger
}
ClientOptions configures a Client. Repos, Arch, and a trust decision (KeysDir with Algorithms, or InsecureSkipVerify) are required; nothing is read from a host path unless the caller names it.
type File ¶
type File struct {
// Name is the install path: slash separated, relative, without "." or
// ".." elements. A directory's trailing slash is added when missing.
Name string
// Mode holds the type and the permission bits, setuid, setgid and sticky
// included.
Mode fs.FileMode
// Size is the length of a regular file's content.
Size int64
// ModTime is the modification time, truncated to the second; the zero time
// is the epoch.
ModTime time.Time
// UID, GID, Uname and Gname are the owner.
UID, GID int
Uname, Gname string
// LinkTarget is the target of a symbolic link.
LinkTarget string
// Open returns the content of a regular file. It is called twice (one pass
// to record the checksum, one to write) and must return Size bytes both
// times. Nil is an empty file.
Open func() (io.ReadCloser, error)
}
File is one entry of the data segment. The kind comes from Mode: a directory, a symbolic link, a named pipe or a regular file; any other kind (devices, sockets) is refused.
func FilesFromDir ¶
FilesFromDir lists the tree under dir for Spec.Files: every entry below dir in lexical order, with names relative to dir, links not followed, the owner root:root and the modification time the epoch, so the package does not depend on who built it or when. The permission bits are kept.
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index is the set of packages of one or more repositories, for lookups and dependency resolution. It is filled with Index.Add and then only read; it is not safe for concurrent Add.
func (*Index) Add ¶
Add lists the packages of repo's index for indexArch. A package whose name is already in the Index is ignored: the repository added first wins, like the order of a repositories file. Every package registers the capabilities of its Provides, without their versions.
func (*Index) Find ¶
func (idx *Index) Find(name string) (*RepoPackage, bool)
Find returns the package called name or, failing that, the provider of the capability name.
func (*Index) Lookup ¶
func (idx *Index) Lookup(name string) (*RepoPackage, bool)
Lookup returns the package of that name. The name has no version constraint.
func (*Index) ResolveDeps ¶
func (idx *Index) ResolveDeps(names []string) (*Resolution, error)
ResolveDeps resolves names and their transitive dependencies with a depth-first walk: a name is a package or a capability, version constraints are dropped, and "!conflict" and "/path" dependencies are skipped. It is not a solver; it picks the first package that matches. A requested name that nothing provides is ErrPackageNotFound. The walk keeps its own stack, so a chain of dependencies as long as a hostile index can make it costs memory, not call depth.
func (*Index) ResolveVirtual ¶
func (idx *Index) ResolveVirtual(name string) (*RepoPackage, bool)
ResolveVirtual returns the package that provides the capability name: the one with the highest provider priority, the first added among equals.
type Info ¶
type Info struct {
// Name is the package name (pkgname), Version the complete version
// including the release (pkgver), for example "1.2.3-r0". Alpine versions
// have no epoch. Arch is the apk architecture such as x86_64 or noarch.
Name, Version, Arch string
// Description (pkgdesc), URL, License (one SPDX expression or a list
// separated by spaces, as abuild writes it), Origin (the package the
// build produced it from; the Name when empty), Maintainer, Packager and
// Commit are the free text lines.
Description, URL, License, Origin, Maintainer, Packager, Commit string
// BuildDate is the builddate; the line is left out when it is zero.
BuildDate time.Time
// InstalledSize is the size line, the bytes the package takes installed.
// Zero selects the sum of the sizes of the regular files.
InstalledSize int64
// Depends, Provides and Replaces get one depend, provides or replaces
// line per entry. InstallIf is one install_if line.
Depends, Provides, Replaces, InstallIf []string
// ProviderPriority is the provider_priority line; zero leaves it out.
ProviderPriority int
// Generator, when set, is written as the first line, a comment:
// "# Generated by <Generator>".
Generator string
}
Info is the metadata of a package: what goes into its .PKGINFO. Name, Version and Arch are required; the zero value of every other field leaves the line out.
type InstalledDB ¶ added in v0.3.1
type InstalledDB struct {
// contains filtered or unexported fields
}
InstalledDB is an apk installed database: the file /lib/apk/db/installed. It is read-only and safe for concurrent use: every call reads the file again.
Example ¶
Read the packages an apk system has installed, with the files they own. On a host, FindInstalled("/") and OpenInstalled give the real database.
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
const text = `C:Q1qvTGHdzF6KLavt4PO0gs2a6pQ00=
P:busybox
V:1.37.0-r31
A:x86_64
p:cmd:busybox=1.37.0-r31 /bin/sh
F:bin
R:busybox
a:0:0:755
Z:Q1y5VcgN7Y1x2d9E1Gp7BkG5mZYGM=
`
db := apk.NewInstalledDB(strings.NewReader(text), int64(len(text)), apk.InstalledOptions{})
for pkg, err := range db.Packages(context.Background()) {
if err != nil {
log.Fatal(err)
}
fmt.Println(pkg.Name, pkg.Version, pkg.FilePaths())
}
provides, _ := db.InstalledProvides(context.Background())
fmt.Println(provides)
}
Output: busybox 1.37.0-r31 [bin/busybox] [/bin/sh busybox cmd:busybox]
func NewInstalledDB ¶ added in v0.3.1
func NewInstalledDB(r io.ReaderAt, size int64, opts InstalledOptions) *InstalledDB
NewInstalledDB reads the database text that r holds, size bytes. Close does not close r. A size over InstalledOptions.MaxBytes makes every read fail with ErrInstalledTooLarge.
func OpenInstalled ¶ added in v0.3.1
func OpenInstalled(path string, opts InstalledOptions) (*InstalledDB, error)
OpenInstalled opens the installed database at path. The file is only read and not locked, so apk can run at the same time; each call reads it as of that moment.
func (*InstalledDB) Close ¶ added in v0.3.1
func (db *InstalledDB) Close() error
Close releases the file of a database opened with OpenInstalled.
func (*InstalledDB) InstalledNames ¶ added in v0.3.1
func (db *InstalledDB) InstalledNames(ctx context.Context) ([]string, error)
InstalledNames returns the names of the installed packages, sorted and without duplicates. It does not keep the file lists.
func (*InstalledDB) InstalledProvides ¶ added in v0.3.1
func (db *InstalledDB) InstalledProvides(ctx context.Context) ([]string, error)
InstalledProvides returns the capabilities the installed packages provide ("so:libc.musl-x86_64.so.1", "cmd:sh", "/bin/sh"), as names without version constraints, sorted and without duplicates. The name of each package is included, as it provides itself. It does not keep the file lists.
func (*InstalledDB) List ¶ added in v0.3.1
func (db *InstalledDB) List(ctx context.Context) ([]*InstalledPackage, error)
List returns every installed package: InstalledDB.Packages collected into a slice.
func (*InstalledDB) Packages ¶ added in v0.3.1
func (db *InstalledDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]
Packages iterates over the installed packages in the order of the database. A record that is not valid is skipped and reported at debug level to InstalledOptions.Logger: a missing P, V or A line, a repeated field, a value that is not valid, a path that climbs out of the root, a package with more than InstalledOptions.MaxFiles file records. The iteration ends with an error when the file is over its limits, cannot be read, or when ctx is done; the error is the last pair it yields. Stopping early releases everything.
type InstalledFile ¶ added in v0.3.1
type InstalledFile struct {
// Path is relative to the root of the system, without a leading slash:
// "usr/lib/libz.so.1".
Path string
// Dir is true for a directory the package owns, and false for a file.
Dir bool
// Checksum is the "Z:" value of a file, "Q1" and the base64 of its SHA-1
// (or, for an install made by a newer apk, the algorithm's own prefix).
// It is empty for a directory.
Checksum string
// HasACL reports that the record carries an "a:" (file) or "M:"
// (directory) line, which gives the owner and the mode.
HasACL bool
// UID and GID are the owner and group of the file, and Mode its
// permission bits, from the ACL line. They are zero without one.
UID, GID uint32
Mode uint32
}
InstalledFile is a file or directory record of an installed package.
type InstalledOptions ¶ added in v0.3.1
type InstalledOptions struct {
// Logger receives debug messages about skipped records. Optional: nil
// discards them.
Logger *slog.Logger
// MaxPackages bounds the package records read; reading more fails with
// [ErrInstalledTooLarge]. Zero selects [DefaultMaxInstalledPackages].
MaxPackages int
// MaxFiles bounds the file and directory records of one package; a
// package with more is skipped. Zero selects [DefaultMaxInstalledFiles].
MaxFiles int
// MaxBytes bounds the size of the database; a larger one fails with
// [ErrInstalledTooLarge]. Zero selects [DefaultMaxInstalledBytes].
MaxBytes int64
// SkipFiles leaves the file records out of the packages. The names and
// the metadata of a large database are then read without keeping the
// lists.
SkipFiles bool
}
InstalledOptions configures OpenInstalled, NewInstalledDB. The zero value is usable.
type InstalledPackage ¶ added in v0.3.1
type InstalledPackage struct {
// Package holds the index fields, P, V, A, S, I, T, U, L, o, m, t, c, D,
// p, i and k, and "r" (Replaces). Checksum is the "C:" value; it is empty
// for a package without one.
Package
// ReplacesPriority is the "q" field: which of two packages that own the
// same file wins.
ReplacesPriority int
// Files are the directories and files of the package, in the order of the
// database: a directory, then the files in it.
Files []InstalledFile
}
InstalledPackage is a package record of the installed database: the fields of an index entry, the files the package owns and what apk adds for an installed package.
func (*InstalledPackage) FilePaths ¶ added in v0.3.1
func (p *InstalledPackage) FilePaths() []string
FilePaths returns the paths of the regular files of the package, as "apk info -L" lists them.
type Keyring ¶
type Keyring struct {
// contains filtered or unexported fields
}
Keyring is the set of public keys a signature is checked against, by key name: the file names of apk's keys directory.
func LoadKeyring ¶
LoadKeyring reads the public keys of dir: every regular file whose name ends in .rsa.pub, as PEM. Other files and subdirectories are ignored; a .rsa.pub file that is not a valid key fails the load, so a damaged key is never silently dropped from the trust set. At most 1000 files of 64 KiB.
type Package ¶
type Package struct {
Name, Version, Arch string
Description, URL, License, Origin, Maintainer, Commit string
// Packager is the PKGINFO packager. It is not an index field.
Packager string
// BuildTime is the PKGINFO builddate (index field t), InstalledSize the
// PKGINFO size (index field I).
BuildTime, InstalledSize int64
Depends, Provides []string
// Replaces is the PKGINFO replaces list. It is not an index field.
Replaces []string
InstallIf []string
ProviderPriority int
// DataHash is the lowercase hex SHA-256 of the data segment (PKGINFO
// datahash); empty for index entries.
DataHash string
// Checksum is the index "C:" value: "Q1" + base64(SHA-1 of the control
// segment).
Checksum string
// Size is the size of the .apk file (index field S).
Size int64
// Signed reports that the file starts with an abuild signature segment.
// [ParsePackage] does not verify the signature, [VerifyPackage] does.
Signed bool
}
Package is a verified .apk and also one APKINDEX entry.
func ParseIndex ¶
ParseIndex reads an APKINDEX: either the plain text or an APKINDEX.tar.gz, told apart by the gzip magic. The archive is read as abuild writes it: any number of gzip members, those whose tar starts with a .SIGN. entry (the signature) skipped, and exactly one holding an APKINDEX entry. Signatures are not verified here. Input is bounded: 512 MiB decompressed, 2 000 000 entries and 1 MiB per line. Every entry must carry the C, P, V and A fields and valid values, otherwise the whole index is refused; unknown field letters are ignored. Control characters in the free text fields (T, U, L, o, m, c) are replaced by a space: a few Alpine descriptions contain tabs. Errors wrap ErrInvalidIndex.
func ParsePackage ¶
ParsePackage parses and verifies an .apk of size bytes: it locates the gzip members exactly, reads the control segment, checks that the PKGINFO datahash is the SHA-256 of the data segment, fully decompresses the data segment (verifying its gzip checksum) and refuses entries that are absolute or climb out of their directory. Every error wraps ErrInvalidPackage.
func VerifyIndex ¶
func VerifyIndex(data []byte, opts VerifyOptions) ([]Package, error)
VerifyIndex parses an APKINDEX.tar.gz like ParseIndex and checks that the signature member in front of the index member holds a valid signature of the index member by a key of opts.Keys, in a type of opts.Algorithms. The errors are those of VerifyPackage; plain APKINDEX text is ErrUnsigned.
func VerifyPackage ¶
VerifyPackage parses the .apk of size bytes like ParsePackage and checks that its signature segment holds a valid signature of the control segment by a key of opts.Keys, in a type of opts.Algorithms. The error is ErrUnsigned for a package without signature, ErrUntrusted when no signature is by a trusted key in an accepted type, ErrBadSignature when a trusted key's signature does not match; a malformed package wraps ErrInvalidPackage.
func WritePackage ¶
WritePackage writes the .apk described by spec to w: the optional signature segment, the control segment (.PKGINFO and the install scripts) and the data segment, three gzip members as abuild writes them. Each regular file of the data segment carries its SHA-1 in a PAX record (APK-TOOLS.checksum.SHA1) and the .PKGINFO records the SHA-256 of the data segment (datahash).
The result is deterministic for a given spec. It returns the package as an index entry: its checksum, size and datahash, ready for BuildIndex. Errors for a spec it refuses wrap ErrInvalidSpec.
type Repo ¶
type Repo struct {
// URL is the base URL of the repository, without a trailing slash: the
// index is at <URL>/<arch>/APKINDEX.tar.gz.
URL string
// Tag is the tag of a tagged repository ("edge" for "@edge https://…"),
// empty for an untagged one. The tag is carried for the caller: the
// resolver does not use it.
Tag string
}
Repo is one repository of a repositories file.
func ParseRepositories ¶
ParseRepositories parses the text of an apk repositories file (the repositories file of /etc/apk): one repository per line, either a URL or "@tag URL", with blank lines and '#' comments ignored. Trailing slashes are dropped. It reads at most 1 MiB and 10 000 repositories. The caller opens the file; the package never reads a host path.
type RepoPackage ¶
type RepoPackage struct {
Package
// Repo is the repository whose index lists the package.
Repo Repo
// IndexArch is the architecture directory of that index. The package file
// is in it whatever the package's own Arch is: noarch packages sit next to
// the architecture-specific ones.
IndexArch string
}
RepoPackage is an index entry together with where it was found.
func (*RepoPackage) URL ¶
func (p *RepoPackage) URL() string
URL returns the download URL of the package file: <repository>/<index arch>/<name>-<version>.apk.
type Resolution ¶
type Resolution struct {
// Packages are the packages to install, dependencies before the packages
// that need them.
Packages []*RepoPackage
// Virtual lists the capabilities that were resolved to a provider.
Virtual []string
// Unresolved lists the dependencies nothing provides. They are skipped,
// not an error: apk itself rejects them at install time if they matter.
Unresolved []string
}
Resolution is the result of Index.ResolveDeps.
type Scripts ¶
type Scripts struct {
PreInstall, PostInstall string
PreUpgrade, PostUpgrade string
PreDeinstall, PostDeinstall string
// Trigger is the .trigger script.
Trigger string
}
Scripts are the install scripts of a package. Each is the complete file, shebang included, and is stored executable in the control segment under the name apk runs it by; an empty script is left out. A script of an install hook that also runs on upgrade is set in both fields (PreInstall and PreUpgrade), as abuild's single pre-install script would not run on upgrade.
type SigAlgorithm ¶
type SigAlgorithm int
SigAlgorithm selects the signature type of an abuild signature entry. The zero value is invalid: every caller states which type it signs with or accepts.
const ( // SigRSASHA1 is RSA PKCS#1 v1.5 over SHA-1, the entry // .SIGN.RSA.<key name>: what abuild-sign writes and every apk-tools // version verifies. SigRSASHA1 SigAlgorithm = iota + 1 // SigRSASHA256 is RSA PKCS#1 v1.5 over SHA-256, the entry // .SIGN.RSA256.<key name>. SigRSASHA256 )
func (SigAlgorithm) String ¶
func (a SigAlgorithm) String() string
String returns "RSA-SHA1", "RSA-SHA256" or "invalid".
type Signature ¶
type Signature struct {
// KeyName is the key name in the entry name, e.g. "alpine-devel@lists.alpinelinux.org-5261cecb.rsa.pub".
KeyName string
// Algorithm is the signature type; zero for an entry of a type this
// package does not know (.SIGN.DSA.…).
Algorithm SigAlgorithm
// Value is the signature bytes.
Value []byte
}
Signature is one signature entry of a package or index.
type Signer ¶
type Signer struct {
// contains filtered or unexported fields
}
Signer signs packages and indexes with an RSA key under the name apk looks the public key up by: the file name in its keys directory.
func NewSigner ¶
func NewSigner(keyName string, key *rsa.PrivateKey, alg SigAlgorithm) (*Signer, error)
NewSigner returns a Signer for key that writes signatures of type alg. keyName must match ^[A-Za-z0-9._@+-]+\.rsa\.pub$ and keep the entry name (the type's prefix and keyName) within 100 bytes, and the key must be a valid RSA key of 2048 to 16384 bits. A zero alg is ErrNoAlgorithm.
func (*Signer) Algorithm ¶
func (s *Signer) Algorithm() SigAlgorithm
Algorithm returns the signature type the Signer writes.
func (*Signer) EntryName ¶
EntryName returns the name of the signature tar entry: .SIGN.RSA.<KeyName> or .SIGN.RSA256.<KeyName>.
func (*Signer) Fingerprint ¶
Fingerprint returns the hex SHA-256 of the DER SubjectPublicKeyInfo.
func (*Signer) PublicKeyPEM ¶
PublicKeyPEM returns the public key as a "PUBLIC KEY" (SubjectPublicKeyInfo) PEM block: what apk keeps in its keys directory.
func (*Signer) Sign ¶
Sign returns the RSA PKCS#1 v1.5 signature of the digest of data: the content of the Signer.EntryName entry. For a package data is the control segment, for an index the index segment; WritePackage, SignPackage and BuildIndex do that.
type UpdatedIndex ¶
type UpdatedIndex struct {
*Index
// Failures are the repositories that were left out.
Failures []*RepoError
}
UpdatedIndex is the result of Client.Update.
type VerifyOptions ¶
type VerifyOptions struct {
// Keys are the trusted public keys.
Keys *Keyring
// Algorithms are the accepted signature types. A SHA-1 signature is only
// accepted when SigRSASHA1 is listed.
Algorithms []SigAlgorithm
}
VerifyOptions says which signatures to trust. Both fields are required: the caller chooses the trust anchors and the signature types it accepts, there is no default.
type WriteOptions ¶
type WriteOptions struct {
// Signer, when set, puts a signature segment of the control segment in
// front of the package.
Signer *Signer
// TempDir is where the compressed data segment is spooled until its hash
// is known (the control segment, which comes first in the file, records
// it). Empty selects os.TempDir.
TempDir string
}
WriteOptions configures WritePackage.