Documentation
¶
Overview ¶
Package config provides Docker container label parsing for roji configuration.
It extracts routing configuration from Docker labels such as:
- roji.host: Custom hostname
- roji.port: Target port
- roji.path: Path prefix for path-based routing
Index ¶
- Constants
- Variables
- func AutoTunnelName(hostname string) string
- func CertCoversHost(hostname, baseDomain string) bool
- func CertsDir() string
- func ConfigDir() string
- func ConfigFilePath() string
- func DataDir() string
- func DefaultHostname(serviceName, baseDomain string) string
- func EnsureDir(path string) error
- func Exists(path string) bool
- func ExpandPath(path string) string
- func IsLoopbackAddr(addr string) bool
- func IsLoopbackHost(host string) bool
- func IsWildcardAddr(addr string) bool
- func LocalFilePath(configPath string) string
- func LogFilePath() string
- func ParseProxyTarget(target string) (*url.URL, error)
- func ReadConfigFiles(configPath string) ([]byte, []string, error)
- func ResolveSiteHost(host, baseDomain string) string
- type BasicAuth
- type DeclaredSite
- type MockRoute
- type Paths
- type ProxySite
- type RouteConfig
- type Settings
- type SiteAuth
- type StaticSite
- type Tunnel
- type ValidationIssue
- type ValidationResult
Constants ¶
const ( // Label prefix for all roji-related labels LabelPrefix = "roji." // Supported labels LabelHost = LabelPrefix + "host" // Custom hostname (default: {service}.{domain}) LabelPort = LabelPrefix + "port" // Target port when multiple ports exposed LabelPath = LabelPrefix + "path" // Path prefix for routing (optional) LabelTunnel = LabelPrefix + "tunnel" // Publish this route through the tunnel // Mock labels prefix LabelMockPrefix = LabelPrefix + "mock." // roji.mock.GET./path = response body LabelMockStatusPrefix = LabelMockPrefix + "status." // roji.mock.status.GET./path = status code // Basic auth labels LabelAuthBasicUser = LabelPrefix + "auth.basic.user" // Basic auth username LabelAuthBasicPass = LabelPrefix + "auth.basic.pass" // Basic auth password LabelAuthBasicRealm = LabelPrefix + "auth.basic.realm" // Basic auth realm (optional) )
const ( SiteSkipReserved = "reserved" // ErrSiteReservedHost SiteSkipRoot = "root" // ErrSiteRoot SiteSkipTarget = "target" // ErrSiteTarget SiteSkipDuplicate = "duplicate" // ErrSiteDuplicate SiteSkipOther = "other" // Anything this version has no code for )
Codes for why a declared site is not served, as DeclaredSite.SkipReason returns them. They cross the API, so a client can choose its own wording.
const (
// AppName is the application name used for directory paths
AppName = "roji"
)
const DefaultBind = "127.0.0.1,::1"
DefaultBind is the address set roji listens on when nothing else is configured: both loopback addresses, and nothing beyond the machine itself.
Both are needed because the wildcard listener this replaced accepted IPv4 and IPv6 alike, and a browser resolving a *.localhost name may pick either.
const DefaultTunnelPort = 8080
DefaultTunnelPort is the port the tunnel listener takes when the tunnel is configured without one.
It is deliberately not 80 or 443: the tunnel listener is a separate door into roji with its own guard, and telling the two apart is what makes the guard possible at all. See Tunnel.Port.
const LocalFileName = "local.yaml"
LocalFileName is the name of the per-machine file read on top of the default config file, config.yaml. See LocalFilePath.
const TunnelNameAuto = "auto"
TunnelNameAuto is the value of Tunnel.Name that asks for AutoTunnelName.
Variables ¶
var ( // ErrSiteReservedHost: the hostname is the dashboard's or the base domain, // which the dashboard answers before any route is looked at. ErrSiteReservedHost = errors.New("hostname belongs to the dashboard") // ErrSiteRoot: a static site's root is not a directory that can be read. ErrSiteRoot = errors.New("root is not a usable directory") // ErrSiteTarget: a proxy site's target is not a URL roji can forward to. ErrSiteTarget = errors.New("target is not usable") // ErrSiteDuplicate: a later site in the file declares the same hostname // and is served in this one's place. ErrSiteDuplicate = errors.New("hostname is declared again later in the config file") )
Reasons roji will not serve a declared site. DeclaredSite.Err wraps one of them, with the detail in its message.
Functions ¶
func AutoTunnelName ¶ added in v1.6.0
AutoTunnelName derives a tunnel name from a hostname: "roji-" and the hostname's first label, lowercased, with anything but letters, digits and hyphens replaced by a hyphen.
The first label only, since whether the rest of an FQDN appears depends on how the machine's DNS is set up rather than on the machine.
It returns an empty string for a hostname with nothing usable in its first label (one written in non-Latin letters, say). Falling back to a fixed name would give every such machine the same tunnel, which is what `name: auto` is for avoiding.
func CertCoversHost ¶ added in v1.4.0
CertCoversHost reports whether the certificate roji generates for baseDomain is valid for hostname: the base domain itself, or one label under it. Any other name is served with a certificate the browser rejects.
One label only. The certificate also lists "*.*.{domain}", but a wildcard stands for a single leftmost label, so that entry matches nothing. A test in certgen holds this function to what the generated certificate accepts.
func CertsDir ¶ added in v0.8.0
func CertsDir() string
CertsDir returns the certificates directory Defaults to DataDir()/certs
func ConfigDir ¶ added in v0.8.0
func ConfigDir() string
ConfigDir returns the configuration directory following XDG spec Linux/macOS: ~/.config/roji Windows: %APPDATA%\roji
func ConfigFilePath ¶ added in v0.8.0
func ConfigFilePath() string
ConfigFilePath returns the path to the configuration file
func DataDir ¶ added in v0.8.0
func DataDir() string
DataDir returns the data directory following XDG spec Linux/macOS: ~/.local/share/roji Windows: %LOCALAPPDATA%\roji
func DefaultHostname ¶
DefaultHostname generates a default hostname from service name and base domain e.g., ("myapp", "kan.localhost") -> "myapp.kan.localhost"
func ExpandPath ¶ added in v0.9.0
ExpandPath expands ~ to home directory
func IsLoopbackAddr ¶ added in v1.1.0
IsLoopbackAddr reports whether addr names the machine roji runs on and nothing else.
A hostname is not judged here: deciding what it points at means resolving it, which belongs to whoever is about to connect or listen. The wildcard is not loopback either, since it accepts connections from anywhere.
func IsLoopbackHost ¶ added in v1.4.0
IsLoopbackHost reports whether host, as written in a URL, names this machine: a loopback address, "localhost", or a name under it. RFC 6761 reserves the last two for loopback, so no resolving is needed to say so.
func IsWildcardAddr ¶ added in v1.1.0
IsWildcardAddr reports whether addr is the wildcard. The bind setting spells it as the empty string, which net.JoinHostPort turns into ":443" — the address that accepts connections on every interface.
func LocalFilePath ¶ added in v1.6.0
LocalFilePath returns the per-machine file that goes with configPath, in the same directory: local.yaml for a file named config.yaml, and <stem>.local<ext> for any other name (roji.yaml pairs with roji.local.yaml).
The name follows the config file's so that `--config /etc/roji.yaml` does not pick up an /etc/local.yaml that belongs to something else.
The directory is taken from the path as given, without following symlinks. A config.yaml linked in from a dotfiles repository is shared between machines; the local file next to the link is the one place that is not.
func LogFilePath ¶ added in v0.9.0
func LogFilePath() string
LogFilePath returns the path to the log file
func ParseProxyTarget ¶ added in v1.4.0
ParseProxyTarget parses the target of a ProxySite.
The scheme is required and has to be http: roji terminates TLS itself, and a dev server on the same machine has no certificate a proxy could verify. A path is allowed and is prepended to every request. Credentials, a query and a fragment have no meaning for a proxy target, so they are refused rather than silently dropped.
func ReadConfigFiles ¶ added in v1.6.0
ReadConfigFiles reads the config file and the per-machine file next to it (LocalFilePath), and returns them merged into one YAML document along with the paths of the files it read.
The local file goes on top. Mappings merge key by key at every level, so it can set tunnel.name alone and keep tunnel.domain from the shared file; anything else, a list included, replaces what the config file says. A key set to null in the local file removes it.
Either file may be missing. The error satisfies errors.Is(err, fs.ErrNotExist) only when both are.
func ResolveSiteHost ¶ added in v1.4.0
ResolveSiteHost returns the full hostname of a site declared in the config file: a name without a dot is a subdomain of the base domain.
Types ¶
type BasicAuth ¶ added in v0.9.0
type BasicAuth struct {
User string // Username
Pass string // Password
Realm string // Authentication realm (optional, default: "Restricted")
}
BasicAuth holds basic authentication credentials
type DeclaredSite ¶ added in v1.4.0
type DeclaredSite struct {
Hostname string
// Exactly one of Static and Proxy is set, pointing at the entry as written.
Static *StaticSite
Proxy *ProxySite
Root string // Static: the root with ~ expanded
Target *url.URL // Proxy: the parsed target, nil when it does not parse
// Err is why roji does not serve the site, nil when it does.
Err error
// CertCovered is false when the hostname is one roji's certificate is not
// valid for. The site is served all the same; browsers reject it.
CertCovered bool
// Unpublishable is true when the site asks for the tunnel and can never
// get it: a public name is the local one with the base domain swapped for
// the tunnel's, so a hostname outside the base domain has no public name.
Unpublishable bool
}
DeclaredSite is one entry of static_sites or proxy_sites with everything roji decides about it worked out: what it is called, whether it is served, and what will not work if it is.
The server registers routes from this and `roji doctor` reports on it. Both read the same answer so that what doctor says about a site is what the server did with it.
func ResolveSiteName ¶ added in v1.4.0
func ResolveSiteName(host string, tunnel bool, baseDomain, dashboardHost string) DeclaredSite
ResolveSiteName works out what follows from a site's name alone: its hostname, whether the certificate and the tunnel can serve it, and whether the name is one roji keeps for itself. What the site serves is left unset.
It is the part of ResolveSites that does not need a config file, for a site that comes from somewhere else — `roji run` registering one over the API — to be held to the same rules.
func ResolveSites ¶ added in v1.4.0
func ResolveSites(staticSites []StaticSite, proxySites []ProxySite, baseDomain, dashboardHost string) []DeclaredSite
ResolveSites works out every site the config file declares, static sites first and in the order written, which is the order they are registered in.
func (DeclaredSite) SkipReason ¶ added in v1.4.0
func (s DeclaredSite) SkipReason() string
SkipReason returns the code for why the site is not served, empty when it is. It is the one place an Err is sorted into a reason: the server's reload report, `roji doctor` and `roji config reload` all go by it.
func (DeclaredSite) Where ¶ added in v1.4.0
func (s DeclaredSite) Where() string
Where returns what the site serves, for showing to a person: a static site's root, or a proxy site's target — as roji parsed it, or as written when it did not parse and there is nothing else to show.
type MockRoute ¶ added in v0.6.0
type MockRoute struct {
Method string // HTTP method (GET, POST, etc.)
Path string // URL path (e.g., "/api/users")
Body string // Response body
StatusCode int // HTTP status code (default: 200)
}
MockRoute defines a mock response for a specific method and path
type Paths ¶ added in v0.8.0
type Paths struct {
ConfigDir string // Directory for configuration files
DataDir string // Directory for data files (projects.json, etc.)
CertsDir string // Directory for certificates
}
Paths holds the resolved paths for configuration and data directories
func DefaultPaths ¶ added in v0.8.0
func DefaultPaths() *Paths
DefaultPaths returns the default paths following XDG Base Directory specification
type ProxySite ¶ added in v1.4.0
type ProxySite struct {
Host string `yaml:"host"` // Hostname or subdomain, resolved like StaticSite.Host
// Target is the URL of the server, e.g. "http://127.0.0.1:8787". A URL is
// the only spelling: a `port:` shorthand would leave two ways to write the
// same site.
Target string `yaml:"target"`
Auth *SiteAuth `yaml:"auth,omitempty"` // Authentication configuration
Tunnel bool `yaml:"tunnel,omitempty"` // Publish through the tunnel (default: false)
}
ProxySite gives a hostname to a server already listening on the host — a dev server started outside Docker, such as `vite dev` or `wrangler dev`.
type RouteConfig ¶
type RouteConfig struct {
Host string // e.g., "myapp.localhost"
Port int // Target port
// PathPrefix is empty, or a rooted path with no trailing slash ("/api").
// Empty is the only spelling of "no prefix": a label naming the root gives
// an empty prefix rather than "/".
PathPrefix string
MockRoutes []*MockRoute // Mock responses for this container
BasicAuth *BasicAuth // Basic authentication (optional)
// Tunnel opts this route into being reachable from the internet. Publishing
// is opt-in per container: roji routes everything on its network without
// asking, and that default is safe only as long as it stays local.
Tunnel bool
}
RouteConfig holds the configuration for a single route
func ParseLabels ¶
func ParseLabels(labels map[string]string) *RouteConfig
ParseLabels extracts roji configuration from container labels
type Settings ¶ added in v0.8.0
type Settings struct {
Network string `yaml:"network"` // Docker network name(s) (comma-separated)
Domain string `yaml:"domain"` // Base domain (e.g., dev.localhost)
Bind string `yaml:"bind"` // Listen address(es) (comma-separated); empty means all interfaces
HTTPPort int `yaml:"http_port"` // HTTP port (for redirect)
HTTPSPort int `yaml:"https_port"` // HTTPS port
CertsDir string `yaml:"certs_dir"` // Directory for TLS certificates
DataDir string `yaml:"data_dir"` // Directory for persistent data
Dashboard string `yaml:"dashboard"` // Dashboard hostname
LogLevel string `yaml:"log_level"` // Log level (debug, info, warn, error)
AutoCert bool `yaml:"auto_cert"` // Auto-generate certificates
StaticSites []StaticSite `yaml:"static_sites,omitempty"` // Static file hosting sites
ProxySites []ProxySite `yaml:"proxy_sites,omitempty"` // Servers on the host given a hostname
Tunnel *Tunnel `yaml:"tunnel,omitempty"` // Cloudflare Tunnel for outside access
}
Settings holds all configuration settings for roji
func Defaults ¶ added in v0.8.0
func Defaults() *Settings
Defaults returns settings with default values
func Load ¶ added in v0.8.0
Load loads configuration with the following priority (highest to lowest): 1. CLI overrides (passed in cliOverrides) 2. Environment variables (ROJI_*) 3. The per-machine file next to the config file (LocalFilePath) 4. Config file 5. Defaults
func (*Settings) BindAddrs ¶ added in v1.1.0
BindAddrs returns the addresses to listen on, one per listener.
An empty setting means every interface, returned as a single wildcard entry; it is the only case where the list holds one, since parsing drops empty parts.
func (*Settings) ListensBeyondLoopback ¶ added in v1.1.0
ListensBeyondLoopback reports whether any listener accepts connections from outside the machine. That matters because roji publishes every container on its network without requiring a label, and the dashboard's Compose endpoints have no authentication: reaching roji is enough to control containers.
func (*Settings) LocalAddr ¶ added in v1.1.0
LocalAddr returns an address this machine can reach the server on.
Loopback is preferred because a connection to it never leaves the machine. The wildcard has no address of its own, so localhost stands in. Otherwise any configured address will do: the server bound it, so it names an interface here. Order within the setting is not meaningful, so nothing depends on it beyond that last case, where every candidate is equivalent.
func (*Settings) SaveToFile ¶ added in v0.8.0
SaveToFile saves settings to a YAML file
type SiteAuth ¶ added in v1.4.0
type SiteAuth struct {
Basic *BasicAuth `yaml:"basic,omitempty"` // Basic authentication
}
SiteAuth holds authentication configuration for a site declared in the config file.
type StaticSite ¶ added in v0.9.0
type StaticSite struct {
Host string `yaml:"host"` // Hostname or subdomain (e.g., "docs" or "docs.example.com")
Root string `yaml:"root"` // Root directory path (supports ~ expansion)
Index *bool `yaml:"index,omitempty"` // Enable directory listing (default: true, set false to disable)
Auth *SiteAuth `yaml:"auth,omitempty"` // Authentication configuration
Tunnel bool `yaml:"tunnel,omitempty"` // Publish through the tunnel (default: false)
}
StaticSite represents a static file hosting configuration
func (*StaticSite) GetBasicAuth ¶ added in v0.9.0
func (s *StaticSite) GetBasicAuth() *BasicAuth
GetBasicAuth returns the basic auth configuration if set
func (*StaticSite) IndexEnabled ¶ added in v0.9.0
func (s *StaticSite) IndexEnabled() bool
IndexEnabled returns whether directory listing is enabled (default: true)
type Tunnel ¶ added in v1.2.0
type Tunnel struct {
// Domain is a zone on the Cloudflare account, e.g. "example.com". A route
// published as "web.dev.localhost" locally answers to "web.example.com".
//
// One level only. Cloudflare's Universal SSL covers "example.com" and
// "*.example.com"; a two-level name like "*.tunnel.example.com" needs the
// paid Advanced Certificate Manager.
Domain string `yaml:"domain"`
// Name is the named tunnel to run, created beforehand with
// `cloudflared tunnel create`.
//
// TunnelNameAuto stands for a name derived from this machine's hostname
// (AutoTunnelName), and Load replaces it with that name. A tunnel's
// credentials live only on the machine that created it, and Cloudflare
// does not choose between two machines running the same one, so each
// machine needs a tunnel of its own while the config file is shared.
Name string `yaml:"name"`
// AutoName records that Name was derived from the hostname rather than
// written in the file.
AutoName bool `yaml:"-"`
// Port is the tunnel listener's port on 127.0.0.1. cloudflared reaches roji
// through it, and every request arriving there is treated as coming from
// the internet.
//
// A separate port is the whole mechanism: cloudflared connects from
// 127.0.0.1 like any local browser, so nothing in the request distinguishes
// the two. The port does.
Port int `yaml:"port,omitempty"`
// AutoStart runs cloudflared alongside roji. With it off the listener still
// opens and whoever wants the tunnel runs `cloudflared tunnel run` himself.
AutoStart bool `yaml:"auto_start,omitempty"`
// Routes publishes the routes on these hostnames without a label or a
// `tunnel` key, in addition to those that have one. A name is written as
// a declared site's host: without a dot it is a subdomain of the base
// domain.
//
// It belongs in the per-machine file (LocalFilePath): a public name's DNS
// record points at one tunnel, so which machine publishes a route is that
// machine's choice, and a label in a compose file shared between machines
// cannot make it.
Routes []string `yaml:"routes,omitempty"`
}
Tunnel configures exposing selected routes to the internet through a Cloudflare Tunnel.
roji runs cloudflared as a child process rather than linking it: the library pulls in a QUIC stack and several megabytes of binary, and roji already shells out to `docker compose` for the same reason.
func (*Tunnel) AutoNameFailed ¶ added in v1.6.0
AutoNameFailed reports whether `name: auto` was asked for and no name could be derived, which leaves the tunnel off.
func (*Tunnel) Enabled ¶ added in v1.2.0
Enabled reports whether the tunnel is configured well enough to open the listener. Both names are required: the domain decides which public hostnames resolve to which route, and the tunnel name decides what cloudflared runs.
func (*Tunnel) ListenPort ¶ added in v1.2.0
ListenPort returns the port the tunnel listener binds, filling in the default for a tunnel configured without one.
func (*Tunnel) ResolveRoutes ¶ added in v1.6.0
func (t *Tunnel) ResolveRoutes(baseDomain, dashboardHost string) []DeclaredSite
ResolveRoutes resolves each name in Routes through ResolveSiteName, so a hostname listed here is held to the rules a declared site's is: Err is set for one roji keeps for itself, and Unpublishable for one outside the base domain, which has no public name. Empty names are left out.
type ValidationIssue ¶ added in v0.9.0
type ValidationIssue struct {
Path string // YAML path (e.g., "static_sites[0].auth.basic")
Type string // Issue type: "unknown_key", "invalid_type"
Message string // Human-readable message
}
ValidationIssue represents a single validation issue
type ValidationResult ¶ added in v0.9.0
type ValidationResult struct {
Issues []ValidationIssue
}
ValidationResult holds the result of config validation
func ValidateConfigYAML ¶ added in v0.9.0
func ValidateConfigYAML(data []byte) *ValidationResult
ValidateConfigYAML validates raw YAML config data
func (*ValidationResult) FormatMessages ¶ added in v0.9.0
func (r *ValidationResult) FormatMessages() []string
FormatMessages returns all issues as formatted strings
func (*ValidationResult) HasIssues ¶ added in v0.9.0
func (r *ValidationResult) HasIssues() bool
HasIssues returns true if any validation issues were found
func (*ValidationResult) LogWarnings ¶ added in v0.9.0
func (r *ValidationResult) LogWarnings()
LogWarnings logs all validation issues as warnings