adminapi

package
v0.35.1 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package adminapi provides shared authentication middleware for admin APIs. It supports two authentication modes following industry best practices:

1. Bearer Token (OAuth2 standard) - Authorization: Bearer <token> 2. API Key (simplified) - X-API-Key: <key>

Both modes use constant-time comparison to prevent timing attacks.

Package adminapi defines the shared domain for admin API servers. Both internal/admin (CLI) and internal/server/admin (Webhook API) import this package to share common types, error codes, and utilities.

Architecture (SOLID/DRY):

┌─────────────────────┐      ┌───────────────────────────┐
│   internal/admin     │      │ internal/server/admin      │
│   (Admin CLI)       │      │   (Webhook API)            │
│   gorilla/mux       │      │   net/http                 │
│   /admin/v1/...     │      │   /api/v1/admin/...        │
└──────────┬──────────┘      └─────────────┬─────────────┘
            │                               │
            └──────────┬────────────────────┘
                       ▼
         ┌─────────────────────────┐
         │   internal/adminapi       │
         │   (Shared Domain)        │
         │   • ErrorCode            │
         │   • MapSessionStatus     │
         │   • writeJSON/writeError │
         │   • Session mapping      │
         └─────────────────────────┘

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(opts AuthMiddlewareOptions) func(http.Handler) http.Handler

AuthMiddleware creates an HTTP middleware that validates authentication. It uses constant-time comparison to prevent timing attacks.

If adminKey is empty, authentication is bypassed (useful for dev/testing).

Example (Bearer mode):

auth := AuthMiddleware(AuthMiddlewareOptions{
    AdminKey: "secret-token",
    Mode:     AuthModeBearer,
    Logger:   logger,
})
handler := auth(myHandler)

Example (API Key mode):

auth := AuthMiddleware(AuthMiddlewareOptions{
    AdminKey: "api-key-123",
    Mode:     AuthModeAPIKey,
    Logger:   logger,
})
handler := auth(myHandler)

func MapSessionStatus

func MapSessionStatus(status intengine.SessionStatus) string

MapSessionStatus maps an internal engine session status to a canonical string.

func ParsePagination

func ParsePagination(r *http.Request) (limit, offset int)

ParsePagination extracts pagination parameters (limit and offset) from the request URL query. It provides sensible defaults and enforces maximum limits to prevent abuse.

Default values:

  • limit: 100 (max: 1000)
  • offset: 0

Invalid values are silently ignored and replaced with defaults.

func ResolvePlatform

func ResolvePlatform(sessionID string) string

ResolvePlatform resolves the platform from a session ID prefix. Session IDs follow the format: {platform}-{uuid}. e.g., "ws-abc123", "slack-def456", "admin-ghi789"

func WriteError

func WriteError(w http.ResponseWriter, status int, code ErrorCode, message string)

WriteError writes a JSON error response. Errors during encoding are logged but the response is still written.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes a JSON response with the given status code. Errors during encoding are logged but not surfaced to the caller.

Types

type AuthMiddlewareOptions

type AuthMiddlewareOptions struct {
	// AdminKey is the secret key/token for authentication.
	// If empty, authentication is bypassed (dev/unsecured mode).
	AdminKey string

	// Mode specifies the authentication mode (Bearer or API Key).
	Mode AuthMode

	// Logger for structured logging. Defaults to slog.Default().
	Logger *slog.Logger
}

AuthMiddlewareOptions configures the authentication middleware.

type AuthMode

type AuthMode int

AuthMode defines the authentication mode for admin APIs.

const (
	// AuthModeBearer uses OAuth2-style Authorization: Bearer <token>
	// Recommended for external integrations and webhook APIs.
	AuthModeBearer AuthMode = iota

	// AuthModeAPIKey uses X-API-Key header
	// Recommended for internal tooling and simple integrations.
	AuthModeAPIKey
)

type ErrorCode

type ErrorCode string

ErrorCode represents a canonical admin API error code.

const (
	ErrCodeAuthFailed           ErrorCode = "AUTH_FAILED"
	ErrCodeForbidden            ErrorCode = "FORBIDDEN"
	ErrCodeNotFound             ErrorCode = "NOT_FOUND"
	ErrCodeInvalidRequest       ErrorCode = "INVALID_REQUEST"
	ErrCodeServerError          ErrorCode = "SERVER_ERROR"
	ErrCodeUnauthorized         ErrorCode = "UNAUTHORIZED"
	ErrCodeEngineNotInitialized ErrorCode = "ENGINE_NOT_INITIALIZED"
)

type ErrorDetail

type ErrorDetail struct {
	Code    ErrorCode              `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorDetail contains the code, message, and optional details of an error.

type ErrorResponse

type ErrorResponse struct {
	Error ErrorDetail `json:"error"`
}

ErrorResponse is the standard error envelope shared by all admin APIs.

func NewError

func NewError(code ErrorCode, message string) ErrorResponse

NewError creates an ErrorResponse with the given code and message.

func NewErrorWithDetails

func NewErrorWithDetails(code ErrorCode, message string, details map[string]interface{}) ErrorResponse

NewErrorWithDetails creates an ErrorResponse with additional details.

type SessionSummary

type SessionSummary struct {
	ID         string    `json:"id"`
	Status     string    `json:"status"`
	CreatedAt  time.Time `json:"created_at"`
	LastActive time.Time `json:"last_active"`
	Platform   string    `json:"platform"`
}

SessionSummary holds fields shared by all session-listing responses.

func ToSessionSummary

func ToSessionSummary(s *intengine.Session) SessionSummary

ToSessionSummary converts an internal engine.Session to a SessionSummary.

Jump to

Keyboard shortcuts

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