guard

package module
v0.0.0-...-9f74c7f Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2021 License: MIT Imports: 24 Imported by: 0

README

Go-guard

Protect your Go application with minimal effort.

Features:

  • zero external dependencies, only std go library
  • pluggable storage; included in-memory and file-based
  • supports token and basic auth
  • prevents bruteforce by slowing down failed request
  • supports granular control by using zones
  • can be used in most HTTP router - it's working as http.Handler wrapper

Check demo app for examples

Documentation

Overview

Package guard protects application by tokens and basic auth.

Code generated by ./jsonstorage.sh TokenStorage Token Value token_storage.go DO NOT EDIT.

Code generated by ./jsonstorage.sh UserStorage User Name user_storage.go DO NOT EDIT.

Index

Constants

View Source
const (
	ZoneDefault = "default"
	ZoneAdmin   = "admin"
	KindToken   = "token"
	KindBasic   = "basic"
	DefaultKind = KindToken
	AuthQuery   = "token" // query parameter for credentials
)
View Source
const SaltSize = 32 // bytes
View Source
const TokenSize = 32 // bytes
View Source
const TokenStorageFileSuffix = ".json"
View Source
const UserStorageFileSuffix = ".json"

Variables

View Source
var ErrTokenInvalid = errors.New("value malformed")
View Source
var ErrTokenNotFound = errors.New("not found")
View Source
var ErrUserInvalid = errors.New("value malformed")
View Source
var ErrUserNotFound = errors.New("not found")

Functions

This section is empty.

Types

type ContextKey

type ContextKey string
const (
	KeyToken ContextKey = "token"
	KeyUser  ContextKey = "user"
)

type FileTokenStorage

type FileTokenStorage struct {
	Directory string
	// contains filtered or unexported fields
}

func (*FileTokenStorage) Delete

func (fts *FileTokenStorage) Delete(_ context.Context, value string) error

func (*FileTokenStorage) Get

func (fts *FileTokenStorage) Get(_ context.Context, value string) (*Token, error)

func (*FileTokenStorage) List

func (fts *FileTokenStorage) List(_ context.Context) ([]Token, error)

func (*FileTokenStorage) Set

func (fts *FileTokenStorage) Set(_ context.Context, value *Token) error

type FileUserStorage

type FileUserStorage struct {
	Directory string
	// contains filtered or unexported fields
}

func (*FileUserStorage) Delete

func (fts *FileUserStorage) Delete(_ context.Context, value string) error

func (*FileUserStorage) Get

func (fts *FileUserStorage) Get(_ context.Context, value string) (*User, error)

func (*FileUserStorage) List

func (fts *FileUserStorage) List(_ context.Context) ([]User, error)

func (*FileUserStorage) Set

func (fts *FileUserStorage) Set(_ context.Context, value *User) error

type Guard

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

func InMemory

func InMemory() *Guard

InMemory guard with in-memory only storages. All data will be lost after restart.

func New

func New(users UserStorage, tokens TokenStorage) *Guard

func Persistent

func Persistent(directory string) *Guard

Persistent guard with file-based storages.

func (*Guard) Basic

func (g *Guard) Basic(enable bool) *Guard

Basic auth request response (ie: www-authenticate) in case of unauthorized (without credentials) request to restricted zone. Useful to show login prompt in browsers. Enabled by default.

func (*Guard) CreateUserIfNotExists

func (g *Guard) CreateUserIfNotExists(ctx context.Context, name string, initialPassword string, zones []string) error

CreateUserIfNotExists creates user if not exists with initial password. Doesn't modify existent user. Thread unsafe.

func (*Guard) Delay

func (g *Guard) Delay(max time.Duration) *Guard

Delay (maximum) for response on invalid login attempt. Will be used random value between 0 and provided duration (exclusive).

func (*Guard) Restrict

func (g *Guard) Restrict(handler http.Handler) http.Handler

Restrict handler. Same as RestrictNamed with ZoneDefault as name.

func (*Guard) RestrictNamed

func (g *Guard) RestrictNamed(zoneName string, handler http.Handler) http.Handler

RestrictNamed protects handler by requiring authorization for each request.

func (*Guard) Router

func (g *Guard) Router() *Router

Router for requests with named restriction zone. Root requests are not restricted. UI included with restriction to ZoneAdmin on /admin. It's basically wrapper on to of http.ServeMux for convenience.

func (*Guard) Tokens

func (g *Guard) Tokens() TokenStorage

Tokens storage same as defined during creation.

func (*Guard) UI

func (g *Guard) UI() http.Handler

UI handler with restriction 'admin' zone. Prefix should be stripped.

func (*Guard) Users

func (g *Guard) Users() UserStorage

Users storage same as defined during creation.

func (*Guard) Zones

func (g *Guard) Zones() []string

Zones names. Copy.

type MemoryTokenStorage

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

func (*MemoryTokenStorage) Delete

func (mts *MemoryTokenStorage) Delete(_ context.Context, value string) error

func (*MemoryTokenStorage) Get

func (mts *MemoryTokenStorage) Get(_ context.Context, value string) (*Token, error)

func (*MemoryTokenStorage) List

func (mts *MemoryTokenStorage) List(_ context.Context) ([]Token, error)

func (*MemoryTokenStorage) Set

func (mts *MemoryTokenStorage) Set(_ context.Context, value *Token) error

type MemoryUserStorage

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

func (*MemoryUserStorage) Delete

func (mts *MemoryUserStorage) Delete(_ context.Context, value string) error

func (*MemoryUserStorage) Get

func (mts *MemoryUserStorage) Get(_ context.Context, value string) (*User, error)

func (*MemoryUserStorage) List

func (mts *MemoryUserStorage) List(_ context.Context) ([]User, error)

func (*MemoryUserStorage) Set

func (mts *MemoryUserStorage) Set(_ context.Context, value *User) error

type Router

type Router struct {
	*http.ServeMux
	// contains filtered or unexported fields
}

func (*Router) Restricted

func (router *Router) Restricted() *Router

Restricted is alis to Zone(ZoneDefault).

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*Router) Zone

func (router *Router) Zone(name string) *Router

type Token

type Token struct {
	Label     string    `json:"label,omitempty"`      // optional human-readable token description.
	Value     string    `json:"value"`                // unique 256-bit random value for crypto source in HEX.
	Zones     []string  `json:"zones,omitempty"`      // allowed zones. Empty means that allowed everything.
	CreatedAt time.Time `json:"created_at"`           // creation time
	ExpiredAt time.Time `json:"expired_at,omitempty"` // optional expiration time
}

func MustToken

func MustToken(label string, zones []string, duration time.Duration) *Token

func NewToken

func NewToken(label string, zones []string, duration time.Duration) (*Token, error)

func TokenFromContext

func TokenFromContext(ctx context.Context) *Token

TokenFromContext returns token saved in the context or nil.

type TokenStorage

type TokenStorage interface {
	// Get Token by value. Must return ErrTokenNotFound if entity not found.
	Get(ctx context.Context, value string) (*Token, error)
	// Set Token indexed by value.
	Set(ctx context.Context, value *Token) error
	// List Token.
	List(ctx context.Context) ([]Token, error)
	// Delete Token by value.
	Delete(ctx context.Context, value string) error
}

type User

type User struct {
	Name      string    `json:"name"`               // unique name of user
	Hash      []byte    `json:"hash"`               // hashed (SHA-512 with salt) password
	Salt      []byte    `json:"salt"`               // salt from cryptographic random source
	CreatedAt time.Time `json:"created_at"`         // creation time
	UpdatedAt time.Time `json:"updated_at"`         // last modification time
	Disabled  bool      `json:"disabled,omitempty"` // disable login
	Zones     []string  `json:"zones,omitempty"`    // allowed zones. Empty means that allowed everything.
}

func MustUser

func MustUser(name, password string, zones []string) *User

func NewUser

func NewUser(name, password string, zones []string) (*User, error)

func UserFromContext

func UserFromContext(ctx context.Context) *User

UserFromContext returns user saved in the context or nil.

func (*User) Check

func (u *User) Check(password string) bool

func (*User) Password

func (u *User) Password(password string) error

type UserStorage

type UserStorage interface {
	// Get User by name. Must return ErrUserNotFound if entity not found.
	Get(ctx context.Context, name string) (*User, error)
	// Set User indexed by name.
	Set(ctx context.Context, value *User) error
	// List User.
	List(ctx context.Context) ([]User, error)
	// Delete User by name.
	Delete(ctx context.Context, name string) error
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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