2023-03-13 10:44:58 +01:00
|
|
|
package thirdparty
|
2023-03-07 23:10:42 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
2023-04-01 19:30:45 +02:00
|
|
|
"time"
|
2023-03-07 23:10:42 +01:00
|
|
|
|
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/auth"
|
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/jwk"
|
2023-07-26 15:14:49 +02:00
|
|
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
2023-03-07 23:10:42 +01:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2023-04-01 19:30:45 +02:00
|
|
|
const DefaultAcceptableSkew = 5 * time.Minute
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
type (
|
|
|
|
GetKeySet func(context.Context) (jwk.Set, error)
|
|
|
|
GetTokenRole func(context.Context, jwt.Token) (string, error)
|
|
|
|
)
|
|
|
|
|
2023-03-07 23:10:42 +01:00
|
|
|
type Authenticator struct {
|
2023-07-26 15:14:49 +02:00
|
|
|
getKeySet GetKeySet
|
|
|
|
getTokenRole GetTokenRole
|
2023-04-01 19:30:45 +02:00
|
|
|
acceptableSkew time.Duration
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Authenticate implements auth.Authenticator.
|
|
|
|
func (a *Authenticator) Authenticate(ctx context.Context, r *http.Request) (auth.User, error) {
|
|
|
|
authorization := r.Header.Get("Authorization")
|
|
|
|
if authorization == "" {
|
|
|
|
return nil, errors.WithStack(auth.ErrUnauthenticated)
|
|
|
|
}
|
|
|
|
|
|
|
|
rawToken := strings.TrimPrefix(authorization, "Bearer ")
|
|
|
|
if rawToken == "" {
|
|
|
|
return nil, errors.WithStack(auth.ErrUnauthenticated)
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
keys, err := a.getKeySet(ctx)
|
2023-03-07 23:10:42 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
token, err := parseToken(ctx, keys, rawToken, a.acceptableSkew)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
rawRole, err := a.getTokenRole(ctx, token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
if !isValidRole(rawRole) {
|
|
|
|
return nil, errors.Errorf("invalid role '%s'", rawRole)
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
user := &User{
|
|
|
|
subject: token.Subject(),
|
2023-07-26 15:14:49 +02:00
|
|
|
role: Role(rawRole),
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
func NewAuthenticator(getKeySet GetKeySet, getTokenRole GetTokenRole, acceptableSkew time.Duration) *Authenticator {
|
2023-03-07 23:10:42 +01:00
|
|
|
return &Authenticator{
|
2023-07-26 15:14:49 +02:00
|
|
|
getTokenRole: getTokenRole,
|
|
|
|
getKeySet: getKeySet,
|
2023-04-01 19:30:45 +02:00
|
|
|
acceptableSkew: acceptableSkew,
|
2023-03-07 23:10:42 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ auth.Authenticator = &Authenticator{}
|