rulesets

package
v0.21.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 26 Imported by: ? 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

Overview

Package rulesets downloads leased rulesets from the SCANOSS rulesets API (/v3/<domain>/rulesets), verifies them, caches them encrypted at rest and unpacks them into a private run directory.

c, err := rulesets.New(rulesets.Options{Domain: "ai", APIURL: url, APIKey: key})
rs, err := c.Fetch(ctx, "ai", "latest")
if errors.Is(err, rulesets.ErrUnavailable) { os.Exit(rulesets.ExitCode) }
defer rs.Close()
// rules are under rs.Dir

Index

Examples

Constants

View Source
const (
	TTLLatest     = 24 * time.Hour
	TTLPinned     = 7 * 24 * time.Hour
	MaxStale      = 30 * 24 * time.Hour
	MaxStaleLimit = 90 * 24 * time.Hour
)

Cache freshness: how long a cached ruleset is used without asking the API, and how old it may be when the API is unreachable (Options.MaxStale, by default MaxStale and at most MaxStaleLimit), as crypto-finder.

View Source
const (
	ReleaseFormat  = "scanoss-ruleset-release/1"
	LeaseFormat    = "scanoss-ruleset-lease/1"
	LeaseHeader    = "SCANOSS-Ruleset-Lease"
	ChecksumHeader = "X-Checksum-SHA256"
)

Wire formats and headers of the rulesets API.

View Source
const DefaultAPIURL = "https://api.scanoss.com"

DefaultAPIURL is used when Options.APIURL is empty.

View Source
const ExitCode = 3

ExitCode is the CLI exit code for "rules unavailable": any error that matches ErrUnavailable.

View Source
const PubKeysEnv = "SCANOSS_RULESET_PUBKEYS"

PubKeysEnv adds trusted lease signing keys, or replaces built-in ones of the same id: "id:base64pub[,id:base64pub...]".

Variables

View Source
var (
	// ErrUnavailable is matched by every error Fetch, List and Release return,
	// so a command maps it to ExitCode with one errors.Is.
	ErrUnavailable = errors.New("rules unavailable")
	// ErrUpgradeRequired is the API refusing this client version (HTTP 410 or 426).
	ErrUpgradeRequired = errors.New("upgrade_required: the rulesets API no longer serves this client version, upgrade scanoss-cli")
	// ErrChecksum is a bundle whose SHA-256 differs from X-Checksum-SHA256 or the lease.
	ErrChecksum = errors.New("ruleset bundle checksum mismatch")
	// ErrSignature is a lease whose Ed25519 signature does not verify.
	ErrSignature = errors.New("ruleset lease signature does not verify")
	// ErrUnknownKey is a lease signed by a key that is not trusted.
	ErrUnknownKey = errors.New("ruleset lease signed by an untrusted key")
	// ErrLeaseExpired is a lease past its expires_at.
	ErrLeaseExpired = errors.New("ruleset lease has expired")
	// ErrBadLease is a lease that is malformed or does not describe the bundle requested.
	ErrBadLease = errors.New("invalid ruleset lease")
	// ErrNoTrustedKeys means neither the built-in list nor PubKeysEnv holds a key.
	ErrNoTrustedKeys = errors.New("no trusted ruleset signing keys (set " + PubKeysEnv + ")")
)

Functions

func DefaultCacheDir

func DefaultCacheDir() (string, error)

DefaultCacheDir is ~/.scanoss/scanoss-cli/cache/rulesets.

func ParsePublicKeys

func ParsePublicKeys(s string) (map[string]ed25519.PublicKey, error)

ParsePublicKeys parses "id:base64pub[,id:base64pub...]"; empty yields none.

func ParseRef

func ParseRef(ref string) (name, version string, err error)

ParseRef splits "name@version"; a missing version is "latest".

func TrustedKeys

func TrustedKeys() (map[string]ed25519.PublicKey, error)

TrustedKeys returns the built-in keys plus those in PubKeysEnv.

Types

type Client

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

Client talks to one rulesets domain of one API.

func New

func New(opts Options) (*Client, error)

New validates opts and returns a Client.

func (*Client) Fetch

func (c *Client) Fetch(ctx context.Context, name, version string) (*Ruleset, error)

Fetch returns name@version ("latest" or a semver version), from the cache when it is fresh, otherwise from the API, falling back to a cached copy up to Options.MaxStale old when the API is unreachable. Every error matches ErrUnavailable.

Example

A command resolves --ruleset name@version against the API it already talks to, and exits with rulesets.ExitCode when the rules are unavailable.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/scanoss/scanoss.go/pkg/rulesets"
	"github.com/scanoss/scanoss.go/pkg/scanoss"
)

func main() {
	cfg := scanoss.Config{APIURL: "https://api.scanoss.com", APIKey: os.Getenv("SCANOSS_API_KEY")}
	hc, err := scanoss.NewHTTPClient(cfg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	name, version, err := rulesets.ParseRef("ai@latest")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	client, err := rulesets.New(rulesets.Options{
		Domain: "ai", APIURL: cfg.APIURL, APIKey: cfg.APIKey, HTTPClient: hc,
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	rs, err := client.Fetch(context.Background(), name, version)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		if errors.Is(err, rulesets.ErrUnavailable) {
			os.Exit(rulesets.ExitCode)
		}
		os.Exit(1)
	}
	defer rs.Close()
	fmt.Printf("using %s@%s from %s (%s)\n", rs.Name, rs.Version, rs.Dir, rs.Source)
}

func (*Client) List

func (c *Client) List(ctx context.Context) ([]Summary, error)

List returns the rulesets the API serves for the domain.

func (*Client) Release

func (c *Client) Release(ctx context.Context, name, version string) (Release, error)

Release returns the release metadata of name@version ("latest" resolves).

type Lease

type Lease struct {
	Format        string    `json:"format"`
	Name          string    `json:"name"`
	Domain        string    `json:"domain"`
	Version       string    `json:"version"`
	PayloadSHA256 string    `json:"payload_sha256"`
	BundleSHA256  string    `json:"bundle_sha256"`
	KeyRef        string    `json:"key_ref,omitempty"`
	Tenant        string    `json:"tenant,omitempty"`
	IssuedAt      time.Time `json:"issued_at"`
	ExpiresAt     time.Time `json:"expires_at"`
	SigningKeyID  string    `json:"signing_key_id"`
}

Lease is the signed grant that comes with a downloaded bundle.

type Options

type Options struct {
	// Domain is the API path segment the rulesets live under, e.g. "ai".
	Domain string
	// APIURL is the API base URL (default DefaultAPIURL), without /v3.
	APIURL string
	// APIKey is sent as x-api-key and x-Session, like the SCANOSS SDK does. It
	// also derives the cache encryption key.
	APIKey string
	// HTTPClient sends the requests (default: a client with a 120s timeout).
	// scanoss.NewHTTPClient builds one with the CLI's proxy and TLS settings.
	HTTPClient *http.Client
	// UserAgent is sent as User-Agent when set.
	UserAgent string
	// CacheDir is the cache root (default DefaultCacheDir()).
	CacheDir string
	// NoCache does not read the cache: the ruleset is downloaded and the cache refreshed, as
	// crypto-finder's --no-cache does.
	NoCache bool
	// MaxStale is how old a cached ruleset may be when the API is unreachable (default MaxStale,
	// at most MaxStaleLimit).
	MaxStale time.Duration
	// Strict fails when the API is unreachable instead of using an expired cached copy.
	Strict bool
	// RunDir is where run-* directories are created (default <CacheDir>/runs). Unpacked rules are
	// plaintext, so stale run-* directories under it are pruned (see runDirTTL).
	RunDir string
	// Keys are the trusted lease signing keys (default TrustedKeys()).
	Keys map[string]ed25519.PublicKey
	// Now is the clock (default time.Now).
	Now func() time.Time
}

Options configures a Client. Domain is required.

type Release

type Release struct {
	Format        string    `json:"format"`
	Name          string    `json:"name"`
	Domain        string    `json:"domain"`
	Version       string    `json:"version"`
	CreatedAt     time.Time `json:"created_at"`
	Description   string    `json:"description,omitempty"`
	PayloadSHA256 string    `json:"payload_sha256"`
	PayloadSize   int64     `json:"payload_size"`
}

Release is GET /v3/<domain>/rulesets/{name}/{version}.

type Ruleset

type Ruleset struct {
	Name      string
	Version   string // resolved, never "latest"
	Requested string // as asked for, e.g. "latest"
	Dir       string
	Lease     Lease
	Source    Source
	// FetchedAt is when the bundle was downloaded (now, or when it was cached).
	FetchedAt time.Time
}

Ruleset is a verified ruleset unpacked into Dir. Close removes Dir.

func (*Ruleset) Close

func (r *Ruleset) Close() error

Close removes the run directory.

type Source

type Source string

Source says where a fetched ruleset came from.

const (
	// SourceNetwork is a bundle downloaded in this call.
	SourceNetwork Source = "network"
	// SourceCache is a cached bundle within its TTL.
	SourceCache Source = "cache"
	// SourceRevalidated is a cached bundle past its TTL that the API confirmed current.
	SourceRevalidated Source = "revalidated"
	// SourceStale is a cached bundle past its TTL, used because the API was unreachable.
	SourceStale Source = "stale"
)

type StatusError

type StatusError struct {
	StatusCode int
	Code       string
	Message    string
}

StatusError is a non-2xx answer from the rulesets API. Code and Message come from the API's JSON error body when it sent one.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Unwrap makes 410 and 426 match ErrUpgradeRequired.

type Summary

type Summary struct {
	Name     string   `json:"name"`
	Domain   string   `json:"domain"`
	Latest   string   `json:"latest"`
	Versions []string `json:"versions"`
}

Summary is one entry of GET /v3/<domain>/rulesets.

Jump to

Keyboard shortcuts

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