search

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0 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.

Documentation

Index

Constants

View Source
const (
	AlgorithmSHA256 = "sha256"
	AlgorithmSHA1   = "sha1"
	AlgorithmMD5    = "md5"
)

Checksum algorithms, named by the length of their hex digests.

View Source
const MaxSearchResults = 10000

MaxSearchResults is the largest match count a search may have; broader queries are rejected so cost stays bounded.

Variables

View Source
var (
	ErrUnknownProjectRole    = errors.New("project_role must be viewer, developer, maintainer or owner")
	ErrTooManyProjectFilters = errors.New("too many project or project_role filters")
)

Errors of CheckProjectFilters.

View Source
var (
	ErrInvalidPropFilter = errors.New(
		"prop must be KEY=VALUE: a key of 1 to 255 bytes without control characters, a value of at most 4096 bytes",
	)
	ErrTooManyPropFilters = fmt.Errorf("at most %d prop filters", maxPropFilters)
)

Errors of CheckPropFilters.

View Source
var ErrChecksumTooBroad = errors.New("checksum matches too many files")

ErrChecksumTooBroad is returned when a digest matches more than maxChecksumResults files.

Functions

func CheckProjectFilters added in v0.23.0

func CheckProjectFilters(f SearchFilter) error

CheckProjectFilters applies the rules GET /api/v1/search answers with 400 invalid_filter to the project filters, so the MCP search tool enforces the same ones: every project_role is a project role, and there are at most maxFilterValues project and project_role values.

func CheckPropFilters added in v0.24.0

func CheckPropFilters(f SearchFilter) error

CheckPropFilters applies the rules GET /api/v1/search answers with 400 invalid_filter to the property filters, and that the MCP search tool shares: at most maxPropFilters, each KEY=VALUE within the limits the property API stores (valid UTF-8; no control characters in the key, no NUL in the value).

func ParseChecksum added in v0.11.0

func ParseChecksum(value string) (string, string, bool)

ParseChecksum normalises a checksum query value (lowercase hex of a SHA-256, SHA-1 or MD5 digest) and names its algorithm; ok is false for anything else.

func TooBroadMessage added in v0.22.0

func TooBroadMessage(filter SearchFilter, usesProjects bool) string

TooBroadMessage is the error text for a query that matches more than MaxSearchResults packages, naming the filters that would narrow it (see narrowingFilters for usesProjects).

Types

type AuthCache added in v0.7.0

type AuthCache interface {
	// AuthCacheTTL is the entry lifetime; 0 disables caching.
	AuthCacheTTL() time.Duration
	// AuthCacheGeneration changes on every write that invalidates the auth cache.
	AuthCacheGeneration() uint64
}

AuthCache is the invalidation signal of the auth cache (DB_AUTH_CACHE_TTL_MS) that the readable-repository cache follows; *database.PostgresDB implements it.

type ChecksumResult added in v0.11.0

type ChecksumResult struct {
	Repository string `json:"repository"`
	Format     string `json:"format"`
	Name       string `json:"name"`
	Version    string `json:"version"`
	// Filename is the file within the package, "" for docker.
	Filename  string `json:"filename"`
	Checksum  string `json:"checksum"`
	Algorithm string `json:"algorithm"`
}

ChecksumResult is a file whose stored checksum equals the one searched for.

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

func NewExecutor

func NewExecutor(db *sql.DB) *Executor

func (*Executor) CountResults

func (e *Executor) CountResults(ctx context.Context, filter SearchFilter, readableRepos map[uuid.UUID]struct{}) (int64, error)

CountResults returns how many rows the filter matches (capped at MaxSearchResults+1), scoped to the caller's readable repositories. An empty readableRepos set (no permission on anything) always yields 0 — it must never fall back to counting all rows. SearchPage already returns the count with its page; this stands alone for the one case that cannot (a page past the end).

func (*Executor) Search

func (e *Executor) Search(
	ctx context.Context,
	filter SearchFilter,
	limit, offset int,
	readableRepos map[uuid.UUID]struct{},
) ([]SearchResult, error)

Search runs the filter scoped to readableRepos. Repo scoping is enforced twice: at the SQL level (repository_id = ANY($n)) and again in Go after scanning, so a caller with no readable repositories always gets an empty result set even if the SQL-level filter were ever bypassed or misapplied.

The query is staged: the page (best match first, then newest, id as final tiebreak so paging is stable; see relevanceExpr) is selected from the narrow union, and only those rows are joined to repositories (name) and blobs (sha256, size).

func (*Executor) SearchChecksum added in v0.11.0

func (e *Executor) SearchChecksum(
	ctx context.Context,
	digest, algorithm string,
	limit, offset int,
	readableRepos map[uuid.UUID]struct{},
) ([]ChecksumResult, int, error)

SearchChecksum finds the files whose stored checksum is digest (see ParseChecksum), in the readableRepos only (scoped in SQL: an empty set always yields nothing), ordered by repository, name, version and file name. It returns the page at offset and the number of matches, or ErrChecksumTooBroad.

A SHA-256 matches through the blob store, so it finds every file stored under that content, whichever format holds it. A SHA-1 or MD5 only matches the files that record one in package_files.checksums (the sha1, shasum and md5 keys, each backed by a partial expression index): the blob store keeps only SHA-256. Other digests of that column (sha512, integrity) have no index in the baseline and are not searchable.

func (*Executor) SearchPage added in v0.6.0

func (e *Executor) SearchPage(
	ctx context.Context,
	filter SearchFilter,
	opts PageOptions,
	limit, offset int,
	readableRepos map[uuid.UUID]struct{},
) ([]SearchResult, int64, error)

SearchPage is Search plus the number of matches, from one scan of the union. The matches are read once, capped at MaxSearchResults+1 rows (a total above MaxSearchResults is only ever used to reject the query), and both the page and the count come from that set; a count query beside a page query would scan the union twice. When the total exceeds MaxSearchResults the returned page is an arbitrary slice of the capped set and must be discarded by the caller. A page past the last match carries no row to read the total from, so that one case asks for it separately. The page is ranked only while the total is within the cap.

func (*Executor) SearchRepositories added in v0.4.0

func (e *Executor) SearchRepositories(
	ctx context.Context,
	filter SearchFilter,
	limit, offset int,
	readableRepos map[uuid.UUID]struct{},
) ([]RepositoryResult, error)

SearchRepositories returns the repositories themselves whose name matches the filter (case-insensitive substring, so "ui-kit" finds "ui-kit", "my-ui-kit-lib" and "ui-kit-docs"), best match first (exact name, prefix, substring; see relevanceExpr), then by name. The package-oriented terms of the filter apply to repositories as follows: name:/free text match the repository name, format: matches the repository format, repo: the repository name exactly. sha256:, flagged and prop identify artifacts, never a repository, so they yield no repositories. Like Search, the result is scoped to readableRepos in SQL and again in Go.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(db *sql.DB, evaluator *auth.Evaluator, log *logger.Logger, opts ...Option) *Handler

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Option added in v0.7.0

type Option func(*Handler)

Option customizes a Handler.

func WithAuthCache added in v0.7.0

func WithAuthCache(src AuthCache) Option

WithAuthCache caches each principal's readable-repository set for the auth cache's TTL, dropping it whenever the auth cache is invalidated (see readableCache). Without it every request resolves the set afresh.

type PageOptions added in v0.7.0

type PageOptions struct {
	// GroupByPackage returns one row per package (repository, format, name):
	// its latest version. Offset and total then count packages. A match set
	// above MaxSearchResults rows is still reported as too broad: the returned
	// total is then the capped row count, not a package count.
	GroupByPackage bool
}

PageOptions shapes the page SearchPage returns.

type ProjectScope added in v0.23.0

type ProjectScope struct {
	// contains filtered or unexported fields
}

ProjectScope applies the project: and project_role: filters of a search for the caller of the request context. The HTTP search and the MCP search tool share it.

func NewProjectScope added in v0.23.0

func NewProjectScope(db *sql.DB, evaluator *auth.Evaluator) *ProjectScope

NewProjectScope returns a ProjectScope that reads repositories from db and the caller's project roles through evaluator.

func (*ProjectScope) NarrowToProjects added in v0.23.0

func (s *ProjectScope) NarrowToProjects(
	ctx context.Context,
	readable map[uuid.UUID]struct{},
	filter SearchFilter,
) (map[uuid.UUID]struct{}, bool, error)

NarrowToProjects returns the repositories of readable that the project filters keep, and whether the caller holds a project role (UsesProjects), which it has resolved anyway, so a too-broad answer need not resolve it again. It never adds a repository: a repository stays only when the caller can already read it, its project matches filter.Projects (name or slug) when that is set, and the caller's effective role there (see callerRoles) is one of filter.ProjectRoles when that is set.

So project_role=viewer finds nothing for an admin, deliberately. A caller without a role in a project keeps none of its repositories, even ones readable through a permission target or anonymous access, which makes a project that does not exist and one the caller has no role in give the same empty answer. The system project grants nothing and never matches.

readable may be shared with other requests (the HTTP handler caches it), so it is never modified; the result is a new map.

func (*ProjectScope) UsesProjects added in v0.23.0

func (s *ProjectScope) UsesProjects(ctx context.Context) (bool, error)

UsesProjects reports whether a project filter can match anything for the caller: whether it holds a role in some project. Only then is project:<project> worth suggesting.

type RepositoryResult added in v0.4.0

type RepositoryResult struct {
	Name        string `json:"name"`
	Format      string `json:"format"`
	Description string `json:"description"`
}

RepositoryResult is a repository whose own name matched the query (as opposed to SearchResult, which is a package/artifact inside a repository).

type SearchFilter

type SearchFilter struct {
	FreeText     string
	Name         string
	Formats      []string
	Repos        []string
	SHA256Prefix string
	// Flagged keeps the packages with a critical or high vulnerability, a secret
	// finding or a quarantined scan result (database.FlaggedArtifactPredicate).
	Flagged bool
	// Projects keeps the repositories of these projects (name or slug), and
	// ProjectRoles those of the projects where the caller's effective role is one
	// of these. Both only narrow the readable set; see ProjectScope.NarrowToProjects.
	Projects     []string
	ProjectRoles []string
	// Props keeps the artifacts carrying every one of these properties, each given
	// as KEY=VALUE (exact match); see CheckPropFilters and whereBuilder.addPropByID and addPropExists.
	Props []string
	// contains filtered or unexported fields
}

func ParseQuery

func ParseQuery(q string) SearchFilter

func (SearchFilter) ProjectScoped added in v0.23.0

func (f SearchFilter) ProjectScoped() bool

ProjectScoped reports whether a project filter applies.

type SearchResult

type SearchResult struct {
	Repository string            `json:"repository"`
	Format     string            `json:"format"`
	Name       string            `json:"name"`
	Version    string            `json:"version"`
	Path       string            `json:"path"`
	SHA256     string            `json:"sha256"`
	Size       int64             `json:"size"`
	CreatedAt  time.Time         `json:"created_at"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	// VersionCount is the number of matching versions of the package; only set
	// by a group=package search.
	VersionCount int `json:"version_count,omitempty"`
}

type Searcher

type Searcher interface {
	// SearchPage returns one page of results and the number of matches (capped
	// at MaxSearchResults+1) from a single scan.
	SearchPage(
		ctx context.Context,
		filter SearchFilter,
		opts PageOptions,
		limit, offset int,
		readableRepos map[uuid.UUID]struct{},
	) ([]SearchResult, int64, error)
	SearchRepositories(
		ctx context.Context,
		filter SearchFilter,
		limit, offset int,
		readableRepos map[uuid.UUID]struct{},
	) ([]RepositoryResult, error)
	// SearchChecksum returns the files whose stored checksum equals digest (see
	// ParseChecksum), or ErrChecksumTooBroad.
	SearchChecksum(
		ctx context.Context,
		digest, algorithm string,
		limit, offset int,
		readableRepos map[uuid.UUID]struct{},
	) ([]ChecksumResult, int, error)
}

type TooBroadBody added in v0.15.0

type TooBroadBody struct {
	Error string `json:"error"`
	Code  string `json:"code"`
	// MaxResults is the largest match count a search answers.
	MaxResults int `json:"max_results"`
	// NarrowBy lists the filters not yet in the query, as the q: tokens or
	// parameters that apply them.
	NarrowBy []string `json:"narrow_by"`
}

TooBroadBody is the 400 answer of a query that matches more than MaxSearchResults packages. It is the {error, code} envelope of httpx plus what the caller can do about it: the cap, and the filters the query does not use yet, each a way to narrow the match set.

Jump to

Keyboard shortcuts

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