security

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package security provides JWT authentication, RBAC middleware, and security configuration for the Helix framework.

Index

Constants

This section is empty.

Variables

View Source
var ErrForbidden = errors.New("security: forbidden")

ErrForbidden is returned when a request is authenticated but lacks permission.

View Source
var ErrTokenExpired = errors.New("security: token expired")

ErrTokenExpired is returned when a JWT token has expired.

View Source
var ErrTokenInvalid = errors.New("security: token invalid")

ErrTokenInvalid is returned when a JWT token cannot be parsed or has an invalid signature.

View Source
var ErrUnauthorized = errors.New("security: unauthorized")

ErrUnauthorized is returned when a request lacks valid credentials.

Functions

func ClaimsFromContext

func ClaimsFromContext(ctx web.Context) (map[string]any, bool)

ClaimsFromContext extracts the JWT claims stored by JWTGuard from the request context. Returns (nil, false) when no claims are present.

func NewRoleGuardFactory

func NewRoleGuardFactory() web.GuardFactory

NewRoleGuardFactory returns a web.GuardFactory that parses a comma-separated roles argument (as produced by //helix:guard role:admin,moderator) and creates a RoleGuard from the result.

Types

type Configurer

type Configurer interface {
	Configure(hs *HTTPSecurity)
}

Configurer is the interface that global security configuration components implement. Embed helix.SecurityConfigurer in your struct to auto-register it.

type HTTPSecurity

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

HTTPSecurity accumulates security rules based on path patterns. Created by the framework during startup and passed to Configurer.Configure().

func NewHTTPSecurity

func NewHTTPSecurity(svc JWTServicer) *HTTPSecurity

NewHTTPSecurity creates an HTTPSecurity builder.

func (*HTTPSecurity) Build

func (hs *HTTPSecurity) Build() web.Guard

Build constructs the global guard that applies rules in definition order.

func (*HTTPSecurity) Route

func (hs *HTTPSecurity) Route(pattern string) *RouteSecurityBuilder

Route returns a RouteSecurityBuilder scoped to the given path pattern. Wildcards: ** (all segments) and * (one segment).

type JWTGuard

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

JWTGuard validates the Authorization: Bearer header and stores parsed claims in the request context under the "jwt_claims" key.

func NewJWTGuard

func NewJWTGuard(svc JWTServicer) *JWTGuard

NewJWTGuard creates a JWTGuard backed by the given JWTServicer.

func (*JWTGuard) CanActivate

func (g *JWTGuard) CanActivate(ctx web.Context) error

CanActivate implements web.Guard. It rejects the request with 401 when no valid Bearer token is present, and stores the claims for use in handlers.

type JWTService

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

JWTService signs and validates JWT tokens using HS256.

func NewJWTService

func NewJWTService(secret string, expiry time.Duration) (*JWTService, error)

NewJWTService creates a JWTService with the given secret and token expiry. A zero expiry defaults to 24 hours. An empty secret returns an error.

func (*JWTService) Generate

func (s *JWTService) Generate(claims map[string]any) (string, error)

Generate creates a signed JWT embedding the provided claims plus an "exp" field.

func (*JWTService) Refresh

func (s *JWTService) Refresh(tokenStr string) (string, error)

Refresh validates the token and returns a new one with a reset expiry. Returns ErrTokenExpired if the token is already expired.

func (*JWTService) Validate

func (s *JWTService) Validate(tokenStr string) (map[string]any, error)

Validate parses and verifies the token, returning its claims on success. Returns ErrTokenExpired or ErrTokenInvalid on failure.

type JWTServicer

type JWTServicer interface {
	Generate(claims map[string]any) (string, error)
	Validate(token string) (map[string]any, error)
	Refresh(token string) (string, error)
}

JWTServicer is the contract for JWT operations.

type RoleGuard

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

RoleGuard implements web.Guard to enforce role-based access control (RBAC). It reads the "roles" claim from JWT claims previously stored in the request context by JWTGuard, and allows the request only when the user possesses at least one of the allowed roles.

Usage with the //helix:guard directive:

//helix:guard role:admin
//helix:guard role:admin,moderator

func NewRoleGuard

func NewRoleGuard(allowedRoles ...string) *RoleGuard

NewRoleGuard creates a RoleGuard that permits access when the authenticated user has at least one of the given roles. It panics if called with no roles.

func (*RoleGuard) CanActivate

func (g *RoleGuard) CanActivate(ctx web.Context) error

CanActivate implements web.Guard. It returns a 403 Forbidden error when:

  • no JWT claims are present in the request context (unauthenticated)
  • the "roles" claim is missing or is not a []any or []string slice
  • none of the user's roles match any of the allowed roles

type RouteSecurityBuilder

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

RouteSecurityBuilder is an intermediate builder for a specific path pattern.

func (*RouteSecurityBuilder) Authenticated

func (b *RouteSecurityBuilder) Authenticated() *HTTPSecurity

Authenticated requires a valid JWT token.

func (*RouteSecurityBuilder) HasRole

func (b *RouteSecurityBuilder) HasRole(roles ...string) *HTTPSecurity

HasRole requires the user to have at least one of the specified roles. If no roles are provided, all requests are denied with 401. For unauthenticated requests (no JWT claims), returns 401 instead of 403.

func (*RouteSecurityBuilder) PermitAll

func (b *RouteSecurityBuilder) PermitAll() *HTTPSecurity

PermitAll allows all requests for this pattern without authentication.

Jump to

Keyboard shortcuts

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