conjur.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package addon
  14. import (
  15. "context"
  16. "crypto/rand"
  17. "encoding/base64"
  18. "encoding/json"
  19. "fmt"
  20. "strings"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. // nolint
  23. ginkgo "github.com/onsi/ginkgo/v2"
  24. "github.com/cyberark/conjur-api-go/conjurapi"
  25. "github.com/cyberark/conjur-api-go/conjurapi/authn"
  26. "github.com/external-secrets/external-secrets-e2e/framework/util"
  27. )
  28. type Conjur struct {
  29. chart *HelmChart
  30. dataKey string
  31. Namespace string
  32. PodName string
  33. ConjurClient *conjurapi.Client
  34. ConjurURL string
  35. AdminApiKey string
  36. ConjurServerCA []byte
  37. }
  38. func NewConjur(namespace string) *Conjur {
  39. repo := "conjur-" + namespace
  40. dataKey := generateConjurDataKey()
  41. return &Conjur{
  42. dataKey: dataKey,
  43. chart: &HelmChart{
  44. Namespace: namespace,
  45. ReleaseName: fmt.Sprintf("conjur-%s", namespace), // avoid cluster role collision
  46. Chart: fmt.Sprintf("%s/conjur-oss", repo),
  47. // Use latest version of Conjur OSS. To pin to a specific version, uncomment the following line.
  48. // ChartVersion: "2.0.7",
  49. Repo: ChartRepo{
  50. Name: repo,
  51. URL: "https://cyberark.github.io/helm-charts",
  52. },
  53. Values: []string{"/k8s/conjur.values.yaml"},
  54. Vars: []StringTuple{
  55. {
  56. Key: "dataKey",
  57. Value: dataKey,
  58. },
  59. },
  60. },
  61. Namespace: namespace,
  62. }
  63. }
  64. func (l *Conjur) Install() error {
  65. ginkgo.By("Installing conjur in " + l.Namespace)
  66. err := l.chart.Install()
  67. if err != nil {
  68. return err
  69. }
  70. err = l.initConjur()
  71. if err != nil {
  72. return err
  73. }
  74. err = l.configureConjur()
  75. if err != nil {
  76. return err
  77. }
  78. return nil
  79. }
  80. func (l *Conjur) initConjur() error {
  81. ginkgo.By("Waiting for conjur pods to be running")
  82. pl, err := util.WaitForPodsRunning(l.chart.config.KubeClientSet, 1, l.Namespace, metav1.ListOptions{
  83. LabelSelector: "app=conjur-oss",
  84. })
  85. if err != nil {
  86. return fmt.Errorf("error waiting for conjur to be running: %w", err)
  87. }
  88. l.PodName = pl.Items[0].Name
  89. ginkgo.By("Initializing conjur")
  90. // Get the auto generated certificates from the K8s secrets
  91. caCertSecret, err := util.GetKubeSecret(l.chart.config.KubeClientSet, l.Namespace, fmt.Sprintf("%s-conjur-ssl-ca-cert", l.chart.ReleaseName))
  92. if err != nil {
  93. return fmt.Errorf("error getting conjur ca cert: %w", err)
  94. }
  95. l.ConjurServerCA = caCertSecret.Data["tls.crt"]
  96. // Create "default" account
  97. _, err = util.ExecCmdWithContainer(
  98. l.chart.config.KubeClientSet,
  99. l.chart.config.KubeConfig,
  100. l.PodName, "conjur-oss", l.Namespace, "conjurctl account create default")
  101. if err != nil {
  102. return fmt.Errorf("error initializing conjur: %w", err)
  103. }
  104. // Retrieve the admin API key
  105. apiKey, err := util.ExecCmdWithContainer(
  106. l.chart.config.KubeClientSet,
  107. l.chart.config.KubeConfig,
  108. l.PodName, "conjur-oss", l.Namespace, "conjurctl role retrieve-key default:user:admin")
  109. if err != nil {
  110. return fmt.Errorf("error fetching admin API key: %w", err)
  111. }
  112. // Note: ExecCmdWithContainer includes the StdErr output with a warning about config directory.
  113. // Therefore we need to split the output and only use the first line.
  114. l.AdminApiKey = strings.Split(apiKey, "\n")[0]
  115. l.ConjurURL = fmt.Sprintf("https://conjur-%s-conjur-oss.%s.svc.cluster.local", l.Namespace, l.Namespace)
  116. cfg := conjurapi.Config{
  117. Account: "default",
  118. ApplianceURL: l.ConjurURL,
  119. SSLCert: string(l.ConjurServerCA),
  120. }
  121. l.ConjurClient, err = conjurapi.NewClientFromKey(cfg, authn.LoginPair{
  122. Login: "admin",
  123. APIKey: l.AdminApiKey,
  124. })
  125. if err != nil {
  126. return fmt.Errorf("unable to create conjur client: %w", err)
  127. }
  128. return nil
  129. }
  130. func (l *Conjur) configureConjur() error {
  131. ginkgo.By("configuring conjur")
  132. // Construct Conjur policy for authn-jwt. This uses the token-app-property "sub" to
  133. // authenticate the host. This means that Conjur will determine which host is authenticating
  134. // based on the "sub" claim in the JWT token, which is provided by the Kubernetes service account.
  135. policy := `- !policy
  136. id: conjur/authn-jwt/eso-tests
  137. body:
  138. - !webservice
  139. - !variable public-keys
  140. - !variable issuer
  141. - !variable token-app-property
  142. - !variable audience`
  143. _, err := l.ConjurClient.LoadPolicy(conjurapi.PolicyModePost, "root", strings.NewReader(policy))
  144. if err != nil {
  145. return fmt.Errorf("unable to load authn-jwt policy: %w", err)
  146. }
  147. // Construct Conjur policy for authn-jwt-hostid. This does not use the token-app-property variable
  148. // and instead uses the HostID passed in the authentication URL to determine which host is authenticating.
  149. // This is not the recommended way to authenticate, but it is needed for certain use cases where the
  150. // JWT token does not contain the "sub" claim.
  151. policy = `- !policy
  152. id: conjur/authn-jwt/eso-tests-hostid
  153. body:
  154. - !webservice
  155. - !variable public-keys
  156. - !variable issuer
  157. - !variable audience`
  158. _, err = l.ConjurClient.LoadPolicy(conjurapi.PolicyModePost, "root", strings.NewReader(policy))
  159. if err != nil {
  160. return fmt.Errorf("unable to load authn-jwt policy: %w", err)
  161. }
  162. // Fetch the jwks info from the k8s cluster
  163. pubKeysJson, issuer, err := l.fetchJWKSandIssuer()
  164. if err != nil {
  165. return fmt.Errorf("unable to fetch jwks and issuer: %w", err)
  166. }
  167. // Set the variables for the authn-jwt policies
  168. secrets := map[string]string{
  169. "conjur/authn-jwt/eso-tests/audience": l.ConjurURL,
  170. "conjur/authn-jwt/eso-tests/issuer": issuer,
  171. "conjur/authn-jwt/eso-tests/public-keys": string(pubKeysJson),
  172. "conjur/authn-jwt/eso-tests/token-app-property": "sub",
  173. "conjur/authn-jwt/eso-tests-hostid/audience": l.ConjurURL,
  174. "conjur/authn-jwt/eso-tests-hostid/issuer": issuer,
  175. "conjur/authn-jwt/eso-tests-hostid/public-keys": string(pubKeysJson),
  176. }
  177. for secretPath, secretValue := range secrets {
  178. err := l.ConjurClient.AddSecret(secretPath, secretValue)
  179. if err != nil {
  180. return fmt.Errorf("unable to add secret %s: %w", secretPath, err)
  181. }
  182. }
  183. return nil
  184. }
  185. func (l *Conjur) fetchJWKSandIssuer() (pubKeysJson string, issuer string, err error) {
  186. kc := l.chart.config.KubeClientSet
  187. // Fetch the openid-configuration
  188. res, err := kc.CoreV1().RESTClient().Get().AbsPath("/.well-known/openid-configuration").DoRaw(context.Background())
  189. if err != nil {
  190. return "", "", fmt.Errorf("unable to fetch openid-configuration: %w", err)
  191. }
  192. var openidConfig map[string]any
  193. json.Unmarshal(res, &openidConfig)
  194. issuer = openidConfig["issuer"].(string)
  195. // Fetch the jwks
  196. jwksJson, err := kc.CoreV1().RESTClient().Get().AbsPath("/openid/v1/jwks").DoRaw(context.Background())
  197. if err != nil {
  198. return "", "", fmt.Errorf("unable to fetch jwks: %w", err)
  199. }
  200. var jwks map[string]any
  201. json.Unmarshal(jwksJson, &jwks)
  202. // Create a JSON object with the jwks that can be used by Conjur
  203. pubKeysObj := map[string]any{
  204. "type": "jwks",
  205. "value": jwks,
  206. }
  207. pubKeysJsonObj, err := json.Marshal(pubKeysObj)
  208. if err != nil {
  209. return "", "", fmt.Errorf("unable to marshal jwks: %w", err)
  210. }
  211. pubKeysJson = string(pubKeysJsonObj)
  212. return pubKeysJson, issuer, nil
  213. }
  214. func (l *Conjur) Logs() error {
  215. return l.chart.Logs()
  216. }
  217. func (l *Conjur) Uninstall() error {
  218. return l.chart.Uninstall()
  219. }
  220. func (l *Conjur) Setup(cfg *Config) error {
  221. return l.chart.Setup(cfg)
  222. }
  223. func generateConjurDataKey() string {
  224. // Generate a 32 byte cryptographically secure random string.
  225. // Normally this is done by running `conjurctl data-key generate`
  226. // but for test purposes we can generate it programmatically.
  227. b := make([]byte, 32)
  228. _, err := rand.Read(b)
  229. if err != nil {
  230. panic(fmt.Errorf("unable to generate random string: %w", err))
  231. }
  232. // Encode the bytes as a base64 string
  233. return base64.StdEncoding.EncodeToString(b)
  234. }