Documentation
¶
Index ¶
- Constants
- Variables
- func AcceptHeader(accept string) func(next http.Handler) http.Handler
- func AdminOnlyMiddleware(next http.Handler) http.Handler
- func AdminOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error
- func ApplyLogicalDump(data []byte, epoch uint64, seq uint64) error
- func ApplyOpTx(m Mutation, seq uint64, preDevices *[]ConstellationDevice) error
- func BandwithLimiterMiddleware(max int64) func(next http.Handler) http.Handler
- func Base64Encode(str string) string
- func BlockBannedIPs(next http.Handler) http.Handler
- func BlockByCountryMiddleware(blockedCountries []string, CountryBlacklistIsWhitelist bool) func(http.Handler) http.Handler
- func BlockPostWithoutReferer(next http.Handler) http.Handler
- func BuildLogicalDump() ([]byte, error)
- func BuildSnapshot() ([]byte, uint64, uint64, error)
- func CORSHeader(origin string) func(next http.Handler) http.Handler
- func CanGrant(req *http.Request, perms []Permission) bool
- func CheckDNS(url string) error
- func CheckHostNetwork()
- func CheckIPAccess(clientIP string, remoteAddr string, restrictToConstellation bool, ...) bool
- func CheckInternet()
- func CheckPassword(nickname, password string) error
- func CheckPermissions(w http.ResponseWriter, req *http.Request, permission Permission) error
- func CheckPermissionsOrSelf(w http.ResponseWriter, req *http.Request, nickname string, ...) error
- func CleanBannedIPs()
- func ClearFormationWriter() error
- func ClientRealIP(next http.Handler) http.Handler
- func CloseMetricsDatabase()
- func CloseStore()
- func CommitMutation(m Mutation) error
- func CommitMutationDirect(m Mutation, preDevices *[]ConstellationDevice) error
- func CommitMutationLocal(m Mutation) error
- func CommitMutations(ms []Mutation) error
- func CommitOplogSeq(seq uint64) error
- func CompareSemver(v1, v2 string) (int, error)
- func ContentTypeMiddleware(contentType string) func(next http.Handler) http.Handler
- func CountDevices(filter map[string]interface{}) (int64, error)
- func CountUsers() (int64, error)
- func CreateDefaultConfigFileIfNecessary() bool
- func CreateDevice(d ConstellationDevice) error
- func CreateUser(u User) error
- func Debug(message string)
- func DecodeOpDoc(table string, op string, raw json.RawMessage) (interface{}, error)
- func DeleteAllUsers() error
- func DeleteAllUsersLocal() error
- func DeleteDevices(filter map[string]interface{}) error
- func DeleteDevicesLocal(filter map[string]interface{}) error
- func DeleteLocalEvents() error
- func DeleteUser(nickname string) error
- func DerivePKCEVerifier(host string, path string) string
- func DeviceFieldsChanged(pre []ConstellationDevice, fields map[string]interface{}, ...) bool
- func DoErr(format string, a ...interface{}) string
- func DoLetsEncrypt() (string, string)
- func DoSuccess(format string, a ...interface{}) string
- func DoWarn(format string, a ...interface{}) string
- func DownloadFile(url string) (string, error)
- func DownloadFileToLocation(path, url string) error
- func EncodeOpDoc(m Mutation) (json.RawMessage, error)
- func EnsureHostname(next http.Handler) http.Handler
- func EnsureHostnameCosmosAPI(next http.Handler) http.Handler
- func Error(message string, err error)
- func Exec(cmd string, args ...string) (string, error)
- func Fatal(message string, err error)
- func FileExists(path string) bool
- func GenerateEd25519Certificates() (string, string)
- func GenerateRSAWebCertificates(domains []string) (string, string, error)
- func GenerateRandomString(n int) string
- func GetAllHostnames(applyWildCard bool, removePorts bool) []string
- func GetAvailableRAM() uint64
- func GetCPUUsage() []float64
- func GetClientIP(req *http.Request) string
- func GetConfigFileName() string
- func GetFileLastModifiedTime(path string) time.Time
- func GetIPAbuseCounter(ip string) int64
- func GetIPLocation(ip string) (string, error)
- func GetLastAppliedSeq() uint64
- func GetNextAvailableLocalPort(startPort int) (string, error)
- func GetNumberCosmosNode() int
- func GetNumberUsers() int
- func GetNumberUsersFromToken(serverToken string) (int, int)
- func GetOplogEpoch() uint64
- func GetPrivateAuthKey() string
- func GetProxyOIDCredentials(route ProxyRouteConfig, hashSecret bool) *fosite.DefaultClient
- func GetPublicAuthKey() string
- func GetRAMUsage() uint64
- func GetRandomNumber(min int, max int) int
- func GetRoles() map[Role]RoleConfig
- func GetRootAppId() string
- func GetServerPort() string
- func GetServerRawAccess() (string, string, string)
- func GetServerURL(overwriteHostname string) string
- func GetSubscriptionTypeFromToken(serverToken string) string
- func HTTPError(w http.ResponseWriter, message string, code int, userCode string)
- func HTTPStoreError(w http.ResponseWriter, err error, userCode string)
- func HasAnyNewItem(after []string, before []string) bool
- func HasPermission(req *http.Request, permission Permission) bool
- func IPInRange(ipStr, cidrStr string) (bool, error)
- func ImageToBase64(path string) (string, error)
- func IncrementIPAbuseCounter(ip string)
- func InitFBL()
- func InitLogs()
- func InitMetricsDatabase() error
- func InitStore() error
- func InsertEvent(e Event) error
- func InsertNotification(n Notification) error
- func IsDomain(domain string) bool
- func IsEmailEnabled() bool
- func IsFormationWriter() bool
- func IsLocalDomain(domain string) bool
- func IsLocalIP(ip string) bool
- func IsLoggedIn(req *http.Request) bool
- func IsNotifyLoginEmailEnabled() bool
- func IsOplogBootstrapped() bool
- func IsTokenValidForProduct(serverToken string) bool
- func IsTrustedProxy(ip string) bool
- func IsValidHostname(hostname string) bool
- func IsValidLBMode(mode string) bool
- func JSONEquals(a, b interface{}) bool
- func LetsEncryptValidOnly(hostnames []string, acceptWildcard bool) []string
- func ListInterfaces(skipNebula bool) ([]string, error)
- func ListIps(skipNebula bool) ([]string, error)
- func LoadBaseMainConfig(config Config)
- func Log(message string)
- func LogReq(message string)
- func LoggedInOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error
- func Logger(next http.Handler) http.Handler
- func MajorError(message string, err error)
- func MarkAsRead(w http.ResponseWriter, req *http.Request)
- func MarkNotificationsRead(recipient string, ids []int64) (int64, error)
- func MarkOplogBootstrapped(epoch uint64) error
- func Max(x, y int) int
- func MiddlewareTimeout(timeout time.Duration) func(next http.Handler) http.Handler
- func MillisToTime(ms int64) time.Time
- func MonitoringDialect() string
- func MonitoringNode() string
- func MonitoringReadDB() (*sql.DB, error)
- func MonitoringRebind(query string) string
- func MonitoringWriteDB() (*sql.DB, error)
- func NormalizeOpFields(table string, fields map[string]interface{}) (map[string]interface{}, error)
- func NormalizeOpFilter(table string, filter map[string]interface{}) (map[string]interface{}, error)
- func NotifGet(w http.ResponseWriter, req *http.Request)
- func NowMillis() int64
- func PermissionLabel(p Permission) string
- func PermissionsHaveSudo(perms []Permission) bool
- func ProcessLicence()
- func PublicCORS(next http.Handler) http.Handler
- func RawLogMessage(level LogLevel, prefix, prefixColor, color, message string)
- func ReformOplogEpoch() (uint64, error)
- func RemoveStringFromSlice(slice []string, s string) []string
- func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler
- func RestartServer(code int)
- func Restrictions(RestrictToConstellation bool, WhitelistInboundIPs []string) func(next http.Handler) http.Handler
- func RoleHasSudoPermissions(role Role) bool
- func RunDatabaseRetention()
- func SPAHandler(targetFolder string) http.Handler
- func Sanitize(s string) string
- func SanitizeNoSpace(s string) string
- func SanitizeSafe(s string) string
- func SaveConfigTofile(config Config)
- func SendEmail(recipients []string, subject string, body string) error
- func SetBaseMainConfig(config Config)
- func SetCosmosHeader(next http.Handler) http.Handler
- func SetFileLastModifiedTime(path string, modTime int64) error
- func SetFormationWriter(epoch uint64) error
- func SetOplogState(epoch uint64, seq uint64) error
- func SetPublishOpHook(h func(Mutation) error)
- func SetSecurityHeaders(next http.Handler) http.Handler
- func SoftRestartServer()
- func SplitIP(ipPort string) (string, string)
- func StringArrayContains(a []string, b string) bool
- func StringArrayEquals(a []string, b []string) bool
- func TimeToMillis(t time.Time) int64
- func TranslateEventFilter(dialect string, filter map[string]interface{}) (string, []interface{}, error)
- func TriggerEvent(eventId string, label string, level string, object string, ...)
- func UpdateDevices(filter map[string]interface{}, fields map[string]interface{}) error
- func UpdateUser(nickname string, fields map[string]interface{}) error
- func VPN(message string)
- func VPNWithLevel(line string)
- func ValidateRolesChange(req *http.Request, prev, next map[Role]RoleConfig) error
- func Values[M ~map[K]V, K comparable, V any](m M) []V
- func Warn(message string)
- func WildcardToLike(pattern string) string
- func WithLogEntry(r *http.Request, entry LogEntry) *http.Request
- func WriteNotification(notification Notification)
- type APIResponse
- type APIResponseMessage
- type APITokenConfig
- type APITokenContext
- type AddionalFiltersConfig
- type Alert
- type AlertAction
- type AlertCondition
- type AlertMetricTrack
- type AuthContext
- type BackupConfig
- type CAConfig
- type CRONConfig
- type CertUser
- type Config
- type ConstellationConfig
- type ConstellationDNSEntry
- type ConstellationDevice
- type ConstellationTunnel
- type DatabaseConfig
- type DefaultLogFormatter
- type Device
- type DiskStatus
- type DockerConfig
- type EmailConfig
- type ErrConstraint
- type Event
- type EventQuery
- type FileStats
- type FirebaseApiSdk
- type HTTPConfig
- type HTTPErrorResult
- type HomepageConfig
- type LocationRemoteStorageConfig
- type LogEntry
- type LogFormatter
- type LogLevel
- type LoggerInterface
- type LoggingLevel
- type MarketConfig
- type MarketSource
- type Mutation
- type MyUser
- type NebulaConfig
- type NebulaConntrackConfig
- type NebulaFirewallRule
- type NetworkStatus
- type Notification
- type NotificationActions
- type OpenIDClient
- type Permission
- type ProxyConfig
- type ProxyMode
- type ProxyRouteConfig
- type RemoteStorageConfig
- type Role
- type RoleConfig
- type SingleBackupConfig
- type SmartShieldPolicy
- type SnapRAIDConfig
- type StatusData
- type StorageConfig
- type ThemeConfig
- type TunnelTarget
- type User
Constants ¶
const ( DialectSQLite = "sqlite" DialectPostgres = "pgx" )
DialectSQLite / DialectPostgres select DDL and placeholder style.
const ( NOONE = -1 GUEST = 0 USER = 1 ADMIN = 2 )
const ( STRICT = 1 NORMAL = 2 LENIENT = 3 )
const AuthCtxKey = "AuthContext"
Variables ¶
var ( Reset = "\033[0m" Bold = "\033[1m" )
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 )
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
var AlphaNumRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
var BannedIPs = sync.Map{}
var CONFIGFOLDER = "/var/lib/cosmos/"
var CheckDockerNetworkMode func() string
var ConfigLock sync.Mutex
var ConfigLockInternal sync.Mutex
var DBStatus bool
DBStatus reports whether the monitoring store is open, surfaced by /api/status.
var DefaultAdminTokenPermissions = []Permission{ PERM_ADMIN_READ, PERM_ADMIN, PERM_USERS_READ, PERM_USERS, PERM_RESOURCES_READ, PERM_RESOURCES, PERM_CONFIGURATION_READ, PERM_CONFIGURATION, PERM_CREDENTIALS_READ, }
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", }, }, }
var DoesContainerExist func(string) bool
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.
var ErrDatabaseClosed = errors.New("database: not initialized")
var ErrNotFound = errors.New("store: not found")
ErrNotFound is returned by typed reads when no row matches.
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.
var GetConstellationTunnelRoutes = func() []ProxyRouteConfig { return []ProxyRouteConfig{} }
var GetContainerIPByName func(string) (string, error)
var HTTPSCertModeList = map[string]string{
"DISABLED": "DISABLED",
"PROVIDED": "PROVIDED",
"SELFSIGNED": "SELFSIGNED",
"LETSENCRYPT": "LETSENCRYPT",
}
var InitBackups func()
var InitPremiumFeatures func()
var InitRemoteStorage func()
var InitSnapRAIDConfig func()
var IsConstellationIP = func(string) bool { return false }
var IsHTTPS = false
var IsHostNetwork = false
var IsInsideContainer = false
var IsPro func() bool = func() bool { return false }
var LBModes = []string{"", "first", "round_robin", "load_based"}
LBModes are the load balancing modes implemented by TunnelLoadBalancer.Select().
var LetsEncryptErrors = []string{}
var LoggingLevelLabels = map[LoggingLevel]LogLevel{ "DEBUG": DEBUG, "INFO": INFO, "WARNING": WARNING, "ERROR": ERROR, }
var NeedsRestart = false
var NewVersionAvailable = false
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)", }
var ProxyModeList = map[string]string{
"PROXY": "PROXY",
"SPA": "SPA",
"STATIC": "STATIC",
"SERVAPP": "SERVAPP",
"REDIRECT": "REDIRECT",
}
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.
var PushShieldMetrics func(string)
var RestartCRON func()
var RestartConstellation func()
var RestartHTTPServer = func() {}
var StopAllRCloneProcess func(bool)
var SudoPermissions = []Permission{ PERM_ADMIN, PERM_USERS, PERM_RESOURCES, PERM_CONFIGURATION, PERM_CREDENTIALS_READ, }
Global: permissions that require sudo for ANY role
var Template = `` /* 1110-byte string literal not displayed */
var UpdateAvailable = map[string]bool{}
var Validate = validator.New()
var WaitForAllJobs func()
Functions ¶
func AdminOnlyMiddleware ¶ added in v0.15.0
func AdminOnlyWithRedirect ¶
func AdminOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error
func ApplyLogicalDump ¶ added in v0.23.0
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 Base64Encode ¶ added in v0.17.0
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 ¶
blockPostWithoutReferer blocks POST requests without a Referer header
func BuildLogicalDump ¶ added in v0.23.0
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
BuildSnapshot returns the users+devices dump plus the (epoch, seq) it is consistent with, all read in one tx.
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 CheckHostNetwork ¶ added in v0.14.0
func CheckHostNetwork()
func CheckIPAccess ¶ added in v0.22.0
func CheckInternet ¶ added in v0.16.0
func CheckInternet()
func CheckPassword ¶ added in v0.15.0
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 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
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
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
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
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
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 CountDevices ¶ added in v0.23.0
func CountUsers ¶ added in v0.22.31
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 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 DeleteDevicesLocal ¶ added in v0.23.0
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 DerivePKCEVerifier ¶ added in v0.22.20
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 DoLetsEncrypt ¶
func DownloadFile ¶ added in v0.10.0
func DownloadFileToLocation ¶ added in v0.17.0
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 EnsureHostnameCosmosAPI ¶ added in v0.12.6
func FileExists ¶
func GenerateRandomString ¶
func GetAllHostnames ¶
func GetAvailableRAM ¶
func GetAvailableRAM() uint64
func GetCPUUsage ¶
func GetCPUUsage() []float64
func GetClientIP ¶ added in v0.9.17
func GetConfigFileName ¶
func GetConfigFileName() string
func GetFileLastModifiedTime ¶ added in v0.21.0
func GetIPAbuseCounter ¶ added in v0.17.0
func GetIPLocation ¶
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 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 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 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 GetServerURL ¶
func GetSubscriptionTypeFromToken ¶ added in v0.22.11
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 HasPermission ¶ added in v0.22.0
func HasPermission(req *http.Request, permission Permission) bool
func ImageToBase64 ¶
func IncrementIPAbuseCounter ¶ added in v0.12.0
func IncrementIPAbuseCounter(ip string)
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
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 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 IsLoggedIn ¶ added in v0.12.6
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
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 IsValidHostname ¶
func IsValidLBMode ¶ added in v0.23.0
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 ListInterfaces ¶ added in v0.18.0
func LoadBaseMainConfig ¶
func LoadBaseMainConfig(config Config)
func LoggedInOnlyWithRedirect ¶
func LoggedInOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error
func Logger ¶ added in v0.17.0
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 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
MarkNotificationsRead flips the read flag on the recipient's own rows only.
func MarkOplogBootstrapped ¶ added in v0.23.0
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 MiddlewareTimeout ¶
func MillisToTime ¶ added in v0.23.0
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
MonitoringReadDB returns the pooled reader handle.
func MonitoringRebind ¶ added in v0.23.0
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
MonitoringWriteDB returns the single-writer handle.
func NormalizeOpFields ¶ added in v0.23.0
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
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 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 RawLogMessage ¶ added in v0.17.0
func ReformOplogEpoch ¶ added in v0.23.0
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 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 RoleHasSudoPermissions ¶ added in v0.22.0
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 SanitizeNoSpace ¶ added in v0.18.0
func SanitizeSafe ¶
func SaveConfigTofile ¶
func SaveConfigTofile(config Config)
func SetBaseMainConfig ¶
func SetBaseMainConfig(config Config)
func SetFileLastModifiedTime ¶ added in v0.21.0
func SetFormationWriter ¶ added in v0.23.0
SetFormationWriter grants the formation write licence for an epoch.
func SetOplogState ¶ added in v0.23.0
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
SetPublishOpHook wires the op-log publisher; nil restores direct writes.
func SoftRestartServer ¶ added in v0.21.0
func SoftRestartServer()
func StringArrayContains ¶
func StringArrayEquals ¶
func TimeToMillis ¶ added in v0.23.0
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 UpdateDevices ¶ added in v0.23.0
UpdateDevices sets the given bson-named fields on all devices matching the filter.
func UpdateUser ¶ added in v0.23.0
UpdateUser sets the given bson-named fields on the user row.
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 WildcardToLike ¶ added in v0.23.0
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
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 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 AlertCondition ¶ added in v0.12.0
type AlertMetricTrack ¶ added in v0.12.0
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 CertUser ¶
type CertUser struct {
Email string
Registration *acme.ExtendedAccount
// contains filtered or unexported fields
}
func (*CertUser) GetPrivateKey ¶
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 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 ¶
func GetDiskUsage ¶
func GetDiskUsage() []DiskStatus
type DockerConfig ¶
type EmailConfig ¶
type ErrConstraint ¶ added in v0.23.0
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 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 HomepageConfig ¶
type LocationRemoteStorageConfig ¶ added in v0.17.0
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
GetLogEntry returns the in-context LogEntry for a request.
type LogFormatter ¶ added in v0.17.0
LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.
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 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) GetPrivateKey ¶
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 NebulaFirewallRule ¶ added in v0.10.0
type NetworkStatus ¶
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 OpenIDClient ¶
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 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 {
}
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 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 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 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
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
ListAllUsers keeps the legacy signature for existing callers.
func ListUsers ¶ added in v0.23.0
ListUsers returns users filtered by role ("admin", "user", or "" for all).
func ListUsersPage ¶ added in v0.23.0
Source Files
¶
- api_responses.go
- certificates.go
- cloud.go
- database.go
- database_events.go
- database_filter.go
- database_notifications.go
- database_schema.go
- dns.go
- emails.go
- events.go
- log.go
- loggedIn.go
- logger.go
- middleware.go
- notifications.go
- store.go
- store_devices.go
- store_mutation.go
- store_op.go
- store_op_codec.go
- store_schema.go
- store_users.go
- types.go
- utils.go
- validator.go