policy.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 conjur
  14. import (
  15. "bytes"
  16. "text/template"
  17. )
  18. const createVariablePolicyTemplate = `- !variable
  19. id: {{ .Key }}
  20. {{ if .Tags }}
  21. annotations:
  22. {{- range $key, $value := .Tags }}
  23. {{ $key }}: "{{ $value }}"
  24. {{- end }}
  25. {{ end }}
  26. - !permit
  27. role: !host system:serviceaccount:{{ .Namespace }}:test-app-sa
  28. privilege: [ read, execute ]
  29. resource: !variable {{ .Key }}
  30. - !permit
  31. role: !host system:serviceaccount:{{ .Namespace }}:test-app-hostid-sa
  32. privilege: [ read, execute ]
  33. resource: !variable {{ .Key }}`
  34. const deleteVariablePolicyTemplate = `- !delete
  35. record: !variable {{ .Key }}`
  36. const jwtHostPolicyTemplate = `- !host
  37. id: {{ .HostID }}
  38. annotations:
  39. authn-jwt/{{ .ServiceID }}/sub: "{{ .HostID }}"
  40. - !permit
  41. role: !host {{ .HostID }}
  42. privilege: [ read, authenticate ]
  43. resource: !webservice conjur/authn-jwt/{{ .ServiceID }}`
  44. func createVariablePolicy(key, namespace string, tags map[string]string) string {
  45. return renderTemplate(createVariablePolicyTemplate, map[string]interface{}{
  46. "Key": key,
  47. "Namespace": namespace,
  48. "Tags": tags,
  49. })
  50. }
  51. func deleteVariablePolicy(key string) string {
  52. return renderTemplate(deleteVariablePolicyTemplate, map[string]interface{}{
  53. "Key": key,
  54. })
  55. }
  56. func createJwtHostPolicy(hostID, serviceID string) string {
  57. return renderTemplate(jwtHostPolicyTemplate, map[string]interface{}{
  58. "HostID": hostID,
  59. "ServiceID": serviceID,
  60. })
  61. }
  62. func renderTemplate(templateText string, data map[string]interface{}) string {
  63. // Use golang templates to render the policy
  64. tmpl, err := template.New("policy").Parse(templateText)
  65. if err != nil {
  66. // The templates are hardcoded, so this should never happen
  67. panic(err)
  68. }
  69. output := new(bytes.Buffer)
  70. err = tmpl.Execute(output, data)
  71. if err != nil {
  72. // The templates are hardcoded, so this should never happen
  73. panic(err)
  74. }
  75. return output.String()
  76. }