server

package
v0.7.19 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server provides reusable scaffolding for building CEDAR command servers (daemons that accept connections, authenticate, and dispatch HTCondor commands). It complements the client-focused packages in this module.

Two kinds of command handlers are supported:

  • Authenticated commands: the client opens the exchange with a DC_AUTHENTICATE command and a security ClassAd that carries the real command (e.g. CCB_REGISTER). The server performs the security handshake and dispatches on the real command. A DC_SEC_QUERY (condor_ping) or a DC_AUTHENTICATE real command dispatches nothing: the server authorizes the command the client names as AuthCommand and answers for it.
  • Raw commands: the client sends a bare command integer with no security handshake (e.g. CCB_REVERSE_CONNECT, which HTCondor registers as ALLOW and sends via the "raw" command protocol). These are dispatched directly with no authentication.

Index

Constants

View Source
const DefaultHandshakeDeadline = 120 * time.Second

DefaultHandshakeDeadline is SEC_TCP_SESSION_DEADLINE's default.

View Source
const DefaultMaxPendingConnections = 4096

DefaultMaxPendingConnections is New's MaxPendingConnections.

View Source
const UnauthenticatedFQU = "unauthenticated@unmapped"

UnauthenticatedFQU is the identity HTCondor gives a peer that did not authenticate (UNAUTHENTICATED_FQU, src/condor_io/authentication.cpp). Sock::getFullyQualifiedUser (sock.cpp) returns it for an unauthenticated socket and DaemonCore passes that to IpVerify::Verify (daemon_command.cpp), so an ALLOW_* list admits such a peer only through an entry matching this string, e.g. "*" or "unauthenticated@unmapped". It is not "", which IpVerify::Verify treats as the wildcard user "*" (condor_ipverify.cpp).

Variables

View Source
var ErrConnectionNotAdmitted = errors.New("cedar/server: connection not admitted")

ErrConnectionNotAdmitted is returned by ServeConn, wrapping the callback's error, for a connection AdmitConnection refused.

View Source
var ErrHandshakeDeadline = errors.New("cedar/server: connection did not reach a handler before the handshake deadline")

ErrHandshakeDeadline is returned by ServeConn for a connection closed because it did not reach its handler within HandshakeDeadline.

View Source
var ErrTooManyPendingConnections = errors.New("cedar/server: too many connections awaiting a handler")

ErrTooManyPendingConnections is returned by ServeConn for a connection refused because MaxPendingConnections connections are already pending.

Functions

func KeepOpen

func KeepOpen() error

KeepOpen is returned by a handler that has taken ownership of the connection (e.g. a persistent CCB registration socket or a proxied stream). ServeConn will not close the underlying connection in that case.

Types

type Conn

type Conn struct {
	// Stream is the CEDAR stream for the connection. For authenticated
	// commands it is authenticated (and possibly encrypted) by the time the
	// handler runs; for raw commands it is plaintext.
	Stream *stream.Stream

	// Command is the real HTCondor command being dispatched.
	Command int

	// Negotiation is the result of the security handshake, or nil for raw
	// commands. Its User is the peer's authenticated identity, or "" when the
	// session did not authenticate (see AuthorizationUser).
	Negotiation *security.SecurityNegotiation

	// Message is the inbound Message the leading command integer was read
	// from. Raw-command handlers read their payload (e.g. a ClassAd) from
	// this message; authenticated handlers normally start a fresh message.
	// For a follow-on command on a kept-alive connection (see KeepAlive) it is
	// the message the follow-on command integer was read from, so the handler
	// reads that command's ad from the same message.
	Message *message.Message

	// RemoteAddr is the peer's network address.
	RemoteAddr string
	// contains filtered or unexported fields
}

Conn is the per-connection context handed to a command handler.

func (*Conn) AuthorizationLimits

func (c *Conn) AuthorizationLimits() []string

AuthorizationLimits returns the authorization levels the peer's credential was limited to (e.g. by an IDTOKEN's "condor:/<LEVEL>" scopes), or nil if the session has no such bounding set (including raw commands). The server applies it to the command's registered levels before dispatch; a handler that authorizes at some other level itself should also check that level with InAuthorizationBoundingSet, as HTCondor daemons call Sock::isAuthorizationInBoundingSet.

func (*Conn) AuthorizationUser

func (c *Conn) AuthorizationUser() string

AuthorizationUser returns the identity to authorize this connection's peer as: its authenticated identity, or UnauthenticatedFQU when the peer did not authenticate (including raw commands). Handlers that consult an authorizer themselves should pass this rather than Negotiation.User.

func (*Conn) FinishTrace added in v0.7.19

func (c *Conn) FinishTrace()

FinishTrace reports the command to Server.TraceCommand's completion now, as having succeeded, rather than when the handler returns. A handler that serves its connection for as long as it lives -- a CCB registration can last days -- calls it once the request is answered, so the command's span ends then. It is safe to call more than once, from any goroutine, and does nothing when the command is not traced.

func (*Conn) InAuthorizationBoundingSet

func (c *Conn) InAuthorizationBoundingSet(perm string) bool

InAuthorizationBoundingSet reports whether the session's authorization bounding set permits the level perm: always for ALLOW or a session with no bounding set, otherwise if perm is one of its levels or a level one of them implies (DAEMON implies WRITE and READ, ADVERTISE_STARTD implies READ, ...).

func (*Conn) KeepAlive

func (c *Conn) KeepAlive()

KeepAlive requests that, after this handler returns nil, the server keep the connection open and dispatch the next command the peer sends on the same session (rather than closing). Used by update handlers to serve HTCondor's persistent command-socket protocol. Ignored if the handler returns an error.

func (*Conn) PeerVersion

func (c *Conn) PeerVersion() string

PeerVersion returns the peer's reported $CondorVersion$ string, or "" if it was not exchanged (e.g. for raw commands).

type HandlerFunc

type HandlerFunc func(ctx context.Context, c *Conn) error

HandlerFunc handles a single dispatched command. Returning an error closes the connection unless the handler has taken ownership of it (see KeepOpen).

type Server

type Server struct {
	// SecurityConfig is used for the server side of the security handshake on
	// authenticated commands. It must be non-nil if any authenticated handler
	// is registered.
	SecurityConfig *security.SecurityConfig

	// SecurityConfigForCommand, if set, selects a per-command security policy for
	// the handshake: once the client's requested command is known, the returned
	// config replaces SecurityConfig for that connection's negotiation. This lets
	// a daemon serve different commands at different HTCondor authorization levels
	// (e.g. a collector negotiating a QUERY at READ but an UPDATE at ADVERTISE).
	// Returning nil falls back to SecurityConfig. A returned config without its
	// own PostAuthPolicy or CommandPerms takes SecurityConfig's (installed by
	// New), so FQUMapper, the advertised ValidCommands and authorization limits
	// apply whatever the command's policy. Optional.
	SecurityConfigForCommand func(command int) *security.SecurityConfig

	// Authorizer, if set, reports whether a peer is allowed at a given
	// authorization level. perm is an HTCondor DCpermission name (e.g. "READ",
	// "DAEMON"); peerAddr is the peer's "host:port"; user is the mapped FQU of an
	// authenticated peer, or UnauthenticatedFQU for one that did not
	// authenticate, whatever identity its session records. The server consults
	// it — for every registered authenticated command's levels — to compute the
	// session's ValidCommands after authentication, so a peer can reuse the
	// session for any command it is authorized for. It also authorizes every
	// command before dispatch, except a command registered with no levels,
	// which carries no authorization requirement; on a full handshake that
	// happens before the handshake's reply, so a refused command is answered
	// DENIED and its session is not cached. Leaving it nil advertises only the
	// negotiated command (no authorization table applied).
	Authorizer func(perm, peerAddr, user string) bool

	// FQUMapper, if set, maps an authenticated identity to the fully-qualified
	// user to advertise and authorize as (e.g. via a mapfile). authUser is the
	// FQU the authentication method produced, as C++ HTCondor reports it before
	// any map file (e.g. condor@pool for an IDTOKENS peer, alice@$(UID_DOMAIN)
	// for FS). As with a C++ map file's result, a returned name without an '@'
	// takes SecurityConfig's UID domain (security.SecurityConfig.CanonicalUser).
	// Returning "" keeps the authenticated identity. Optional.
	FQUMapper func(authUser, peerAddr string) string

	// KeepAlive configures TCP keepalives applied to every connection accepted
	// in Serve. New() initializes it to stream.DefaultKeepAliveConfig
	// (SO_KEEPALIVE on; idle 360s, interval 5s, count 5), mirroring C++
	// HTCondor which enables keepalives on accepted daemon sockets so a
	// silently-dead peer (e.g. a powered-off execute host) is detected rather
	// than leaking a blocked handler goroutine. Set Enable=false to disable.
	KeepAlive stream.KeepAliveConfig

	// HandshakeDeadline bounds how long a connection may take to reach its
	// handler: reading the command and, for an authenticated command, the
	// whole security handshake. A connection still short of its handler then
	// is closed. Handlers themselves are not bounded by it, nor are follow-on
	// commands on a kept-alive connection. It matches DaemonCore's
	// SEC_TCP_SESSION_DEADLINE, the deadline C++ sets on a new command socket
	// while it waits for the command protocol to finish. New() sets it to
	// DefaultHandshakeDeadline; zero means no deadline.
	HandshakeDeadline time.Duration

	// MaxPendingConnections caps the connections that have not yet reached
	// a handler (those HandshakeDeadline bounds), so unauthenticated peers
	// cannot hold an unbounded number of descriptors and goroutines. A
	// connection beyond the cap is closed at once. New() sets it to
	// DefaultMaxPendingConnections; zero or less means no cap. DaemonCore has
	// no inbound counterpart: its NETWORK_MAX_PENDING_CONNECTS limits
	// outbound connection attempts.
	MaxPendingConnections int

	// AdmitConnection, if set, decides whether to take a connection before
	// anything is read from it. Serve calls it once per connection, after the
	// MaxPendingConnections check; ServeConn does too, so a connection a
	// program hands it directly is subject to the same policy (a program that
	// trusts such a connection can recognise it in the callback).
	//
	// A non-nil error refuses the connection: it is closed unread and ServeConn
	// returns the error wrapped in ErrConnectionNotAdmitted. Otherwise release,
	// if non-nil, runs exactly once when the connection leaves the pending
	// phase -- it reached its handler, or it failed or ran out of
	// HandshakeDeadline first. Between the two the connection is pending, so a
	// program can bound what one source holds there (a per-source
	// MaxPendingConnections) as well as how often it may connect.
	//
	// It runs on the accept path, so it must be quick and must not block.
	AdmitConnection func(conn net.Conn) (release func(), err error)

	// TraceCommand, if set, is called for each command the server dispatches,
	// so the embedder can record it as a span: once the handshake has
	// established the session (authenticated commands) or the command integer
	// is read (raw commands), for each follow-on command on a kept-alive
	// connection, and for a command the handshake refused. It is called
	// whether or not the peer sent a trace context: most CEDAR peers are C++
	// daemons that never do, and the embedder's sampler decides whether such a
	// command gets a root span.
	//
	// ctx carries the peer's trace context (rpctrace.TraceContextFromContext)
	// only when cmd.Trusted and the command is the one the handshake carried,
	// not a follow-on. An untrusted context, and the connection's context on a
	// follow-on command, are reported in cmd.Trace for the embedder to record
	// as a span link, never as a parent.
	//
	// The context the hook returns becomes the handler's, so the handler's
	// work nests under the hook's span. It may only ADD VALUES to ctx (as
	// trace.ContextWithSpan does): one whose Done channel is not ctx's -- a
	// deadline, a cancel, context.WithoutCancel -- is ignored and the handler
	// gets ctx. Handlers treat their context's end as the connection closing
	// and stop without replying, so a context the hook could end on its own
	// would leave the peer waiting for an answer that never comes. A nil
	// context is ctx.
	//
	// The returned function, if non-nil, is called once the command is done
	// -- its handler returned, or it was refused -- with what it did. A
	// handshake that fails before the command is known is not reported.
	//
	// Leaving it nil adds nothing to a connection, not even an allocation:
	// the trace attribute is not even read. Called from connection goroutines
	// concurrently; it must be safe for that and must not block.
	TraceCommand func(ctx context.Context, cmd TracedCommand) (context.Context, func(TraceResult))
	// contains filtered or unexported fields
}

Server accepts CEDAR connections and dispatches commands to handlers.

func New

func New(secConfig *security.SecurityConfig) *Server

New creates a Server with the given server-side security configuration. It installs the server's ValidCommands computation as the security layer's post-auth policy, so authenticating peers learn every command they are authorized for (see Authorizer).

func (*Server) CommandPerms

func (s *Server) CommandPerms(command int) []string

CommandPerms returns the authorization levels registered for command, or nil if it is unregistered or raw. Callers enforcing per-command authorization should verify a peer against these levels so their decision matches the ValidCommands the server advertises.

func (*Server) Handle

func (s *Server) Handle(command int, fn HandlerFunc, perms ...string)

Handle registers an authenticated handler for a command. The optional perms are the authorization levels (HTCondor DCpermission names, e.g. "READ" or "DAEMON") that authorize the command; a peer is authorized if it satisfies any one of them. The levels drive both the ValidCommands the server advertises after authentication and, for callers that enforce it, per-command authorization (see CommandPerms). Registering with no perms advertises the command only as the negotiated one and applies no authorization table; a session whose credential limits its authorization levels may not run it.

func (*Server) HandleRaw

func (s *Server) HandleRaw(command int, fn HandlerFunc)

HandleRaw registers a handler for a raw (un-authenticated) command. The command integer arrives with no preceding DC_AUTHENTICATE.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, l net.Listener) error

Serve accepts connections from l until the context is cancelled or the listener is closed. Each connection is handled in its own goroutine.

func (*Server) ServeConn

func (s *Server) ServeConn(ctx context.Context, conn net.Conn) error

ServeConn handles a single already-accepted connection: it reads the leading command integer, performs the security handshake for authenticated commands, and dispatches to the registered handler. Until the handler runs the connection counts against MaxPendingConnections and is bounded by HandshakeDeadline.

type TraceResult added in v0.7.19

type TraceResult struct {
	// Class is the outcome: ErrorNone; ErrorDenied for a command the session
	// may not run (refused by the handshake or at dispatch); ErrorCanceled
	// when the connection's context ended; ErrorHandler for a handler that
	// returned an error.
	Class rpctrace.ErrorClass

	// KeptOpen reports that the handler took the connection over (KeepOpen),
	// as a CCB registration or a relayed stream does: the command ended but
	// the connection lives on outside the server.
	KeptOpen bool

	// KeepAlive reports that the handler asked for a follow-on command on the
	// same connection (Conn.KeepAlive).
	KeepAlive bool

	// FinishedEarly reports that the handler ended the command with
	// Conn.FinishTrace before returning, as a handler serving a connection
	// for its whole life (a CCB registration) does. KeptOpen and KeepAlive
	// are then unknown and false, and Class is ErrorNone.
	FinishedEarly bool

	// BytesSent and BytesReceived count the bytes exchanged on the
	// connection while the command ran, from its dispatch to its handler's
	// return. The handshake's bytes are not included.
	BytesSent     uint64
	BytesReceived uint64
}

TraceResult is what a traced command did, passed to the function Server.TraceCommand returned. It carries no error text: a handler's error can quote what the peer sent.

type TracedCommand added in v0.7.19

type TracedCommand struct {
	// Command is the command being dispatched: the real command for an
	// authenticated one (DC_SEC_QUERY for condor_ping), the integer read for
	// a raw one.
	Command int

	// Peer is the peer's network address.
	Peer string

	// Raw is a command sent without a security handshake. It has no
	// Negotiation and can carry no trace context.
	Raw bool

	// FollowOn is a command sent on a kept-alive connection after the first
	// (see Conn.KeepAlive), and Sequence its place on the connection: 0 for
	// the command the handshake carried, 1 for the first follow-on, and so
	// on. A follow-on is a bare command integer on the established session,
	// so it carries no trace context of its own. Trace is still the one the
	// connection's handshake carried, but it is not put on ctx: it is the
	// context of the command that opened the connection, so record it as a
	// link.
	FollowOn bool
	Sequence int

	// Negotiation is the session the command runs on: whether it was resumed
	// (SessionResumed), the authentication method (NegotiatedAuth), whether
	// it authenticated and is encrypted, the handshake's start and duration,
	// and the peer's identity (User, for a trust decision). nil for a raw
	// command. Read it; do not change it.
	Negotiation *security.SecurityNegotiation

	// Trace is the trace context the peer sent with the handshake; the zero
	// value, which is not IsValid, when it sent none.
	Trace rpctrace.TraceContext

	// Trusted reports whether the server honours Trace as the parent of its
	// span for the command: Trace is valid, and the session authenticated
	// its peer and is encrypted, which with AES-GCM also binds the ad that
	// carried Trace into the session's integrity check. Any other context
	// could have been chosen by the peer, or rewritten on the way, along with
	// its sampling decision; record it as a span link, or ignore it. The
	// hook may apply a stricter rule (an identity, an authorization level)
	// from Negotiation.
	Trusted bool
}

TracedCommand describes a command the server is dispatching, for Server.TraceCommand.

It names the command, the peer and the session, and nothing the command carries: an ad can name private attributes and their values, and a span is exported to wherever traces go.

Directories

Path Synopsis
Package sharedport implements the server half of HTCondor's shared-port connect protocol, routing accepted connections to in-process registrations rather than to other processes.
Package sharedport implements the server half of HTCondor's shared-port connect protocol, routing accepted connections to in-process registrations rather than to other processes.

Jump to

Keyboard shortcuts

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