From deecdb9acf0ac29469fa59c413c726870d613013 Mon Sep 17 00:00:00 2001 From: aahel Date: Fri, 18 Aug 2023 10:49:28 +0530 Subject: [PATCH] added check if anonymous token policy exists --- .../server-acl-init/anonymous_token.go | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/control-plane/subcommand/server-acl-init/anonymous_token.go b/control-plane/subcommand/server-acl-init/anonymous_token.go index 32c19ec208..b721c1b6fe 100644 --- a/control-plane/subcommand/server-acl-init/anonymous_token.go +++ b/control-plane/subcommand/server-acl-init/anonymous_token.go @@ -10,6 +10,13 @@ import ( // configureAnonymousPolicy sets up policies and tokens so that Consul DNS and // cross-datacenter Consul connect calls will work. func (c *Command) configureAnonymousPolicy(consulClient *api.Client) error { + exists, err := checkIfAnonymousTokenPolicyExists(consulClient) + if err != nil { + return err + } + if exists { + return nil + } anonRules, err := c.anonymousTokenRules() if err != nil { c.log.Error("Error templating anonymous token rules", "err", err) @@ -44,3 +51,26 @@ func (c *Command) configureAnonymousPolicy(consulClient *api.Client) error { return err }) } + +func checkIfAnonymousTokenPolicyExists(consulClient *api.Client) (bool, error) { + token, _, err := consulClient.ACL().TokenRead("00000000-0000-0000-0000-000000000002", nil) + if err != nil { + return false, err + } + existingPolicies, _, err := consulClient.ACL().PolicyList(&api.QueryOptions{}) + if err != nil { + return false, err + } + policyID := "" + for _, existingPolicy := range existingPolicies { + if existingPolicy.Name == "anonymous-token-policy" && existingPolicy.Description == "Anonymous token Policy" { + policyID = existingPolicy.ID + } + } + for _, policy := range token.Policies { + if policy.ID == policyID { + return true, nil + } + } + return false, nil +}