plugin

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: Apache-2.0 Imports: 27 Imported by: ? 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

Index

Constants

View Source
const (
	ActionRead  = "read"
	ActionWrite = "write"
	ActionAdmin = "admin"
)

Casbin action constants used in authorization policy evaluation.

View Source
const (
	FieldStartupMessage      = "startupMessage"
	FieldPasswordMessage     = "passwordMessage"
	FieldSASLInitialResponse = "saslInitialResponse"
	FieldSASLResponse        = "saslResponse"
	FieldQuery               = "query"
	FieldParse               = "parse"
	FieldRequest             = "request"
	FieldResponse            = "response"
)

PostgreSQL wire protocol field names (as produced by the SDK's HandleClientMessage).

View Source
const (
	ParamUser     = "user"
	ParamDatabase = "database"
)

PostgreSQL startup message parameter keys.

View Source
const (
	ErrorSeverity     = "ERROR"
	ErrorCodeAuthFail = "28P01"
	ErrorCodeDenied   = "42501"
	ErrorMsgAuthFail  = "authentication failed"
	ErrorMsgDenied    = "permission denied"
)

PostgreSQL error constants.

View Source
const DefaultSessionTTLSeconds = 3600

DefaultSessionTTLSeconds is the default TTL for auth sessions in seconds.

View Source
const MD5PasswordLength = 35

MD5 hashed password length ("md5" + 32 hex chars = 35).

View Source
const SaltSize = 4

Salt size for MD5 authentication.

View Source
const (
	// ScramIterations is the PBKDF2 iteration count for SCRAM-SHA-256.
	ScramIterations = 4096
)

SCRAM protocol constants.

Variables

View Source
var (
	// ErrNoSASLInitialData is returned when no SASL initial data is found in the message.
	ErrNoSASLInitialData = errors.New("no SASL initial data found in message")
	// ErrNoSASLResponseData is returned when no SASL response data is found in the message.
	ErrNoSASLResponseData = errors.New("no SASL response data found in message")
)
View Source
var (
	// ErrUserNotFound is returned when a user is not found in the credential store.
	ErrUserNotFound = errors.New("user not found")
	// ErrUserDisabled is returned when a user exists but is disabled.
	ErrUserDisabled = errors.New("user is disabled")
	// ErrDatabaseNotAllowed is returned when a user is not allowed to connect to the requested database.
	ErrDatabaseNotAllowed = errors.New("database not allowed for user")
)
View Source
var (
	// AuthSuccesses counts successful authentications.
	AuthSuccesses = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "gatewayd",
		Name:      "auth_successes_total",
		Help:      "Total number of successful authentications",
	})

	// AuthFailures counts failed authentication attempts.
	AuthFailures = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "gatewayd",
		Name:      "auth_failures_total",
		Help:      "Total number of failed authentication attempts",
	})

	// AuthzDenials counts authorization denials.
	AuthzDenials = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "gatewayd",
		Name:      "authz_denials_total",
		Help:      "Total number of authorization denials",
	})

	// OnTrafficFromClientCalls counts OnTrafficFromClient hook invocations.
	OnTrafficFromClientCalls = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "gatewayd",
		Name:      "auth_on_traffic_from_client_total",
		Help:      "Total number of OnTrafficFromClient hook calls",
	})

	// GetPluginConfigCalls counts GetPluginConfig invocations.
	GetPluginConfigCalls = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "gatewayd",
		Name:      "auth_get_plugin_config_total",
		Help:      "Total number of GetPluginConfig calls",
	})

	// ActiveSessions tracks the current number of active auth sessions.
	ActiveSessions = promauto.NewGauge(prometheus.GaugeOpts{
		Namespace: "gatewayd",
		Name:      "auth_active_sessions",
		Help:      "Current number of active authentication sessions",
	})
)
View Source
var (
	// PluginID identifies this plugin.
	PluginID = v1.PluginID{
		Name:      "gatewayd-plugin-auth",
		Version:   "1.0.0",
		RemoteUrl: "github.com/gatewayd-io/gatewayd-plugin-auth",
	}

	// PluginMap is the plugin map for HashiCorp go-plugin.
	PluginMap = map[string]goplugin.Plugin{
		"gatewayd-plugin-auth": &AuthGRPCPlugin{},
	}

	// PluginConfig is the compile-time plugin configuration returned to GatewayD.
	PluginConfig = map[string]interface{}{
		"id": map[string]interface{}{
			"name":      PluginID.GetName(),
			"version":   PluginID.GetVersion(),
			"remoteUrl": PluginID.GetRemoteUrl(),
		},
		"description": "GatewayD plugin for authentication, authorization, and access control",
		"authors": []interface{}{
			"Mostafa Moradian <mostafa@gatewayd.io>",
		},
		"license":    "Apache 2.0",
		"projectUrl": "https://github.com/gatewayd-io/gatewayd-plugin-auth",
		"config": map[string]interface{}{
			"metricsEnabled":          "true",
			"metricsUnixDomainSocket": "/tmp/gatewayd-plugin-auth.sock",
			"metricsEndpoint":         "/metrics",
			"authType":                sdkConfig.GetEnv("AUTH_TYPE", "md5"),
			"credentialsFile":         sdkConfig.GetEnv("CREDENTIALS_FILE", "credentials.yaml"),
			"serverVersion":           sdkConfig.GetEnv("SERVER_VERSION", "17.4"),
			"authorizationEnabled":    sdkConfig.GetEnv("AUTHORIZATION_ENABLED", "false"),
			"casbinModelPath":         sdkConfig.GetEnv("CASBIN_MODEL_PATH", ""),
			"casbinPolicyPath":        sdkConfig.GetEnv("CASBIN_POLICY_PATH", ""),
		},
		"hooks": []interface{}{
			int32(v1.HookName_HOOK_NAME_ON_TRAFFIC_FROM_CLIENT),
			int32(v1.HookName_HOOK_NAME_ON_CLOSED),
		},
		"tags":       []interface{}{"plugin", "auth", "authorization", "access-control"},
		"categories": []interface{}{"auth", "security"},
	}
)
View Source
var (
	// ErrNoParameters is returned when a startup message has no parameters.
	ErrNoParameters = errors.New("no parameters in startup message")
	// ErrNoUser is returned when a startup message has no user parameter.
	ErrNoUser = errors.New("no user in startup message")
)

Functions

func BuildAccessDeniedResponse

func BuildAccessDeniedResponse(detail string) ([]byte, error)

BuildAccessDeniedResponse builds an ErrorResponse+ReadyForQuery for authorization denial. Unlike auth failure, we use ReadyForQuery (not Terminate) so the client knows the server is ready for the next command — the session stays open after a denied query.

func BuildAuthFailResponse

func BuildAuthFailResponse(detail string) ([]byte, error)

BuildAuthFailResponse builds a Terminate+ErrorResponse for authentication failure.

func DecodeBase64Field

func DecodeBase64Field(encoded string) ([]byte, error)

DecodeBase64Field decodes a base64-encoded string field from the request struct.

func GenerateSalt

func GenerateSalt(_ int) ([SaltSize]byte, error)

GenerateSalt generates a random salt of SaltSize bytes.

func GetClientRemote

func GetClientRemote(fields map[string]interface{}) string

GetClientRemote extracts the client remote address from the request fields.

func ParsePasswordMessage

func ParsePasswordMessage(passwordDecoded []byte) map[string]string

ParsePasswordMessage extracts the password from a decoded password message.

func ParseStartupParams

func ParseStartupParams(startupDecoded []byte) (string, string, error)

ParseStartupParams extracts user and database from a decoded startup message.

Types

type AuthGRPCPlugin

type AuthGRPCPlugin struct {
	goplugin.NetRPCUnsupportedPlugin
	Impl Plugin
}

AuthGRPCPlugin implements the HashiCorp go-plugin GRPCPlugin interface.

func (*AuthGRPCPlugin) GRPCClient

func (p *AuthGRPCPlugin) GRPCClient(
	_ context.Context, _ *goplugin.GRPCBroker, c *grpc.ClientConn,
) (interface{}, error)

GRPCClient returns the plugin client.

func (*AuthGRPCPlugin) GRPCServer

func (p *AuthGRPCPlugin) GRPCServer(_ *goplugin.GRPCBroker, s *grpc.Server) error

GRPCServer registers the plugin with the gRPC server.

type AuthHandler

type AuthHandler struct {
	Logger         hclog.Logger
	Sessions       *SessionManager
	CredStore      CredentialStore
	Authenticators map[AuthType]Authenticator
	Authorizer     *Authorizer
	DefaultAuth    AuthType
}

AuthHandler is the central auth state machine dispatcher. It coordinates credential lookup, authenticator selection, and session management.

func NewAuthHandler

func NewAuthHandler(
	logger hclog.Logger,
	sessions *SessionManager,
	credStore CredentialStore,
	authorizer *Authorizer,
	defaultAuth AuthType,
	serverVersion string,
) *AuthHandler

NewAuthHandler creates a new AuthHandler with the given components.

func (*AuthHandler) HandleTrafficFromClient

func (h *AuthHandler) HandleTrafficFromClient(ctx context.Context, req *v1.Struct) (*v1.Struct, error)

HandleTrafficFromClient processes a client message through the auth state machine. Returns the (possibly modified) request struct.

type AuthState

type AuthState int

AuthState tracks the state machine for a client connection's authentication.

const (
	StateInit          AuthState = iota // Waiting for StartupMessage
	StateChallengeSent                  // Auth challenge sent, waiting for password/SASL
	StateScramContinue                  // SCRAM server-first sent, waiting for client-final
	StateAuthenticated                  // Successfully authenticated
	StateFailed                         // Authentication failed
)

type AuthType

type AuthType string

AuthType represents a PostgreSQL authentication method.

const (
	AuthCleartext   AuthType = "cleartext"
	AuthMD5         AuthType = "md5"
	AuthScramSHA256 AuthType = "scram-sha-256"
)

type Authenticator

type Authenticator interface {
	// Name returns the auth method name (e.g., "md5", "scram-sha-256").
	Name() AuthType

	// HandleStartup is called when a StartupMessage arrives for a user.
	// It returns the auth challenge bytes to send to the client.
	HandleStartup(session *Session, cred *UserCredential) ([]byte, error)

	// HandleResponse processes the client's password/SASL response.
	// It returns (response bytes to send, authenticated bool, error).
	// If authenticated is true, response contains AuthOk sequence.
	// If authenticated is false and error is nil, response contains the next
	// challenge (e.g., SASL continue).
	HandleResponse(session *Session, cred *UserCredential, msgData map[string]string) ([]byte, bool, error)
}

Authenticator is the interface for PostgreSQL authentication method implementations.

type Authorizer

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

Authorizer performs Casbin-based RBAC authorization on SQL queries.

func NewAuthorizer

func NewAuthorizer(modelPath, policyPath string, logger hclog.Logger) (*Authorizer, error)

NewAuthorizer creates a new Authorizer with the given Casbin model and policy files. Returns nil if either path is empty (authorization disabled).

func (*Authorizer) Authorize

func (a *Authorizer) Authorize(username, database, query string) (bool, error)

Authorize checks if the given user can execute the given SQL query on the given database. It parses the query to extract tables and maps the SQL operation to a Casbin action.

func (*Authorizer) ReloadPolicy

func (a *Authorizer) ReloadPolicy() error

ReloadPolicy reloads the Casbin policy from the backing store.

type CleartextAuthenticator

type CleartextAuthenticator struct {
	ServerVersion string
}

CleartextAuthenticator implements cleartext password authentication.

func (*CleartextAuthenticator) HandleResponse

func (a *CleartextAuthenticator) HandleResponse(
	session *Session, cred *UserCredential, msgData map[string]string,
) ([]byte, bool, error)

HandleResponse validates the cleartext password.

func (*CleartextAuthenticator) HandleStartup

func (a *CleartextAuthenticator) HandleStartup(session *Session, _ *UserCredential) ([]byte, error)

HandleStartup sends an AuthenticationCleartextPassword challenge.

func (*CleartextAuthenticator) Name

func (a *CleartextAuthenticator) Name() AuthType

Name returns the auth method name.

type ConfigValues

type ConfigValues struct {
	// AuthType is the default authentication method.
	AuthType AuthType
	// CredentialsFile is the path to the YAML credentials file.
	CredentialsFile string
	// ServerVersion is the PostgreSQL server version to advertise to clients.
	ServerVersion string
	// SessionTTLSeconds is the TTL for auth sessions in seconds.
	SessionTTLSeconds int
	// MetricsEnabled controls Prometheus metrics exposure.
	MetricsEnabled bool
	// MetricsUnixDomainSocket is the Unix socket path for metrics.
	MetricsUnixDomainSocket string
	// MetricsEndpoint is the HTTP endpoint for metrics.
	MetricsEndpoint string
	// CasbinModelPath is the path to the Casbin model file (optional).
	CasbinModelPath string
	// CasbinPolicyPath is the path to the Casbin policy file (optional).
	CasbinPolicyPath string
	// AuthorizationEnabled controls whether query authorization is active.
	AuthorizationEnabled bool
}

ConfigValues holds the runtime configuration for the auth plugin.

func DefaultConfig

func DefaultConfig() *ConfigValues

DefaultConfig returns the default plugin configuration.

func ParseConfig

func ParseConfig(cfg map[string]interface{}) *ConfigValues

ParseConfig parses runtime config from the plugin's config map.

type CredentialStore

type CredentialStore interface {
	// LookupUser returns the user's credentials or ErrUserNotFound.
	LookupUser(ctx context.Context, username string) (*UserCredential, error)

	// Reload refreshes credentials from the backing store.
	Reload(ctx context.Context) error
}

CredentialStore is the interface for looking up user credentials.

type FileCredentialStore

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

FileCredentialStore implements CredentialStore backed by a YAML file.

func NewFileCredentialStore

func NewFileCredentialStore(filePath string) (*FileCredentialStore, error)

NewFileCredentialStore creates a FileCredentialStore and loads credentials from the given path.

func (*FileCredentialStore) LookupUser

func (s *FileCredentialStore) LookupUser(_ context.Context, username string) (*UserCredential, error)

LookupUser returns the credential for the given username.

func (*FileCredentialStore) Reload

Reload re-reads the YAML file and replaces the in-memory user map.

type MD5Authenticator

type MD5Authenticator struct {
	ServerVersion string
}

MD5Authenticator implements PostgreSQL MD5 password authentication. Each session gets a unique salt generated at challenge time.

func (*MD5Authenticator) HandleResponse

func (a *MD5Authenticator) HandleResponse(
	session *Session, cred *UserCredential, msgData map[string]string,
) ([]byte, bool, error)

HandleResponse validates the MD5-hashed password. PostgreSQL MD5 format: "md5" + md5(md5(password + username) + salt).

func (*MD5Authenticator) HandleStartup

func (a *MD5Authenticator) HandleStartup(session *Session, _ *UserCredential) ([]byte, error)

HandleStartup generates a per-connection salt and sends an AuthenticationMD5Password challenge.

func (*MD5Authenticator) Name

func (a *MD5Authenticator) Name() AuthType

Name returns the auth method name.

type Plugin

type Plugin struct {
	v1.GatewayDPluginServiceServer

	Logger      hclog.Logger
	AuthHandler *AuthHandler
}

Plugin is the main auth plugin implementation.

func (*Plugin) GetPluginConfig

func (p *Plugin) GetPluginConfig(
	_ context.Context, _ *v1.Struct,
) (*v1.Struct, error)

GetPluginConfig returns the plugin configuration to GatewayD.

func (*Plugin) OnClosed

func (p *Plugin) OnClosed(_ context.Context, req *v1.Struct) (*v1.Struct, error)

OnClosed cleans up the session when a client connection closes.

func (*Plugin) OnTrafficFromClient

func (p *Plugin) OnTrafficFromClient(
	ctx context.Context, req *v1.Struct,
) (*v1.Struct, error)

OnTrafficFromClient intercepts client traffic for authentication and authorization.

func (*Plugin) OnTrafficFromServer

func (p *Plugin) OnTrafficFromServer(
	_ context.Context, req *v1.Struct,
) (*v1.Struct, error)

OnTrafficFromServer is a pass-through -- no modifications needed.

type ScramAuthenticator

type ScramAuthenticator struct {
	ServerVersion string
}

ScramAuthenticator implements SCRAM-SHA-256 authentication (RFC 5802). The multi-round handshake requires state across multiple hook invocations.

func (*ScramAuthenticator) HandleResponse

func (a *ScramAuthenticator) HandleResponse(
	session *Session, cred *UserCredential, msgData map[string]string,
) ([]byte, bool, error)

HandleResponse handles either the SASLInitialResponse (client-first) or the SASLResponse (client-final).

func (*ScramAuthenticator) HandleStartup

func (a *ScramAuthenticator) HandleStartup(session *Session, _ *UserCredential) ([]byte, error)

HandleStartup sends an AuthenticationSASL challenge listing SCRAM-SHA-256.

func (*ScramAuthenticator) Name

func (a *ScramAuthenticator) Name() AuthType

Name returns the auth method name.

type ScramServerState

type ScramServerState struct {
	ServerFirstMsg []byte
	AuthID         string
	Conversation   interface{} // *scram.ServerConversation from xdg-go/scram
}

ScramServerState holds the server-side state for a SCRAM-SHA-256 handshake.

type Session

type Session struct {
	State           AuthState
	Username        string
	Database        string
	AuthMethod      AuthType
	Salt            [SaltSize]byte    // per-connection salt for MD5
	ScramState      *ScramServerState // multi-round SCRAM state
	Roles           []string          // populated after auth for authorization
	CreatedAt       time.Time
	AuthenticatedAt time.Time
}

Session holds the authentication state for a single client connection.

type SessionManager

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

SessionManager provides thread-safe session tracking for client connections.

func NewSessionManager

func NewSessionManager(ttl time.Duration) *SessionManager

NewSessionManager creates a new SessionManager with the given session TTL.

func (*SessionManager) Cleanup

func (sm *SessionManager) Cleanup()

Cleanup removes all sessions older than the TTL.

func (*SessionManager) Count

func (sm *SessionManager) Count() int

Count returns the number of active sessions.

func (*SessionManager) Get

func (sm *SessionManager) Get(key string) *Session

Get returns the session for the given key, or nil if not found.

func (*SessionManager) GetOrCreate

func (sm *SessionManager) GetOrCreate(key string) *Session

GetOrCreate returns the session for the given key, creating a new one if it doesn't exist.

func (*SessionManager) IsAuthenticated

func (sm *SessionManager) IsAuthenticated(key string) bool

IsAuthenticated returns true if the session exists and is in the Authenticated state.

func (*SessionManager) Remove

func (sm *SessionManager) Remove(key string)

Remove deletes the session for the given key.

func (*SessionManager) StartCleanupLoop

func (sm *SessionManager) StartCleanupLoop(interval time.Duration, done <-chan struct{})

StartCleanupLoop starts a background goroutine that periodically cleans up expired sessions.

type UserCredential

type UserCredential struct {
	Username    string   `yaml:"username"`
	Password    string   `yaml:"password"`               // Plaintext password (used to derive hashes at runtime)
	AuthMethods []string `yaml:"auth_methods,omitempty"` // Allowed auth methods: ["md5", "scram-sha-256", "cleartext"]
	Roles       []string `yaml:"roles,omitempty"`        // Roles for authorization
	Databases   []string `yaml:"databases,omitempty"`    // Allowed databases (empty = all)
	Enabled     *bool    `yaml:"enabled,omitempty"`      // Whether the user is enabled (default: true)
}

UserCredential represents a user's stored credentials and access configuration.

func (*UserCredential) IsDatabaseAllowed

func (u *UserCredential) IsDatabaseAllowed(database string) bool

IsDatabaseAllowed checks if the user can connect to the given database. An empty Databases list means all databases are allowed.

func (*UserCredential) IsEnabled

func (u *UserCredential) IsEnabled() bool

IsEnabled returns true if the user is enabled (defaults to true if not set).

func (*UserCredential) SupportsAuthMethod

func (u *UserCredential) SupportsAuthMethod(method AuthType) bool

SupportsAuthMethod checks if the user supports the given auth method. An empty AuthMethods list means all methods are supported.

Jump to

Keyboard shortcuts

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