|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/grafana/authlib/authn" |
| 8 | + "k8s.io/apiserver/pkg/authentication/authenticator" |
| 9 | + "k8s.io/apiserver/pkg/authentication/user" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + headerKeyAccessToken = "X-Access-Token" |
| 14 | + headerKeyGrafanaID = "X-Grafana-Id" |
| 15 | + |
| 16 | + extraKeyAccessToken = "access-token" |
| 17 | + extraKeyGrafanaID = "id-token" |
| 18 | + extraKeyGLSA = "glsa" |
| 19 | +) |
| 20 | + |
| 21 | +func NewAccessTokenAuthenticator(config *authn.IDVerifierConfig) authenticator.RequestFunc { |
| 22 | + verifier := authn.NewVerifier[CustomClaims](authn.IDVerifierConfig{ |
| 23 | + SigningKeysURL: config.SigningKeysURL, |
| 24 | + AllowedAudiences: config.AllowedAudiences, |
| 25 | + }) |
| 26 | + return getAccessTokenAuthenticatorFunc(&TokenValidator{verifier}) |
| 27 | +} |
| 28 | + |
| 29 | +func getAccessTokenAuthenticatorFunc(validator *TokenValidator) authenticator.RequestFunc { |
| 30 | + return func(req *http.Request) (*authenticator.Response, bool, error) { |
| 31 | + accessToken := req.Header.Get(headerKeyAccessToken) |
| 32 | + if accessToken == "" { |
| 33 | + return nil, false, nil |
| 34 | + } |
| 35 | + |
| 36 | + // While the authn token system is in development, we can temporarily use |
| 37 | + // service account tokens. Note this does not grant any real permissions/verification, |
| 38 | + // it simply allows forwarding the token to the next request |
| 39 | + if strings.HasPrefix(accessToken, "glsa_") { |
| 40 | + return &authenticator.Response{ |
| 41 | + Audiences: authenticator.Audiences([]string{}), |
| 42 | + User: &user.DefaultInfo{ |
| 43 | + Name: "glsa-forwarding-request", |
| 44 | + UID: "", |
| 45 | + Groups: []string{}, |
| 46 | + Extra: map[string][]string{ |
| 47 | + extraKeyGLSA: {accessToken}, |
| 48 | + }, |
| 49 | + }, |
| 50 | + }, true, nil |
| 51 | + } |
| 52 | + |
| 53 | + result, err := validator.Validate(req.Context(), accessToken) |
| 54 | + if err != nil { |
| 55 | + return nil, false, err |
| 56 | + } |
| 57 | + |
| 58 | + return &authenticator.Response{ |
| 59 | + Audiences: authenticator.Audiences(result.Claims.Audience), |
| 60 | + User: &user.DefaultInfo{ |
| 61 | + Name: result.Subject, |
| 62 | + UID: "", |
| 63 | + Groups: []string{}, |
| 64 | + Extra: map[string][]string{ |
| 65 | + extraKeyAccessToken: {accessToken}, |
| 66 | + extraKeyGrafanaID: {req.Header.Get("X-Grafana-Id")}, // this may exist if starting with a user |
| 67 | + }, |
| 68 | + }, |
| 69 | + }, true, nil |
| 70 | + } |
| 71 | +} |
0 commit comments