utils

package
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 72 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

Index

Constants

View Source
const (
	DialectSQLite   = "sqlite"
	DialectPostgres = "pgx"
)

DialectSQLite / DialectPostgres select DDL and placeholder style.

View Source
const (
	ManagedByDeployment   = "deployment"
	ManagedByFunction     = "function"
	ManagedBySeaweedFS    = "seaweedfs"
	ManagedByManagedDB    = "manageddb"
	ManagedByRegistry     = "registry"
	ManagedByRegistrySite = "registry-site"
	ManagedByCI           = "ci"
	ManagedByShare        = "share"
)

Owner kinds a proxy route can be managed by. The set is closed on purpose: the URLs page renders the badge and the link to the owner from the kind, and an unknown kind would be a route nobody can edit anywhere.

View Source
const (
	SHIELD_STRIKE = 0
	SHIELD_TEMP   = 1
	SHIELD_PERM   = 2
)
View Source
const (
	NOONE = -1
	GUEST = 0
	USER  = 1
	ADMIN = 2
)
View Source
const (
	STRICT  = 1
	NORMAL  = 2
	LENIENT = 3
)
View Source
const APITokenPrefix = "cosmos_"

APITokenPrefix is the raw-value marker of a Cosmos API token.

View Source
const AuthCtxKey = "AuthContext"

Variables

View Source
var (
	Reset = "\033[0m"
	Bold  = "\033[1m"
)
View Source
var (
	// LogEntryCtxKey is the context.Context key to store the request log entry.
	LogEntryCtxKey = "LogEntry"

	// DefaultLogger is called by the Logger middleware handler to log each request.
	// Its made a package-level variable so that it can be reconfigured for custom
	// logging configurations.
	DefaultLogger func(next http.Handler) http.Handler
)
View Source
var AdminRoleRequiredPermissions = []Permission{PERM_LOGIN, PERM_ADMIN, PERM_USERS, PERM_CONFIGURATION}

permissions the built-in Admin role can never lose, so nobody locks the server out

View Source
var AlphaNumRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
View Source
var BannedIPs = sync.Map{}
View Source
var CONFIGFOLDER = "/var/lib/cosmos/"
View Source
var CheckDockerNetworkMode func() string
View Source
var ClusterHostnames = func() []string { return nil }

ClusterHostnames lists the hostnames served by the other nodes of the cluster, constellation overrides it.

View Source
var ConfigLock sync.Mutex
View Source
var ConfigLockInternal sync.Mutex
View Source
var ConstellationDNSAddress = func() (string, error) { return "", nil }

ConstellationDNSAddress is the address this node serves the Constellation DNS on, empty when it serves none. An error means it cannot tell right now. Wired in constellation/index.go.

View Source
var DBStatus bool

DBStatus reports whether the monitoring store is open, surfaced by /api/status.

View Source
var DefaultConfig = Config{
	LoggingLevel:     "INFO",
	NewInstall:       true,
	AutoUpdate:       true,
	BlockedCountries: []string{},
	HTTPConfig: HTTPConfig{
		HTTPSCertificateMode:    "DISABLED",
		GenerateMissingAuthCert: true,
		HTTPPort:                "80",
		HTTPSPort:               "443",
		Hostname:                "0.0.0.0",
		PublishMDNS:             true,
		ProxyConfig: ProxyConfig{
			Routes: []ProxyRouteConfig{},
		},
		DisablePropagationChecks:    false,
		DNSChallengePropagationWait: 30,
	},
	DockerConfig: DockerConfig{
		DefaultDataPath: "/cosmos-storage",
	},
	MarketConfig: MarketConfig{
		Sources: []MarketSource{},
	},
	ConstellationConfig: ConstellationConfig{
		Enabled:     false,
		DNSDisabled: false,
		DNSFallback: "8.8.8.8:53",
		DNSAdditionalBlocklists: []string{
			"https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt",
			"https://s3.amazonaws.com/lists.disconnect.me/simple_ad.txt",
			"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts",
			"https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-only/hosts",
		},
	},
	MonitoringAlerts: map[string]Alert{
		"Anti Crypto-Miner": {
			Name:           "Anti Crypto-Miner",
			Enabled:        false,
			Period:         "daily",
			TrackingMetric: "cosmos.system.docker.cpu.*",
			LastTriggered:  time.Time{},
			Condition: AlertCondition{
				Operator: "gt",
				Value:    80,
				Percent:  false,
			},
			Actions: []AlertAction{
				AlertAction{
					Type:   "notification",
					Target: "",
				},
				AlertAction{
					Type:   "email",
					Target: "",
				},
				AlertAction{
					Type:   "stop",
					Target: "",
				},
			},
			Throttled: false,
			Severity:  "warn",
		},
		"Anti Memory Leak": {
			Name:           "Anti Memory Leak",
			Enabled:        false,
			Period:         "daily",
			TrackingMetric: "cosmos.system.docker.ram.*",
			LastTriggered:  time.Time{},
			Condition: AlertCondition{
				Operator: "gt",
				Value:    80,
				Percent:  true,
			},
			Actions: []AlertAction{
				{
					Type:   "notification",
					Target: "",
				},
				{
					Type:   "email",
					Target: "",
				},
				{
					Type:   "stop",
					Target: "",
				},
			},
			Throttled: false,
			Severity:  "warn",
		},
		"Disk Health": {
			Name:           "Disk Health",
			Enabled:        true,
			Period:         "latest",
			TrackingMetric: "system.disk-health.temperature.*",
			LastTriggered:  time.Time{},
			Condition: AlertCondition{
				Operator: "gt",
				Value:    50,
				Percent:  false,
			},
			Actions: []AlertAction{
				{
					Type:   "notification",
					Target: "",
				},
			},
			Throttled: true,
			Severity:  "warn",
		},
		"Disk Full Notification": {
			Name:           "Disk Full Notification",
			Enabled:        true,
			Period:         "latest",
			TrackingMetric: "cosmos.system.disk./",
			LastTriggered:  time.Time{},
			Condition: AlertCondition{
				Operator: "gt",
				Value:    95,
				Percent:  true,
			},
			Actions: []AlertAction{
				{
					Type:   "notification",
					Target: "",
				},
			},
			Throttled: true,
			Severity:  "warn",
		},
	},
}
View Source
var DoesContainerExist func(string) bool
View Source
var ErrApplyTimeout = errors.New("store: timed out waiting for the op to apply")

ErrApplyTimeout: the op was published but did not apply locally in time.

View Source
var ErrDatabaseClosed = errors.New("database: not initialized")
View Source
var ErrNotFound = errors.New("store: not found")

ErrNotFound is returned by typed reads when no row matches.

View Source
var ErrReadOnly = errors.New("store: config is read-only, no writable op-log")

ErrReadOnly: the op-log publish failed, so this node cannot write config.

View Source
var GetConstellationTunnelRoutes = func() []ProxyRouteConfig { return []ProxyRouteConfig{} }
View Source
var GetContainerIPByName func(string) (string, error)
View Source
var HTTPSCertModeList = map[string]string{
	"DISABLED":    "DISABLED",
	"PROVIDED":    "PROVIDED",
	"SELFSIGNED":  "SELFSIGNED",
	"LETSENCRYPT": "LETSENCRYPT",
}
View Source
var HTTPSListening = false
View Source
var InitBackups func()
View Source
var InitPremiumFeatures func()
View Source
var InitRemoteStorage func()
View Source
var InitSnapRAIDConfig func()
View Source
var InternalProcessTracker = NewProcessTracker()

InternalProcessTracker is the tracker every restart path waits on.

View Source
var IsConstellationIP = func(string) bool { return false }
View Source
var IsHTTPS = false

IsHTTPS: the server's own hostname is served over HTTPS. HTTPSListening: the HTTPS listener is up, some hostnames may still be HTTP-only (see HostServedOverHTTPS for the scheme of a given hostname).

View Source
var IsHostNetwork = false
View Source
var IsInsideContainer = false
View Source
var IsLocalDockerIP = func(string) bool { return false }

Wired to docker.IsLocalDockerIP in src/index.go (utils cannot import docker); defaults to strict "no".

View Source
var IsPro func() bool = func() bool { return false }
View Source
var IsZoneIssuer = func() bool { return true }

IsZoneIssuer reports whether this node issues zone certificates. Standalone nodes always do, constellation overrides it with the leader check.

View Source
var LBModes = []string{"", "first", "round_robin", "load_based"}

LBModes are the load balancing modes implemented by TunnelLoadBalancer.Select().

View Source
var LetsEncryptErrors = []string{}
View Source
var LoggingLevelLabels = map[LoggingLevel]LogLevel{
	"DEBUG":   DEBUG,
	"INFO":    INFO,
	"WARNING": WARNING,
	"ERROR":   ERROR,
}
View Source
var NeedsRestart = false
View Source
var NewVersionAvailable = false
View Source
var PermissionLabels = map[Permission]string{
	PERM_ADMIN_READ:         "Admin Read (view logs)",
	PERM_ADMIN:              "Admin (system ops)",
	PERM_USERS_READ:         "Users Read (view users)",
	PERM_USERS:              "Users (manage users)",
	PERM_RESOURCES_READ:     "Resources Read (view containers/storage)",
	PERM_RESOURCES:          "Resources (manage containers/storage)",
	PERM_CONFIGURATION_READ: "Configuration Read (view config)",
	PERM_CONFIGURATION:      "Configuration (modify config)",
	PERM_CREDENTIALS_READ:   "Credentials Read (view secrets/env vars)",
	PERM_LOGIN:              "Login",
	PERM_LOGIN_WEAK:         "Login (weak)",
}
View Source
var ProxyModeList = map[string]string{
	"PROXY":    "PROXY",
	"SPA":      "SPA",
	"STATIC":   "STATIC",
	"SERVAPP":  "SERVAPP",
	"REDIRECT": "REDIRECT",
}
View Source
var PublishMigratedZones = func(zones []DNSZoneConfig) {}

PublishMigratedZones hands zones created by a local migration to the rest of the cluster, constellation overrides it.

View Source
var PublishRolesOp = func(roles map[Role]RoleConfig) error {
	return errors.New("constellation op-log not initialised")
}

PublishRolesOp publishes the roles config domain through the constellation op-log. Wired in constellation/index.go: the pro package can't call constellation.PublishDomainOp directly because constellation imports pro.

View Source
var PublishZoneCerts = func() {}

PublishZoneCerts hands the zone certificates of the issuer to the rest of the cluster, constellation overrides it.

View Source
var PushShieldMetrics func(string)
View Source
var RecordsSupported = func(provider string) bool { return false }

RecordsSupported reports whether the records of a zone can be managed through a DNS challenge provider, wired by the dnsrecords package.

View Source
var RefreshZoneCerts = func() {}

RefreshZoneCerts issues whatever zone certificate is missing and serves it, without restarting the server. ReloadZoneCerts only re-reads them from the config. Both are wired by the HTTP server.

View Source
var ReloadZoneCerts = func() {}
View Source
var RestartCRON func()
View Source
var RestartConstellation func()
View Source
var RestartHTTPServer = func() {}
View Source
var RevertHostDNS = func() {}

RevertHostDNS gives the server its own resolver back, called before the process exits. Wired in constellation/index.go (utils cannot import constellation).

View Source
var StopAllRCloneProcess func(bool)

Global: permissions that require sudo for ANY role

View Source
var Template = `` /* 1110-byte string literal not displayed */
View Source
var UpdateAvailable = map[string]bool{}
View Source
var Validate = validator.New()
View Source
var WaitForAllJobs func()
View Source
var ZonesPending = func() bool { return false }

ZonesPending reports that this server has joined a cluster whose zones it has not received yet, constellation overrides it.

Functions

func APITokenHasPermission added in v0.24.0

func APITokenHasPermission(token APITokenConfig, permission Permission) bool

APITokenHasPermission reports whether an API token carries a permission.

func AcceptHeader

func AcceptHeader(accept string) func(next http.Handler) http.Handler

func AdminOnlyMiddleware added in v0.15.0

func AdminOnlyMiddleware(next http.Handler) http.Handler

func AdminOnlyWithRedirect

func AdminOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error

func ApplyLogicalDump added in v0.23.0

func ApplyLogicalDump(data []byte, epoch uint64, seq uint64) error

ApplyLogicalDump replaces users+devices with the snapshot content and adopts its (epoch, seq) in the same tx, so a crash mid-install can never leave the node claiming a log position its data doesn't match.

func ApplyManagedRoutes added in v0.24.0

func ApplyManagedRoutes(kind, name string, desired []ProxyRouteConfig) bool

ApplyManagedRoutes materializes an owner's desired route set into this node's config: ConfigLock → read the FILE (not the in-memory copy a concurrent edit may have moved on from) → MergeManagedRoutes → SetBaseMainConfig → async HTTP restart. One rewrite and one restart for the whole batch, and neither when nothing changed. Returns whether the config changed.

The restart is asynchronous like every other route mutation in the codebase: it tears down the HTTP server the calling handler may be answering on.

func ApplyOpTx added in v0.23.0

func ApplyOpTx(m Mutation, seq uint64, preDevices *[]ConstellationDevice) error

ApplyOpTx applies one op-log mutation and commits its sequence in the SAME tx — that atomicity, not JetStream ack state, is what makes apply exactly-once. preDevices, when non-nil, receives the matching device rows read inside the tx (pre-image the apply loop diffs to pick a reaction).

func BandwithLimiterMiddleware

func BandwithLimiterMiddleware(max int64) func(next http.Handler) http.Handler

func Base64Encode added in v0.17.0

func Base64Encode(str string) string

func BlockBannedIPs added in v0.12.0

func BlockBannedIPs(next http.Handler) http.Handler

func BlockByCountryMiddleware

func BlockByCountryMiddleware(blockedCountries []string, CountryBlacklistIsWhitelist bool) func(http.Handler) http.Handler

BlockByCountryMiddleware returns a middleware function that blocks requests from specified countries.

func BlockPostWithoutReferer

func BlockPostWithoutReferer(next http.Handler) http.Handler

blockPostWithoutReferer blocks POST requests without a Referer header

func BuildLogicalDump added in v0.23.0

func BuildLogicalDump() ([]byte, error)

BuildLogicalDump serializes users+devices as canonical sorted JSON in one read tx. Body of the op-log snapshot, and the canonical form E2E convergence asserts on.

func BuildPlatforms added in v0.24.0

func BuildPlatforms() []string

BuildPlatforms lists the container platforms this host can run: its own, plus those an enabled QEMU binfmt handler emulates (what a cross-platform image build needs). Sorted, the native one first.

func BuildSnapshot added in v0.23.0

func BuildSnapshot() ([]byte, uint64, uint64, error)

BuildSnapshot returns the users+devices dump plus the (epoch, seq) it is consistent with, all read in one tx.

func CORSHeader

func CORSHeader(origin string) func(next http.Handler) http.Handler

func CanGrant added in v0.23.2

func CanGrant(req *http.Request, perms []Permission) bool

CanGrant: nobody can hand out a permission they do not hold themselves

func CertCovers added in v0.24.0

func CertCovers(certHosts []string, host string) bool

CertCovers reports whether a certificate issued for certHosts serves host

func CertificateInfo added in v0.24.0

func CertificateInfo(certPEM string) ([]string, time.Time, error)

CertificateInfo reads what a PEM certificate covers and until when

func CheckDNS

func CheckDNS(url string) error

func CheckHostNetwork added in v0.14.0

func CheckHostNetwork()

func CheckIPAccess added in v0.22.0

func CheckIPAccess(clientIP string, remoteAddr string, restrictToConstellation bool, whitelistIPs []string) bool

CheckIPAccess reports whether a peer passes the constellation restriction and inbound whitelist. Only a Nebula device IP satisfies restrictToConstellation.

func CheckInternet added in v0.16.0

func CheckInternet()

func CheckPassword added in v0.15.0

func CheckPassword(nickname, password string) error

func CheckPermissions added in v0.22.0

func CheckPermissions(w http.ResponseWriter, req *http.Request, permission Permission) error

func CheckPermissionsOrSelf added in v0.22.0

func CheckPermissionsOrSelf(w http.ResponseWriter, req *http.Request, nickname string, permission Permission) error

CheckPermissionsOrSelf allows access if the user is acting on themselves (nickname matches), even without the specified permission. Otherwise falls back to standard permission check.

func CheckRouteIPAccess added in v0.24.0

func CheckRouteIPAccess(clientIP string, remoteAddr string, restrictToConstellation bool, whitelistIPs []string) bool

CheckRouteIPAccess additionally lets a local peer (IsLocalPeer) satisfy restrictToConstellation; the whitelist is never relaxed.

func CleanBannedIPs added in v0.12.0

func CleanBannedIPs()

func ClearFormationWriter added in v0.23.0

func ClearFormationWriter() error

ClearFormationWriter ends formation: from here this node publishes like any other.

func ClearPlannedRestart added in v0.24.0

func ClearPlannedRestart()

ClearPlannedRestart lifts the marker when a restart did not end the process (soft restart, failed host restart).

func ClientRealIP added in v0.21.0

func ClientRealIP(next http.Handler) http.Handler

func CloseMetricsDatabase added in v0.23.0

func CloseMetricsDatabase()

CloseMetricsDatabase closes both handles; only for shutdown and tests.

func CloseStore added in v0.23.0

func CloseStore()

CloseStore closes both handles; only for shutdown and tests.

func CommitMutation added in v0.23.0

func CommitMutation(m Mutation) error

CommitMutation routes one mutation through the op-log when it is wired, and writes it directly otherwise. The hook itself decides between publishing and falling back to a direct tx (standalone install, pre-NATS boot).

func CommitMutationDirect added in v0.23.0

func CommitMutationDirect(m Mutation, preDevices *[]ConstellationDevice) error

CommitMutationDirect writes one mutation straight to SQLite, still capturing the pre-image so the direct write path fires the same reactions as the loop.

func CommitMutationLocal added in v0.23.0

func CommitMutationLocal(m Mutation) error

CommitMutationLocal writes to this node ONLY, bypassing the op-log entirely and unconditionally — it never consults the write-mode ladder.

RESERVED for leave/teardown semantics, where the intent is inherently local: "delete my devices because I am leaving the constellation" must never become a cluster op. Routed through CommitMutation instead, a reset's delete-all carries an empty filter, which compiles to an unqualified DELETE and wipes the device registry on every node that applies it.

Do NOT use for ordinary writes — they must go through CommitMutation so the cluster stays a single materialization of one log.

func CommitMutations added in v0.23.0

func CommitMutations(ms []Mutation) error

CommitMutations applies several mutations in one direct tx; never published (migrations and the op-log's own direct fallback are its only callers).

func CommitOplogSeq added in v0.23.0

func CommitOplogSeq(seq uint64) error

CommitOplogSeq advances last_applied_seq alone — a rejected op still consumes its sequence so every replica stays at the same position.

func CompareSemver added in v0.14.0

func CompareSemver(v1, v2 string) (int, error)

compareSemver compares two semantic version strings. Returns:

 0 if v1 == v2
 1 if v1 > v2
-1 if v1 < v2
 error if there's a problem parsing either version string

func ConfigHostnames added in v0.24.0

func ConfigHostnames(config Config) []string

ConfigHostnames lists every hostname the config serves: main hostname and host-based routes. Multi-host routes are skipped, like everywhere else.

func ContentTypeMiddleware added in v0.15.0

func ContentTypeMiddleware(contentType string) func(next http.Handler) http.Handler

func CountDevices added in v0.23.0

func CountDevices(filter map[string]interface{}) (int64, error)

func CountUsers added in v0.22.31

func CountUsers() (int64, error)

CountUsers returns the number of users registered on this server.

func CreateDefaultConfigFileIfNecessary

func CreateDefaultConfigFileIfNecessary() bool

func CreateDevice added in v0.23.0

func CreateDevice(d ConstellationDevice) error

func CreateUser added in v0.23.0

func CreateUser(u User) error

func Debug

func Debug(message string)

func DecodeOpDoc added in v0.23.0

func DecodeOpDoc(table string, op string, raw json.RawMessage) (interface{}, error)

DecodeOpDoc rebuilds a Doc from the wire form for this table and op.

func DeleteAllUsers added in v0.23.0

func DeleteAllUsers() error

func DeleteAllUsersLocal added in v0.23.0

func DeleteAllUsersLocal() error

DeleteAllUsersLocal wipes users on this node only, never publishing. Reserved for fresh-install setup, where the intent is "this box starts empty" rather than "empty the cluster" — an empty filter compiles to an unqualified DELETE, so published it would take every user on every node with it.

func DeleteDevices added in v0.23.0

func DeleteDevices(filter map[string]interface{}) error

func DeleteDevicesLocal added in v0.23.0

func DeleteDevicesLocal(filter map[string]interface{}) error

DeleteDevicesLocal removes devices on this node only, never publishing. Reserved for leave/reset semantics — see CommitMutationLocal for why a published delete-all is a cluster-wide data loss rather than a local teardown.

func DeleteLocalEvents added in v0.23.0

func DeleteLocalEvents() error

DeleteLocalEvents drops this node's events, used by the metrics reset endpoint.

func DeleteUser added in v0.23.0

func DeleteUser(nickname string) error

func DerivePKCEVerifier added in v0.22.20

func DerivePKCEVerifier(host string, path string) string

DerivePKCEVerifier deterministically derives a PKCE code_verifier from a route host and request path, so the Cosmos-gated proxy flow can compute the same verifier in performLogin (which sends the code_challenge) and later in detectCallbackEndpoint (which sends the verifier) without storing any session state between the two requests. The host is mixed in so same-path apps on different hosts don't share a challenge.

This is safe ONLY because both ends run server-side inside Cosmos: the verifier never reaches a browser/device (only its challenge hash is sent on the front channel), so its secrecy rests on AuthPrivateKey staying secret - the same assumption the deterministic secret already made. Native/SPA apps (Path B) generate their own random verifier and never use this function.

The whole key is hashed: its first characters are the same on every server. The domain-separation prefix keeps the result apart from the state hash. RawURLEncoding of a 32-byte SHA-256 yields 43 chars from [A-Za-z0-9-_], meeting RFC 7636's verifier rules.

func DeviceFieldsChanged added in v0.23.0

func DeviceFieldsChanged(pre []ConstellationDevice, fields map[string]interface{}, names map[string]bool) bool

DeviceFieldsChanged reports whether an update actually moves any of the named fields away from what the matched rows already hold. Lets the apply loop tell a real topology move from an edit that merely resubmits the same values.

func DoErr added in v0.11.0

func DoErr(format string, a ...interface{}) string

func DoLetsEncrypt

func DoLetsEncrypt(domains []string, zone *DNSZoneConfig) (string, string)

DoLetsEncrypt obtains a certificate for the domains: through the DNS provider of the zone when one is given, through HTTP-01/TLS-ALPN-01 otherwise.

func DoSuccess added in v0.11.0

func DoSuccess(format string, a ...interface{}) string

func DoWarn added in v0.11.0

func DoWarn(format string, a ...interface{}) string

func DownloadFile added in v0.10.0

func DownloadFile(url string) (string, error)

func DownloadFileToLocation added in v0.17.0

func DownloadFileToLocation(path, url string) error

func EncodeOpDoc added in v0.23.0

func EncodeOpDoc(m Mutation) (json.RawMessage, error)

EncodeOpDoc renders a mutation's Doc into its canonical wire form.

func EnsureHostname

func EnsureHostname(next http.Handler) http.Handler

func EnsureHostnameCosmosAPI added in v0.12.6

func EnsureHostnameCosmosAPI(next http.Handler) http.Handler

func Error

func Error(message string, err error)

func Exec added in v0.15.0

func Exec(cmd string, args ...string) (string, error)

func Fatal

func Fatal(message string, err error)

func FileExists

func FileExists(path string) bool

func FindRouteConflicts added in v0.24.0

func FindRouteConflicts(candidates []ProxyRouteConfig, kind, name string) error

FindRouteConflicts checks candidate routes against the routes this node can see — its own config plus the tunnel advertisements of the cluster — and returns the first conflict. A candidate conflicts with an existing route of a different owner (or with an unmanaged route) when it reuses its name or its exact matcher (host + path prefix). Routes of the same owner pair never conflict: an update legitimately re-materializes them.

Best effort by construction: proxy routes are node-local, so a route on a node that neither hosts nor tunnels it is invisible here. It still catches every case the URLs page can show the operator.

func FindZone added in v0.24.0

func FindZone(zones []DNSZoneConfig, host string) int

FindZone returns the index of the explicit zone owning the hostname (longest suffix wins), -1 if none.

func GenerateEd25519Certificates

func GenerateEd25519Certificates() (string, string)

func GenerateRSAWebCertificates

func GenerateRSAWebCertificates(domains []string) (string, string, error)

func GenerateRandomString

func GenerateRandomString(n int) string

GenerateRandomString is used for secrets: it has to stay on crypto/rand

func GetAllHostnames

func GetAllHostnames(removePorts bool) []string

func GetAvailableRAM

func GetAvailableRAM() uint64

func GetCPUUsage

func GetCPUUsage() []float64

func GetClientIP added in v0.9.17

func GetClientIP(req *http.Request) string

func GetConfigFileName

func GetConfigFileName() string

func GetFileLastModifiedTime added in v0.21.0

func GetFileLastModifiedTime(path string) time.Time

func GetIPAbuseCounter added in v0.17.0

func GetIPAbuseCounter(ip string) int64

func GetIPLocation

func GetIPLocation(ip string) (string, error)

GetIPLocation returns the ISO country code for a given IP address.

func GetLastAppliedSeq added in v0.23.0

func GetLastAppliedSeq() uint64

GetLastAppliedSeq returns the last op-log sequence committed to this node.

func GetNextAvailableLocalPort added in v0.17.0

func GetNextAvailableLocalPort(startPort int) (string, error)

func GetNumberCosmosNode added in v0.19.0

func GetNumberCosmosNode() int

func GetNumberUsers added in v0.17.0

func GetNumberUsers() int

func GetNumberUsersFromToken added in v0.17.0

func GetNumberUsersFromToken(serverToken string) (int, int)

func GetOplogEpoch added in v0.23.0

func GetOplogEpoch() uint64

GetOplogEpoch returns the current op-log epoch (1 until a reform bumps it).

func GetPrivateAuthKey

func GetPrivateAuthKey() string

func GetProxyOIDCredentials added in v0.18.0

func GetProxyOIDCredentials(route ProxyRouteConfig, hashSecret bool) *fosite.DefaultClient

func GetPublicAuthKey

func GetPublicAuthKey() string

func GetRAMUsage

func GetRAMUsage() uint64

func GetRandomNumber added in v0.21.0

func GetRandomNumber(min int, max int) int

func GetRoles added in v0.22.0

func GetRoles() map[Role]RoleConfig

func GetRootAppId

func GetRootAppId() string

func GetServerPort added in v0.16.3

func GetServerPort() string

func GetServerRawAccess added in v0.21.0

func GetServerRawAccess() (string, string, string)

func GetServerURL

func GetServerURL(overwriteHostname string) string

func GetSubscriptionTypeFromToken added in v0.22.11

func GetSubscriptionTypeFromToken(serverToken string) string

func HTTPError

func HTTPError(w http.ResponseWriter, message string, code int, userCode string)

func HTTPStoreError added in v0.23.0

func HTTPStoreError(w http.ResponseWriter, err error, userCode string)

HTTPStoreError maps a store/op-log failure onto the status the client expects: read-only and duplicate-value both surface as 409, a lost apply as 503.

func HasAnyNewItem

func HasAnyNewItem(after []string, before []string) bool

func HasPermission added in v0.22.0

func HasPermission(req *http.Request, permission Permission) bool

func HostHTTPSMode added in v0.24.0

func HostHTTPSMode(config Config, host string) (string, int)

HostHTTPSMode is how a hostname is served, with the index of the explicit zone deciding it (-1 for an automatic one). The zone decides alone, unless the server does not serve HTTPS at all.

func HostIsHTTPOnly added in v0.24.0

func HostIsHTTPOnly(config Config, host string) bool

HostIsHTTPOnly reports that a hostname is served over plain HTTP

func HostServedOverHTTPS added in v0.24.0

func HostServedOverHTTPS(host string) bool

HostServedOverHTTPS reports whether the requests for a hostname come in over HTTPS on this server. Same answer as IsHTTPS for every hostname, until a zone is HTTP-only on a server that otherwise serves HTTPS.

func IPInRange added in v0.10.0

func IPInRange(ipStr, cidrStr string) (bool, error)

func ImageToBase64

func ImageToBase64(path string) (string, error)

func IncrementIPAbuseCounter added in v0.12.0

func IncrementIPAbuseCounter(ip string)

func InitFBL added in v0.16.0

func InitFBL()

func InitLogs added in v0.17.0

func InitLogs()

func InitMetricsDatabase added in v0.23.0

func InitMetricsDatabase() error

InitMetricsDatabase opens the monitoring store (metrics, events, notifications) and runs its schema. Deliberately close-then-open so it can be re-invoked when CONFIGFOLDER or the Postgres config changes, mirroring InitStore.

func InitStore added in v0.23.0

func InitStore() error

InitStore opens auth.db (two handles: single writer, pooled readers) and runs schema migrations. Deliberately close-then-open: calling it again re-points the store at the current CONFIGFOLDER (tests and the E2E harness rely on this).

func InsertEvent added in v0.23.0

func InsertEvent(e Event) error

InsertEvent writes one event. Silently a no-op before the store opens (setup runs before InitMetricsDatabase and must not error-storm).

func InsertNotification added in v0.23.0

func InsertNotification(n Notification) error

InsertNotification writes one already-fanned-out notification row.

func IsDomain added in v0.10.0

func IsDomain(domain string) bool

func IsEmailEnabled

func IsEmailEnabled() bool

func IsFormationWriter added in v0.23.0

func IsFormationWriter() bool

IsFormationWriter reports whether this node is the constellation's single writer during formation — the creator, or the survivor of a force-reform.

Epoch-tied for the same reason as the bootstrapped marker: the flag stores the epoch it was granted for, so a reform that bumps the epoch invalidates any older grant automatically and no node can carry a formation licence forward into a log it did not seed.

func IsLocalDomain added in v0.21.0

func IsLocalDomain(domain string) bool

func IsLocalIP added in v0.15.7

func IsLocalIP(ip string) bool

func IsLocalPeer added in v0.24.0

func IsLocalPeer(ip string) bool

IsLocalPeer reports whether a peer address belongs to this very machine: loopback, or one of our own docker networks. Deliberately separate from IsConstellationIP, which also gates trust of node tokens and X-Forwarded-For — a local container must not inherit those.

func IsLoggedIn added in v0.12.6

func IsLoggedIn(req *http.Request) bool

func IsNotifyLoginEmailEnabled added in v0.16.0

func IsNotifyLoginEmailEnabled() bool

func IsOplogBootstrapped added in v0.23.0

func IsOplogBootstrapped() bool

IsOplogBootstrapped reports whether this node holds state it materialized from the log for the CURRENT epoch — either by installing a snapshot or by seeding as founder.

This exists because `last_applied_seq > 0` cannot answer the question. A founder that seeded its own store, and every peer that snapshots from it, legitimately sit at seq 0 with real rows; seq 0 is therefore not evidence of a fresh node. Using it as such both re-triggered the always-snapshot rule forever (the joiner never attached) and let an enrolled node fall through to a direct write during a bounce (the write forked, never published).

The marker stores the epoch it was set for, so a reform that bumps the epoch invalidates it automatically — there is no separate clear path to forget.

func IsShieldWhitelisted added in v0.24.0

func IsShieldWhitelisted(ip string) bool

func IsTokenValidForProduct added in v0.22.11

func IsTokenValidForProduct(serverToken string) bool

IsTokenValidForProduct returns false when running the Pro build against a non-Pro subscription token — a Pro-only binary must refuse regular licences.

func IsTrustedProxy added in v0.21.0

func IsTrustedProxy(ip string) bool

func IsValidHostname

func IsValidHostname(hostname string) bool

func IsValidHostnameSyntax added in v0.24.0

func IsValidHostnameSyntax(hostname string) bool

IsValidHostnameSyntax checks a bare server hostname, "host" or "host:port": an IP or dot-separated DNS labels, no scheme, path or trailing slash

func IsValidLBMode added in v0.23.0

func IsValidLBMode(mode string) bool

IsValidLBMode reports whether mode is one of LBModes, case-insensitively.

func IsValidManagedByKind added in v0.24.0

func IsValidManagedByKind(kind string) bool

IsValidManagedByKind reports whether kind is one of ManagedByKinds. The empty string is NOT valid here: callers that accept "unmanaged" test IsManaged first.

func IssuesZoneCert added in v0.24.0

func IssuesZoneCert(zone DNSZoneConfig) bool

IssuesZoneCert reports whether the zone gets its own certificate from the zone issuer. That takes a DNS provider: without one the hosts of the zone stay in the node-local HTTP-01 certificate, like a derived zone.

func JSONEquals added in v0.22.19

func JSONEquals(a, b interface{}) bool

JSONEquals reports whether two values serialize to identical JSON. Handy for change-detection where you want to ignore differences that don't survive a marshal round-trip (e.g. comparing a freshly-built struct against a cached one). JSON preserves slice/map-key order, so callers must normalize order-unstable slices (sort them) and zero out volatile fields they don't care about BEFORE calling. A marshal error makes the values compare unequal (fail-open: treat as "changed" rather than silently swallowing a real diff).

func LetsEncryptValidOnly

func LetsEncryptValidOnly(hostnames []string, acceptWildcard bool) []string

LetsEncryptValidOnly keeps the hostnames a public CA can certify (see letsEncryptable for the rule) and logs what it drops.

func ListInterfaces added in v0.18.0

func ListInterfaces(skipNebula bool) ([]string, error)

func ListIps added in v0.16.0

func ListIps(skipNebula bool) ([]string, error)

func LoadBaseMainConfig

func LoadBaseMainConfig(config Config)

func LocalCertGroups added in v0.24.0

func LocalCertGroups(config Config, hosts []string) map[string][]string

LocalCertGroups groups the hostnames of the server's own certificates by domain: one order per domain, so a hostname that fails validation only costs its own domain.

func LocalCertHostnames added in v0.24.0

func LocalCertHostnames(config Config, hosts []string) []string

LocalCertHostnames filters the hostnames this node must put in its own Let's Encrypt certificate: the ones of automatic zones, and of the Let's Encrypt zones without a DNS provider. Every other zone has a certificate of its own, serves another one, or none.

func LocalCertHostnamesNow added in v0.24.0

func LocalCertHostnamesNow(config Config) []string

LocalCertHostnamesNow is what this server has to certify by itself right now

func LocalCertZone added in v0.24.0

func LocalCertZone(config Config, host string) string

LocalCertZone names the certificate a hostname is served from among the ones this server gets by itself: its explicit zone, or the hostname itself for an automatic one.

func LocalCertsToIssue added in v0.24.0

func LocalCertsToIssue(config Config, hosts []string, force bool) map[string][]string

LocalCertsToIssue lists the domains whose certificate this server has to order: none yet, a hostname it does not cover, or expiring within 45 days. The single certificate of older versions keeps serving the domains it covers until then.

func Log

func Log(message string)

func LogReq added in v0.17.0

func LogReq(message string)

func LoggedInOnlyWithRedirect

func LoggedInOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error

func Logger added in v0.17.0

func Logger(next http.Handler) http.Handler

Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return. When standard output is a TTY, Logger will print in color, otherwise it will print in black and white. Logger prints a request ID if one is provided.

Alternatively, look at https://github.com/goware/httplog for a more in-depth http logger with structured logging support.

IMPORTANT NOTE: Logger should go before any other middleware that may change the response, such as middleware.Recoverer. Example:

r := chi.NewRouter()
r.Use(middleware.Logger)        // <--<< Logger should come before Recoverer
r.Use(middleware.Recoverer)
r.Get("/", handler)

func MajorError added in v0.12.0

func MajorError(message string, err error)

func MarkAsRead added in v0.12.0

func MarkAsRead(w http.ResponseWriter, req *http.Request)

MarkAsRead godoc @Summary Mark notifications as read @Tags Notifications @Produce json @Param ids query string true "Comma-separated list of notification ids" @Security BearerAuth @Success 200 {object} map[string]interface{} @Failure 400 {object} utils.HTTPErrorResult @Failure 403 {object} utils.HTTPErrorResult @Failure 404 {object} utils.HTTPErrorResult @Failure 500 {object} utils.HTTPErrorResult @Router /api/notifications/read [get]

func MarkNotificationsRead added in v0.23.0

func MarkNotificationsRead(recipient string, ids []int64) (int64, error)

MarkNotificationsRead flips the read flag on the recipient's own rows only.

func MarkOplogBootstrapped added in v0.23.0

func MarkOplogBootstrapped(epoch uint64) error

MarkOplogBootstrapped records that this node holds valid state for the epoch. Snapshot installs set it inside their own tx; this is for the founder-seed path.

func Max

func Max(x, y int) int

func MiddlewareTimeout

func MiddlewareTimeout(timeout time.Duration) func(next http.Handler) http.Handler

func MigrateToZones added in v0.24.0

func MigrateToZones(config *Config, manageRecords bool) bool

MigrateToZones moves the HTTPS setup a server used to hold for itself into zones: its DNS challenge provider, then its self-signed or provided mode. The install wizard and the older clients still fill those legacy fields, so this is also what turns their form into zones. Returns true when the config was changed.

func MillisToTime added in v0.23.0

func MillisToTime(ms int64) time.Time

func MonitoringDialect added in v0.23.0

func MonitoringDialect() string

MonitoringDialect reports which SQL dialect the store speaks.

func MonitoringNode added in v0.23.0

func MonitoringNode() string

MonitoringNode is the node column value for locally produced rows. Never empty: an empty node would recreate the multi-server collision the column exists to prevent.

func MonitoringReadDB added in v0.23.0

func MonitoringReadDB() (*sql.DB, error)

MonitoringReadDB returns the pooled reader handle.

func MonitoringRebind added in v0.23.0

func MonitoringRebind(query string) string

MonitoringRebind turns `?` placeholders into `$n` for Postgres. Queries in this package never contain a literal `?` outside a placeholder.

func MonitoringWriteDB added in v0.23.0

func MonitoringWriteDB() (*sql.DB, error)

MonitoringWriteDB returns the single-writer handle.

func NativePlatform added in v0.24.0

func NativePlatform() string

NativePlatform is the container platform of this host.

func NeedsLetsEncrypt added in v0.24.0

func NeedsLetsEncrypt(config Config) bool

NeedsLetsEncrypt reports whether this server orders certificates from Let's Encrypt

func NewACMEAccountKey added in v0.24.0

func NewACMEAccountKey() (*ecdsa.PrivateKey, string, error)

NewACMEAccountKey generates the key of an account to register, PEM encoded

func NormalizeOpFields added in v0.23.0

func NormalizeOpFields(table string, fields map[string]interface{}) (map[string]interface{}, error)

NormalizeOpFields converts a set-fields map to its DB representation, rejecting unknown field names before they ever reach the log.

func NormalizeOpFilter added in v0.23.0

func NormalizeOpFilter(table string, filter map[string]interface{}) (map[string]interface{}, error)

NormalizeOpFilter does the same for a filter's equality values.

func NotifGet added in v0.12.0

func NotifGet(w http.ResponseWriter, req *http.Request)

NotifGet godoc @Summary Get notifications for the authenticated user @Tags Notifications @Produce json @Param from query string false "Pagination cursor (notification id for older notifications)" @Security BearerAuth @Success 200 {object} map[string]interface{} @Failure 403 {object} utils.HTTPErrorResult @Failure 500 {object} utils.HTTPErrorResult @Router /api/notifications [get]

func NowMillis added in v0.23.0

func NowMillis() int64

func OnExit added in v0.24.0

func OnExit(hook func())

OnExit registers a cleanup to run when the process receives SIGTERM or SIGINT. The hooks run in the order they were registered, then the process exits.

func PermissionLabel added in v0.22.0

func PermissionLabel(p Permission) string

func PermissionsHaveSudo added in v0.22.0

func PermissionsHaveSudo(perms []Permission) bool

func PlanRestart added in v0.24.0

func PlanRestart()

PlanRestart marks that this node is draining ahead of a restart.

func ProcessLicence added in v0.21.0

func ProcessLicence()

func PublicCORS added in v0.12.0

func PublicCORS(next http.Handler) http.Handler

func PublicTLD added in v0.24.0

func PublicTLD(host string) bool

PublicTLD reports whether the last label of a hostname is a top-level domain a public CA will issue under: one in the ICANN section of the public suffix list. Ports are ignored; a trailing dot is tolerated.

func RawLogMessage added in v0.17.0

func RawLogMessage(level LogLevel, prefix, prefixColor, color, message string)

func ReformOplogEpoch added in v0.23.0

func ReformOplogEpoch() (uint64, error)

ReformOplogEpoch re-enters formation on this node in ONE tx: the epoch moves past anything the old cluster can publish (its subjects match no stream), the sequence restarts, the bootstrapped marker is dropped so peers must re-materialize, and this node takes the formation write licence.

func RemoveManagedRoutes added in v0.24.0

func RemoveManagedRoutes(kind, name string) int

RemoveManagedRoutes withdraws every route owned by kind+name. A missing route is not an error — a delete retried after a partial teardown must be able to finish. Returns the number of routes removed.

func RemoveStringFromSlice added in v0.16.0

func RemoveStringFromSlice(slice []string, s string) []string

func RequestLogger added in v0.17.0

func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler

RequestLogger returns a logger handler using a custom LogFormatter.

func ResetIPAbuseCounter added in v0.24.0

func ResetIPAbuseCounter(ip string)

ResetIPAbuseCounter clears the counter that drops TCP/UDP connections outright once an IP has been blocked too often; unban must clear it too.

func RestartPlanned added in v0.24.0

func RestartPlanned() bool

RestartPlanned reports whether a restart is waiting on this node.

func RestartServer

func RestartServer(code int)

func Restrictions added in v0.10.0

func Restrictions(RestrictToConstellation bool, WhitelistInboundIPs []string) func(next http.Handler) http.Handler

func RoleHasSudoPermissions added in v0.22.0

func RoleHasSudoPermissions(role Role) bool

func RunDatabaseRetention added in v0.23.0

func RunDatabaseRetention()

RunDatabaseRetention prunes expired metric buckets and month-old events and notifications. Wired to the daily maintenance cron.

func SPAHandler added in v0.15.0

func SPAHandler(targetFolder string) http.Handler

func Sanitize

func Sanitize(s string) string

func SanitizeNoSpace added in v0.18.0

func SanitizeNoSpace(s string) string

func SanitizeSafe

func SanitizeSafe(s string) string

func SaveACMEAccount added in v0.24.0

func SaveACMEAccount(account ACMEAccount) error

SaveACMEAccount writes the account for the next orders to reuse

func SaveConfigTofile

func SaveConfigTofile(config Config)

func SelfSignedHostnames added in v0.24.1

func SelfSignedHostnames(config Config, hosts []string) []string

SelfSignedHostnames is what the self-signed certificate names: wildcard zones collapsed like their zone certificate, so it does not list every subdomain.

func SendEmail

func SendEmail(recipients []string, subject string, body string) error

func ServerHTTPSDisabled added in v0.24.0

func ServerHTTPSDisabled(http HTTPConfig) bool

ServerHTTPSDisabled reports that this server serves plain HTTP only. It is the one HTTPS setting a server keeps for itself (HTTPConfig.HTTPSCertificateMode DISABLED, or never set up): it is the only one a hostname without a domain, such as an IP, can carry.

func ServesSelfSigned added in v0.24.0

func ServesSelfSigned() bool

ServesSelfSigned reports whether the server's own hostname is served with a certificate no client trusts on its own

func SetBaseMainConfig

func SetBaseMainConfig(config Config)

func SetCORSHeaders added in v0.24.0

func SetCORSHeaders(w http.ResponseWriter, r *http.Request, allowed string)

SetCORSHeaders writes the CORS answer for a request, given the allowed origins (comma or space separated). "*" allows every origin without credentials: browsers refuse "*" together with Allow-Credentials, so the two are never sent together. Any other list is matched against the request's Origin: the matched origin is echoed with credentials allowed, and Vary: Origin keeps caches from serving it to another origin. An entry can be a full origin ("https://app.example.com") or a bare host ("app.example.com", "app.example.com:8443"), which then matches any scheme.

func SetCosmosHeader added in v0.20.0

func SetCosmosHeader(next http.Handler) http.Handler

func SetFileLastModifiedTime added in v0.21.0

func SetFileLastModifiedTime(path string, modTime int64) error

func SetFormationWriter added in v0.23.0

func SetFormationWriter(epoch uint64) error

SetFormationWriter grants the formation write licence for an epoch.

func SetOplogState added in v0.23.0

func SetOplogState(epoch uint64, seq uint64) error

SetOplogState overwrites (epoch, seq) and CLEARS the bootstrapped marker; used by reform, which deliberately makes the node re-materialize at the new epoch.

func SetPublishOpHook added in v0.23.0

func SetPublishOpHook(h func(Mutation) error)

SetPublishOpHook wires the op-log publisher; nil restores direct writes.

func SetSecurityHeaders

func SetSecurityHeaders(next http.Handler) http.Handler

func ShieldBypassesGeo added in v0.24.0

func ShieldBypassesGeo(ip string) bool

func ShieldBypassesIPRestriction added in v0.24.0

func ShieldBypassesIPRestriction(ip string) bool

func SoftRestartServer added in v0.21.0

func SoftRestartServer()

func SplitIP added in v0.16.0

func SplitIP(ipPort string) (string, string)

func StringArrayContains

func StringArrayContains(a []string, b string) bool

func StringArrayEquals

func StringArrayEquals(a []string, b []string) bool

func TimeToMillis added in v0.23.0

func TimeToMillis(t time.Time) int64

Timestamps are stored as INTEGER unix milliseconds everywhere to avoid dialect drift.

func TranslateEventFilter added in v0.23.0

func TranslateEventFilter(dialect string, filter map[string]interface{}) (string, []interface{}, error)

TranslateEventFilter turns the Mongo-ish JSON filter the UI sends into a parameterized WHERE fragment. Values are never interpolated; unsupported operators are an error so the caller can answer 400 instead of silently dropping the filter.

func TriggerEvent added in v0.12.0

func TriggerEvent(eventId string, label string, level string, object string, data map[string]interface{})

func UpdateDevices added in v0.23.0

func UpdateDevices(filter map[string]interface{}, fields map[string]interface{}) error

UpdateDevices sets the given bson-named fields on all devices matching the filter.

func UpdateUser added in v0.23.0

func UpdateUser(nickname string, fields map[string]interface{}) error

UpdateUser sets the given bson-named fields on the user row.

func UseConstellationDNSOnHost added in v0.24.0

func UseConstellationDNSOnHost() bool

UseConstellationDNSOnHost reports whether this server resolves its own lookups through the Constellation DNS, so that it reaches the registries and services of the cluster by their names like any Constellation device. Defaults to the edition: on for Pro, off for the community edition. Never inside a container, which cannot reach the resolver of its host.

func VPN added in v0.17.0

func VPN(message string)

func VPNWithLevel added in v0.20.0

func VPNWithLevel(line string)

VPNWithLevel parses Nebula log lines (which contain level=info/debug/warning/error) and logs them at level-1 (so info lines only show if log level is DEBUG)

func ValidateDNSFallback added in v0.24.0

func ValidateDNSFallback(fallback string) error

ValidateDNSFallback rejects the stub of systemd-resolved as a fallback: a server that resolves through the Constellation DNS would send it its own lookups back, in a loop.

func ValidateManagedBy added in v0.24.0

func ValidateManagedBy(route ProxyRouteConfig) error

ValidateManagedBy checks the owner pair a route carries: either both empty, or a known kind with a non-empty name.

func ValidateRolesChange added in v0.23.2

func ValidateRolesChange(req *http.Request, prev, next map[Role]RoleConfig) error

ValidateRolesChange enforces grant rules for a roles-matrix update

func Values added in v0.15.0

func Values[M ~map[K]V, K comparable, V any](m M) []V

func Warn

func Warn(message string)

func WildcardToLike added in v0.23.0

func WildcardToLike(pattern string) string

WildcardToLike translates a metric key wildcard ("a.b.*") into a LIKE pattern. Matching is prefix-anchored, the same as the regex it replaces.

func WithLogEntry added in v0.17.0

func WithLogEntry(r *http.Request, entry LogEntry) *http.Request

WithLogEntry sets the in-context LogEntry for a request.

func WriteNotification added in v0.12.0

func WriteNotification(notification Notification)

func ZoneCertCovers added in v0.24.0

func ZoneCertCovers(cert ZoneCert, wanted []string) bool

ZoneCertCovers reports whether the certificate serves every wanted hostname

func ZoneCertHostnames added in v0.24.0

func ZoneCertHostnames(zone DNSZoneConfig, hosts []string) []string

ZoneCertHostnames is what the certificate of a zone must cover given the hostnames filed under it: the wildcard pair plus anything deeper than one level, or just the hostnames.

func ZoneCertsToIssue added in v0.24.0

func ZoneCertsToIssue(config Config, force bool) map[string][]string

ZoneCertsToIssue lists the explicit zones whose certificate is missing, expiring or not covering their hostnames anymore, with what it must cover.

Types

type ACMEAccount added in v0.24.0

type ACMEAccount struct {
	// Directory is the CA the account was registered at: a staging account
	// is no use against production, and the other way round.
	Directory string `json:"directory"`
	URL       string `json:"url"`
	Email     string `json:"email"`
	// Key is the account's private key, PEM encoded.
	Key string `json:"key"`
}

func LoadACMEAccount added in v0.24.0

func LoadACMEAccount(directory string) *ACMEAccount

LoadACMEAccount returns the account registered at the directory, nil when there is none yet (or it belongs to another CA).

func (ACMEAccount) PrivateKey added in v0.24.0

func (a ACMEAccount) PrivateKey() (*ecdsa.PrivateKey, error)

type APIResponse added in v0.22.0

type APIResponse struct {
	Status string      `json:"status" example:"OK"`
	Data   interface{} `json:"data,omitempty"`
}

APIResponse is the standard success response wrapper used by all endpoints.

type APIResponseMessage added in v0.22.0

type APIResponseMessage struct {
	Status  string `json:"status" example:"OK"`
	Message string `json:"message,omitempty"`
}

APIResponseMessage is used when only status and message are returned.

type APITokenConfig added in v0.22.0

type APITokenConfig struct {
	Name                    string       `json:"name"`
	Description             string       `json:"description,omitempty"`
	Owner                   string       `json:"owner,omitempty"`
	TokenHash               string       `json:"tokenHash"`
	TokenSuffix             string       `json:"tokenSuffix,omitempty"`
	Permissions             []Permission `json:"permissions"`
	IPWhitelist             []string     `json:"ipWhitelist,omitempty"`
	RestrictToConstellation bool         `json:"restrictToConstellation"`
	CreatedAt               time.Time    `json:"createdAt"`
	ExpiresAt               time.Time    `json:"expiresAt,omitempty"`
}

func VerifyAPIToken added in v0.24.0

func VerifyAPIToken(rawToken string) (string, APITokenConfig, bool)

VerifyAPIToken returns the name and config of the configured token matching rawToken (constant-time hash comparison). Expiry, IP restrictions and permissions are NOT checked here.

type APITokenContext added in v0.22.0

type APITokenContext struct {
	Name        string
	Owner       string
	Permissions []Permission
}

type AddionalFiltersConfig added in v0.9.9

type AddionalFiltersConfig struct {
	Type  string `yaml:"type"`
	Name  string `yaml:"name"`
	Value string `yaml:"value"`
}

type Alert added in v0.12.0

type Alert struct {
	Name           string `validate:"required"`
	Enabled        bool
	Period         string
	TrackingMetric string
	Condition      AlertCondition
	Actions        []AlertAction
	LastTriggered  time.Time
	Throttled      bool
	Severity       string
}

type AlertAction added in v0.12.0

type AlertAction struct {
	Type   string
	Target string
}

type AlertCondition added in v0.12.0

type AlertCondition struct {
	Operator string
	Value    int
	Percent  bool
}

type AlertMetricTrack added in v0.12.0

type AlertMetricTrack struct {
	Key    string
	Object string
	Max    uint64
}

type AuthContext added in v0.22.0

type AuthContext struct {
	Nickname    string
	Role        Role
	UserRole    Role
	Permissions []Permission
	IsSudoed    bool
	MFAState    int
	APIToken    *APITokenContext
}

func GetAuthContext added in v0.22.0

func GetAuthContext(req *http.Request) *AuthContext

type BackupConfig added in v0.18.0

type BackupConfig struct {
	Disable bool
	Backups map[string]SingleBackupConfig
}

type CAConfig added in v0.18.0

type CAConfig struct {
	Certificate *x509.Certificate
	PrivateKey  *rsa.PrivateKey
}

type CRONConfig added in v0.15.0

type CRONConfig struct {
	Enabled   bool
	Name      string `validate:"required"`
	Crontab   string
	Command   string
	Container string
}

type CertUser

type CertUser struct {
	Email        string
	Registration *acme.ExtendedAccount
	// contains filtered or unexported fields
}

func (*CertUser) GetEmail

func (u *CertUser) GetEmail() string

func (*CertUser) GetPrivateKey

func (u *CertUser) GetPrivateKey() crypto.Signer

func (CertUser) GetRegistration

func (u CertUser) GetRegistration() *acme.ExtendedAccount

type Config

type Config struct {
	LoggingLevel                LoggingLevel   `required,validate:"oneof=DEBUG INFO WARNING ERROR"`
	Database                    DatabaseConfig ``
	DisableUserManagement       bool
	NewInstall                  bool        `validate:"boolean"`
	HTTPConfig                  HTTPConfig  `validate:"required"`
	EmailConfig                 EmailConfig `validate:"required"`
	DockerConfig                DockerConfig
	BlockedCountries            []string
	CountryBlacklistIsWhitelist bool
	ShieldWhitelist             []ShieldWhitelistEntry
	ServerCountry               string
	RequireMFA                  bool
	AutoUpdate                  bool
	BetaUpdates                 bool
	OpenIDClients               []OpenIDClient
	MarketConfig                MarketConfig
	HomepageConfig              HomepageConfig
	ThemeConfig                 ThemeConfig
	ConstellationConfig         ConstellationConfig
	MonitoringDisabled          bool
	MonitoringAlerts            map[string]Alert
	BackupOutputDir             string
	IncrBackupOutputDir         string
	DisableHostModeWarning      bool
	AdminWhitelistIPs           []string
	AdminConstellationOnly      bool
	Storage                     StorageConfig
	CRON                        map[string]CRONConfig
	Licence                     string
	ServerToken                 string
	AgentMode                   bool
	RemoteStorage               RemoteStorageConfig
	DisableOpenIDDirect         bool
	Backup                      BackupConfig
	Mpdu_                       string
	Mpdn_                       string
	APITokens                   map[string]APITokenConfig `json:"APITokens,omitempty"`
	Roles                       map[Role]RoleConfig       `json:"Roles,omitempty"`
}

func GetBaseMainConfig

func GetBaseMainConfig() Config

func GetMainConfig

func GetMainConfig() Config

func ReadConfigFromFile

func ReadConfigFromFile() Config

type ConstellationConfig added in v0.10.0

type ConstellationConfig struct {
	Enabled bool
	// ClusterDomain is the domain servers joining with a constellation file get
	// their hostname under (<device>.<domain>). Empty: the zone of this server's hostname.
	ClusterDomain  string `json:"ClusterDomain,omitempty"`
	DoNotSyncNodes bool
	DNSDisabled    bool
	// DoNotUseConstellationDNSOnHost keeps the resolver of this server as it is.
	// Unset, the server uses the Constellation DNS on Pro and keeps its own
	// resolver on the community edition (see UseConstellationDNSOnHost).
	DoNotUseConstellationDNSOnHost  *bool `json:"DoNotUseConstellationDNSOnHost,omitempty"`
	DNSPort                         string
	DNSFallback                     string
	DNSBlockBlacklist               bool
	DNSAdditionalBlocklists         []string
	CustomDNSEntries                []ConstellationDNSEntry
	Tunnels                         []ProxyRouteConfig
	FirewallBlockedClients          []string `json:"FirewallBlockedClients" bson:"FirewallBlockedClients"`
	OverrideNebulaExitNodeInterface string
	ThisDeviceName                  string
	ConstellationHostname           string
	IPRange                         string
	NATSReplicas                    int `json:"NATSReplicas,omitempty"`
}

type ConstellationDNSEntry added in v0.10.0

type ConstellationDNSEntry struct {
	Type  string
	Key   string `validate:"required"`
	Value string
}

type ConstellationDevice added in v0.10.0

type ConstellationDevice struct {
	Nickname   string `json:"nickname" bson:"Nickname"`
	DeviceName string `json:"deviceName" bson:"DeviceName"`
	// legacy field: used to hold the device private key, never expose it
	PublicKey      string `json:"-" bson:"PublicKey"`
	IP             string `json:"ip" bson:"IP"`
	IsLighthouse   bool   `json:"isLighthouse" bson:"IsLighthouse"`
	CosmosNode     int    `json:"cosmosNode" bson:"CosmosNode"`
	IsRelay        bool   `json:"isRelay" bson:"IsRelay"`
	IsLoadBalancer bool   `json:"isLoadBalancer" bson:"IsLoadBalancer"`
	IsExitNode     bool   `json:"isExitNode" bson:"IsExitNode"`
	PublicHostname string `json:"publicHostname" bson:"PublicHostname"`
	Port           string `json:"port" bson:"Port"`
	Blocked        bool   `json:"blocked" bson:"Blocked"`
	Fingerprint    string `json:"fingerprint" 	bson:"Fingerprint"`
	APIKey         string `json:"-" bson:"APIKey"`
	Invisible      bool   `json:"invisible" bson:"Invisible"`
	// Tags are free-form labels assigned to this device. Deployments with a
	// matching Tags selector will only land on devices whose Tags contain
	// every requested tag (AND semantics). Used by the scheduler's placement
	// filter — see src/pro/scheduler.go.
	Tags []string `json:"tags,omitempty" bson:"Tags,omitempty"`
}

func FindDevices added in v0.23.0

func FindDevices(filter map[string]interface{}) ([]ConstellationDevice, error)

FindDevices returns devices matching a flat equality filter with bson field names.

func GetDeviceByIP added in v0.23.0

func GetDeviceByIP(ip string) (ConstellationDevice, error)

GetDeviceByIP returns the active (non-blocked) device holding this IP.

func GetDeviceByName added in v0.23.0

func GetDeviceByName(name string, mustBeActive bool) (ConstellationDevice, error)

GetDeviceByName returns one device by name (active only when mustBeActive); on any error it returns a zero-value struct, never partial data.

func ListDevices added in v0.23.0

func ListDevices(includeBlocked bool) ([]ConstellationDevice, error)

type ConstellationTunnel added in v0.21.0

type ConstellationTunnel struct {
	Route   ProxyRouteConfig
	Targets []TunnelTarget
}

type DNSZoneConfig added in v0.24.0

type DNSZoneConfig struct {
	Zone string `validate:"required,excludesall=0x2C/ "`

	// HTTPS setup. The mode is LETSENCRYPT, SELFSIGNED, PROVIDED (the
	// certificate below) or DISABLED (the hostnames are served over plain HTTP).
	// The zone decides alone: no server has an HTTPS mode of its own to
	// override it, only the choice of not serving HTTPS at all.
	HTTPSCertificateMode        string
	TLSCert                     string `json:"TLSCert,omitempty"`
	TLSKey                      string `json:"TLSKey,omitempty"`
	UseWildcardCertificate      bool
	DNSChallengeProvider        string
	DNSChallengeConfig          map[string]string `json:"DNSChallengeConfig,omitempty"`
	DNSChallengeResolvers       string
	DNSChallengePropagationWait int
	DisablePropagationChecks    bool

	// DynDNS setup, needs a DNSChallengeProvider
	ManageRecords  bool
	WildcardRecord bool
}

DNSZoneConfig is an explicit zone: a domain with its HTTPS setup and its DynDNS setup. Hostnames no explicit zone covers get a derived zone of their own at runtime (see ResolveZones), which is never stored.

type DatabaseConfig added in v0.14.0

type DatabaseConfig struct {
	PostgresHost     string // "host" or "host:port"
	PostgresDatabase string
	PostgresUsername string
	PostgresPassword string
	NodeName         string // overrides the node column on metrics rows
}

DatabaseConfig points the monitoring store at Postgres; empty PostgresHost keeps SQLite. The Postgres* prefix is deliberate: pre-0.23 configs carry Hostname/Username/Password from the Mongo era and must not unmarshal into these fields.

type DefaultLogFormatter added in v0.17.0

type DefaultLogFormatter struct {
	Logger  LoggerInterface
	NoColor bool
}

DefaultLogFormatter is a simple logger that implements a LogFormatter.

func (*DefaultLogFormatter) NewLogEntry added in v0.17.0

func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry

NewLogEntry creates a new LogEntry for the request.

type Device added in v0.10.0

type Device struct {
	DeviceName string `json:"deviceName" validate:"required,min=3,max=32,alphanum" bson:"DeviceName"`
	Nickname   string `json:"nickname" validate:"required,min=3,max=32,alphanum" bson:"Nickname"`
	PublicKey  string `json:"publicKey,omitempty" bson:"PublicKey"`
	PrivateKey string `json:"privateKey,omitempty" bson:"PrivateKey"`
	IP         string `json:"ip" validate:"required,ipv4" bson:"IP"`
}

type DiskStatus

type DiskStatus struct {
	Path       string
	TotalBytes uint64
	UsedBytes  uint64
}

func GetDiskUsage

func GetDiskUsage() []DiskStatus

type DockerConfig

type DockerConfig struct {
	SkipPruneNetwork bool
	SkipPruneImages  bool
	DefaultDataPath  string
}

type EmailConfig

type EmailConfig struct {
	Enabled          bool
	Host             string
	Port             string
	Username         string
	Password         string
	From             string
	UseTLS           bool
	AllowInsecureTLS bool
	NotifyLogin      bool
}

type ErrConstraint added in v0.23.0

type ErrConstraint struct {
	Table string
	Index string
}

ErrConstraint is returned when a unique index rejects a write.

func (*ErrConstraint) Error added in v0.23.0

func (e *ErrConstraint) Error() string

type Event added in v0.23.0

type Event struct {
	Id          int64                  `json:"id"`
	Label       string                 `json:"label"`
	Application string                 `json:"application"`
	EventId     string                 `json:"eventId"`
	Date        time.Time              `json:"date"`
	Level       string                 `json:"level"`
	Data        map[string]interface{} `json:"data"`
	Object      string                 `json:"object"`
}

Event is the wire shape the events explorer consumes. Id replaced the Mongo ObjectID; the client treats it as an opaque pagination cursor.

func QueryEvents added in v0.23.0

func QueryEvents(q EventQuery) ([]Event, int64, error)

QueryEvents returns one page of events plus the total matching count. Reads are deliberately not node-scoped: on a shared Postgres, cross-node visibility is the point.

type EventQuery added in v0.23.0

type EventQuery struct {
	From   time.Time
	To     time.Time
	Levels []string
	Search string
	Filter map[string]interface{}
	Cursor int64
	Limit  int
}

EventQuery is the parsed form of the events explorer request.

type FileStats

type FileStats struct {
	Name    string      `json:"name"`
	Path    string      `json:"path"`
	Size    int64       `json:"size"`
	Mode    os.FileMode `json:"mode"`
	ModTime time.Time   `json:"modTime"`
	IsDir   bool        `json:"isDir"`
}

type FirebaseApiSdk added in v0.16.0

type FirebaseApiSdk struct {
	BaseURL          string
	LValid           bool
	ServerToken      string
	UserNumber       int
	CosmosNodeNumber int
	AgentMode        bool
}
var FBL *FirebaseApiSdk

func NewFirebaseApiSdk added in v0.16.0

func NewFirebaseApiSdk(baseURL string) *FirebaseApiSdk

func (*FirebaseApiSdk) CreateClientLicense added in v0.16.0

func (sdk *FirebaseApiSdk) CreateClientLicense(clientID string) (string, error)

func (*FirebaseApiSdk) RenewLicense added in v0.16.0

func (sdk *FirebaseApiSdk) RenewLicense(oldToken string) (string, int, error)

type HTTPConfig

type HTTPConfig struct {
	CACert                string
	CAPrivateKey          string
	TLSCert               string `validate:"omitempty,contains=\n`
	TLSKey                string
	TLSKeyHostsCached     []string
	TLSValidUntil         time.Time
	SelfTLSCert           string `validate:"omitempty,contains=\n`
	SelfTLSKey            string
	SelfTLSKeyHostsCached []string
	SelfTLSValidUntil     time.Time
	AuthPrivateKey        string
	AuthPublicKey         string
	// OIDCSigningKey signs the OpenID tokens, one for the whole cluster
	OIDCSigningKey               string `json:"OIDCSigningKey,omitempty"`
	OIDCSigningKeyShared         bool   `json:"OIDCSigningKeyShared,omitempty"`
	GenerateMissingAuthCert      bool
	HTTPSCertificateMode         string
	DNSChallengeProvider         string
	DisablePropagationChecks     bool
	DNSChallengePropagationWait  int
	ForceHTTPSCertificateRenewal bool
	HTTPPort                     string `validate:"required,containsany=0123456789,min=1,max=6"`
	HTTPSPort                    string `validate:"required,containsany=0123456789,min=1,max=6"`
	ProxyConfig                  ProxyConfig
	Hostname                     string `validate:"required,excludesall=0x2C/ "`
	AllowHTTPLocalIPAccess       bool   `validate:"omitempty"`
	// SSLEmail is the contact of the Let's Encrypt certificates. One for the
	// whole cluster, whichever server issues: SSLEmailShared is set once the
	// cluster's value was received, a server's own one from before is offered
	// to the cluster until then.
	SSLEmail                  string `validate:"omitempty,email"`
	SSLEmailShared            bool   `json:"SSLEmailShared,omitempty"`
	UseWildcardCertificate    bool
	OverrideWildcardDomains   string `validate:"omitempty,excludesall=/ "`
	AcceptAllInsecureHostname bool
	DNSChallengeConfig        map[string]string `json:"DNSChallengeConfig,omitempty"`
	DNSChallengeResolvers     string
	DNSZones                  []DNSZoneConfig     `json:"DNSZones,omitempty"`
	ZoneCerts                 map[string]ZoneCert `json:"ZoneCerts,omitempty"`
	// LocalCerts are the certificates this server gets by itself over HTTP-01,
	// one per domain, keyed by LocalCertZone. Never shared: each server
	// validates its own hostnames.
	LocalCerts map[string]ZoneCert `json:"LocalCerts,omitempty"`
	// AdvertisedAddress is what the DNS records of this node point at: empty for
	// the detected public IP, "iface:<name>" for a network interface, or an IPv4
	AdvertisedAddress string `json:"AdvertisedAddress,omitempty"`
	UseForwardedFor   bool
	AllowSearchEngine bool
	PublishMDNS       bool
	TrustedProxies    []string
}

type HTTPErrorResult

type HTTPErrorResult struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Code    string `json:"code"`
}

type HomepageConfig

type HomepageConfig struct {
	Background string
	Widgets    []string
	Expanded   bool
}

type HostCertificate added in v0.24.0

type HostCertificate struct {
	// Source is "zone", "node" (this node's own Let's Encrypt certificate),
	// "selfsigned", "provided" or "none" (HTTPS disabled)
	Source     string    `json:"source"`
	Zone       string    `json:"zone,omitempty"`
	Hosts      []string  `json:"hosts"`
	ValidUntil time.Time `json:"validUntil"`
	// Covered is false when the certificate served does not list the hostname
	Covered bool `json:"covered"`
	// PEM is the certificate itself, kept out of the zones listing
	PEM string `json:"-"`
}

HostCertificate describes the certificate a hostname is served with, for display.

func GetHostCertificate added in v0.24.0

func GetHostCertificate(config Config, host string) HostCertificate

GetHostCertificate mirrors the choice the TLS handshake makes for a hostname

type LocationRemoteStorageConfig added in v0.17.0

type LocationRemoteStorageConfig struct {
	Name     string
	Protocol string
	Target   string
	Source   string
	Route    ProxyRouteConfig
	Settings map[string]string
}

type LogEntry added in v0.17.0

type LogEntry interface {
	Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
	Panic(v interface{}, stack []byte)
}

LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation.

func GetLogEntry added in v0.17.0

func GetLogEntry(r *http.Request) LogEntry

GetLogEntry returns the in-context LogEntry for a request.

type LogFormatter added in v0.17.0

type LogFormatter interface {
	NewLogEntry(r *http.Request) LogEntry
}

LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.

type LogLevel added in v0.17.0

type LogLevel int
const (
	DEBUG LogLevel = iota
	INFO
	WARNING
	ERROR
	FATAL
)

type LoggerInterface added in v0.17.0

type LoggerInterface interface {
	Print(v ...interface{})
}

LoggerInterface accepts printing to stdlib logger or compatible logger.

type LoggingLevel

type LoggingLevel string

type MarketConfig

type MarketConfig struct {
	Sources []MarketSource
}

type MarketSource

type MarketSource struct {
	Name string
	Url  string
}

type Mutation added in v0.23.0

type Mutation struct {
	Table      string
	Op         string // insert|insertMany|update|updateMany|delete|deleteMany
	Filter     map[string]interface{}
	Doc        interface{}
	BestEffort bool // LastLogin only
}

Mutation is the single write descriptor; Filter/Doc keys use bson field names.

type MyUser

type MyUser struct {
	Email        string
	Registration *acme.ExtendedAccount
	// contains filtered or unexported fields
}

You'll need a user or account type that implements acme.User

func (*MyUser) GetEmail

func (u *MyUser) GetEmail() string

func (*MyUser) GetPrivateKey

func (u *MyUser) GetPrivateKey() crypto.Signer

func (MyUser) GetRegistration

func (u MyUser) GetRegistration() *acme.ExtendedAccount

type NebulaConfig added in v0.10.0

type NebulaConfig struct {
	PKI struct {
		CA        string   `yaml:"ca"`
		Cert      string   `yaml:"cert"`
		Key       string   `yaml:"key"`
		Blocklist []string `yaml:"blocklist"`
	} `yaml:"pki"`

	StaticHostMap map[string][]string `yaml:"static_host_map"`

	Lighthouse struct {
		AMLighthouse bool     `yaml:"am_lighthouse"`
		Interval     int      `yaml:"interval"`
		Hosts        []string `yaml:"hosts"`
	} `yaml:"lighthouse"`

	Listen struct {
		Host string `yaml:"host"`
		Port int    `yaml:"port"`
	} `yaml:"listen"`

	Punchy struct {
		Punch   bool `yaml:"punch"`
		Respond bool `yaml:"respond"`
	} `yaml:"punchy"`

	Relay struct {
		AMRelay   bool     `yaml:"am_relay"`
		UseRelays bool     `yaml:"use_relays"`
		Relays    []string `yaml:"relays"`
	} `yaml:"relay"`

	TUN struct {
		Disabled           bool     `yaml:"disabled"`
		Dev                string   `yaml:"dev"`
		DropLocalBroadcast bool     `yaml:"drop_local_broadcast"`
		DropMulticast      bool     `yaml:"drop_multicast"`
		TxQueue            int      `yaml:"tx_queue"`
		MTU                int      `yaml:"mtu"`
		Routes             []string `yaml:"routes"`
		UnsafeRoutes       []string `yaml:"unsafe_routes"`
	} `yaml:"tun"`

	Logging struct {
		Level  string `yaml:"level"`
		Format string `yaml:"format"`
	} `yaml:"logging"`

	Firewall struct {
		OutboundAction string                `yaml:"outbound_action"`
		InboundAction  string                `yaml:"inbound_action"`
		Conntrack      NebulaConntrackConfig `yaml:"conntrack"`
		Outbound       []NebulaFirewallRule  `yaml:"outbound"`
		Inbound        []NebulaFirewallRule  `yaml:"inbound"`
	} `yaml:"firewall"`
}

type NebulaConntrackConfig added in v0.10.0

type NebulaConntrackConfig struct {
	TCPTimeout     string `yaml:"tcp_timeout"`
	UDPTimeout     string `yaml:"udp_timeout"`
	DefaultTimeout string `yaml:"default_timeout"`
}

type NebulaFirewallRule added in v0.10.0

type NebulaFirewallRule struct {
	Port   string   `yaml:"port"`
	Proto  string   `yaml:"proto"`
	Host   string   `yaml:"host"`
	Groups []string `yaml:"groups,omitempty"`
}

type NetworkStatus

type NetworkStatus struct {
	BytesSent uint64
	BytesRecv uint64
}

func GetNetworkUsage

func GetNetworkUsage() NetworkStatus

type Notification added in v0.12.0

type Notification struct {
	ID        int64
	Title     string
	Message   string
	Vars      string
	Icon      string
	Link      string
	Date      time.Time
	Level     string
	Read      bool
	Recipient string
	Actions   []NotificationActions
}

func ListNotifications added in v0.23.0

func ListNotifications(recipient string, cursor int64, limit int) ([]Notification, error)

ListNotifications returns a recipient's newest notifications, keyset-paginated on id. Not node-scoped: a shared Postgres should surface every node's notifications.

type NotificationActions added in v0.12.0

type NotificationActions struct {
	Text string
	Link string
}

type OpenIDClient

type OpenIDClient struct {
	ID       string `json:"id" validate:"required"`
	Secret   string `json:"secret"`
	Redirect string `json:"redirect"`
	Public   bool   `json:"public"`
}

type Permission added in v0.22.0

type Permission int
const (
	PERM_ADMIN_READ Permission = 1 // View logs
	PERM_ADMIN      Permission = 2 // System ops: restart, shutdown, update, terminal

	PERM_USERS_READ Permission = 10 // View user list/details
	PERM_USERS      Permission = 11 // Create, delete, edit users, 2FA reset

	PERM_RESOURCES_READ Permission = 20 // View containers, storage, devices, backups, cron, metrics
	PERM_RESOURCES      Permission = 21 // Manage containers, storage, devices, backups, cron

	PERM_CONFIGURATION_READ Permission = 30 // View config
	PERM_CONFIGURATION      Permission = 31 // Set/patch config, DNS

	PERM_CREDENTIALS_READ Permission = 40 // View credentials (env vars, passwords, secrets)

	PERM_LOGIN      Permission = 100 // Any logged-in user, MFA required
	PERM_LOGIN_WEAK Permission = 101 // Any logged-in user, no MFA check
)

func GetRolePermissions added in v0.22.0

func GetRolePermissions(role Role) []Permission

func MissingGrants added in v0.23.2

func MissingGrants(req *http.Request, perms []Permission) []Permission

MissingGrants returns the permissions in perms the caller cannot grant

func NewlyGrantedPermissions added in v0.23.2

func NewlyGrantedPermissions(prev, next map[Role]RoleConfig) []Permission

NewlyGrantedPermissions lists permissions next grants that prev did not

type ProcessTracker added in v0.24.0

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

ProcessTracker counts long-running jobs (CRON jobs, CI builds) a restart has to wait for. WaitForZero blocks every caller until the count is zero.

func NewProcessTracker added in v0.24.0

func NewProcessTracker() *ProcessTracker

func (*ProcessTracker) Count added in v0.24.0

func (pt *ProcessTracker) Count() int

Count is the number of jobs currently registered.

func (*ProcessTracker) EndProcess added in v0.24.0

func (pt *ProcessTracker) EndProcess()

func (*ProcessTracker) StartProcess added in v0.24.0

func (pt *ProcessTracker) StartProcess()

func (*ProcessTracker) WaitForZero added in v0.24.0

func (pt *ProcessTracker) WaitForZero()

WaitForZero blocks until no job is registered. Safe for several waiters.

type ProxyConfig

type ProxyConfig struct {
	Routes []ProxyRouteConfig
}

type ProxyMode

type ProxyMode string

type ProxyRouteConfig

type ProxyRouteConfig struct {
	Disabled                  bool                    `yaml:"disabled"`
	Name                      string                  `yaml:"name" validate:"required"`
	Description               string                  `yaml:"description,omitempty"`
	UseHost                   bool                    `yaml:"use_host"`
	Host                      string                  `yaml:"host,omitempty"`
	UsePathPrefix             bool                    `yaml:"use_path_prefix"`
	PathPrefix                string                  `yaml:"path_prefix,omitempty"`
	Timeout                   time.Duration           `yaml:"timeout"`
	ThrottlePerMinute         int                     `yaml:"throttle_per_minute"`
	CORSOrigin                string                  `yaml:"cors_origin,omitempty"`
	StripPathPrefix           bool                    `yaml:"strip_path_prefix"`
	MaxBandwith               int64                   `yaml:"max_bandwidth"`
	AuthEnabled               bool                    `yaml:"auth_enabled"`
	AdminOnly                 bool                    `yaml:"admin_only"`
	PublicOpenIDRedirectURIs  string                  `yaml:"public_openid_redirect_uris,omitempty"`
	PublicOpenIDName          string                  `yaml:"public_openid_name,omitempty"`
	Target                    string                  `yaml:"target" validate:"required"`
	SmartShield               SmartShieldPolicy       `yaml:"smart_shield"`
	Mode                      ProxyMode               `yaml:"mode"`
	BlockCommonBots           bool                    `yaml:"block_common_bots"`
	BlockAPIAbuse             bool                    `yaml:"block_api_abuse"`
	AcceptInsecureHTTPSTarget bool                    `yaml:"accept_insecure_https_target"`
	HideFromDashboard         bool                    `yaml:"hide_from_dashboard"`
	DisableHeaderHardening    bool                    `yaml:"disable_header_hardening"`
	SpoofHostname             bool                    `yaml:"spoof_hostname"`
	AddionalFilters           []AddionalFiltersConfig `yaml:"additional_filters,omitempty"`
	RestrictToConstellation   bool                    `yaml:"restrict_to_constellation"`
	OverwriteHostHeader       string                  `yaml:"overwrite_host_header,omitempty"`
	WhitelistInboundIPs       []string                `yaml:"whitelist_inbound_ips,omitempty"`
	Icon                      string                  `yaml:"icon,omitempty"`
	Tunnel                    string                  `yaml:"tunnel,omitempty"`
	TunneledHost              string                  `yaml:"tunneled_host,omitempty"`
	ExtraHeaders              map[string]string       `yaml:"extra_headers,omitempty"`
	DisableLegacyHTTPHeaders  bool                    `yaml:"disable_legacy_http_headers"`
	SkipURLClean              bool                    `yaml:"skip_url_clean"`
	UseH2C                    bool                    `yaml:"use_h2c"`
	LBMode                    string                  `yaml:"lb_mode" json:"LBMode,omitempty"`
	LBStickyMode              bool                    `yaml:"lb_sticky_mode" json:"LBStickyMode,omitempty"`
	AdditionalTargets         []string                `yaml:"additional_targets,omitempty" json:"AdditionalTargets,omitempty"`
	// ManagedByKind / ManagedByName identify the feature that owns this route (see ManagedByKinds); both empty for a user-created route.
	ManagedByKind string `yaml:"managed_by_kind,omitempty" json:"ManagedByKind,omitempty"`
	ManagedByName string `yaml:"managed_by_name,omitempty" json:"ManagedByName,omitempty"`
	// ManagedByVersion is the owner's spec version this copy was rendered from (deployments only; see the routes-only apply in scheduler_node.go).
	ManagedByVersion int  `yaml:"managed_by_version,omitempty" json:"ManagedByVersion,omitempty"`
	Const_IsTunneled bool `yaml:"-" json:"-"`
}

func FindRouteByReqHost added in v0.18.0

func FindRouteByReqHost(hostname string) (string, *ProxyRouteConfig)

func ManagedRoutesOf added in v0.24.0

func ManagedRoutesOf(kind, name string) []ProxyRouteConfig

ManagedRoutesOf returns the routes of the in-memory config owned by kind+name.

func MergeManagedRoutes added in v0.24.0

func MergeManagedRoutes(routes []ProxyRouteConfig, kind, name string, desired []ProxyRouteConfig) ([]ProxyRouteConfig, bool)

MergeManagedRoutes is the pure half of ApplyManagedRoutes: it returns the route list with every route owned by kind+name replaced by `desired`, and reports whether anything changed.

Semantics, in order:

  • an existing route owned by this pair whose name is not in desired is dropped (the owner withdrew it: tags changed, record deleted...);
  • an existing route with a desired name is replaced in place by the desired copy, whatever its previous owner — the owner's materialization wins over a stale or hand-made route of the same name (callers validate name collisions BEFORE writing the owner record; by the time the owner applies, the name is its own);
  • desired routes not present yet are PREPENDED, like every owner did before: a managed route is host-exact and must win over any broader catch-all a user added below it.

Every desired route is stamped with the owner pair, so an owner cannot accidentally materialize an unowned route through this path.

func PreserveManagedRoutes added in v0.24.0

func PreserveManagedRoutes(incoming []ProxyRouteConfig, stored []ProxyRouteConfig) []ProxyRouteConfig

PreserveManagedRoutes rebuilds a wholesale route list (a PUT /api/config payload) so that managed routes come out exactly as the current file has them: an incoming route carrying a managed name is replaced by the stored copy, an incoming route that claims an owner the file does not know is dropped, and a stored managed route the payload omitted is put back at the front. Request order is preserved for everything else, so the settings UI round-trip cannot edit, rename or delete what an owner materializes.

func StampManagedBy added in v0.24.0

func StampManagedBy(route ProxyRouteConfig, kind, name string) ProxyRouteConfig

StampManagedBy returns the route with the owner pair set.

func (ProxyRouteConfig) IsManaged added in v0.24.0

func (r ProxyRouteConfig) IsManaged() bool

IsManaged reports whether the route is owned by a feature.

func (ProxyRouteConfig) ManagedBy added in v0.24.0

func (r ProxyRouteConfig) ManagedBy() string

ManagedBy renders the owner pair for logs and error messages ("seaweedfs:test").

func (ProxyRouteConfig) SameOwner added in v0.24.0

func (r ProxyRouteConfig) SameOwner(kind, name string) bool

SameOwner reports whether the route is owned by exactly this kind+name pair.

type RemoteStorageConfig added in v0.17.0

type RemoteStorageConfig struct {
	Shares []LocationRemoteStorageConfig
}

type ResolvedZone added in v0.24.0

type ResolvedZone struct {
	DNSZoneConfig
	Derived bool
	Hosts   []string
}

ResolvedZone is a zone as the server sees it: explicit or derived, with the hostnames currently filed under it.

func GetZoneForHost added in v0.24.0

func GetZoneForHost(host string) (ResolvedZone, bool)

GetZoneForHost returns the zone a hostname resolves to in the live config.

func ResolveZones added in v0.24.0

func ResolveZones(config Config, hosts []string) []ResolvedZone

ResolveZones files the hostnames under their zones: every explicit zone (even empty), then one derived zone per hostname left over. Sorted by name.

type Role

type Role int

type RoleConfig added in v0.22.0

type RoleConfig struct {
	Name        string       `json:"name"`
	Permissions []Permission `json:"permissions"`
}

type RouteConflict added in v0.24.0

type RouteConflict struct {
	Route    string
	Existing string
	Owner    string
	Reason   string
}

RouteConflict describes why a candidate route cannot be created.

func (RouteConflict) Error added in v0.24.0

func (c RouteConflict) Error() string

type ShieldBan added in v0.24.0

type ShieldBan struct {
	ID       string          `json:"id"`
	ClientID string          `json:"clientID"`
	BanType  int             `json:"banType"`
	Time     time.Time       `json:"time"`
	Reason   ShieldBanReason `json:"reason"`
	ShieldID string          `json:"shieldID"`
	Node     string          `json:"node"`
}

ShieldBan is one entry in a client's history. ID is unique across the cluster (identity, timestamp and issuing node) so replicated copies dedupe.

type ShieldBanReason added in v0.24.0

type ShieldBanReason struct {
	Limit   string  `json:"limit"` // requests, bytes, time, simultaneous, packets, escalation
	Used    float64 `json:"used"`
	Allowed float64 `json:"allowed"`
	Route   string  `json:"route"`
}

ShieldBanReason names the limit a client tripped, so the dashboard can say "requests: 36012 of 36000 on route X" instead of dumping two structs.

type ShieldWhitelistEntry added in v0.24.0

type ShieldWhitelistEntry struct {
	IP                  string `json:"IP"`
	Label               string `json:"Label"`
	BypassGeo           bool   `json:"BypassGeo"`
	BypassIPRestriction bool   `json:"BypassIPRestriction"`
}

ShieldWhitelistEntry exempts a source IP or CIDR from SmartShield budgets, strikes and the abuse counter. The two flags extend the exemption to the geo block and to the per-route IP restrictions. Entries are IPs only: a user identity could otherwise let a geo-blocked client reach login.

func ShieldWhitelistMatch added in v0.24.0

func ShieldWhitelistMatch(ip string) (ShieldWhitelistEntry, bool)

ShieldWhitelistMatch returns the first whitelist entry covering an IP.

type SingleBackupConfig added in v0.18.0

type SingleBackupConfig struct {
	Name               string `validate:"required"`
	Repository         string `validate:"required"`
	Password           string
	Source             string
	Crontab            string
	CrontabForget      string
	RetentionPolicy    string
	AutoStopContainers bool
}

type SmartShieldPolicy

type SmartShieldPolicy struct {
	Enabled               bool    `yaml:"enabled"`
	PolicyStrictness      int     `yaml:"policy_strictness"`
	PerUserTimeBudget     float64 `yaml:"per_user_time_budget"`
	PerUserRequestLimit   int     `yaml:"per_user_request_limit"`
	PerUserByteLimit      int64   `yaml:"per_user_byte_limit"`
	PerUserSimultaneous   int     `yaml:"per_user_simultaneous"`
	MaxGlobalSimultaneous int     `yaml:"max_global_simultaneous"`
	PrivilegedGroups      int     `yaml:"privileged_groups"`
}

func ApplySmartShieldDefaults added in v0.24.0

func ApplySmartShieldDefaults(policy SmartShieldPolicy) SmartShieldPolicy

ApplySmartShieldDefaults fills every zero field of a route policy from the deployment profile. PerUserTimeBudget is in milliseconds of cumulative request time per rolling hour; 0 leaves it unlimited.

func LenientExternalSmartShield added in v0.24.0

func LenientExternalSmartShield(byteLimit int64) SmartShieldPolicy

LenientExternalSmartShield is a SmartShield policy sized for external bulk-traffic routes (e.g. registry pushes, websites).

type SmartShieldProfile added in v0.24.0

type SmartShieldProfile struct {
	Defaults     SmartShieldPolicy
	UDPByteLimit int64
	// AllowPermanentBan: when false, escalation stops at temporary bans. In-memory
	// permanent bans on a public server only ever hit NATs, and only a restart
	// clears them.
	AllowPermanentBan bool
	// GlobalCapWait / GlobalCapPoll: how long a request parks when the route's
	// MaxGlobalSimultaneous is reached before being rejected with 429.
	GlobalCapWait time.Duration
	GlobalCapPoll time.Duration
}

SmartShieldProfile is the deployment-wide shape of SmartShield: the values a route policy falls back to for every field it leaves at zero, plus the knobs that are not per-route. OSS is sized for a home server behind one public IP; Pro is sized for a public deployment serving thousands of concurrent users, where a single source IP is routinely a whole office or carrier NAT.

func GetSmartShieldProfile added in v0.24.0

func GetSmartShieldProfile() SmartShieldProfile

GetSmartShieldProfile picks the profile for this deployment. Routes never persist these numbers: a zero field in a route policy always means "the profile default", so upgrading the license re-sizes every default route.

type SnapRAIDConfig added in v0.15.0

type SnapRAIDConfig struct {
	Name         string
	Enabled      bool
	Data         map[string]string
	Parity       []string
	SyncCrontab  string
	ScrubCrontab string
	CheckOnFix   bool
}

type StatusData added in v0.22.0

type StatusData struct {
	HomepageConfig       HomepageConfig `json:"homepage"`
	ThemeConfig          ThemeConfig    `json:"theme"`
	CPU                  string         `json:"CPU"`
	AVX                  bool           `json:"AVX"`
	LetsEncryptErrors    []string       `json:"LetsEncryptErrors"`
	IsAdmin              bool           `json:"isAdmin"`
	MonitoringDisabled   bool           `json:"MonitoringDisabled"`
	Hostname             string         `json:"hostname"`
	Domain               bool           `json:"domain"`
	HTTPSCertificateMode string         `json:"HTTPSCertificateMode"`
	NewVersionAvailable  string         `json:"newVersionAvailable"`
	NeedsRestart         bool           `json:"needRestart"`
	Database             bool           `json:"database"`
	Docker               bool           `json:"docker"`
	BackupStatus         string         `json:"backup_status"`
	Constellation        bool           `json:"constellation"`
}

StatusData represents the data returned by the /api/status endpoint.

type StorageConfig added in v0.15.0

type StorageConfig struct {
	SnapRAIDs []SnapRAIDConfig
}

type ThemeConfig

type ThemeConfig struct {
	PrimaryColor   string
	SecondaryColor string
}

type TunnelTarget added in v0.22.0

type TunnelTarget struct {
	DeviceName string `json:"deviceName"`
	TargetURL  string `json:"targetURL"`
	// Latest resource sample from the advertiser's heartbeat, used by the
	// "load_based" LB mode. Only trustworthy when MonitoringOn is true.
	CPUPercent   float64 `json:"cpuPercent,omitempty"`
	RAMPercent   float64 `json:"ramPercent,omitempty"`
	MonitoringOn bool    `json:"monitoringOn,omitempty"`
}

type User

type User struct {
	Nickname              string    `validate:"required" json:"nickname" bson:"Nickname"`
	Password              string    `validate:"required" json:"-" bson:"Password"`
	RegisterKey           string    `json:"-" bson:"RegisterKey"`
	RegisterKeyExp        time.Time `json:"registerKeyExp" bson:"RegisterKeyExp"`
	Role                  Role      `validate:"required" json:"role" bson:"Role"`
	PasswordCycle         int       `json:"-" bson:"PasswordCycle"`
	Link                  string    `json:"link" bson:"-"`
	Email                 string    `validate:"email" json:"email" bson:"Email"`
	RegisteredAt          time.Time `json:"registeredAt" bson:"RegisteredAt"`
	LastPasswordChangedAt time.Time `json:"lastPasswordChangedAt" bson:"LastPasswordChangedAt"`
	CreatedAt             time.Time `json:"createdAt" bson:"CreatedAt"`
	LastLogin             time.Time `json:"lastLogin" bson:"LastLogin"`
	MFAKey                string    `json:"-" bson:"MFAKey"`
	Was2FAVerified        bool      `json:"-" bson:"Was2FAVerified"`
	MFAState              int       `json:"-" bson:"-"`
}

func GetUser added in v0.23.0

func GetUser(nickname string) (User, error)

GetUser returns the user by nickname; on any error it returns a zero-value User (never partial data) so field checks at call sites stay fail-closed.

func ListAllUsers added in v0.12.0

func ListAllUsers(role string) []User

ListAllUsers keeps the legacy signature for existing callers.

func ListUsers added in v0.23.0

func ListUsers(role string) ([]User, error)

ListUsers returns users filtered by role ("admin", "user", or "" for all).

func ListUsersPage added in v0.23.0

func ListUsersPage(limit int) ([]User, error)

type ZoneCert added in v0.24.0

type ZoneCert struct {
	TLSCert    string
	TLSKey     string
	Hosts      []string
	ValidUntil time.Time
	IssuedBy   string `json:"IssuedBy,omitempty"`
}

ZoneCert is the certificate of an explicit zone. The zone issuer (the node itself when standalone, the cluster leader otherwise) is the only one writing it; every node serves from it.

Jump to

Keyboard shortcuts

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