Add/Delete API keys to Service accounts (#44871)

* ServiceAccounts: move token handlers to specific file

* ServiceAccounts: move Add API key to Service account

* APIKeys: api keys can still be used even when service accounts are enabled

* APIKeys: legacy endpoint can't be used to add SA tokens

* ServiceAccount: add tests for creation with nil and non-nil service account ids

* ServiceAccounts: fix unnasigned cfg and AC typo

* Test: test service account token adding

* fix linting error

* ServiceAccounts: Handle Token deletion

* rename token funcs

* rename token funcs and api wrapping

* add token deletion tests

* review

Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com>

* remove bus

* Update pkg/api/apikey.go

Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com>
This commit is contained in:
J Guerreiro
2022-02-07 14:51:54 +01:00
committed by GitHub
co-authored by eleijonmarck
parent 12176e24ef
commit 94820e1f29
13 changed files with 453 additions and 59 deletions
-1
View File
@@ -258,7 +258,6 @@ func (hs *HTTPServer) registerRoutes() {
apiRoute.Group("/auth/keys", func(keysRoute routing.RouteRegister) {
keysRoute.Get("/", routing.Wrap(hs.GetAPIKeys))
keysRoute.Post("/", quota("api_key"), routing.Wrap(hs.AddAPIKey))
keysRoute.Post("/additional", quota("api_key"), routing.Wrap(hs.AdditionalAPIKey))
keysRoute.Delete("/:id", routing.Wrap(hs.DeleteAPIKey))
}, reqOrgAdmin)
+2 -19
View File
@@ -10,7 +10,6 @@ import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/components/apikeygen"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/web"
)
@@ -80,12 +79,9 @@ func (hs *HTTPServer) AddAPIKey(c *models.ReqContext) response.Response {
return response.Error(400, "Number of seconds before expiration is greater than the global limit", nil)
}
}
cmd.ServiceAccountId = nil // Security: API keys can't be added to SAs through this endpoint since we do not implement access checks here
cmd.OrgId = c.OrgId
var err error
if hs.Features.IsEnabled(featuremgmt.FlagServiceAccounts) {
// Api keys should now be created with addadditionalapikey endpoint
return response.Error(400, "API keys should now be added via the AdditionalAPIKey endpoint.", err)
}
newKeyInfo, err := apikeygen.New(cmd.OrgId, cmd.Name)
if err != nil {
@@ -111,16 +107,3 @@ func (hs *HTTPServer) AddAPIKey(c *models.ReqContext) response.Response {
return response.JSON(200, result)
}
// AddAPIKey adds an additional API key to a service account
func (hs *HTTPServer) AdditionalAPIKey(c *models.ReqContext) response.Response {
cmd := models.AddApiKeyCommand{}
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if !hs.Features.IsEnabled(featuremgmt.FlagServiceAccounts) {
return response.Error(500, "Requires services-accounts feature", errors.New("feature missing"))
}
return hs.AddAPIKey(c)
}