From 7aa7f7638dc54bb1e11af899223b79bdb2cf44b7 Mon Sep 17 00:00:00 2001 From: Masoud Golestaneh Date: Mon, 28 Aug 2023 20:30:24 +0330 Subject: [PATCH] feat: add extra headers in response --- pkg/auth/authenticator.go | 48 ++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/pkg/auth/authenticator.go b/pkg/auth/authenticator.go index 6d06eec..b41ae71 100644 --- a/pkg/auth/authenticator.go +++ b/pkg/auth/authenticator.go @@ -22,6 +22,7 @@ type Authenticator struct { updateLock sync.Mutex } +type ExtraHeaders map[string]string type AccessCache map[string]AccessCacheEntry type ServicesCache map[string]struct{} @@ -136,35 +137,44 @@ func (a *Authenticator) UpdateCache(c client.Client, ctx context.Context, readOn return nil } -func (a *Authenticator) TestAccess(wsvc string, token string) (bool, CerberusReason) { + +func (a *Authenticator) TestAccess(wsvc string, token string) (bool, CerberusReason, ExtraHeaders) { a.cacheLock.RLock() defer a.cacheLock.RUnlock() + newExtraHeaders := make(ExtraHeaders) + if wsvc == "" { - return false, CerberusReasonLookupEmpty + return false, CerberusReasonLookupEmpty, newExtraHeaders } if token == "" { - return false, CerberusReasonTokenEmpty + return false, CerberusReasonTokenEmpty, newExtraHeaders } if _, ok := (*a.servicesCache)[wsvc]; !ok { - return false, CerberusReasonWebserviceNotFound + return false, CerberusReasonWebserviceNotFound, newExtraHeaders } - if _, ok := (*a.accessCache)[token]; !ok { - return false, CerberusReasonTokenNotFound + + ac, ok := (*a.accessCache)[token] + + if !ok { + return false, CerberusReasonTokenNotFound, newExtraHeaders } + newExtraHeaders["Access-Token-Name"] = ac.AccessToken.ObjectMeta.Name + if _, ok := (*a.accessCache)[token].allowedServices[wsvc]; !ok { - return false, CerberusReasonUnauthorized + return false, CerberusReasonUnauthorized, newExtraHeaders } - return true, CerberusReasonOK + + return true, CerberusReasonOK, newExtraHeaders } func (a *Authenticator) Check(ctx context.Context, request *Request) (*Response, error) { wsvc := request.Context["webservice"] token := request.Request.Header.Get("X-Cerberus-Token") - ok, reason := a.TestAccess(wsvc, token) + ok, reason, extraHeaders := a.TestAccess(wsvc, token) a.logger.Info("checking request", "res(ok)", ok, "req", request) var httpStatusCode int @@ -174,15 +184,21 @@ func (a *Authenticator) Check(ctx context.Context, request *Request) (*Response, httpStatusCode = http.StatusUnauthorized } + response := http.Response{ + StatusCode: httpStatusCode, + Header: http.Header{ + "Auth-Handler": {"cerberus"}, + "Cerberus-Reason": {string(reason)}, + }, + } + + for key, value := range extraHeaders { + response.Header.Add(key, value) + } + return &Response{ Allow: ok, - Response: http.Response{ - StatusCode: httpStatusCode, - Header: http.Header{ - "Auth-Handler": {"cerberus"}, - "Cerberus-Reason": {string(reason)}, - }, - }, + Response: response, }, nil }