utils

package
v0.23.4 Latest Latest
Warning

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

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

Documentation

Index

Constants

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

DialectSQLite / DialectPostgres select DDL and placeholder style.

View Source
const (
	NOONE = -1
	GUEST = 0
	USER  = 1
	ADMIN = 2
)
View Source
const (
	STRICT  = 1
	NORMAL  = 2
	LENIENT = 3
)
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 ConfigLock sync.Mutex
View Source
var ConfigLockInternal sync.Mutex
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 InitBackups func()
View Source
var InitPremiumFeatures func()
View Source
var InitRemoteStorage func()
View Source
var InitSnapRAIDConfig func()
View Source
var IsConstellationIP = func(string) bool { return false }
View Source
var IsHTTPS = false
View Source
var IsHostNetwork = false
View Source
var IsInsideContainer = false
View Source
var IsPro func() bool = func() bool { return false }
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 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 PushShieldMetrics func(string)
View Source
var RestartCRON func()
View Source
var RestartConstellation func()
View Source
var RestartHTTPServer = func() {}
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()

Functions

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 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 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 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

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 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 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 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.

A distinct key slice ([0:32]) and domain-separation prefix are used so the result never collides with the state hash (which uses AuthPrivateKey[32:64]). 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() (string, string)

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 GenerateEd25519Certificates

func GenerateEd25519Certificates() (string, string)

func GenerateRSAWebCertificates

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

func GenerateRandomString

func GenerateRandomString(n int) string

func GetAllHostnames

func GetAllHostnames(applyWildCard bool, 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 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 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 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 IsValidLBMode added in v0.23.0

func IsValidLBMode(mode string) bool

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

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

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 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 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 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 PermissionLabel added in v0.22.0

func PermissionLabel(p Permission) string

func PermissionsHaveSudo added in v0.22.0

func PermissionsHaveSudo(perms []Permission) bool

func ProcessLicence added in v0.21.0

func ProcessLicence()

func PublicCORS added in v0.12.0

func PublicCORS(next http.Handler) http.Handler

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 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 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 SaveConfigTofile

func SaveConfigTofile(config Config)

func SendEmail

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

func SetBaseMainConfig

func SetBaseMainConfig(config Config)

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 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 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 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)

Types

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"`
}

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
	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
	DoNotSyncNodes                  bool
	DNSDisabled                     bool
	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 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
	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                     string `validate:"omitempty,email"`
	UseWildcardCertificate       bool
	OverrideWildcardDomains      string `validate:"omitempty,excludesall=/ "`
	AcceptAllInsecureHostname    bool
	DNSChallengeConfig           map[string]string `json:"DNSChallengeConfig,omitempty"`
	DNSChallengeResolvers        string
	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 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 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"`
	Const_IsTunneled          bool                    `yaml:"-" json:"-"`
}

func FindRouteByReqHost added in v0.18.0

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

type RemoteStorageConfig added in v0.17.0

type RemoteStorageConfig struct {
	Shares []LocationRemoteStorageConfig
}

type Role

type Role int

type RoleConfig added in v0.22.0

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

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"`
}

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)

Jump to

Keyboard shortcuts

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