bouncer/internal/proxy/director/layer/authn/layer_options.go

123 lines
3.0 KiB
Go
Raw Normal View History

package authn
import (
"reflect"
"time"
"forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
const DefaultSessionName = "bouncer-authn"
type LayerOptions struct {
MatchURLs []string `mapstructure:"matchURLs"`
Cookie CookieOptions `mapstructure:"cookie"`
Session SessionOptions `mapstructure:"session"`
Headers HeadersOptions `mapstructure:"headers"`
}
type CookieOptions struct {
Domain string `mapstructure:"domain"`
Name string `mapstructure:"name"`
Path string `mapstructure:"path"`
SameSite bool `mapstructure:"sameSite"`
Secure bool `mapstructure:"secure"`
HTTPOnly bool `mapstructure:"httpOnly"`
MaxAge time.Duration `mapstructure:"maxAge"`
}
type SessionOptions struct {
Name string `mapstructure:"name"`
TTL time.Duration `mapstructure:"ttl"`
}
type HeadersOptions struct {
Rules []string `mapstructure:"rules"`
}
func DefaultLayerOptions() LayerOptions {
return LayerOptions{
MatchURLs: []string{"*"},
Cookie: CookieOptions{
Path: "/",
HTTPOnly: true,
MaxAge: time.Hour,
},
Session: SessionOptions{
Name: DefaultSessionName,
TTL: time.Hour,
},
Headers: HeadersOptions{
Rules: []string{
"del_headers('Remote-*')",
"set_header('Remote-User', lower(user.subject))",
"set_header('Remote-Name', user.attrs.claim_name != nil ? user.attrs.claim_name : '')",
"user.attrs.claim_groups != nil ? set_header('Remote-Groups', join(user.attrs.claim_groups, ',')) : nil",
"set_header('Remote-Email', user.attrs.claim_email != nil ? user.attrs.claim_email : '')",
`map(
toPairs(user.attrs), {
let name = replace(upper(string(get(#, 0))), '_', '-');
set_header(
'Remote-User-Attr-' + name,
get(#, 1)
)
})
`,
},
},
}
}
func fromStoreOptions(storeOptions store.LayerOptions) (*LayerOptions, error) {
layerOptions := DefaultLayerOptions()
if err := FromStoreOptions(storeOptions, &layerOptions); err != nil {
return nil, errors.WithStack(err)
}
return &layerOptions, nil
}
func FromStoreOptions(storeOptions store.LayerOptions, dest any) error {
config := mapstructure.DecoderConfig{
Result: dest,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
toDurationHookFunc(),
),
}
decoder, err := mapstructure.NewDecoder(&config)
if err != nil {
return errors.WithStack(err)
}
if err := decoder.Decode(storeOptions); err != nil {
return errors.WithStack(err)
}
return nil
}
func toDurationHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if t != reflect.TypeOf(*new(time.Duration)) {
return data, nil
}
switch f.Kind() {
case reflect.String:
return time.ParseDuration(data.(string))
case reflect.Int64:
return time.Duration(data.(int64) * int64(time.Second)), nil
default:
return data, nil
}
// Convert it by parsing
}
}