apk

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 35 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

apk

Part of pkgformat.

Go Reference

A Go library to build, read, verify and sign Alpine Linux packages (.apk, the v2 format of apk-tools) and repository indexes, and to fetch them from repositories. It is pure Go: no abuild, no apk binary, no fakeroot and no access to the file system to do its job, other than the paths you pass in.

Install

go get github.com/M0Rf30/pkgformat/apk

Requires Go 1.27 or later.

What it does

Write a package WritePackage from a Spec of plain structs (Info, Scripts, File); FilesFromDir lists a staged tree. The output is deterministic.
Read a package ParsePackage returns the metadata, the SHA-1 index checksum, the size and the data hash, under explicit limits.
Sign and verify SignPackage, WriteOptions.Signer, VerifyPackage. RSA with PKCS#1 v1.5, SHA-1 (.SIGN.RSA.) or SHA-256 (.SIGN.RSA256.).
Indexes BuildIndex, RenderIndex, ParseIndex, VerifyIndex.
Keys GenerateKey, ParsePrivateKeyPEM, ParsePublicKeyPEM, Keyring, LoadKeyring for an apk keys directory.
Repositories ParseRepositories; Client fetches and verifies the indexes and downloads packages; Index resolves names, capabilities and dependencies.

A package written by WritePackage has, as abuild writes it: an optional signature segment, a control segment (.PKGINFO first, then the install scripts as .pre-install, .post-install, .pre-upgrade, .post-upgrade, .pre-deinstall, .post-deinstall and .trigger) and a data segment in which every regular file carries its SHA-1 in the APK-TOOLS.checksum.SHA1 PAX record. The .PKGINFO records the SHA-256 of the data segment (datahash) and the installed size.

Examples

The tested examples are on pkg.go.dev (example_test.go). In short:

Write, sign, verify and index a package:

spec := &apk.Spec{
	Info: apk.Info{Name: "hello", Version: "1.0-r0", Arch: "x86_64", License: "MIT"},
	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")),
	},
}

key, _ := apk.GenerateKey(2048)
signer, _ := apk.NewSigner("me@example.org-5f0a1b2c.rsa.pub", key, apk.SigRSASHA256)

pkg, err := apk.WritePackage(out, spec, apk.WriteOptions{Signer: signer}) // out is an io.Writer
if err != nil {
	log.Fatal(err)
}

index, _ := apk.BuildIndex([]apk.Package{*pkg}, "my repository", signer)

Install from a repository:

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},
})
index, err := client.Update(ctx)
res, err := index.ResolveDeps([]string{"curl"})
paths, err := client.Download(ctx, "/var/cache/apk", res.Packages...)

Signature types

There is no default signature type. NewSigner takes the SigAlgorithm, and VerifyOptions.Algorithms (and ClientOptions.Algorithms) list the types a verifier accepts. Alpine's own repositories are signed with SHA-1 (.SIGN.RSA.); apk-tools 3 also reads SHA-256 (.SIGN.RSA256.). A caller who accepts SHA-1 says so. Keys are RSA of 2048 to 16384 bits.

The client

Client needs a trust decision: a KeysDir with Algorithms, or an explicit InsecureSkipVerify. Update loads the repositories in parallel; one that cannot be fetched or verified is left out and listed in Failures, and ErrNoIndex is returned only when none loads. Download resumes partial files and checks each package against its index entry (size, SHA-1 checksum, name and version) before keeping it, as apk does: the signed index is the trust anchor of the packages it lists. Package files are found next to the index of their repository, whatever their own arch is (noarch packages included).

The caller supplies everything that comes from the host: the repositories (ParseRepositories reads text, it opens no file), the architecture and the keys directory. Retry, backoff and timeouts come from the httpclient.Client you pass in ClientOptions.HTTP.

The resolver is not a solver. ResolveDeps follows depend entries depth-first, drops version constraints, skips !conflicts and /path dependencies and picks the first package that provides a capability (the highest provider_priority wins). It does not compare versions and has no notion of @tag pinning; the tag of a repository is only carried along.

Not covered

  • Package versions have no epoch: Alpine's version syntax has none, and WritePackage refuses 1:2.0-r0.
  • Info.License is one string (abuild joins several licenses with a space).
  • Entries of the data segment are directories, regular files, symbolic links and named pipes. Devices and hard links are refused.
  • Installing packages, the apk database, version comparison and @tag repository pinning are out of scope.

Security notes

Everything that reads untrusted bytes is bounded and returns typed errors, wrapping ErrInvalidPackage, ErrInvalidIndex, ErrInvalidRepositories, ErrUnsigned, ErrUntrusted or ErrBadSignature; none of it panics on malformed input, and every parser has a fuzz target.

Limit Value
Package control segment, compressed / decompressed 4 MiB / 8 MiB
.PKGINFO 1 MiB
Control entries 1000
Data segment, decompressed / entries 8 GiB / 1,000,000
Index, decompressed / entries / line 512 MiB / 2,000,000 / 1 MiB
Signature entry / signatures per package 4096 bytes / 16
Index download 100 MiB
Package download its index size, else 1 GiB
Repositories file 1 MiB, 10,000 lines

File names in a package are checked against .. and absolute paths, and the names the client builds from an index entry are checked before they touch the file system.

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.

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

Examples

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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.

View Source
var ErrAlreadySigned = errors.New("apk: package is already signed")

ErrAlreadySigned is returned by SignPackage for a package that already starts with a signature segment.

View Source
var ErrInvalidIndex = errors.New("invalid apk index")

ErrInvalidIndex is wrapped by every error ParseIndex and BuildIndex return for malformed or over-limit input.

View Source
var ErrInvalidPackage = errors.New("invalid apk package")

ErrInvalidPackage is wrapped by every error ParsePackage returns.

View Source
var ErrInvalidRepositories = errors.New("apk: invalid repositories file")

ErrInvalidRepositories is wrapped by every error ParseRepositories returns.

View Source
var ErrInvalidSpec = errors.New("apk: invalid package spec")

ErrInvalidSpec is wrapped by every error WritePackage returns for a Spec it refuses.

View Source
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.

View Source
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

func BuildIndex(pkgs []Package, description string, s *Signer) ([]byte, error)

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

func DependencyName(spec string) string

DependencyName returns the package or capability name of a dependency entry, without its version constraint: "musl-dev>=1.2" gives "musl-dev".

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

func ParseFileName(s string) (string, string, bool)

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

func ParsePublicKeyPEM(data []byte) (*rsa.PublicKey, error)

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

func RenderIndex(pkgs []Package) []byte

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

func SignPackage(w io.Writer, ra io.ReaderAt, size int64, s *Signer) error

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

func ValidSegment(s string) bool

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)
}

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

func (c *Client) FetchIndex(ctx context.Context, repo Repo) ([]Package, error)

FetchIndex downloads, verifies (when the client has keys) and parses the index of one repository.

func (*Client) IndexURL

func (c *Client) IndexURL(repo Repo) string

IndexURL returns the URL of repo's index for the client's architecture.

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

func FilesFromDir(dir string) ([]File, error)

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.

func MemFile

func MemFile(name string, mode fs.FileMode, data []byte) File

MemFile returns a regular file with the given content, owned by root and stamped with the epoch. mode holds the permission bits and may add setuid, setgid or sticky.

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 NewIndex

func NewIndex() *Index

NewIndex returns an empty Index.

func (*Index) Add

func (idx *Index) Add(repo Repo, indexArch string, pkgs []Package)

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.

func (*Index) Stats

func (idx *Index) Stats() (packages, capabilities int)

Stats returns the number of packages and of provided capabilities.

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 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

func LoadKeyring(dir string) (*Keyring, error)

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.

func NewKeyring

func NewKeyring() *Keyring

NewKeyring returns an empty Keyring.

func (*Keyring) Add

func (k *Keyring) Add(name string, key *rsa.PublicKey) error

Add trusts key under name, which must match ^[A-Za-z0-9._@+-]+\.rsa\.pub$. A later Add of the same name replaces the key.

func (*Keyring) Len

func (k *Keyring) Len() int

Len returns the number of trusted keys.

func (*Keyring) Lookup

func (k *Keyring) Lookup(name string) (*rsa.PublicKey, bool)

Lookup returns the key trusted under name.

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

func ParseIndex(r io.Reader) ([]Package, error)

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

func ParsePackage(r io.ReaderAt, size int64) (*Package, error)

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

func VerifyPackage(ra io.ReaderAt, size int64, opts VerifyOptions) (*Package, error)

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

func WritePackage(w io.Writer, spec *Spec, opts WriteOptions) (*Package, error)

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.

func (*Package) FileName

func (p *Package) FileName() string

FileName returns the name the package is served under: name-version.apk.

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

func ParseRepositories(r io.Reader) ([]Repo, error)

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 RepoError

type RepoError struct {
	Repo Repo
	Err  error
}

RepoError is the failure to load one repository's index.

func (*RepoError) Error

func (e *RepoError) Error() string

func (*RepoError) Unwrap

func (e *RepoError) Unwrap() error

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

func (s *Signer) EntryName() string

EntryName returns the name of the signature tar entry: .SIGN.RSA.<KeyName> or .SIGN.RSA256.<KeyName>.

func (*Signer) Fingerprint

func (s *Signer) Fingerprint() string

Fingerprint returns the hex SHA-256 of the DER SubjectPublicKeyInfo.

func (*Signer) KeyName

func (s *Signer) KeyName() string

KeyName returns the name of the public key, as given to NewSigner.

func (*Signer) PublicKey

func (s *Signer) PublicKey() *rsa.PublicKey

PublicKey returns the public half of the signing key.

func (*Signer) PublicKeyPEM

func (s *Signer) PublicKeyPEM() ([]byte, error)

PublicKeyPEM returns the public key as a "PUBLIC KEY" (SubjectPublicKeyInfo) PEM block: what apk keeps in its keys directory.

func (*Signer) Sign

func (s *Signer) Sign(data []byte) ([]byte, error)

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 Spec

type Spec struct {
	Info    Info
	Scripts Scripts
	Files   []File
}

Spec is everything a package consists of.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL