Skip to content

Commit

Permalink
[Elastic Agent] Fix issues with enrollment key fetching (elastic#24319)
Browse files Browse the repository at this point in the history
* Fix issues with enrollment key fetching for Kibana 7.13.

* Fix issue with regex.

* Add comment, add strings.TrimSpace
  • Loading branch information
blakerouse authored Mar 4, 2021
1 parent 74a3a44 commit 3f00537
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions x-pack/elastic-agent/pkg/agent/cmd/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/url"
"os"
"os/exec"
"regexp"
"strings"
"time"

Expand All @@ -35,6 +36,12 @@ const (
maxRequestRetries = 30 // maximum number of retries for HTTP requests
)

var (
// Used to strip the appended ({uuid}) from the name of an enrollment token. This makes much easier for
// a container to reference a token by name, without having to know what the generated UUID is for that name.
tokenNameStrip = regexp.MustCompile(`\s\([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\)$`)
)

func newContainerCommand(flags *globalFlags, _ []string, streams *cli.IOStreams) *cobra.Command {
return &cobra.Command{
Hidden: true, // not exposed over help; used by container entrypoint only
Expand Down Expand Up @@ -272,7 +279,12 @@ func kibanaFetchToken(client *kibana.Client, policy *kibanaPolicy, streams *cli.
if err != nil {
return "", err
}
return key.APIKey, nil
var keyDetail kibanaAPIKeyDetail
err = performGET(client, fmt.Sprintf("/api/fleet/enrollment-api-keys/%s", key.ID), &keyDetail, streams.Err, "Kibana fetch token detail")
if err != nil {
return "", err
}
return keyDetail.Item.APIKey, nil
}

func kibanaClient() (*kibana.Client, error) {
Expand Down Expand Up @@ -317,7 +329,7 @@ func findPolicy(policies []kibanaPolicy) (*kibanaPolicy, error) {
func findKey(keys []kibanaAPIKey, policy *kibanaPolicy) (*kibanaAPIKey, error) {
tokenName := envWithDefault(defaultTokenName, "FLEET_TOKEN_NAME")
for _, key := range keys {
name := strings.TrimSpace(strings.Replace(key.Name, fmt.Sprintf(" (%s)", key.ID), "", 1))
name := strings.TrimSpace(tokenNameStrip.ReplaceAllString(key.Name, ""))
if name == tokenName && key.PolicyID == policy.ID {
return &key, nil
}
Expand Down Expand Up @@ -425,3 +437,7 @@ type kibanaAPIKey struct {
type kibanaAPIKeys struct {
List []kibanaAPIKey `json:"list"`
}

type kibanaAPIKeyDetail struct {
Item kibanaAPIKey `json:"item"`
}

0 comments on commit 3f00537

Please sign in to comment.