Documentation
¶
Overview ¶
Package hubauth implements authentication, authorization, OAuth 2.1 + PKCE (S256), multi-user GitHub OAuth, the /admin Control Center & AES-256-GCM MCP credential vault, and connection/origin/header hardening for the Go Hub.
Index ¶
- Constants
- Variables
- func ApplySecurityHeaders(w http.ResponseWriter, isHTTPS bool)
- func MintGitHubSessionJWT(secret string, u GitHubUser, now time.Time, ttl time.Duration) (token, jti, csrf string, err error)
- func NormalizeSignupMode(raw, allowedUsers string) string
- func OpenGitHubToken(secret, userID, ciphertext string) (string, error)
- func OpenVaultPayload(params mcpfed.UnsealVaultParams) mcpfed.UnsealVaultResult
- func ParseRedirectAllowlist(raw string) []string
- func ResolveClientIP(r *http.Request, trustProxy, trustFly bool) string
- func ResolveConfiguredPublicOrigin(getenv func(string) string) string
- func ResolveRequestPublicOrigin(r *http.Request, configuredOrigin, fallbackOrigin string, trustProxy bool) (origin string, validHost bool)
- func SealGitHubToken(secret, userID, plainToken string) (string, error)
- func SealVaultPayload(params mcpfed.SealVaultParams) mcpfed.SealVaultResult
- func TrackConnState(srv *http.Server, opts ConnGuardOptions)
- func ValidateFederatedMcpServerURL(rawURL, selfHost string) mcpfed.SafeHTTPSURLResult
- func VerifyGitHubSessionJWT(token, secret string, now time.Time) (sessionJWTClaims, bool)
- type AdminFetchRequest
- type AdminHubState
- type Callbacks
- type Config
- type ConnGuardOptions
- type ConnectedMcpServer
- type Decision
- type FleetAgentVersion
- type GitHubAllowlist
- type GitHubConfig
- type GitHubUser
- type GuardedListener
- type Manager
- func (m *Manager) AuthorizeCaller(r *http.Request, requiredScope string, allowMcpToken bool, ownerOnly bool) Decision
- func (m *Manager) CheckHubUpdateStatus(ctx context.Context, agents []FleetAgentVersion) UpdateStatus
- func (m *Manager) HandleAdmin(w http.ResponseWriter, r *http.Request, origin string) bool
- func (m *Manager) HandleAdminAffinityClear(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminEventsClear(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminFetch(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminGrantsRevoke(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminLogin(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleAdminLogout(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleAdminMcpServers(w http.ResponseWriter, r *http.Request, sess verifiedSession, origin string, ...)
- func (m *Manager) HandleAdminPage(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleAdminState(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminTelemetry(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAdminTrackerListRefresh(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
- func (m *Manager) HandleAuthServerMetadata(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleAuthorize(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleGitHubCallback(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleGitHubStart(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleOAuthOrWellKnown(w http.ResponseWriter, r *http.Request, origin string) bool
- func (m *Manager) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) HandleRegister(w http.ResponseWriter, r *http.Request)
- func (m *Manager) HandleRevoke(w http.ResponseWriter, r *http.Request)
- func (m *Manager) HandleToken(w http.ResponseWriter, r *http.Request, origin string)
- func (m *Manager) ListDecryptedMcpServers(ownerID string) ([]ConnectedMcpServer, error)
- type OAuthClient
- type OAuthGrant
- type Principal
- type UpdateStatus
Constants ¶
const ( DefaultMaxTotalConns = 512 DefaultMaxConnsPerIP = 64 DefaultLoopbackReserved = 32 DefaultPreHeaderTimeout = 10 * time.Second )
const ( CookieOAuthCSRFDev = "ef_oauth_csrf" CookieOAuthCSRFSecure = "__Host-ef_oauth_csrf" CookieAdminDev = "ef_admin_session" CookieAdminSecure = "__Host-ef_admin_session" CookieUserDev = "ef_user_session" CookieUserSecure = "__Host-ef_user_session" CookieGHStateDev = "ef_gh_oauth" CookieGHStateSecure = "__Host-ef_gh_oauth" )
Variables ¶
var ( SupportedScopes = []string{"crawl:read", "crawl:fetch", "mcp:call"} DefaultScopes = []string{"crawl:read", "crawl:fetch"} )
Functions ¶
func ApplySecurityHeaders ¶
func ApplySecurityHeaders(w http.ResponseWriter, isHTTPS bool)
ApplySecurityHeaders sets baseline browser security headers on w.
func MintGitHubSessionJWT ¶
func MintGitHubSessionJWT(secret string, u GitHubUser, now time.Time, ttl time.Duration) (token, jti, csrf string, err error)
MintGitHubSessionJWT mints an HS256 JWT derived via HKDF-SHA256 from secret.
func NormalizeSignupMode ¶
NormalizeSignupMode normalizes SIGNUP_MODE ("closed" default, "allowlist", "open").
func OpenGitHubToken ¶
OpenGitHubToken decrypts and authenticates a "ght1." AES-256-GCM GitHub token ciphertext.
func OpenVaultPayload ¶
func OpenVaultPayload(params mcpfed.UnsealVaultParams) mcpfed.UnsealVaultResult
OpenVaultPayload authenticates and decrypts a v2. AES-256-GCM vault ciphertext.
func ParseRedirectAllowlist ¶
ParseRedirectAllowlist splits a comma/whitespace OAUTH_REDIRECT_ALLOWLIST env value.
func ResolveClientIP ¶
ResolveClientIP extracts the canonical client IP (or IPv6 /64 prefix) for rate limiting and audit logging.
func ResolveConfiguredPublicOrigin ¶
ResolveConfiguredPublicOrigin resolves explicit or platform-injected public origin env vars.
func ResolveRequestPublicOrigin ¶
func ResolveRequestPublicOrigin(r *http.Request, configuredOrigin, fallbackOrigin string, trustProxy bool) (origin string, validHost bool)
ResolveRequestPublicOrigin resolves the canonical origin for r while rejecting malformed or multi-Host headers.
func SealGitHubToken ¶
SealGitHubToken encrypts a GitHub user token using HKDF-SHA256 + AES-256-GCM ("ght1.<salt>.<iv>.<ct>").
func SealVaultPayload ¶
func SealVaultPayload(params mcpfed.SealVaultParams) mcpfed.SealVaultResult
SealVaultPayload encrypts a VaultSecretPayload with v2. AES-256-GCM row-bound AAD.
func TrackConnState ¶
func TrackConnState(srv *http.Server, opts ConnGuardOptions)
TrackConnState installs pre-header timeout and per-IP/global pre-header socket tracking onto srv.
func ValidateFederatedMcpServerURL ¶
func ValidateFederatedMcpServerURL(rawURL, selfHost string) mcpfed.SafeHTTPSURLResult
ValidateFederatedMcpServerURL validates a 3rd-party HTTPS MCP server URL via internal/mcpfed.
Types ¶
type AdminFetchRequest ¶
type AdminFetchRequest struct {
URL string `json:"url"`
Kind string `json:"kind"`
Target string `json:"target"`
Site string `json:"site,omitempty"`
PauseMs int `json:"pauseMs,omitempty"`
PauseJitterMs int `json:"pauseJitterMs,omitempty"`
RespectRobots bool `json:"respectRobots"`
IncludeBody bool `json:"includeBody"`
}
AdminFetchRequest represents an interactive fetch triggered from /admin.
type AdminHubState ¶
type AdminHubState struct {
Connected int `json:"connected"`
DistinctPublicIPs int `json:"distinctPublicIps"`
Agents []FleetAgentVersion `json:"-"`
AgentsRaw any `json:"agents"`
Affinities any `json:"affinities"`
TrackerList any `json:"trackerList,omitempty"`
Events any `json:"events"`
}
AdminHubState carries live fleet/affinity/event state into GET /admin/api/state.
type Callbacks ¶
type Callbacks struct {
GetAdminState func(ctx context.Context) (AdminHubState, error)
ExecuteAdminFetch func(ctx context.Context, req AdminFetchRequest) (status int, via string, body []byte, err error)
ClearAffinities func(ctx context.Context, siteID string) error
ClearEvents func(ctx context.Context) error
RefreshTrackerList func(ctx context.Context) (updated bool, status any, err error)
OnTelemetryToggle func(enabled bool)
}
Callbacks connects /admin endpoints to live Hub operations.
type Config ¶
type Config struct {
DataDir, ServiceName, McpSlug, HubVersion string
CallerToken, McpToken string
SessionSecret, VaultMasterKey, PublicOrigin string
AllowedLoopbackPort, ReleaseAPIURL string
TrustProxy, TrustFly, DisableUpdateCheck bool
RedirectAllowlist []string
GitHub GitHubConfig
Getenv func(string) string
HTTPClient *http.Client
OtelExporter *otel.Exporter
Now func() time.Time
Callbacks Callbacks
}
Config configures a hubauth Manager.
type ConnGuardOptions ¶
type ConnGuardOptions struct {
MaxTotal int
MaxPerIP int
LoopbackReserved int
PreHeaderTimeout time.Duration
IdleTimeout time.Duration
}
ConnGuardOptions configures socket admission and pre-header timeout limits.
type ConnectedMcpServer ¶
type ConnectedMcpServer struct {
ID string `json:"id"`
UserID string `json:"userId"`
Slug string `json:"slug"`
Name string `json:"name"`
RemoteURL string `json:"remoteUrl"`
RemoteOrigin string `json:"remoteOrigin"`
Transport string `json:"transport"`
AuthType string `json:"authType"`
Domains []string `json:"domains"`
AutoRouteScrape bool `json:"autoRouteScrape"`
Tools []mcpfed.CachedMCPToolSchema `json:"tools"`
Headers map[string]string `json:"-"`
OAuth *mcpfed.VaultSecretOAuth `json:"-"`
}
ConnectedMcpServer holds a decrypted user-scoped MCP connector for /v1/mcp/query and call_connected_mcp.
type FleetAgentVersion ¶
type FleetAgentVersion struct {
SiteID string `json:"siteId"`
Version string `json:"version,omitempty"`
}
FleetAgentVersion describes a connected worker node version for CheckHubUpdateStatus.
type GitHubAllowlist ¶
GitHubAllowlist holds parsed GITHUB_ALLOWED_USERS entries.
func ParseGitHubAllowlist ¶
func ParseGitHubAllowlist(raw string) GitHubAllowlist
ParseGitHubAllowlist parses comma/whitespace-separated logins, id:<num>, and @org entries.
type GitHubConfig ¶
type GitHubConfig struct {
ClientID, ClientSecret string
OwnerID, OwnerLogin string
SignupMode, AllowedUsers string // SignupMode: "closed" (default), "allowlist", "open"
AuthorizeURL, TokenURL string
APIBaseURL string
}
GitHubConfig configures optional multi-user GitHub OAuth sign-in.
type GitHubUser ¶
type GitHubUser struct {
UserID string `json:"userId"`
GitHubID string `json:"githubId"`
GitHubLogin string `json:"githubLogin"`
AvatarURL string `json:"avatarUrl,omitempty"`
Role string `json:"role"` // "owner" or "member"
SessionEpoch int `json:"sessionEpoch"`
Disabled bool `json:"disabled,omitempty"`
AdmittedVia string `json:"admittedVia,omitempty"`
AdmittedOrg string `json:"admittedOrg,omitempty"`
EncryptedGHToken string `json:"encryptedGhToken,omitempty"`
CreatedAt int64 `json:"createdAt"`
LastLoginAt int64 `json:"lastLoginAt"`
}
GitHubUser stores a multi-user GitHub identity and role in oauth_state.json.
type GuardedListener ¶
GuardedListener wraps a net.Listener with global and per-IP active socket caps while preserving dedicated loopback headroom so local /health probes never starve.
func WrapListener ¶
func WrapListener(ln net.Listener, opts ConnGuardOptions) *GuardedListener
WrapListener wraps ln with per-IP and global socket limits plus loopback reservation.
func (*GuardedListener) Accept ¶
func (g *GuardedListener) Accept() (net.Conn, error)
Accept waits for and returns the next admitted connection to the listener.
func (*GuardedListener) Stats ¶
func (g *GuardedListener) Stats() (nonLoopbackActive, loopbackActive int, rejectedTotal, rejectedPerIP int64)
Stats returns a snapshot of active and rejected socket counters.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager coordinates OAuth 2.1, GitHub OAuth, /admin sessions, and the MCP credential vault.
func NewManager ¶
NewManager initializes a Manager and loads persisted state from DataDir/state/oauth_state.json when DataDir != "".
func (*Manager) AuthorizeCaller ¶
func (m *Manager) AuthorizeCaller(r *http.Request, requiredScope string, allowMcpToken bool, ownerOnly bool) Decision
AuthorizeCaller evaluates Bearer, X-Api-Key, OAuth efa_*, GitHub session cookies, and tokenless loopback mode.
func (*Manager) CheckHubUpdateStatus ¶
func (m *Manager) CheckHubUpdateStatus(ctx context.Context, agents []FleetAgentVersion) UpdateStatus
CheckHubUpdateStatus returns cached GitHub release status (skipping network when EDGEFETCH_DISABLE_UPDATE_CHECK=1).
func (*Manager) HandleAdmin ¶
HandleAdmin routes /admin and /admin/* requests, returning true if the path belongs to /admin.
func (*Manager) HandleAdminAffinityClear ¶
func (m *Manager) HandleAdminAffinityClear(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminAffinityClear serves POST /admin/api/affinity/clear with a strict 64 KiB body cap.
func (*Manager) HandleAdminEventsClear ¶
func (m *Manager) HandleAdminEventsClear(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminEventsClear serves POST /admin/api/events/clear.
func (*Manager) HandleAdminFetch ¶
func (m *Manager) HandleAdminFetch(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminFetch serves POST /admin/api/fetch.
func (*Manager) HandleAdminGrantsRevoke ¶
func (m *Manager) HandleAdminGrantsRevoke(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminGrantsRevoke serves POST /admin/api/grants/revoke.
func (*Manager) HandleAdminLogin ¶
HandleAdminLogin authenticates POST /admin/login with per-IP brute-force lockout.
func (*Manager) HandleAdminLogout ¶
HandleAdminLogout revokes the active session cookie and redirects to /admin.
func (*Manager) HandleAdminMcpServers ¶
func (m *Manager) HandleAdminMcpServers(w http.ResponseWriter, r *http.Request, sess verifiedSession, origin string, isHTTPS bool)
HandleAdminMcpServers implements GET/POST/DELETE /admin/api/mcp/servers(/:id).
func (*Manager) HandleAdminPage ¶
HandleAdminPage renders the /admin Control Center or login HTML.
func (*Manager) HandleAdminState ¶
func (m *Manager) HandleAdminState(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminState serves GET /admin/api/state.
func (*Manager) HandleAdminTelemetry ¶
func (m *Manager) HandleAdminTelemetry(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminTelemetry serves GET and POST /admin/api/telemetry, enforcing DO_NOT_TRACK=1 hard disable.
func (*Manager) HandleAdminTrackerListRefresh ¶
func (m *Manager) HandleAdminTrackerListRefresh(w http.ResponseWriter, r *http.Request, sess verifiedSession, isHTTPS bool)
HandleAdminTrackerListRefresh serves POST /admin/api/tracker-list/refresh (owner-only).
func (*Manager) HandleAuthServerMetadata ¶
HandleAuthServerMetadata serves RFC 8414 Authorization Server Metadata.
func (*Manager) HandleAuthorize ¶
HandleAuthorize serves GET and POST /oauth/authorize (OAuth 2.1 + PKCE S256 consent).
func (*Manager) HandleGitHubCallback ¶
HandleGitHubCallback completes GET /admin/auth/github/callback, enforcing founder pinning and SIGNUP_MODE.
func (*Manager) HandleGitHubStart ¶
HandleGitHubStart initiates GET /admin/auth/github PKCE + state redirect.
func (*Manager) HandleOAuthOrWellKnown ¶
func (m *Manager) HandleOAuthOrWellKnown(w http.ResponseWriter, r *http.Request, origin string) bool
HandleOAuthOrWellKnown dispatches OAuth 2.1 and RFC 9728/8414 discovery routes, returning true if handled.
func (*Manager) HandleProtectedResourceMetadata ¶
func (m *Manager) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request, origin string)
HandleProtectedResourceMetadata serves RFC 9728 Protected Resource Metadata.
func (*Manager) HandleRegister ¶
func (m *Manager) HandleRegister(w http.ResponseWriter, r *http.Request)
HandleRegister implements POST /oauth/register (RFC 7591 Dynamic Client Registration).
func (*Manager) HandleRevoke ¶
func (m *Manager) HandleRevoke(w http.ResponseWriter, r *http.Request)
HandleRevoke implements POST /oauth/revoke (RFC 7009).
func (*Manager) HandleToken ¶
HandleToken implements POST /oauth/token (authorization_code + rotating refresh_token).
func (*Manager) ListDecryptedMcpServers ¶
func (m *Manager) ListDecryptedMcpServers(ownerID string) ([]ConnectedMcpServer, error)
ListDecryptedMcpServers decrypts all enabled MCP servers belonging to ownerID for /v1/mcp/query and call_connected_mcp.
type OAuthClient ¶
type OAuthClient struct {
ClientID string `json:"clientId"`
ClientName string `json:"clientName"`
RedirectURIs []string `json:"redirectUris"`
CreatedAt int64 `json:"createdAt"`
}
OAuthClient represents a dynamically registered RFC 7591 OAuth client.
type OAuthGrant ¶
type OAuthGrant struct {
GrantID string `json:"grantId"`
ClientID string `json:"clientId"`
ClientName string `json:"clientName"`
UserID string `json:"userId"`
Role string `json:"role"`
Scopes []string `json:"scopes"`
Resource string `json:"resource"`
CurrentGen int `json:"currentGen"`
RefreshSecretHash string `json:"refreshSecretHash"`
Revoked bool `json:"revoked"`
CreatedAt int64 `json:"createdAt"`
ExpiresAt int64 `json:"expiresAt"`
}
OAuthGrant represents a persistent OAuth 2.1 refresh lineage.
type Principal ¶
type Principal struct {
Authenticated bool `json:"authenticated"`
Kind string `json:"kind"` // "owner", "mcp_token", "oauth", "github", "admin_cookie", "loopback"
UserID string `json:"userId,omitempty"`
GitHubLogin string `json:"githubLogin,omitempty"`
AvatarURL string `json:"avatarUrl,omitempty"`
Role string `json:"role,omitempty"` // "owner", "member"
Scopes []string `json:"scopes,omitempty"`
GrantID string `json:"grantId,omitempty"`
ClientID string `json:"clientId,omitempty"`
IsOwner bool `json:"isOwner"`
}
Principal describes an authenticated caller or browser session.
func (Principal) EffectiveOwnerID ¶
EffectiveOwnerID returns the isolated tenant key ("owner" for single-tenant owner/loopback, else UserID).
type UpdateStatus ¶
type UpdateStatus struct {
Enabled bool `json:"enabled"`
PillStatus string `json:"pillStatus"`
PillLabel string `json:"pillLabel"`
CurrentVersion string `json:"currentVersion"`
LatestVersion string `json:"latestVersion,omitempty"`
LatestTag string `json:"latestTag,omitempty"`
ReleaseURL string `json:"releaseUrl,omitempty"`
HubUpdateAvailable bool `json:"hubUpdateAvailable"`
OutdatedAgents []FleetAgentVersion `json:"outdatedAgents"`
CheckedAt int64 `json:"checkedAt,omitempty"`
SigningKeySPKIB64 string `json:"signingKeySpkiB64"`
}
UpdateStatus summarizes Hub and worker fleet release status for /admin.