server

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: GPL-3.0 Imports: 64 Imported by: 0

Documentation

Overview

Package server implements the proxy HTTP server.

Package server provides the HTTP server and router for the proxy.

The server mounts protocol handlers at their respective paths:

  • /npm/* - npm registry protocol
  • /cargo/* - Cargo registry protocol (sparse index)
  • /gem/* - RubyGems registry protocol
  • /go/* - Go module proxy protocol
  • /hex/* - Hex.pm registry protocol
  • /pub/* - pub.dev registry protocol
  • /pypi/* - PyPI registry protocol
  • /maven/* - Maven repository protocol
  • /gradle/* - Gradle HttpBuildCache protocol
  • /nuget/* - NuGet V3 API protocol
  • /composer/* - Composer/Packagist protocol
  • /conan/* - Conan C/C++ protocol
  • /chef/* - Chef Supermarket protocol
  • /conda/* - Conda/Anaconda protocol
  • /cran/* - CRAN (R) protocol
  • /julia/* - Julia Pkg server protocol
  • /swift/* - Swift Package Registry protocol
  • /v2/* - OCI/Docker container registry protocol
  • /apk/* - Alpine APK repository protocol
  • /arch/* - Arch Linux pacman repository protocol
  • /freebsd/* - FreeBSD pkg repository protocol
  • /debian/* - Debian/APT repository protocol
  • /rpm/* - RPM/Yum repository protocol

Additional endpoints:

  • /health - Health check endpoint
  • /stats - Cache statistics (JSON)
  • /openapi.json - OpenAPI spec (JSON)
  • /metrics - Prometheus metrics

Web UI (HTML), mounted under /ui so reverse proxies can gate it separately from the package endpoints:

  • /ui/ - Dashboard
  • /ui/analytics - Download and cache analytics
  • /ui/install - Client configuration guide
  • /ui/packages - List all cached packages
  • /ui/search - Search packages
  • /ui/package/... - Package and version detail pages
  • /ui/api/browse/... - Archive browsing (used by the UI)
  • /ui/api/compare/... - Archive diffing (used by the UI)

API endpoints for enrichment data:

  • GET /api/package/{ecosystem}/{name} - Package metadata
  • GET /api/package/{ecosystem}/{name}/{version} - Version metadata with vulns
  • GET /api/vulns/{ecosystem}/{name} - Package vulnerabilities
  • GET /api/vulns/{ecosystem}/{name}/{version} - Version vulnerabilities
  • POST /api/outdated - Check outdated packages
  • POST /api/bulk - Bulk package lookup
  • GET /api/packages - List cached packages (JSON)

Index

Constants

View Source
const (
	ErrCodeBadRequest   = "BAD_REQUEST"
	ErrCodeNotFound     = "NOT_FOUND"
	ErrCodeUnauthorized = "UNAUTHORIZED"
	ErrCodeConflict     = "CONFLICT"
	ErrCodeUpstream     = "UPSTREAM_ERROR"
	ErrCodeInternal     = "INTERNAL_ERROR"
	ErrCodeBusy         = "BUSY"

	ErrCodeUnsupportedMediaType = "UNSUPPORTED_MEDIA_TYPE"
)

Error codes returned in API error responses. These are stable identifiers that clients can match on; the message text is for humans and may change.

Variables

This section is empty.

Functions

func ConfigureDenylist added in v0.11.0

func ConfigureDenylist(cfg *config.Config, proxy *handler.Proxy) error

ConfigureDenylist sets proxy's denylist from cfg, resolving Swift source repositories through the upstream first. serve and proxy mirror call it once proxy can fetch metadata. An entry that can't be resolved is an error, so neither starts with a denylist that lets its versions through.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from context.

func NewMirrorProxy added in v0.10.0

func NewMirrorProxy(cfg *config.Config, db *database.DB, store storage.Storage, logger *slog.Logger) (*handler.Proxy, *handler.ContainerHandler)

NewMirrorProxy builds the proxy for the mirror command with the same upstream clients, SSRF guard and upstream authentication as serve, and a container handler with the same OCI routes for mirroring images. Artifact downloads have no overall time limit; the caller cancels through ctx.

func NewMirrorVersions added in v0.11.0

func NewMirrorVersions(upstream config.UpstreamConfig, client *http.Client) mirror.VersionLister

NewMirrorVersions lists versions for proxy mirror from the configured upstreams, through client, so upstream.auth and the private address rules apply as they do when serving.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware adds a sequential request ID to the context and response headers. IDs are formatted as [001], [002], etc. for easy log correlation.

func UseMirrorUpstreams added in v0.11.0

func UseMirrorUpstreams(m *mirror.Mirror, upstream config.UpstreamConfig, client *http.Client)

UseMirrorUpstreams points m at the configured upstreams: it lists versions from them, through client, and fetches Julia packages from upstream.julia.

Types

type APIHandler

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

APIHandler provides REST endpoints for package enrichment data.

func NewAPIHandler

func NewAPIHandler(svc *enrichment.Service, db DBSearcher) *APIHandler

NewAPIHandler creates a new API handler with enrichment services.

func (*APIHandler) HandleBulkLookup

func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request)

HandleBulkLookup handles POST /api/bulk @Summary Bulk package lookup by PURL @Tags api @Accept json @Produce json @Param request body BulkRequest true "PURLs" @Success 200 {object} BulkResponse @Failure 400 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /api/bulk [post]

func (*APIHandler) HandleOutdated

func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request)

HandleOutdated handles POST /api/outdated @Summary Check outdated packages @Tags api @Accept json @Produce json @Param request body OutdatedRequest true "Packages to check" @Success 200 {object} OutdatedResponse @Failure 400 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /api/outdated [post]

func (*APIHandler) HandlePackagePath

func (h *APIHandler) HandlePackagePath(w http.ResponseWriter, r *http.Request)

HandlePackagePath dispatches /api/package/{ecosystem}/* to the appropriate handler. Resolves namespaced package names (Composer vendor/name, npm @scope/name) from the path.

func (*APIHandler) HandlePackagesList

func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request)

HandlePackagesList handles GET /api/packages @Summary List cached packages @Tags api @Produce json @Param ecosystem query string false "Ecosystem" @Param sort query string false "Sort" Enums(hits,name,size,cached_at,ecosystem,vulns) @Success 200 {object} PackagesListResponse @Failure 400 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /api/packages [get]

func (*APIHandler) HandleSearch

func (h *APIHandler) HandleSearch(w http.ResponseWriter, r *http.Request)

HandleSearch handles GET /api/search @Summary Search cached packages @Tags api @Produce json @Param q query string true "Query" @Param ecosystem query string false "Ecosystem" @Success 200 {object} SearchResponse @Failure 400 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /api/search [get]

func (*APIHandler) HandleVulnsPath

func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request)

HandleVulnsPath dispatches /api/vulns/{ecosystem}/* to the vulns handler. Supports both {name} and {name}/{version} paths with namespaced package names.

type AnalyticsData added in v0.9.1

type AnalyticsData struct {
	Layout
	Totals          AnalyticsTotals
	Donut           DonutView
	EnrichmentStats EnrichmentStatsView
	Ecosystems      []EcosystemRow
	Metadata        MetadataCacheView
	Runtime         RuntimeView
	// StatsFailed records that the per-ecosystem query errored, so the page
	// can say the figures are unavailable instead of claiming an empty cache.
	StatsFailed bool
	// StatsStale is set when the query errored but a previous snapshot was
	// retained and is being shown. Without it a database that has been down
	// for an hour renders hour-old figures as current, with the failure
	// visible only in the logs.
	StatsStale bool
	// StatsAge is when the retained snapshot was read, phrased for display.
	StatsAge string
}

AnalyticsData contains data for rendering the analytics dashboard.

type AnalyticsTotals added in v0.9.1

type AnalyticsTotals struct {
	DownloadedBytes  int64
	Downloaded       string
	Downloads        string
	CacheSize        string
	CachedArtifacts  string
	Packages         string
	Versions         string
	Ecosystems       int
	ActiveEcosystems int
	// Amplification is accumulated download volume divided by the bytes
	// currently held in cache: how many times over the cache has served
	// what it stores. Empty when nothing is cached.
	Amplification string
}

AnalyticsTotals holds the headline figures across every ecosystem.

type BreakerRow added in v0.9.1

type BreakerRow struct {
	Registry string
	State    string
	Open     bool
}

BreakerRow is one upstream's circuit breaker state.

type BrowseFileInfo

type BrowseFileInfo struct {
	Path    string `json:"path"`
	Name    string `json:"name"`
	Size    int64  `json:"size"`
	IsDir   bool   `json:"is_dir"`
	ModTime string `json:"mod_time,omitempty"`
}

BrowseFileInfo contains metadata about a file in an archives.

type BrowseListResponse

type BrowseListResponse struct {
	Path  string           `json:"path"`
	Files []BrowseFileInfo `json:"files"`
}

BrowseListResponse contains the file listing for a directory in an archives.

type BrowseSourceData

type BrowseSourceData struct {
	Layout
	Ecosystem      string
	PackageName    string
	Version        string
	EscapedVersion string
}

BrowseSourceData contains data for the browse source page.

Version is the decoded version, for display. EscapedVersion is the same value escaped as a single URL path segment and is what the links and the browse API calls must use; see database.Version.EscapedVersion.

type BuildInfo added in v0.8.0

type BuildInfo struct {
	Version string
	Commit  string
}

BuildInfo identifies the running proxy binary.

type BulkRequest

type BulkRequest struct {
	PURLs []string `json:"purls"`
}

BulkRequest is the request body for bulk package lookups.

type BulkResponse

type BulkResponse struct {
	Packages map[string]*PackageResponse `json:"packages"`
}

BulkResponse contains bulk lookup results.

type CacheDeleteResponse added in v0.10.0

type CacheDeleteResponse struct {
	PURL    string   `json:"purl"`
	Deleted []string `json:"deleted"`
}

CacheDeleteResponse lists the cached files removed for a version.

type CacheLookups added in v0.10.0

type CacheLookups struct {
	Hits       string
	Misses     string
	HitRatio   string
	HasTraffic bool
}

CacheLookups is one cache's hits and misses since the process started.

type ClientRow added in v0.9.1

type ClientRow struct {
	Client   string
	Requests string
	Bytes    string
}

ClientRow is one client tool's share of requests and bytes.

type ComparePageData

type ComparePageData struct {
	Layout
	Ecosystem          string
	PackageName        string
	FromVersion        string
	ToVersion          string
	EscapedFromVersion string
	EscapedToVersion   string
}

ComparePageData contains data for the version comparison page.

FromVersion and ToVersion are decoded, for display; the Escaped variants are the path-segment form used to build the compare API URL.

type CooldownOverride added in v0.11.0

type CooldownOverride struct {
	Ecosystem   string
	Duration    string
	Unsupported bool
}

CooldownOverride is one ecosystem's cooldown. Unsupported marks an ecosystem the proxy applies no cooldown to, so the setting has no effect.

type CooldownSummary added in v0.11.0

type CooldownSummary struct {
	Enabled          bool
	Default          string
	Ecosystems       []CooldownOverride
	PackageOverrides int
	PackagePatterns  int
}

CooldownSummary describes the cooldown configuration on the dashboard. The UI has no auth, so package overrides and patterns are only counted: their names often list internal packages.

type DBSearcher

type DBSearcher interface {
	SearchPackages(query string, ecosystem string, limit int, offset int) ([]database.SearchResult, error)
	CountSearchResults(query string, ecosystem string) (int64, error)
	ListCachedPackages(ecosystem string, sortBy string, limit int, offset int) ([]database.PackageListItem, error)
	CountCachedPackages(ecosystem string) (int64, error)
}

DBSearcher defines the interface for database search operations.

type DashboardData

type DashboardData struct {
	Layout
	Stats           DashboardStats
	EnrichmentStats EnrichmentStatsView
	Cooldown        CooldownSummary
	RecentPackages  []PackageInfo
	PopularPackages []PackageInfo
}

DashboardData contains data for rendering the dashboard.

type DashboardStats

type DashboardStats struct {
	CachedArtifacts int64
	TotalSize       string
	TotalPackages   int64
	TotalVersions   int64
}

DashboardStats contains cache statistics for the dashboard.

type DonutSlice added in v0.9.1

type DonutSlice struct {
	// Index selects the fixed categorical slot. The hues themselves live in
	// the .donut-slot-N and .swatch-N rules in the analytics template, so the
	// validated palette has exactly one definition; slots are assigned here in
	// sequence and never cycled.
	Index     int
	Label     string
	Value     string
	SharePct  string
	Downloads string
	CacheSize string
	Dash      string
	Gap       string
	Offset    string
	// IsOther marks the folded tail, which has no single ecosystem behind it.
	IsOther bool
	// Members lists what was folded in, for the tooltip.
	Members string
}

DonutSlice is one arc of the ring plus its legend row.

type DonutView added in v0.9.1

type DonutView struct {
	Slices []DonutSlice
	// Size, Radius, Stroke and Center are handed to the template so the SVG
	// geometry has exactly one definition.
	Size   string
	Radius string
	Stroke string
	Center string
	// CenterValue is the accumulated download size across every ecosystem,
	// stated in the middle of the ring.
	CenterValue string
	CenterLabel string
	HasSlices   bool
}

DonutView is the whole chart: the ring, its centre figure and its legend.

type EcosystemFilter added in v0.9.1

type EcosystemFilter struct {
	Ecosystem string
	Count     int64
}

EcosystemFilter represents an ecosystem filter pill with a package count.

type EcosystemRow added in v0.9.1

type EcosystemRow struct {
	Ecosystem       string
	DownloadedBytes int64
	Downloaded      string
	Downloads       string
	CacheSize       string
	AvgArtifactSize string
	Artifacts       string
	Packages        string
	Versions        string
	// SharePct is this ecosystem's share of the accumulated download total.
	SharePct string
}

EcosystemRow is one ecosystem's row in the analytics table.

type EcosystemStatsEntry added in v0.9.1

type EcosystemStatsEntry struct {
	Ecosystem       string `json:"ecosystem"`
	DownloadedBytes int64  `json:"downloaded_bytes"`
	Downloaded      string `json:"downloaded"`
	Downloads       int64  `json:"downloads"`
	CacheSize       int64  `json:"cache_size_bytes"`
	Artifacts       int64  `json:"cached_artifacts"`
	Packages        int64  `json:"packages"`
	Versions        int64  `json:"versions"`
}

EcosystemStatsEntry is one ecosystem's slice of the cache statistics.

type EnrichmentResponse

type EnrichmentResponse struct {
	Package         *PackageResponse `json:"package,omitempty"`
	Version         *VersionResponse `json:"version,omitempty"`
	Vulnerabilities []VulnResponse   `json:"vulnerabilities,omitempty"`
	IsOutdated      bool             `json:"is_outdated"`
	LicenseCategory string           `json:"license_category"`
}

EnrichmentResponse contains full enrichment data.

type EnrichmentStatsView

type EnrichmentStatsView struct {
	EnrichedPackages     int64
	VulnSyncedPackages   int64
	TotalVulnerabilities int64
	CriticalVulns        int64
	HighVulns            int64
	MediumVulns          int64
	LowVulns             int64
	HasVulns             bool
}

EnrichmentStatsView contains enrichment statistics for display.

type ErrorResponse added in v0.3.2

type ErrorResponse struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ErrorResponse is the JSON body returned for API errors.

type FailureRow added in v0.10.0

type FailureRow struct {
	Age      string
	PURL     string
	Filename string
	URL      string
	Path     string
	Error    string
}

FailureRow is one recorded failure behind a failure counter.

type HealthCheck added in v0.4.0

type HealthCheck struct {
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
	Step   string `json:"step,omitempty"`
}

HealthCheck reports the status of a single subsystem check.

type HealthResponse added in v0.4.0

type HealthResponse struct {
	Status string                 `json:"status"`
	Checks map[string]HealthCheck `json:"checks"`
	// CircuitBreakers reports the state ("open" or "closed") of each upstream
	// registry's artifact-fetch circuit breaker, keyed by the host fetched from
	// or, where the fetch URL has none to read, by an opaque placeholder
	// standing in for it. It is omitted when no breaker has been created yet.
	// An open breaker fails every artifact fetch it covers without contacting
	// the upstream, but says nothing about this proxy's own health, so it does
	// not change Status.
	CircuitBreakers map[string]string `json:"circuit_breakers,omitempty"`
	// UpstreamHolds lists upstream hosts that rate limited the proxy and
	// the RFC 3339 time until which it sends them nothing. A held host
	// fails cache misses without contacting it and does not change Status.
	UpstreamHolds map[string]string `json:"upstream_holds,omitempty"`
}

HealthResponse is the JSON payload returned by /health.

type HostedAPIHandler added in v0.10.0

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

HostedAPIHandler serves /api/hosted, where operators push archives that the proxy serves in place of, or in addition to, what the upstream has.

func NewHostedAPIHandler added in v0.10.0

func NewHostedAPIHandler(proxy *handler.Proxy, maxUploadBytes int64, logger *slog.Logger) *HostedAPIHandler

NewHostedAPIHandler creates the /api/hosted handler.

func (*HostedAPIHandler) HandleDelete added in v0.10.0

func (h *HostedAPIHandler) HandleDelete(w http.ResponseWriter, r *http.Request)

HandleDelete handles DELETE /api/hosted/{ecosystem}/{name}/{version}, and DELETE /api/hosted/generic/{name}/{version}/{file} for one generic file. @Summary Delete a pushed version @Description Removes the archives pushed for name@version. If the upstream has the version, clients get the upstream archive again. For generic files, /api/hosted/generic/{name}/{version}/{file} removes only that file. @Tags hosted @Security BearerAuth @Param ecosystem path string true "Ecosystem" @Param name path string true "Package name" @Param version path string true "Version" @Success 204 @Failure 401 {object} ErrorResponse @Failure 404 {object} ErrorResponse @Router /api/hosted/{ecosystem}/{name}/{version} [delete]

func (*HostedAPIHandler) HandleList added in v0.10.0

func (h *HostedAPIHandler) HandleList(w http.ResponseWriter, r *http.Request)

HandleList handles GET /api/hosted/{ecosystem}/{name} @Summary List pushed package archives @Tags hosted @Produce json @Param ecosystem path string true "Ecosystem" @Param name path string true "Package name" @Success 200 {object} HostedListResponse @Failure 400 {object} ErrorResponse @Router /api/hosted/{ecosystem}/{name} [get]

func (*HostedAPIHandler) HandlePush added in v0.10.0

func (h *HostedAPIHandler) HandlePush(w http.ResponseWriter, r *http.Request)

HandlePush handles PUT /api/hosted/{ecosystem}/{name}/{version}, and PUT /api/hosted/generic/{name}/{version}/{file} for generic files. @Summary Push a package archive @Description Stores the request body as the archive for name@version. It is served in place of the upstream archive with the same version and is never evicted. Generic files are pushed to /api/hosted/generic/{name}/{version}/{file} and served at /generic/hosted/{name}/{version}/{file}. A file that was already pushed is refused with 409; delete it first to push it again. @Tags hosted @Accept octet-stream @Produce json @Security BearerAuth @Param ecosystem path string true "Ecosystem (npm, composer or generic)" @Param name path string true "Package name, including an npm scope or the Composer vendor" @Param version path string true "Version" @Param sha256 query string false "Expected sha256 of the body, hex-encoded; a mismatch is refused" @Success 201 {object} HostedPushResponse @Failure 400 {object} ErrorResponse @Failure 401 {object} ErrorResponse @Failure 403 {object} ErrorResponse @Failure 409 {object} ErrorResponse @Failure 413 {object} ErrorResponse @Router /api/hosted/{ecosystem}/{name}/{version} [put]

type HostedListResponse added in v0.10.0

type HostedListResponse struct {
	Ecosystem string                   `json:"ecosystem"`
	Name      string                   `json:"name"`
	Artifacts []handler.HostedArtifact `json:"artifacts"`
}

HostedListResponse lists the archives pushed for a package.

type HostedPushResponse added in v0.10.0

type HostedPushResponse struct {
	Ecosystem string `json:"ecosystem"`
	Name      string `json:"name"`
	handler.HostedArtifact
}

HostedPushResponse describes a pushed archive.

type LabelledCount added in v0.9.1

type LabelledCount struct {
	Label string
	Count string
	// Bad marks a failure row, which the template tints.
	Bad bool
	// Recent lists the latest failures behind the count, newest first.
	Recent []FailureRow
	// contains filtered or unexported fields
}

LabelledCount is a single counter series rendered as a row.

type LabelledStat added in v0.9.1

type LabelledStat struct {
	Label string
	Count string
	Mean  string
}

LabelledStat is a histogram series rendered as a row: how many observations, and their mean.

type Layout added in v0.5.0

type Layout struct {
	BuildInfo     BuildInfo
	UIBaseURL     string
	CanonicalPath string
	// CacheDelete shows the controls for deleting cached artifacts.
	CacheDelete bool
}

Layout carries shared fields consumed by the base template. It is embedded in every page data struct so templates can access canonical URL and build information alongside the page's own fields.

type MetadataCacheRow added in v0.10.0

type MetadataCacheRow struct {
	Ecosystem string
	Entries   string
	Size      string
	SharePct  string
}

MetadataCacheRow is one ecosystem's share of the metadata cache.

type MetadataCacheView added in v0.10.0

type MetadataCacheView struct {
	// Enabled reports whether cache_metadata is on. Entries can remain from
	// an earlier run with it on, so both are shown independently.
	Enabled bool
	// Failed records that the query errored, so the card can say so rather
	// than claim the cache is empty.
	Failed  bool
	Entries string
	Size    string
	Rows    []MetadataCacheRow
}

MetadataCacheView summarises the metadata cache, which is stored separately from artifacts and so appears in none of the artifact figures.

type MirrorAPIHandler

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

MirrorAPIHandler handles mirror API requests.

func NewMirrorAPIHandler

func NewMirrorAPIHandler(jobs *mirror.JobStore) *MirrorAPIHandler

NewMirrorAPIHandler creates a new mirror API handler.

func (*MirrorAPIHandler) HandleCancel

func (h *MirrorAPIHandler) HandleCancel(w http.ResponseWriter, r *http.Request)

HandleCancel cancels a running mirror job.

func (*MirrorAPIHandler) HandleCreate

func (h *MirrorAPIHandler) HandleCreate(w http.ResponseWriter, r *http.Request)

HandleCreate starts a new mirror job.

func (*MirrorAPIHandler) HandleGet

func (h *MirrorAPIHandler) HandleGet(w http.ResponseWriter, r *http.Request)

HandleGet returns the status of a mirror job.

type OutdatedPackage

type OutdatedPackage struct {
	Ecosystem string `json:"ecosystem"`
	Name      string `json:"name"`
	Version   string `json:"version"`
}

OutdatedPackage represents a package to check for outdatedness.

type OutdatedRequest

type OutdatedRequest struct {
	Packages []OutdatedPackage `json:"packages"`
}

OutdatedRequest is the request body for checking outdated packages.

type OutdatedResponse

type OutdatedResponse struct {
	Results []OutdatedResult `json:"results"`
}

OutdatedResponse contains outdated check results.

type OutdatedResult

type OutdatedResult struct {
	Ecosystem     string `json:"ecosystem"`
	Name          string `json:"name"`
	Version       string `json:"version"`
	LatestVersion string `json:"latest_version,omitempty"`
	IsOutdated    bool   `json:"is_outdated"`
}

OutdatedResult contains the outdated status for a package.

type PackageCooldown added in v0.11.0

type PackageCooldown struct {
	Duration string
	Rule     string
}

PackageCooldown is the cooldown that applies to one package, and the kind of rule it comes from.

type PackageInfo

type PackageInfo struct {
	Ecosystem       string
	Name            string
	Version         string
	Size            string
	Hits            int64
	CachedAt        string
	License         string
	LicenseCategory string
	VulnCount       int64
	LatestVersion   string
	IsOutdated      bool
}

PackageInfo contains information about a cached package.

type PackageListResult

type PackageListResult struct {
	Ecosystem       string `json:"ecosystem"`
	Name            string `json:"name"`
	LatestVersion   string `json:"latest_version,omitempty"`
	License         string `json:"license,omitempty"`
	LicenseCategory string `json:"license_category,omitempty"`
	Hits            int64  `json:"hits"`
	Size            int64  `json:"size"`
	CachedAt        string `json:"cached_at,omitempty"`
	VulnCount       int64  `json:"vuln_count"`
}

PackageListResult represents a single package in the list.

type PackageResponse

type PackageResponse struct {
	Ecosystem       string `json:"ecosystem"`
	Name            string `json:"name"`
	LatestVersion   string `json:"latest_version,omitempty"`
	License         string `json:"license,omitempty"`
	LicenseCategory string `json:"license_category,omitempty"`
	Description     string `json:"description,omitempty"`
	Homepage        string `json:"homepage,omitempty"`
	Repository      string `json:"repository,omitempty"`
	RegistryURL     string `json:"registry_url,omitempty"`
}

PackageResponse contains enriched package metadata.

type PackageShowData

type PackageShowData struct {
	Layout
	Package         *database.Package
	Versions        []database.Version
	Vulnerabilities []database.Vulnerability
	LicenseCategory string
	// Cooldown is nil with cooldown off.
	Cooldown *PackageCooldown
}

PackageShowData contains data for rendering the package show page.

type PackagesListPageData

type PackagesListPageData struct {
	Layout
	Ecosystem        string
	SortBy           string
	Results          []SearchResultItem
	Count            int
	TotalPackages    int64
	EcosystemFilters []EcosystemFilter
	Page             int
	PerPage          int
	TotalPages       int
}

PackagesListPageData contains data for rendering the packages list page.

type PackagesListResponse

type PackagesListResponse struct {
	Results   []PackageListResult `json:"results"`
	Count     int                 `json:"count"`
	Total     int64               `json:"total"`
	Ecosystem string              `json:"ecosystem,omitempty"`
	SortBy    string              `json:"sort_by"`
	Page      int                 `json:"page"`
	PerPage   int                 `json:"per_page"`
}

PackagesListResponse contains a list of cached packages.

type RegistryConfig

type RegistryConfig struct {
	ID           string
	Name         string
	Language     string
	Endpoint     string
	Instructions template.HTML
}

RegistryConfig contains configuration instructions for a package registry.

type RuntimeView added in v0.9.1

type RuntimeView struct {
	Available bool

	Requests       string
	ActiveRequests string
	RequestMean    string
	StatusClasses  []LabelledCount
	// Artifact and metadata lookups are counted apart: they are separate
	// caches. Only artifacts feed the database figures above.
	ArtifactCache  CacheLookups
	MetadataCache  CacheLookups
	MetadataServed string

	UpstreamFetches   string
	UpstreamFetchMean string
	UpstreamErrors    []LabelledCount

	StorageOps        []LabelledStat
	StorageErrors     []LabelledCount
	IntegrityFailures []LabelledCount
	ProbeFailures     []LabelledCount
	Evictions         []LabelledCount
	MetadataEvictions []LabelledCount

	Breakers     []BreakerRow
	BreakerTrips []LabelledCount

	Scans        []LabelledStat
	ScansBlocked []LabelledCount
	ScanErrors   []LabelledCount
	ScanningOn   bool

	ResponseBytes string
	Clients       []ClientRow
	Sources       []SourceRow
	SourceCount   int
	TrustsForward bool
	// SourcesOn gates the caller table. The page is unauthenticated, so the
	// addresses behind it are published only when asked for.
	SourcesOn bool
	// FailureDetailsOn gates the recent failures listed under each failure
	// row, for the same reason as SourcesOn.
	FailureDetailsOn bool
	// HasFailures is set when any failure counter has fired, which is when the
	// note about turning failure details on is worth showing.
	HasFailures bool
}

RuntimeView holds the process-lifetime figures read out of the Prometheus registry. Unlike the cache figures, which are computed from the database and survive a restart, everything here starts at zero when the proxy starts.

type SearchPackageResult

type SearchPackageResult struct {
	Ecosystem     string `json:"ecosystem"`
	Name          string `json:"name"`
	LatestVersion string `json:"latest_version,omitempty"`
	License       string `json:"license,omitempty"`
	Hits          int64  `json:"hits"`
	Size          int64  `json:"size"`
	CachedAt      string `json:"cached_at,omitempty"`
}

SearchPackageResult represents a single search result.

type SearchPageData

type SearchPageData struct {
	Layout
	Query      string
	Ecosystem  string
	Results    []SearchResultItem
	Count      int
	Page       int
	PerPage    int
	TotalPages int
}

SearchPageData contains data for rendering the search results page.

type SearchResponse

type SearchResponse struct {
	Results []SearchPackageResult `json:"results"`
	Query   string                `json:"query"`
	Count   int                   `json:"count"`
}

SearchResponse contains search results.

type SearchResultItem

type SearchResultItem struct {
	Ecosystem       string
	Name            string
	LatestVersion   string
	License         string
	LicenseCategory string
	Hits            int64
	Size            int64
	SizeFormatted   string
	CachedAt        string
	VulnCount       int64
}

SearchResultItem represents a single search result for display.

type Server

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

Server is the main proxy server.

func New

func New(cfg *config.Config, logger *slog.Logger, buildInfo BuildInfo) (*Server, error)

New creates a new Server with the given configuration.

func (*Server) LoggerMiddleware

func (s *Server) LoggerMiddleware(next http.Handler) http.Handler

LoggerMiddleware logs HTTP requests with request ID correlation.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

func (*Server) Start

func (s *Server) Start(listeners ...net.Listener) error

Start starts the HTTP server.

type SourceRow added in v0.9.1

type SourceRow struct {
	Addr     string
	Client   string
	Requests string
	Bytes    string
	LastSeen string
	// IsOverflow marks the row that stands for every caller past the limit.
	IsOverflow bool
}

SourceRow is one caller's row on the analytics page.

type StatsResponse

type StatsResponse struct {
	CachedArtifacts int64  `json:"cached_artifacts"`
	TotalSize       int64  `json:"total_size_bytes"`
	TotalSizeHuman  string `json:"total_size"`
	StorageURL      string `json:"storage_url"`
	DatabasePath    string `json:"database_path"`
	// DownloadedBytes is the accumulated download volume across every
	// ecosystem: cache hits multiplied by the artifact size they served.
	DownloadedBytes      int64                 `json:"downloaded_bytes"`
	DownloadedBytesHuman string                `json:"downloaded"`
	Downloads            int64                 `json:"downloads"`
	Ecosystems           []EcosystemStatsEntry `json:"ecosystems"`
	// StatsUnavailable distinguishes a proxy that has served nothing from one
	// whose aggregation failed with no snapshot to fall back on. Without it
	// both report zeros and an empty array.
	StatsUnavailable bool `json:"stats_unavailable,omitempty"`
}

StatsResponse contains cache statistics.

type Templates

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

Templates holds lazily-parsed templates for each page.

func (*Templates) Render

func (t *Templates) Render(w http.ResponseWriter, pageName string, data any) error

Render renders a page template with the given data.

type VersionResponse

type VersionResponse struct {
	Ecosystem   string `json:"ecosystem"`
	Name        string `json:"name"`
	Version     string `json:"version"`
	License     string `json:"license,omitempty"`
	PublishedAt string `json:"published_at,omitempty"`
	Integrity   string `json:"integrity,omitempty"`
	Yanked      bool   `json:"yanked"`
	IsOutdated  bool   `json:"is_outdated"`
}

VersionResponse contains enriched version metadata.

type VersionShowData

type VersionShowData struct {
	Layout
	Package           *database.Package
	Version           *database.Version
	Artifacts         []database.Artifact
	Vulnerabilities   []database.Vulnerability
	IsOutdated        bool
	LicenseCategory   string
	HasCachedArtifact bool
	// HasDeletableArtifact is true when a stored artifact was fetched from
	// the upstream rather than pushed.
	HasDeletableArtifact bool
}

VersionShowData contains data for rendering the version show page.

type VulnResponse

type VulnResponse struct {
	ID           string   `json:"id"`
	Summary      string   `json:"summary,omitempty"`
	Severity     string   `json:"severity,omitempty"`
	CVSSScore    float64  `json:"cvss_score,omitempty"`
	FixedVersion string   `json:"fixed_version,omitempty"`
	References   []string `json:"references,omitempty"`
}

VulnResponse contains vulnerability information.

type VulnsResponse

type VulnsResponse struct {
	Ecosystem       string         `json:"ecosystem"`
	Name            string         `json:"name"`
	Version         string         `json:"version,omitempty"`
	Vulnerabilities []VulnResponse `json:"vulnerabilities"`
	Count           int            `json:"count"`
}

VulnsResponse contains vulnerabilities for a package/version.

Jump to

Keyboard shortcuts

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