platform

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClassifiedRateLimiter added in v0.9.0

func ClassifiedRateLimiter(cfg RateLimitConfig) func(http.Handler) http.Handler

ClassifiedRateLimiter returns middleware that applies a separate per-minute budget to each route class.

The auth class (login, signup, password reset) is keyed on IP alone: these requests are unauthenticated, so any X-API-Key header on them is unverified and must never influence the brute-force budget.

Every other class is checked against two buckets, both of which must allow: a shared IP ceiling (ipCeilingFactor × the class limit), checked first, and a per-subject budget keyed by API key where present and by IP otherwise. Checking the IP bucket first means a denial there rejects the request immediately without ever touching — or creating — a per-subject bucket, so a burst of forged keys is stopped by the shared ceiling before it can grow the per-subject map.

Clients over either limit receive 429 with a Retry-After header, which the CLI honours.

func ClientIP added in v0.9.0

func ClientIP(trusted *TrustedProxies) func(http.Handler) http.Handler

ClientIP returns middleware that resolves the address a request should be attributed to and stores it on the request context, where the rate limiter and the request logger both read it via ClientIPFromRequest.

It deliberately replaces chi's RealIP, which overwrites RemoteAddr from X-Real-IP / X-Forwarded-For for anyone who sends them. Those headers are plain client input: trusting them unconditionally lets a single attacker present a fresh source address on every request, which defeats per-IP rate limiting entirely and lets the limiter's subject maps grow without bound. Here they are read only when the peer that opened the connection is itself a trusted proxy, and RemoteAddr is left untouched so the true socket address stays available.

func ClientIPFromRequest added in v0.9.0

func ClientIPFromRequest(r *http.Request) string

ClientIPFromRequest returns the address a request is attributed to: the value resolved by the ClientIP middleware, or — if that middleware is not installed — the socket address it connected from. The fallback never consults a header, so forgetting the middleware costs accuracy behind a proxy but can never be exploited.

func InitLogger

func InitLogger()

InitLogger configures zerolog. When LOG_FORMAT=pretty (or LOG_PRETTY=true), uses colorized console output for development. Otherwise outputs JSON for production/log aggregation.

func IsDuplicateKey

func IsDuplicateKey(err error) bool

IsDuplicateKey returns true if err is a Postgres unique-violation (SQLSTATE 23505).

func MetricsMiddleware added in v0.7.0

func MetricsMiddleware(next http.Handler) http.Handler

func Migrate

func Migrate(db *sql.DB) error

func MigrateDown

func MigrateDown(db *sql.DB) error

func MigrateStatus

func MigrateStatus(db *sql.DB) error

func MigrateUpTo added in v0.10.0

func MigrateUpTo(db *sql.DB, version int64) error

MigrateUpTo applies migrations up to and including version, leaving later ones unapplied. It exists so a migration can be tested against a database populated at the prior version — the only way that test means anything. A test that opens a fully-migrated database and then "upgrades" it passes with the migration deleted.

func NewPool

func NewPool(ctx context.Context, databaseURL string, cfg *PoolConfig) (*pgxpool.Pool, error)

func OpenDB

func OpenDB(databaseURL string) (*sql.DB, error)

func RequestID added in v0.7.0

func RequestID(next http.Handler) http.Handler

RequestID is a Chi-compatible middleware that reads X-Request-ID from the incoming request, or generates a UUID if absent. It sets the ID on the response header and in the request context.

func RequestIDFromContext added in v0.7.0

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID stored in ctx, or "".

func RequestLogger

func RequestLogger(next http.Handler) http.Handler

RequestLogger is a Chi-compatible middleware that logs every request using zerolog. Logs method, path, status, duration, and client IP.

The IP is the one ClientIP resolved, so the logs name the same client the rate limiter charged — reading a 429 against the wrong address would make every limiter incident impossible to trace.

func RunMigrations

func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error

func SecurityHeaders added in v0.7.0

func SecurityHeaders(cookieSecure bool) func(http.Handler) http.Handler

SecurityHeaders returns middleware that sets common security response headers. When cookieSecure is true, Strict-Transport-Security is also set.

Types

type Config

type Config struct {
	DatabaseURL   string
	StoragePath   string
	ListenAddr    string
	DisableSignup bool
	GitHubToken   string

	// EventRetentionDays controls how many days of skill_events to keep.
	// Events older than this are purged on startup. 0 disables cleanup.
	EventRetentionDays int

	// ExternalScanCmd, when set, is an opt-in external security scanner command
	// run over each skill on publish/import (Phase 2). The token "{dir}" is
	// replaced with the skill directory and the command must emit SARIF on
	// stdout, e.g. "gitleaks dir {dir} --report-format sarif --report-path
	// /dev/stdout". Empty disables the feature.
	ExternalScanCmd     string
	ExternalScanTimeout time.Duration

	DBMaxConns          int
	DBMinConns          int
	DBMaxConnLifetime   time.Duration
	DBMaxConnIdleTime   time.Duration
	DBHealthCheckPeriod time.Duration

	CORSOrigins string
	LogLevel    string

	// TrustedProxies is the comma-separated list of proxy addresses and CIDR
	// blocks whose X-Forwarded-For / X-Real-IP headers may be believed. Empty
	// means trust none of them — see ParseTrustedProxies.
	TrustedProxies string

	RateLimitAuth   int
	RateLimitEvents int
	RateLimitRead   int
	RateLimitWrite  int
	RateLimitSuites int

	// QualityFloor is the minimum headline quality score (0-100) a verified
	// evaluation must reach to release a version held for review. 0 (the
	// default) accepts any verified report with a complete panel and no
	// critical contract violations.
	QualityFloor float64
}

Config holds all runtime configuration for the skael server.

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig reads configuration from environment variables. DATABASE_URL is required; returns an error if absent. STORAGE_PATH defaults to "./data/skills" (or "s3://bucket/prefix" for S3); LISTEN_ADDR defaults to ":8080". DISABLE_SIGNUP=true prevents new registrations.

type LocalStorage added in v0.5.0

type LocalStorage struct {
	BasePath string
}

LocalStorage provides local filesystem storage for skill archive files.

func NewLocalStorage added in v0.5.0

func NewLocalStorage(basePath string) (*LocalStorage, error)

NewLocalStorage creates a LocalStorage rooted at basePath, creating the directory if it does not already exist.

func (*LocalStorage) Delete added in v0.5.0

func (s *LocalStorage) Delete(_ context.Context, name string) error

Delete removes the file stored under name (relative to BasePath).

func (*LocalStorage) Ping added in v0.6.0

func (s *LocalStorage) Ping(_ context.Context) error

Ping verifies the base path still exists and is a directory.

func (*LocalStorage) Read added in v0.5.0

func (s *LocalStorage) Read(_ context.Context, name string) (io.ReadCloser, error)

Read opens the file stored under name (relative to BasePath) for reading. The caller is responsible for closing the returned ReadCloser.

func (*LocalStorage) Write added in v0.5.0

func (s *LocalStorage) Write(_ context.Context, name string, r io.Reader) (string, error)

Write stores the content from r under name (relative to BasePath). It uses an atomic write: content is first written to a .tmp file which is then renamed to the final destination, ensuring no partial files are visible. Returns the full path of the written file.

type PoolConfig added in v0.7.0

type PoolConfig struct {
	MaxConns          int
	MinConns          int
	MaxConnLifetime   time.Duration
	MaxConnIdleTime   time.Duration
	HealthCheckPeriod time.Duration
}

PoolConfig holds optional pgxpool tuning parameters. A nil value keeps pgxpool's built-in defaults.

type RateLimitConfig added in v0.9.0

type RateLimitConfig struct {
	Auth   int // /api/auth/* — login, signup, password reset
	Events int // POST /api/events — activation tracking
	Read   int // GET/HEAD — list, search, manifest, downloads
	Write  int // everything else — publish, import, delete
	Suites int // POST /api/eval/suites — accepts up to a base64-encoded 10MB archive
}

RateLimitConfig holds the per-minute request budget for each route class. The classes exist because one number cannot serve all of them: hook events arrive once per skill activation across a whole team, archive downloads arrive in bursts during a sync, and login attempts are a brute-force surface that should stay tight.

type S3Storage added in v0.5.0

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

S3Storage stores archives in any S3-compatible object store.

func (*S3Storage) Delete added in v0.5.0

func (s *S3Storage) Delete(ctx context.Context, name string) error

func (*S3Storage) Ping added in v0.6.0

func (s *S3Storage) Ping(ctx context.Context) error

Ping verifies the bucket is reachable.

func (*S3Storage) Read added in v0.5.0

func (s *S3Storage) Read(ctx context.Context, name string) (io.ReadCloser, error)

func (*S3Storage) Write added in v0.5.0

func (s *S3Storage) Write(ctx context.Context, name string, r io.Reader) (string, error)

type Storage

type Storage interface {
	// Write stores r under name and returns the stored key (name).
	Write(ctx context.Context, name string, r io.Reader) (string, error)
	// Read opens the blob stored under name; caller closes the ReadCloser.
	Read(ctx context.Context, name string) (io.ReadCloser, error)
	// Delete removes the blob stored under name.
	Delete(ctx context.Context, name string) error
	// Ping verifies the backing store is reachable (readiness checks).
	Ping(ctx context.Context) error
}

Storage abstracts archive blob storage (local filesystem or object storage). Names are relative keys, e.g. "code-review/abc123.tar.gz".

func NewStorageFromConfig added in v0.5.0

func NewStorageFromConfig(cfg *Config) (Storage, error)

NewStorageFromConfig builds the Storage backend selected by STORAGE_PATH: "s3://bucket/prefix" → S3; anything else → local filesystem.

type TrustedProxies added in v0.9.0

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

TrustedProxies is the set of peers whose forwarding headers may be believed. The zero value — and a nil *TrustedProxies — trusts nobody, which is the correct default: every X-Forwarded-For and X-Real-IP arriving at a directly-exposed server is written by the client itself.

func ParseTrustedProxies added in v0.9.0

func ParseTrustedProxies(list string) *TrustedProxies

ParseTrustedProxies parses a comma-separated TRUSTED_PROXIES list. Entries may be CIDR blocks ("10.0.0.0/8", "fd00::/8") or bare addresses ("192.168.1.5", "2001:db8::1"), IPv4 or IPv6; a bare address is treated as a single-host range.

Unparseable entries are dropped with a warning rather than failing startup. Dropping is the safe direction: an entry that is not understood simply does not become trusted, so a typo costs the operator forwarded addresses, never spoofable ones.

func (*TrustedProxies) Contains added in v0.9.0

func (t *TrustedProxies) Contains(addr netip.Addr) bool

Contains reports whether addr belongs to a trusted proxy range.

func (*TrustedProxies) Empty added in v0.9.0

func (t *TrustedProxies) Empty() bool

Empty reports whether no proxy is trusted, in which case forwarding headers are ignored outright.

Jump to

Keyboard shortcuts

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