middleware

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2025 License: MIT Imports: 21 Imported by: 0

README

Porter Middleware

This package provides authentication and authorization middleware for the Porter server. It supports multiple authentication methods and integrates with gRPC interceptors for both unary and streaming RPCs.

Features

  • Multiple authentication methods:
    • Basic Authentication
    • Bearer Token Authentication
    • JWT Authentication (HMAC, RSA, and ECDSA)
    • OAuth2 Authentication
  • Role-based access control
  • Health check endpoint bypass
  • Configurable authentication settings
  • Comprehensive test coverage

Authentication Methods

Basic Authentication

Basic authentication uses username/password pairs stored in the configuration. Passwords are stored as plain text in the configuration file.

auth:
  enabled: true
  type: basic
  basic_auth:
    users:
      admin:
        password: "admin123"
        roles: ["admin"]
      user:
        password: "user123"
        roles: ["user"]
Bearer Token Authentication

Bearer token authentication uses predefined tokens mapped to users. Each token is associated with a specific user.

auth:
  enabled: true
  type: bearer
  bearer_auth:
    tokens:
      "token1": "user1"
      "token2": "user2"
JWT Authentication

JWT authentication supports multiple signing methods:

  • HMAC (HS256, HS384, HS512)
  • RSA (RS256, RS384, RS512)
  • ECDSA (ES256, ES384, ES512)
auth:
  enabled: true
  type: jwt
  jwt_auth:
    secret: "your-secret-key"  # For HMAC
    public_key: "path/to/public.pem"  # For RSA/ECDSA
    issuer: "your-issuer"
    audience: "your-audience"
OAuth2 Authentication

OAuth2 authentication supports:

  • Authorization Code flow
  • Client Credentials flow
  • Refresh Token flow
auth:
  enabled: true
  type: oauth2
  oauth2_auth:
    clients:
      client1:
        secret: "client1secret"
        redirect_uris: ["http://localhost:8080/callback"]
        grant_types: ["authorization_code", "refresh_token"]
    token_expiry: 3600  # in seconds
    refresh_token_expiry: 604800  # in seconds

Usage

The middleware can be used with both unary and streaming gRPC interceptors:

// Create middleware instance
middleware := NewAuthMiddleware(config, logger)

// Use with unary interceptor
server := grpc.NewServer(
    grpc.UnaryInterceptor(middleware.UnaryInterceptor()),
)

// Use with stream interceptor
server := grpc.NewServer(
    grpc.StreamInterceptor(middleware.StreamInterceptor()),
)

Context Values

The middleware adds the following values to the context:

  • UserKey: The authenticated username
  • RolesKey: The user's roles

These can be accessed using the provided helper functions:

user := AuthenticatedUser(ctx)
roles := AuthenticatedRoles(ctx)

Health Check Bypass

The middleware automatically bypasses authentication for health check endpoints:

  • /grpc.health.v1.Health/Check
  • /grpc.health.v1.Health/Watch

Security Considerations

  1. Basic Auth:

    • Use HTTPS in production
    • Consider using a more secure authentication method
    • Regularly rotate passwords
  2. Bearer Tokens:

    • Use strong, random tokens
    • Implement token rotation
    • Store tokens securely
  3. JWT:

    • Use appropriate key sizes
    • Set reasonable expiration times
    • Validate all claims
    • Use secure signing algorithms
  4. OAuth2:

    • Use HTTPS for all endpoints
    • Implement proper token storage
    • Validate all redirect URIs
    • Use secure client secrets

Testing

The package includes comprehensive tests for all authentication methods and edge cases. Run the tests using:

go test -v ./...

Contributing

When adding new authentication methods or features:

  1. Add appropriate configuration options
  2. Implement the authentication logic
  3. Add comprehensive tests
  4. Update this documentation
  5. Follow the existing code style and patterns

Documentation

Overview

Package middleware provides gRPC middleware for the Flight SQL server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthenticatedUser

func AuthenticatedUser(ctx context.Context) string

AuthenticatedUser returns the user‐id (JWT "sub") previously placed in the context by the authentication middleware, or "" if absent.

func GetRoles

func GetRoles(ctx context.Context) ([]string, bool)

GetRoles extracts the user's roles from context.

func GetUser

func GetUser(ctx context.Context) (string, bool)

GetUser extracts the authenticated user from context.

Types

type AuthMiddleware

type AuthMiddleware struct {
	HSKey []byte
	RSKey interface{}
	Iss   string
	Aud   string
	// contains filtered or unexported fields
}

AuthMiddleware provides authentication middleware.

func NewAuthMiddleware

func NewAuthMiddleware(cfg config.AuthConfig, logger zerolog.Logger) *AuthMiddleware

NewAuthMiddleware creates a new authentication middleware.

func (*AuthMiddleware) CreateSessionToken

func (m *AuthMiddleware) CreateSessionToken(user string) string

CreateSessionToken stores a new session token for the given user.

func (*AuthMiddleware) HandleOAuth2Authorize

func (m *AuthMiddleware) HandleOAuth2Authorize(w http.ResponseWriter, r *http.Request)

HandleOAuth2Authorize handles the OAuth2 authorization endpoint

func (*AuthMiddleware) HandleOAuth2Token

func (m *AuthMiddleware) HandleOAuth2Token(w http.ResponseWriter, r *http.Request)

HandleOAuth2Token handles the OAuth2 token endpoint

func (*AuthMiddleware) StreamInterceptor

func (m *AuthMiddleware) StreamInterceptor() grpc.StreamServerInterceptor

StreamInterceptor returns a stream server interceptor for authentication.

func (*AuthMiddleware) UnaryInterceptor

func (m *AuthMiddleware) UnaryInterceptor() grpc.UnaryServerInterceptor

UnaryInterceptor returns a unary server interceptor for authentication.

func (*AuthMiddleware) ValidateHandshakePayload

func (m *AuthMiddleware) ValidateHandshakePayload(payload []byte) (string, error)

ValidateHandshakePayload validates the handshake payload and returns the authenticated user identity.

type LoggingMiddleware

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

LoggingMiddleware provides request logging middleware.

func NewLoggingMiddleware

func NewLoggingMiddleware(logger zerolog.Logger) *LoggingMiddleware

NewLoggingMiddleware creates a new logging middleware.

func (*LoggingMiddleware) StreamInterceptor

func (m *LoggingMiddleware) StreamInterceptor() grpc.StreamServerInterceptor

StreamInterceptor returns a stream server interceptor for logging.

func (*LoggingMiddleware) UnaryInterceptor

func (m *LoggingMiddleware) UnaryInterceptor() grpc.UnaryServerInterceptor

UnaryInterceptor returns a unary server interceptor for logging.

type MetricsCollector

type MetricsCollector interface {
	IncrementCounter(name string, labels ...string)
	RecordHistogram(name string, value float64, labels ...string)
	RecordGauge(name string, value float64, labels ...string)
	StartTimer(name string) Timer
}

MetricsCollector defines the interface for collecting metrics.

type MetricsMiddleware

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

MetricsMiddleware provides metrics collection middleware.

func NewMetricsMiddleware

func NewMetricsMiddleware(collector MetricsCollector) *MetricsMiddleware

NewMetricsMiddleware creates a new metrics middleware.

func (*MetricsMiddleware) StreamInterceptor

func (m *MetricsMiddleware) StreamInterceptor() grpc.StreamServerInterceptor

StreamInterceptor returns a stream server interceptor for metrics.

func (*MetricsMiddleware) UnaryInterceptor

func (m *MetricsMiddleware) UnaryInterceptor() grpc.UnaryServerInterceptor

UnaryInterceptor returns a unary server interceptor for metrics.

type OAuth2Token

type OAuth2Token struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	ExpiresAt    time.Time `json:"expires_at"`
	Scope        string    `json:"scope,omitempty"`
	UserID       string    `json:"user_id,omitempty"`
}

OAuth2Token represents an OAuth2 token with additional metadata

type RecoveryMiddleware

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

RecoveryMiddleware provides panic recovery middleware.

func NewRecoveryMiddleware

func NewRecoveryMiddleware(logger zerolog.Logger) *RecoveryMiddleware

NewRecoveryMiddleware creates a new recovery middleware.

func (*RecoveryMiddleware) StreamInterceptor

func (m *RecoveryMiddleware) StreamInterceptor() grpc.StreamServerInterceptor

StreamInterceptor returns a stream server interceptor for panic recovery.

func (*RecoveryMiddleware) UnaryInterceptor

func (m *RecoveryMiddleware) UnaryInterceptor() grpc.UnaryServerInterceptor

UnaryInterceptor returns a unary server interceptor for panic recovery.

type Timer

type Timer interface {
	Stop() float64
}

Timer represents a timing measurement.

type TokenStore

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

TokenStore manages OAuth2 tokens

Jump to

Keyboard shortcuts

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