firewallstate

package
v0.16.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 30 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

Overview

Package firewallstate provides authoritative, scoped shared counters. SQLite is a fenced singleton; optional PostgreSQL coordinates active-active replicas.

Index

Constants

View Source
const MaxKeys = 4096
View Source
const MaxWindow = 24 * time.Hour

Variables

This section is empty.

Functions

func Bearer

func Bearer(r *http.Request) string

func Decode

func Decode(raw []byte, v any) error

Decode rejects duplicate keys as well as unknown fields and trailing input.

func Digest

func Digest(v string) string

func Endpoint

func Endpoint(raw string) (*url.URL, error)

Endpoint rejects credentials in URLs, redirects, and cleartext nonloopback peers. Loopback HTTP is only for local trusted deployments/tests.

func Fail

func Fail(status int, message string) error

func HTTPClient

func HTTPClient(timeout time.Duration, transport http.RoundTripper) *http.Client

HTTPClient owns its timeout and redirect policy; transport customization may supply a trusted TLS root, but must not disable certificate verification.

func MatchToken

func MatchToken(got, want string) bool

func PrivateDir

func PrivateDir(dir string) error

func PrivateFile

func PrivateFile(path string) error

func RequestJSON

func RequestJSON(ctx context.Context, client *http.Client, method, endpoint, token string, input, output any, max int64) error

func Restore

func Restore(ctx context.Context, backup, dir, name string) error

Restore is offline: acquires the destination singleton lock and refuses an existing database. New/validation must succeed before exposing a restored service.

func ValidID

func ValidID(v string) bool

func WriteError

func WriteError(w http.ResponseWriter, err error)

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

Types

type Client

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

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

func (*Client) Close

func (c *Client) Close()

func (*Client) Count

func (c *Client) Count(ctx context.Context, k Key, w Window, _ time.Time) (CountResult, error)

Count never retries a POST: ambiguous network failure may already have counted. The supplied timestamp is ignored remotely; the authoritative server owns time.

func (*Client) Probe

func (c *Client) Probe(ctx context.Context) error

type ClientConfig

type ClientConfig struct {
	URL       string
	Token     string
	Timeout   time.Duration
	Transport http.RoundTripper
}

type Config

type Config struct {
	Auth                        *firewallauth.Authority
	Environment, Target, Origin string
	StateDir                    string
	DatabaseURL                 string
	DatabaseNamespace           string
	Principals                  []Principal
	MaxKeys                     int
}

type CountRequest

type CountRequest struct {
	Key    Key    `json:"key"`
	Window Window `json:"window"`
}

type CountResult

type CountResult struct {
	Count   int64     `json:"count"`
	Expires time.Time `json:"expires"`
}

type Database

type Database struct {
	DB *sql.DB
	// contains filtered or unexported fields
}

Database holds a separate SQLite lifetime lock or a PostgreSQL connection pool. Stop listeners and users before Close. Copying a SQLite database does not fence its old host; PostgreSQL writers must use Begin's namespace transaction lock.

func OpenDatabase

func OpenDatabase(dir, name string) (*Database, error)

func OpenPostgres

func OpenPostgres(ctx context.Context, rawURL, namespace string) (*Database, error)

OpenPostgres opens an independent connection pool. Namespace is a dedicated schema and serialization domain, shared by all replicas of one service. Database URLs are bootstrap secrets and are never included in returned errors.

func (*Database) AuthNamespace

func (d *Database) AuthNamespace() string

func (*Database) AuthTransaction

func (d *Database) AuthTransaction(ctx context.Context, f func(firewallauth.SQLTransaction) error) error

func (*Database) Backup

func (d *Database) Backup(ctx context.Context, destination string) error

Backup uses a consistent SQLite snapshot. Destination is an operator-supplied local path, never bundle input, and must not exist. Protect the backup as secrets.

func (*Database) Begin

func (d *Database) Begin(ctx context.Context) (*Transaction, error)

func (*Database) Bootstrap

func (d *Database) Bootstrap(ctx context.Context, fingerprint string, statements []string) error

Bootstrap atomically creates the service schema and pins its canonical hashed bootstrap configuration. Mismatched replicas fail before touching service state.

func (*Database) CheckBootstrap

func (d *Database) CheckBootstrap(ctx context.Context) error

func (*Database) Close

func (d *Database) Close() error

func (*Database) Coordination

func (d *Database) Coordination() string

func (*Database) IsPostgres

func (d *Database) IsPostgres() bool

func (*Database) Rebind

func (d *Database) Rebind(query string) string

Rebind is for this package's SQL constants, not arbitrary PostgreSQL operators. Quoted strings/identifiers, comments and dollar-quoted bodies are preserved.

type Error

type Error struct {
	Status  int
	Message string
}

func (*Error) Error

func (e *Error) Error() string

type Guard

type Guard struct {
	Operations *runtimeobs.Monitor
	// contains filtered or unexported fields
}

func NewGuard

func NewGuard(cfg GuardConfig) (*Guard, error)

func NewGuardWithStore

func NewGuardWithStore(cfg GuardConfig, store Store) (*Guard, error)

func (*Guard) Evaluate

func (g *Guard) Evaluate(ctx context.Context, c *policy.Compiled, e policy.Event) (policy.Decision, error)

func (*Guard) Probe

func (g *Guard) Probe(ctx context.Context) error

Probe checks authoritative availability without consuming quota. A stale completion cannot overwrite the result of an operation started later.

func (*Guard) Ready

func (g *Guard) Ready() (bool, error)

Ready reports ordered count/probe outcomes; no contact is unready.

type GuardConfig

type GuardConfig struct {
	URL     string        `json:"url"`
	Token   string        `json:"token"`
	Window  time.Duration `json:"window"`
	Limit   int64         `json:"limit"`
	GroupBy string        `json:"group_by"`
	ID      string        `json:"id"`
	Unit    string        `json:"unit,omitempty"`
}

GuardConfig is runtime configuration, separate from native policy thresholds. The remote principal owns tenant/app scope. GroupBy supports only these bounded scalar fields: empty (global), ClientIP, Host, Method, Path. Unit defaults to request; message counts only request-phase inspection messages.

type Key

type Key struct {
	Revision string `json:"revision"`
	Group    string `json:"group"`
}

type Principal

type Principal struct {
	ID    string
	Token string
	Scope Scope
}

Principal scope is configured on the authoritative server, never from requests.

type Scope

type Scope struct {
	Tenant string `json:"tenant"`
	App    string `json:"app"`
}

func (Scope) Valid

func (s Scope) Valid() bool

type Service

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

func New

func New(cfg Config) (*Service, error)

func (*Service) Backup

func (s *Service) Backup(ctx context.Context, path string) error

func (*Service) Bind

func (s *Service) Bind(scope Scope) Store

Bind is for trusted in-process callers only. Network callers are bound by token.

func (*Service) Close

func (s *Service) Close() error

func (*Service) Handler

func (s *Service) Handler() http.Handler

type Store

type Store interface {
	Count(context.Context, Key, Window, time.Time) (CountResult, error)
}

type Transaction

type Transaction struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Transaction uses READ COMMITTED plus a transaction-scoped exclusive advisory lock. Reads happen AFTER lock acquisition and see the preceding writer's commit. No ambiguous commit is retried, and no process-local lock provides PG safety.

func (*Transaction) Clock

func (t *Transaction) Clock(ctx context.Context, fallback int64) (int64, error)

PostgreSQL owns counter time; the caller's process clock is not authoritative.

func (*Transaction) Commit

func (t *Transaction) Commit() error

func (*Transaction) ExecContext

func (t *Transaction) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*Transaction) QueryContext

func (t *Transaction) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

func (*Transaction) QueryRowContext

func (t *Transaction) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

type Window

type Window struct {
	Mode     string        `json:"mode"`
	Duration time.Duration `json:"duration"`
}

Window is a fixed window anchored at its first count, not a sliding window.

Jump to

Keyboard shortcuts

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