policy.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package conjur
  13. import (
  14. "bytes"
  15. "text/template"
  16. )
  17. const createVariablePolicyTemplate = `- !variable
  18. id: {{ .Key }}
  19. {{ if .Tags }}
  20. annotations:
  21. {{- range $key, $value := .Tags }}
  22. {{ $key }}: "{{ $value }}"
  23. {{- end }}
  24. {{ end }}
  25. - !permit
  26. role: !host system:serviceaccount:{{ .Namespace }}:test-app-sa
  27. privilege: [ read, execute ]
  28. resource: !variable {{ .Key }}
  29. - !permit
  30. role: !host system:serviceaccount:{{ .Namespace }}:test-app-hostid-sa
  31. privilege: [ read, execute ]
  32. resource: !variable {{ .Key }}`
  33. const deleteVariablePolicyTemplate = `- !delete
  34. record: !variable {{ .Key }}`
  35. const jwtHostPolicyTemplate = `- !host
  36. id: {{ .HostID }}
  37. annotations:
  38. authn-jwt/{{ .ServiceID }}/sub: "{{ .HostID }}"
  39. - !permit
  40. role: !host {{ .HostID }}
  41. privilege: [ read, authenticate ]
  42. resource: !webservice conjur/authn-jwt/{{ .ServiceID }}`
  43. func createVariablePolicy(key, namespace string, tags map[string]string) string {
  44. return renderTemplate(createVariablePolicyTemplate, map[string]interface{}{
  45. "Key": key,
  46. "Namespace": namespace,
  47. "Tags": tags,
  48. })
  49. }
  50. func deleteVariablePolicy(key string) string {
  51. return renderTemplate(deleteVariablePolicyTemplate, map[string]interface{}{
  52. "Key": key,
  53. })
  54. }
  55. func createJwtHostPolicy(hostID, serviceID string) string {
  56. return renderTemplate(jwtHostPolicyTemplate, map[string]interface{}{
  57. "HostID": hostID,
  58. "ServiceID": serviceID,
  59. })
  60. }
  61. func renderTemplate(templateText string, data map[string]interface{}) string {
  62. // Use golang templates to render the policy
  63. tmpl, err := template.New("policy").Parse(templateText)
  64. if err != nil {
  65. // The templates are hardcoded, so this should never happen
  66. panic(err)
  67. }
  68. output := new(bytes.Buffer)
  69. err = tmpl.Execute(output, data)
  70. if err != nil {
  71. // The templates are hardcoded, so this should never happen
  72. panic(err)
  73. }
  74. return output.String()
  75. }