icalmiddleware

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

ICal Middleware для Traefik

Плагин для Traefik, который проверяет токены авторизации для доступа к iCal календарям PSU.

Функциональность

  • Проверка токенов авторизации через upstream сервер
  • Кэширование валидных токенов для уменьшения нагрузки на upstream
  • Мультиплексирование идентичных запросов авторизации
  • Ограничение скорости запросов (rate limiting) глобально и по IP
  • Поддержка белых списков подсетей
  • Настраиваемое логирование

Особенности работы

  • Upstream сервер всегда возвращает HTTP статус 200 (OK), поэтому валидация токена происходит по содержимому ответа
  • Валидный ответ должен начинаться с "BEGIN"
  • Токен должен быть длиной 16 символов

Установка

Предварительные требования
  • Traefik v2.5 или выше с поддержкой плагинов
  • Go 1.16 или выше (для разработки)
Установка плагина
  1. Добавьте плагин в конфигурацию Traefik:
# Статическая конфигурация Traefik
experimental:
  plugins:
    icalmiddleware:
      moduleName: "github.com/ijo42/icalmiddleware"
      version: "v1.0.0"
  1. Настройте плагин в динамической конфигурации:
# Динамическая конфигурация
http:
  middlewares:
    ical-auth:
      plugin:
        icalmiddleware:
          headerName: "Authorization"
          forwardToken: false
          freshness: 3600
          allowSubnet: ["192.168.1.0/24", "10.0.0.0/8"]
          timeout: 10
          globalRateLimit: 100
          perIPRateLimit: 10
          rateLimitWindow: 60
          logLevel: "info"
          cleanupInterval: 300
          upstreamURL: "https://ical.psu.ru/calendars/"
  1. Примените middleware к вашему роуту:
http:
  routers:
    ical:
      rule: "Host(`calendar.example.com`)"
      service: "ical-service"
      middlewares:
        - "ical-auth"

Конфигурация

Параметр Тип По умолчанию Описание
headerName string "Authorization" Имя заголовка, содержащего токен авторизации
forwardToken bool false Передавать ли токен авторизации upstream сервису
freshness int64 3600 Время жизни кэша токенов в секундах
allowSubnet []string ["0.0.0.0/24"] Список подсетей, которым разрешен доступ без авторизации
timeout int64 10 Таймаут запросов к upstream в секундах
globalRateLimit int 100 Глобальное ограничение запросов в период
perIPRateLimit int 10 Ограничение запросов по IP в период
rateLimitWindow int64 60 Период для ограничения запросов в секундах
logLevel string "info" Уровень логирования ("error", "info", "debug")
cleanupInterval int64 300 Интервал очистки устаревших данных в секундах
upstreamURL string "https://ical.psu.ru/calendars/" URL upstream сервера для проверки токенов

Примеры использования

Базовая конфигурация
http:
  middlewares:
    ical-auth:
      plugin:
        icalmiddleware:
          headerName: "Authorization"
          freshness: 3600
Расширенная конфигурация с белым списком и ограничением скорости
http:
  middlewares:
    ical-auth:
      plugin:
        icalmiddleware:
          headerName: "Authorization"
          forwardToken: false
          freshness: 3600
          allowSubnet: ["192.168.1.0/24", "10.0.0.0/8"]
          timeout: 10
          globalRateLimit: 100
          perIPRateLimit: 10
          rateLimitWindow: 60
          logLevel: "debug"

Разработка

Сборка плагина
go build -o icalmiddleware.so -buildmode=plugin ./
Тестирование
go test -v ./...

Лицензия

MIT

Documentation

Index

Constants

View Source
const (
	// NoExpiration indicates that the item never expires
	NoExpiration time.Duration = -1

	// DefaultExpiration indicates to use the default expiration time
	DefaultExpiration time.Duration = 0
)

Variables

This section is empty.

Functions

func New

func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error)

New creates a new ICalMiddleware instance

func ReadUserIP added in v0.0.2

func ReadUserIP(r *http.Request) string

ReadUserIP extracts the user's IP address from the request

Types

type Cache added in v0.0.2

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

Cache is the main cache structure

func NewCache added in v0.0.2

func NewCache(defaultExpiration, cleanupInterval time.Duration) *Cache

NewCache creates a new cache with the given expiration and cleanup interval

func NewFrom added in v0.0.2

func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache

NewFrom creates a new cache with the given expiration, cleanup interval, and items

func (Cache) Add added in v0.0.2

func (c Cache) Add(k string, x bool, d time.Duration) error

Add adds an item to the cache only if it doesn't already exist

func (Cache) Delete added in v0.0.2

func (c Cache) Delete(k string)

Delete removes an item from the cache

func (Cache) DeleteExpired added in v0.0.2

func (c Cache) DeleteExpired()

DeleteExpired deletes all expired items from the cache

func (Cache) DeleteLeastRecent added in v0.0.8

func (c Cache) DeleteLeastRecent(maxSize int)

DeleteLeastRecent removes the least recently accessed items when the cache exceeds the given size

func (Cache) Flush added in v0.0.2

func (c Cache) Flush()

Flush removes all items from the cache

func (Cache) Get added in v0.0.2

func (c Cache) Get(k string) (bool, bool)

Get retrieves an item from the cache

func (Cache) GetWithExpiration added in v0.0.2

func (c Cache) GetWithExpiration(k string) (interface{}, time.Time, bool)

GetWithExpiration retrieves an item and its expiration time

func (Cache) Has added in v0.0.2

func (c Cache) Has(k string) bool

Has checks if an item exists in the cache

func (Cache) ItemCount added in v0.0.2

func (c Cache) ItemCount() int

ItemCount returns the number of items in the cache

func (Cache) Items added in v0.0.2

func (c Cache) Items() map[string]Item

Items returns all unexpired items in the cache

func (Cache) Load added in v0.0.2

func (c Cache) Load(r io.Reader) error

Load deserializes the cache from an io.Reader

func (Cache) LoadFile added in v0.0.2

func (c Cache) LoadFile(fname string) error

LoadFile loads the cache from a file

func (Cache) OnEvicted added in v0.0.2

func (c Cache) OnEvicted(f func(string, bool))

OnEvicted sets a callback for when items are evicted

func (Cache) Replace added in v0.0.2

func (c Cache) Replace(k string, x bool, d time.Duration) error

Replace replaces an existing item in the cache

func (Cache) Save added in v0.0.2

func (c Cache) Save(w io.Writer) (err error)

Save serializes the cache to an io.Writer

func (Cache) SaveFile added in v0.0.2

func (c Cache) SaveFile(fname string) error

SaveFile saves the cache to a file

func (Cache) Set added in v0.0.2

func (c Cache) Set(k string, x bool, d time.Duration)

Set adds an item to the cache

func (Cache) SetDefault added in v0.0.2

func (c Cache) SetDefault(k string, x bool)

SetDefault adds an item to the cache with the default expiration

type Config

type Config struct {
	ForwardToken    bool     `json:"forwardToken,omitempty" yaml:"forwardToken,omitempty" toml:"forwardToken,omitempty"`
	Freshness       int64    `json:"freshness,omitempty" yaml:"freshness,omitempty" toml:"freshness,omitempty"`
	HeaderName      string   `json:"headerName,omitempty" yaml:"headerName,omitempty" toml:"headerName,omitempty"`
	AllowSubnet     []string `json:"allowSubnet,omitempty" yaml:"allowSubnet,omitempty" toml:"allowSubnet,omitempty"`
	Timeout         int64    `json:"timeout,omitempty" yaml:"timeout,omitempty" toml:"timeout,omitempty"`
	GlobalRateLimit int      `json:"globalRateLimit,omitempty" yaml:"globalRateLimit,omitempty" toml:"globalRateLimit,omitempty"`
	PerIPRateLimit  int      `json:"perIPRateLimit,omitempty" yaml:"perIPRateLimit,omitempty" toml:"perIPRateLimit,omitempty"`
	RateLimitWindow int64    `json:"rateLimitWindow,omitempty" yaml:"rateLimitWindow,omitempty" toml:"rateLimitWindow,omitempty"`
	LogLevel        string   `json:"logLevel,omitempty" yaml:"logLevel,omitempty" toml:"logLevel,omitempty"`
	CleanupInterval int64    `json:"cleanupInterval,omitempty" yaml:"cleanupInterval,omitempty" toml:"cleanupInterval,omitempty"`
	UpstreamURL     string   `json:"upstreamURL,omitempty" yaml:"upstreamURL,omitempty" toml:"upstreamURL,omitempty"`
}

Config represents the middleware configuration

func CreateConfig

func CreateConfig() *Config

CreateConfig creates a default configuration

type ICalMiddleware

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

ICalMiddleware is the main middleware struct

func (*ICalMiddleware) ServeHTTP

func (plugin *ICalMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP handles the HTTP request

type Item added in v0.0.2

type Item struct {
	Object     bool      // The cached value
	Expiration int64     // When the item expires (Unix nano time)
	LastAccess time.Time // When the item was last accessed
}

Item represents a cache item

func (Item) Expired added in v0.0.2

func (item Item) Expired() bool

Expired returns true if the item has expired

type LogLevel added in v0.0.8

type LogLevel int

LogLevel represents the level of logging

const (
	// LogLevelError only logs errors
	LogLevelError LogLevel = iota
	// LogLevelInfo logs errors and important information
	LogLevelInfo
	// LogLevelDebug logs everything
	LogLevelDebug
)

type RequestMultiplexer added in v0.0.8

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

RequestMultiplexer represents an in-flight request for a specific token

Jump to

Keyboard shortcuts

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