grafana/pkg/api/apikey.go
J Guerreiro 94820e1f29
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>
2022-02-07 14:51:54 +01:00

110 lines
3.1 KiB
Go

package api
import (
"errors"
"net/http"
"strconv"
"time"
"github.com/grafana/grafana/pkg/api/dtos"
"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/web"
)
// GetAPIKeys returns a list of API keys
func (hs *HTTPServer) GetAPIKeys(c *models.ReqContext) response.Response {
query := models.GetApiKeysQuery{OrgId: c.OrgId, IncludeExpired: c.QueryBool("includeExpired")}
if err := hs.SQLStore.GetAPIKeys(c.Req.Context(), &query); err != nil {
return response.Error(500, "Failed to list api keys", err)
}
result := make([]*models.ApiKeyDTO, len(query.Result))
for i, t := range query.Result {
var expiration *time.Time = nil
if t.Expires != nil {
v := time.Unix(*t.Expires, 0)
expiration = &v
}
result[i] = &models.ApiKeyDTO{
Id: t.Id,
Name: t.Name,
Role: t.Role,
Expiration: expiration,
}
}
return response.JSON(200, result)
}
// DeleteAPIKey deletes an API key
func (hs *HTTPServer) DeleteAPIKey(c *models.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err)
}
cmd := &models.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId}
err = hs.SQLStore.DeleteApiKey(c.Req.Context(), cmd)
if err != nil {
var status int
if errors.Is(err, models.ErrApiKeyNotFound) {
status = 404
} else {
status = 500
}
return response.Error(status, "Failed to delete API key", err)
}
return response.Success("API key deleted")
}
// AddAPIKey adds an API key
func (hs *HTTPServer) AddAPIKey(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 !cmd.Role.IsValid() {
return response.Error(400, "Invalid role specified", nil)
}
if hs.Cfg.ApiKeyMaxSecondsToLive != -1 {
if cmd.SecondsToLive == 0 {
return response.Error(400, "Number of seconds before expiration should be set", nil)
}
if cmd.SecondsToLive > hs.Cfg.ApiKeyMaxSecondsToLive {
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
newKeyInfo, err := apikeygen.New(cmd.OrgId, cmd.Name)
if err != nil {
return response.Error(500, "Generating API key failed", err)
}
cmd.Key = newKeyInfo.HashedKey
if err := hs.SQLStore.AddAPIKey(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, models.ErrInvalidApiKeyExpiration) {
return response.Error(400, err.Error(), nil)
}
if errors.Is(err, models.ErrDuplicateApiKey) {
return response.Error(409, err.Error(), nil)
}
return response.Error(500, "Failed to add API Key", err)
}
result := &dtos.NewApiKeyResult{
ID: cmd.Result.Id,
Name: cmd.Result.Name,
Key: newKeyInfo.ClientSecret,
}
return response.JSON(200, result)
}