auth

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PQCPolicyDisabled      = "disabled"
	PQCPolicyOpportunistic = "opportunistic"
	PQCPolicyMandatory     = "mandatory"
)

PQC policy constants.

View Source
const (
	// RoleAdmin grants full network management: create invites, manage peers,
	// modify policy. The first peer to join via relay pairing is auto-promoted.
	RoleAdmin = "admin"

	// RoleMember grants standard network access: connect, use services, verify peers.
	// This is the default when no role attribute is set (backward compatible).
	RoleMember = "member"
)

Role constants for peer authorization tiers.

Variables

View Source
var (
	// ErrPeerAlreadyAuthorized is returned when trying to add a peer
	// that is already in the authorized_keys file.
	ErrPeerAlreadyAuthorized = errors.New("peer already authorized")

	// ErrPeerNotFound is returned when trying to remove a peer
	// that is not in the authorized_keys file.
	ErrPeerNotFound = errors.New("peer not found")

	// ErrInvalidPeerID is returned when a peer ID string cannot be decoded.
	ErrInvalidPeerID = errors.New("invalid peer ID")
)

Functions

func AddPeer

func AddPeer(authKeysPath, peerIDStr, comment string) error

AddPeer validates and appends a peer ID to the authorized_keys file. Returns nil if the peer was added, or an error if invalid/duplicate.

func ComputeFileHash

func ComputeFileHash(path string) (string, error)

ComputeFileHash returns the SHA-256 hex digest of a file.

func CountAdmins

func CountAdmins(authKeysPath string) (int, error)

CountAdmins returns the number of peers with role=admin in the authorized_keys file.

func GetPeerAttr

func GetPeerAttr(authKeysPath, peerIDStr, key string) string

GetPeerAttr returns the value of a specific attribute for a peer. Returns empty string if the peer or attribute is not found. Uses string comparison on encoded peer IDs to avoid costly decoding per line.

func GetPeerRole

func GetPeerRole(authKeysPath string, peerID peer.ID) string

GetPeerRole returns the role attribute for a peer from the authorized_keys file. Returns RoleMember if the peer has no explicit role (backward compatible default).

func IsAdmin

func IsAdmin(authKeysPath string, peerID peer.ID) bool

IsAdmin checks whether a peer has the admin role.

func IsAuthorized

func IsAuthorized(peerID peer.ID, authorizedPeers map[peer.ID]bool) bool

IsAuthorized checks if a peer ID is in the authorized list

func LoadAuthorizedKeys

func LoadAuthorizedKeys(path string) (map[peer.ID]bool, error)

LoadAuthorizedKeys loads and parses an authorized_keys file. Returns a simple peer ID -> bool map for backward compatibility. Format: <peer-id> [key=value attrs...] [# comment]

func LoadCommentMap added in v0.4.0

func LoadCommentMap(path string) (map[string]peer.ID, error)

LoadCommentMap loads an authorized_keys file and returns a map from comment (lowercased) to peer ID. Only entries with non-empty comments are included. This enables resolving friendly names like "relay" or "home-node" to their peer IDs.

func LoadPQCOverrides added in v0.4.1

func LoadPQCOverrides(path string) (map[peer.ID]string, error)

LoadPQCOverrides loads per-peer PQC policy overrides from an authorized_keys file. Returns a map of peer ID -> policy string for peers that have a "pqc=mandatory" or "pqc=opportunistic" attribute. Peers without the attr are not included (they use the global policy).

func PeerComment

func PeerComment(authKeysPath string, peerID peer.ID) string

PeerComment returns the comment (friendly name) for a peer in authorized_keys. Returns empty string if the peer is not found or on error.

func RemovePeer

func RemovePeer(authKeysPath, peerIDStr string) error

RemovePeer removes a peer ID from the authorized_keys file using atomic write. Returns nil if the peer was removed, or an error if not found/invalid.

func SaveIntegrityHash

func SaveIntegrityHash(authKeysPath string)

SaveIntegrityHash computes and saves the SHA-256 hash of the authorized_keys file. Called after every mutation (add, remove, set-attr) to maintain the integrity record. Preserves file ownership when running as root.

func SetPeerAttr

func SetPeerAttr(authKeysPath, peerIDStr, key, value string) error

SetPeerAttr sets or updates an attribute on an existing peer in the authorized_keys file. Uses atomic write via temp file + rename.

func SetPeerRole

func SetPeerRole(authKeysPath, peerIDStr, role string) error

SetPeerRole sets the role attribute on an authorized peer.

func VerifyIntegrity

func VerifyIntegrity(authKeysPath string) bool

VerifyIntegrity checks the authorized_keys file against its stored hash. Returns true if the hash matches or no hash file exists (first run). Returns false if the file was modified out-of-band (tampering detected).

func WriteFilePreserveOwnership

func WriteFilePreserveOwnership(path string, data []byte, perm os.FileMode) error

WriteFilePreserveOwnership is like os.WriteFile but preserves file ownership when running as root on files owned by a different user. This prevents root-run CLI commands from flipping ownership on service user files.

Types

type AuthDecisionFunc

type AuthDecisionFunc func(peerID, result string)

AuthDecisionFunc is called on every inbound auth decision with the peer ID (truncated) and result ("allow" or "deny"). Used for metrics and audit logging without creating a circular dependency on pkg/sdk.

type AuthorizedPeerGater

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

AuthorizedPeerGater implements the ConnectionGater interface. It blocks connections from peers that are not in the authorized list. Supports enrollment mode for relay pairing and expiring peer authorization.

func NewAuthorizedPeerGater

func NewAuthorizedPeerGater(authorizedPeers map[peer.ID]bool) *AuthorizedPeerGater

NewAuthorizedPeerGater creates a new connection gater with the given authorized peers.

func (*AuthorizedPeerGater) CleanupProbation

func (g *AuthorizedPeerGater) CleanupProbation(disconnect func(peer.ID))

CleanupProbation evicts probation peers that have exceeded the timeout. The disconnect callback is called for each evicted peer (outside the lock).

func (*AuthorizedPeerGater) GetAuthorizedPeerIDs

func (g *AuthorizedPeerGater) GetAuthorizedPeerIDs() []peer.ID

GetAuthorizedPeerIDs returns a slice of all currently authorized peer IDs. Used by PeerManager to build the reconnection watchlist.

func (*AuthorizedPeerGater) GetAuthorizedPeersCount

func (g *AuthorizedPeerGater) GetAuthorizedPeersCount() int

GetAuthorizedPeersCount returns the number of authorized peers

func (*AuthorizedPeerGater) InterceptAccept

func (g *AuthorizedPeerGater) InterceptAccept(cm network.ConnMultiaddrs) bool

InterceptAccept is called when accepting a connection (before crypto handshake)

func (*AuthorizedPeerGater) InterceptAddrDial

func (g *AuthorizedPeerGater) InterceptAddrDial(id peer.ID, addr ma.Multiaddr) bool

InterceptAddrDial is called when dialing an address. When a LAN dial filter is set, blocks non-LAN dials to peers that already have a LAN connection (prevents identify/DHT address leaks from displacing established LAN paths).

func (*AuthorizedPeerGater) InterceptPeerDial

func (g *AuthorizedPeerGater) InterceptPeerDial(p peer.ID) bool

InterceptPeerDial is called when dialing a peer

func (*AuthorizedPeerGater) InterceptSecured

func (g *AuthorizedPeerGater) InterceptSecured(dir network.Direction, p peer.ID, addr network.ConnMultiaddrs) bool

InterceptSecured is called after the crypto handshake (peer ID is verified). This is the PRIMARY authorization check point.

Uses a write lock (not RWMutex read lock) because the enrollment/probation path mutates state. A single lock type eliminates the RLock->Lock upgrade gap that could allow brief probation limit overruns under contention. This is called per-connection (not per-packet), so the cost is negligible.

func (*AuthorizedPeerGater) InterceptUpgraded

func (g *AuthorizedPeerGater) InterceptUpgraded(conn network.Conn) (bool, control.DisconnectReason)

InterceptUpgraded is called after connection upgrade (after muxer negotiation). Enforces PQC policy as belt-and-suspenders: rejects classical Noise connections when the effective policy for the peer is "mandatory".

QUIC connections report empty Security (PQC handled at TLS layer via X25519MLKEM768) and are always allowed through this check.

func (*AuthorizedPeerGater) IsAuthorized

func (g *AuthorizedPeerGater) IsAuthorized(p peer.ID) bool

IsAuthorized checks if a peer is authorized

func (*AuthorizedPeerGater) IsEnrollmentEnabled

func (g *AuthorizedPeerGater) IsEnrollmentEnabled() bool

IsEnrollmentEnabled returns whether enrollment mode is active.

func (*AuthorizedPeerGater) PQCPolicy added in v0.4.1

func (g *AuthorizedPeerGater) PQCPolicy() string

PQCPolicy returns the current global PQC policy.

func (*AuthorizedPeerGater) PrintAuthorizedPeers

func (g *AuthorizedPeerGater) PrintAuthorizedPeers()

PrintAuthorizedPeers prints the list of authorized peers (for debugging)

func (*AuthorizedPeerGater) ProbationCount

func (g *AuthorizedPeerGater) ProbationCount() int

ProbationCount returns the current number of probation peers.

func (*AuthorizedPeerGater) PromotePeer

func (g *AuthorizedPeerGater) PromotePeer(p peer.ID)

PromotePeer moves a peer from probation to the authorized list.

func (*AuthorizedPeerGater) SetDecisionCallback

func (g *AuthorizedPeerGater) SetDecisionCallback(fn AuthDecisionFunc)

SetDecisionCallback sets a callback invoked on every inbound auth decision. This is used by the observability layer to record metrics and audit events without creating a circular import from internal/auth to pkg/sdk.

func (*AuthorizedPeerGater) SetEnrollmentMode

func (g *AuthorizedPeerGater) SetEnrollmentMode(enabled bool, limit int, timeout time.Duration)

SetEnrollmentMode enables or disables enrollment mode for relay pairing. When enabled, unknown peers are admitted on probation up to the limit.

func (*AuthorizedPeerGater) SetLANDialFilter added in v0.4.0

func (g *AuthorizedPeerGater) SetLANDialFilter(fn func(peer.ID, ma.Multiaddr) bool)

SetLANDialFilter sets a callback that controls outbound address dials. The callback receives the target peer ID and address. Return true to allow the dial, false to block it.

func (*AuthorizedPeerGater) SetPQCPolicy added in v0.4.1

func (g *AuthorizedPeerGater) SetPQCPolicy(policy string) error

SetPQCPolicy sets the global PQC policy. Only "mandatory" and "opportunistic" are valid runtime values. "disabled" can only be set at startup (F151). Returns an error if attempting to set "disabled" at runtime.

func (*AuthorizedPeerGater) SetPQCPolicyStartup added in v0.4.1

func (g *AuthorizedPeerGater) SetPQCPolicyStartup(policy string)

SetPQCPolicyStartup sets the PQC policy at startup (allows all values including "disabled").

func (*AuthorizedPeerGater) SetPeerExpiry

func (g *AuthorizedPeerGater) SetPeerExpiry(p peer.ID, expiresAt time.Time)

SetPeerExpiry sets an expiration time for an authorized peer. Zero time means never expires.

func (*AuthorizedPeerGater) SetPeerPQCOverride added in v0.4.1

func (g *AuthorizedPeerGater) SetPeerPQCOverride(p peer.ID, policy string)

SetPeerPQCOverride sets a per-peer PQC policy override. Pass empty string to remove the override.

func (*AuthorizedPeerGater) UpdateAuthorizedPeers

func (g *AuthorizedPeerGater) UpdateAuthorizedPeers(authorizedPeers map[peer.ID]bool)

UpdateAuthorizedPeers updates the authorized peers list (for hot-reload support)

func (*AuthorizedPeerGater) UpdatePeerPQCOverrides added in v0.4.1

func (g *AuthorizedPeerGater) UpdatePeerPQCOverrides(overrides map[peer.ID]string)

UpdatePeerPQCOverrides replaces all per-peer PQC overrides with the given map. Used during hot-reload to sync with authorized_keys file.

type PeerEntry

type PeerEntry struct {
	PeerID    peer.ID
	Comment   string
	ExpiresAt time.Time // zero = never expires
	Verified  string    // empty = unverified, otherwise fingerprint prefix
	Group     string    // pairing group ID (empty = manually added or invited)
	Role      string    // "admin" or "member" (empty = member, backward compatible)
}

PeerEntry represents an authorized peer with optional comment and attributes.

func ListPeers

func ListPeers(authKeysPath string) ([]PeerEntry, error)

ListPeers reads the authorized_keys file and returns all peer entries including attributes (expires, verified).

Jump to

Keyboard shortcuts

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