2014-12-17 06:58:39 +00:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto"
|
|
|
|
"crypto/x509"
|
2023-10-08 22:02:45 +00:00
|
|
|
"encoding/json"
|
2014-12-17 06:58:39 +00:00
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2022-11-02 21:55:22 +00:00
|
|
|
"io"
|
2014-12-17 06:58:39 +00:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
2020-08-24 11:18:39 +00:00
|
|
|
"github.com/distribution/distribution/v3/registry/auth"
|
2023-10-08 22:02:45 +00:00
|
|
|
"github.com/go-jose/go-jose/v3"
|
2023-11-18 06:50:40 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2014-12-17 06:58:39 +00:00
|
|
|
)
|
|
|
|
|
2023-11-28 06:50:48 +00:00
|
|
|
// init handles registering the token auth backend.
|
|
|
|
func init() {
|
|
|
|
if err := auth.Register("token", auth.InitFunc(newAccessController)); err != nil {
|
|
|
|
logrus.Errorf("tailed to register token auth: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-17 06:58:39 +00:00
|
|
|
// accessSet maps a typed, named resource to
|
|
|
|
// a set of actions requested or authorized.
|
|
|
|
type accessSet map[auth.Resource]actionSet
|
|
|
|
|
|
|
|
// newAccessSet constructs an accessSet from
|
|
|
|
// a variable number of auth.Access items.
|
|
|
|
func newAccessSet(accessItems ...auth.Access) accessSet {
|
|
|
|
accessSet := make(accessSet, len(accessItems))
|
|
|
|
|
|
|
|
for _, access := range accessItems {
|
|
|
|
resource := auth.Resource{
|
|
|
|
Type: access.Type,
|
|
|
|
Name: access.Name,
|
|
|
|
}
|
|
|
|
|
2014-12-17 18:57:05 +00:00
|
|
|
set, exists := accessSet[resource]
|
|
|
|
if !exists {
|
|
|
|
set = newActionSet()
|
2014-12-17 06:58:39 +00:00
|
|
|
accessSet[resource] = set
|
|
|
|
}
|
|
|
|
|
2015-01-06 02:21:03 +00:00
|
|
|
set.add(access.Action)
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return accessSet
|
|
|
|
}
|
|
|
|
|
|
|
|
// contains returns whether or not the given access is in this accessSet.
|
|
|
|
func (s accessSet) contains(access auth.Access) bool {
|
|
|
|
actionSet, ok := s[access.Resource]
|
|
|
|
if ok {
|
2015-01-06 02:21:03 +00:00
|
|
|
return actionSet.contains(access.Action)
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// scopeParam returns a collection of scopes which can
|
|
|
|
// be used for a WWW-Authenticate challenge parameter.
|
|
|
|
// See https://tools.ietf.org/html/rfc6750#section-3
|
|
|
|
func (s accessSet) scopeParam() string {
|
|
|
|
scopes := make([]string, 0, len(s))
|
|
|
|
|
|
|
|
for resource, actionSet := range s {
|
2015-01-06 02:21:03 +00:00
|
|
|
actions := strings.Join(actionSet.keys(), ",")
|
2014-12-17 06:58:39 +00:00
|
|
|
scopes = append(scopes, fmt.Sprintf("%s:%s:%s", resource.Type, resource.Name, actions))
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Join(scopes, " ")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Errors used and exported by this package.
|
|
|
|
var (
|
|
|
|
ErrInsufficientScope = errors.New("insufficient scope")
|
|
|
|
ErrTokenRequired = errors.New("authorization token required")
|
|
|
|
)
|
|
|
|
|
|
|
|
// authChallenge implements the auth.Challenge interface.
|
|
|
|
type authChallenge struct {
|
2017-03-13 23:35:15 +00:00
|
|
|
err error
|
|
|
|
realm string
|
|
|
|
autoRedirect bool
|
|
|
|
service string
|
|
|
|
accessSet accessSet
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2015-07-24 02:39:56 +00:00
|
|
|
var _ auth.Challenge = authChallenge{}
|
|
|
|
|
2014-12-17 06:58:39 +00:00
|
|
|
// Error returns the internal error string for this authChallenge.
|
2015-07-24 02:39:56 +00:00
|
|
|
func (ac authChallenge) Error() string {
|
2014-12-17 06:58:39 +00:00
|
|
|
return ac.err.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Status returns the HTTP Response Status Code for this authChallenge.
|
2015-07-24 02:39:56 +00:00
|
|
|
func (ac authChallenge) Status() int {
|
2014-12-17 06:58:39 +00:00
|
|
|
return http.StatusUnauthorized
|
|
|
|
}
|
|
|
|
|
|
|
|
// challengeParams constructs the value to be used in
|
|
|
|
// the WWW-Authenticate response challenge header.
|
|
|
|
// See https://tools.ietf.org/html/rfc6750#section-3
|
2017-03-13 23:35:15 +00:00
|
|
|
func (ac authChallenge) challengeParams(r *http.Request) string {
|
|
|
|
var realm string
|
|
|
|
if ac.autoRedirect {
|
|
|
|
realm = fmt.Sprintf("https://%s/auth/token", r.Host)
|
|
|
|
} else {
|
|
|
|
realm = ac.realm
|
|
|
|
}
|
|
|
|
str := fmt.Sprintf("Bearer realm=%q,service=%q", realm, ac.service)
|
2014-12-17 06:58:39 +00:00
|
|
|
|
|
|
|
if scope := ac.accessSet.scopeParam(); scope != "" {
|
2014-12-18 00:16:02 +00:00
|
|
|
str = fmt.Sprintf("%s,scope=%q", str, scope)
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if ac.err == ErrInvalidToken || ac.err == ErrMalformedToken {
|
2014-12-18 00:16:02 +00:00
|
|
|
str = fmt.Sprintf("%s,error=%q", str, "invalid_token")
|
2014-12-17 06:58:39 +00:00
|
|
|
} else if ac.err == ErrInsufficientScope {
|
2014-12-18 00:16:02 +00:00
|
|
|
str = fmt.Sprintf("%s,error=%q", str, "insufficient_scope")
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
|
2024-04-23 09:48:53 +00:00
|
|
|
// SetHeaders sets the WWW-Authenticate value for the response.
|
2017-03-13 23:35:15 +00:00
|
|
|
func (ac authChallenge) SetHeaders(r *http.Request, w http.ResponseWriter) {
|
|
|
|
w.Header().Add("WWW-Authenticate", ac.challengeParams(r))
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// accessController implements the auth.AccessController interface.
|
|
|
|
type accessController struct {
|
2017-03-13 23:35:15 +00:00
|
|
|
realm string
|
|
|
|
autoRedirect bool
|
|
|
|
issuer string
|
|
|
|
service string
|
|
|
|
rootCerts *x509.CertPool
|
2023-10-08 22:02:45 +00:00
|
|
|
trustedKeys map[string]crypto.PublicKey
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// tokenAccessOptions is a convenience type for handling
|
2024-04-19 09:49:51 +00:00
|
|
|
// options to the constructor of an accessController.
|
2014-12-17 06:58:39 +00:00
|
|
|
type tokenAccessOptions struct {
|
|
|
|
realm string
|
2017-03-13 23:35:15 +00:00
|
|
|
autoRedirect bool
|
2014-12-17 06:58:39 +00:00
|
|
|
issuer string
|
|
|
|
service string
|
|
|
|
rootCertBundle string
|
2023-10-08 22:02:45 +00:00
|
|
|
jwks string
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// checkOptions gathers the necessary options
|
|
|
|
// for an accessController from the given map.
|
|
|
|
func checkOptions(options map[string]interface{}) (tokenAccessOptions, error) {
|
|
|
|
var opts tokenAccessOptions
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
keys := []string{"realm", "issuer", "service", "rootcertbundle", "jwks"}
|
2014-12-17 06:58:39 +00:00
|
|
|
vals := make([]string, 0, len(keys))
|
|
|
|
for _, key := range keys {
|
|
|
|
val, ok := options[key].(string)
|
|
|
|
if !ok {
|
2023-10-08 22:02:45 +00:00
|
|
|
// NOTE(milosgajdos): this func makes me intensely sad
|
|
|
|
// just like all the other weakly typed config options.
|
|
|
|
// Either of these config options may be missing, but
|
|
|
|
// at least one must be present: we handle those cases
|
|
|
|
// in newAccessController func which consumes this one.
|
|
|
|
if key == "rootcertbundle" || key == "jwks" {
|
|
|
|
vals = append(vals, "")
|
|
|
|
continue
|
|
|
|
}
|
2014-12-17 06:58:39 +00:00
|
|
|
return opts, fmt.Errorf("token auth requires a valid option string: %q", key)
|
|
|
|
}
|
|
|
|
vals = append(vals, val)
|
|
|
|
}
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
opts.realm, opts.issuer, opts.service, opts.rootCertBundle, opts.jwks = vals[0], vals[1], vals[2], vals[3], vals[4]
|
2014-12-17 06:58:39 +00:00
|
|
|
|
2019-01-04 19:02:57 +00:00
|
|
|
autoRedirectVal, ok := options["autoredirect"]
|
|
|
|
if ok {
|
|
|
|
autoRedirect, ok := autoRedirectVal.(bool)
|
|
|
|
if !ok {
|
|
|
|
return opts, fmt.Errorf("token auth requires a valid option bool: autoredirect")
|
|
|
|
}
|
|
|
|
opts.autoRedirect = autoRedirect
|
2017-03-13 23:35:15 +00:00
|
|
|
}
|
|
|
|
|
2014-12-17 06:58:39 +00:00
|
|
|
return opts, nil
|
|
|
|
}
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
func getRootCerts(path string) ([]*x509.Certificate, error) {
|
|
|
|
fp, err := os.Open(path)
|
2014-12-17 06:58:39 +00:00
|
|
|
if err != nil {
|
2023-10-08 22:02:45 +00:00
|
|
|
return nil, fmt.Errorf("unable to open token auth root certificate bundle file %q: %s", path, err)
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
defer fp.Close()
|
|
|
|
|
2022-11-02 21:55:22 +00:00
|
|
|
rawCertBundle, err := io.ReadAll(fp)
|
2014-12-17 06:58:39 +00:00
|
|
|
if err != nil {
|
2023-10-08 22:02:45 +00:00
|
|
|
return nil, fmt.Errorf("unable to read token auth root certificate bundle file %q: %s", path, err)
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var rootCerts []*x509.Certificate
|
|
|
|
pemBlock, rawCertBundle := pem.Decode(rawCertBundle)
|
|
|
|
for pemBlock != nil {
|
2016-08-31 17:00:12 +00:00
|
|
|
if pemBlock.Type == "CERTIFICATE" {
|
|
|
|
cert, err := x509.ParseCertificate(pemBlock.Bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to parse token auth root certificate: %s", err)
|
|
|
|
}
|
2014-12-17 06:58:39 +00:00
|
|
|
|
2016-08-31 17:00:12 +00:00
|
|
|
rootCerts = append(rootCerts, cert)
|
|
|
|
}
|
2014-12-17 06:58:39 +00:00
|
|
|
|
|
|
|
pemBlock, rawCertBundle = pem.Decode(rawCertBundle)
|
|
|
|
}
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
return rootCerts, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getJwks(path string) (*jose.JSONWebKeySet, error) {
|
|
|
|
// TODO(milosgajdos): we should consider providing a JWKS
|
|
|
|
// URL from which the JWKS could be fetched
|
|
|
|
jp, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to open jwks file %q: %s", path, err)
|
|
|
|
}
|
|
|
|
defer jp.Close()
|
|
|
|
|
|
|
|
rawJWKS, err := io.ReadAll(jp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to read token jwks file %q: %s", path, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var jwks jose.JSONWebKeySet
|
|
|
|
if err := json.Unmarshal(rawJWKS, &jwks); err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse jwks: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &jwks, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// newAccessController creates an accessController using the given options.
|
|
|
|
func newAccessController(options map[string]interface{}) (auth.AccessController, error) {
|
|
|
|
config, err := checkOptions(options)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
rootCerts []*x509.Certificate
|
|
|
|
jwks *jose.JSONWebKeySet
|
|
|
|
)
|
|
|
|
|
|
|
|
if config.rootCertBundle != "" {
|
|
|
|
rootCerts, err = getRootCerts(config.rootCertBundle)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.jwks != "" {
|
|
|
|
jwks, err = getJwks(config.jwks)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (len(rootCerts) == 0 && jwks == nil) || // no certs bundle and no jwks
|
|
|
|
(len(rootCerts) == 0 && jwks != nil && len(jwks.Keys) == 0) { // no certs bundle and empty jwks
|
|
|
|
return nil, errors.New("token auth requires at least one token signing key")
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
rootPool := x509.NewCertPool()
|
|
|
|
for _, rootCert := range rootCerts {
|
|
|
|
rootPool.AddCert(rootCert)
|
2023-10-08 22:02:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
trustedKeys := make(map[string]crypto.PublicKey)
|
|
|
|
if jwks != nil {
|
|
|
|
for _, key := range jwks.Keys {
|
|
|
|
trustedKeys[key.KeyID] = key.Public()
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &accessController{
|
2017-03-13 23:35:15 +00:00
|
|
|
realm: config.realm,
|
|
|
|
autoRedirect: config.autoRedirect,
|
|
|
|
issuer: config.issuer,
|
|
|
|
service: config.service,
|
|
|
|
rootCerts: rootPool,
|
|
|
|
trustedKeys: trustedKeys,
|
2014-12-17 06:58:39 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Authorized handles checking whether the given request is authorized
|
|
|
|
// for actions on resources described by the given access items.
|
2023-10-24 20:41:54 +00:00
|
|
|
func (ac *accessController) Authorized(req *http.Request, accessItems ...auth.Access) (*auth.Grant, error) {
|
2014-12-17 06:58:39 +00:00
|
|
|
challenge := &authChallenge{
|
2017-03-13 23:35:15 +00:00
|
|
|
realm: ac.realm,
|
|
|
|
autoRedirect: ac.autoRedirect,
|
|
|
|
service: ac.service,
|
|
|
|
accessSet: newAccessSet(accessItems...),
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
replace strings.Split(N) for strings.Cut() or alternatives
Go 1.18 and up now provides a strings.Cut() which is better suited for
splitting key/value pairs (and similar constructs), and performs better:
```go
func BenchmarkSplit(b *testing.B) {
b.ReportAllocs()
data := []string{"12hello=world", "12hello=", "12=hello", "12hello"}
for i := 0; i < b.N; i++ {
for _, s := range data {
_ = strings.SplitN(s, "=", 2)[0]
}
}
}
func BenchmarkCut(b *testing.B) {
b.ReportAllocs()
data := []string{"12hello=world", "12hello=", "12=hello", "12hello"}
for i := 0; i < b.N; i++ {
for _, s := range data {
_, _, _ = strings.Cut(s, "=")
}
}
}
```
BenchmarkSplit
BenchmarkSplit-10 8244206 128.0 ns/op 128 B/op 4 allocs/op
BenchmarkCut
BenchmarkCut-10 54411998 21.80 ns/op 0 B/op 0 allocs/op
While looking at occurrences of `strings.Split()`, I also updated some for alternatives,
or added some constraints;
- for cases where an specific number of items is expected, I used `strings.SplitN()`
with a suitable limit. This prevents (theoretical) unlimited splits.
- in some cases it we were using `strings.Split()`, but _actually_ were trying to match
a prefix; for those I replaced the code to just match (and/or strip) the prefix.
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-11-02 19:32:03 +00:00
|
|
|
prefix, rawToken, ok := strings.Cut(req.Header.Get("Authorization"), " ")
|
|
|
|
if !ok || rawToken == "" || !strings.EqualFold(prefix, "bearer") {
|
2014-12-17 06:58:39 +00:00
|
|
|
challenge.err = ErrTokenRequired
|
2015-02-04 01:59:24 +00:00
|
|
|
return nil, challenge
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
token, err := NewToken(rawToken)
|
|
|
|
if err != nil {
|
|
|
|
challenge.err = err
|
2015-02-04 01:59:24 +00:00
|
|
|
return nil, challenge
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
verifyOpts := VerifyOptions{
|
2015-01-06 02:21:03 +00:00
|
|
|
TrustedIssuers: []string{ac.issuer},
|
|
|
|
AcceptedAudiences: []string{ac.service},
|
2014-12-17 06:58:39 +00:00
|
|
|
Roots: ac.rootCerts,
|
|
|
|
TrustedKeys: ac.trustedKeys,
|
|
|
|
}
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
claims, err := token.Verify(verifyOpts)
|
|
|
|
if err != nil {
|
2014-12-17 06:58:39 +00:00
|
|
|
challenge.err = err
|
2015-02-04 01:59:24 +00:00
|
|
|
return nil, challenge
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2023-10-08 22:02:45 +00:00
|
|
|
accessSet := claims.accessSet()
|
2014-12-17 06:58:39 +00:00
|
|
|
for _, access := range accessItems {
|
|
|
|
if !accessSet.contains(access) {
|
|
|
|
challenge.err = ErrInsufficientScope
|
2015-02-04 01:59:24 +00:00
|
|
|
return nil, challenge
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-24 20:41:54 +00:00
|
|
|
return &auth.Grant{
|
|
|
|
User: auth.UserInfo{Name: claims.Subject},
|
|
|
|
Resources: claims.resources(),
|
|
|
|
}, nil
|
2014-12-17 06:58:39 +00:00
|
|
|
}
|