|
| 1 | +package interpolation |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "regexp" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/grafana/synthetic-monitoring-agent/internal/model" |
| 10 | + "github.com/rs/zerolog" |
| 11 | +) |
| 12 | + |
| 13 | +// VariableRegex matches ${variable_name} patterns |
| 14 | +var VariableRegex = regexp.MustCompile(`\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}`) |
| 15 | + |
| 16 | +// SecretRegex matches ${secrets.secret_name} patterns |
| 17 | +var SecretRegex = regexp.MustCompile(`\$\{secrets\.([^}]*)\}`) |
| 18 | + |
| 19 | +// VariableProvider defines the interface for resolving variables |
| 20 | +type VariableProvider interface { |
| 21 | + GetVariable(name string) (string, error) |
| 22 | +} |
| 23 | + |
| 24 | +// SecretProvider defines the interface for resolving secrets |
| 25 | +type SecretProvider interface { |
| 26 | + GetSecretValue(ctx context.Context, tenantID model.GlobalID, secretKey string) (string, error) |
| 27 | +} |
| 28 | + |
| 29 | +// Resolver handles string interpolation for both variables and secrets |
| 30 | +type Resolver struct { |
| 31 | + variableProvider VariableProvider |
| 32 | + secretProvider SecretProvider |
| 33 | + tenantID model.GlobalID |
| 34 | + logger zerolog.Logger |
| 35 | + secretEnabled bool |
| 36 | +} |
| 37 | + |
| 38 | +// NewResolver creates a new interpolation resolver |
| 39 | +func NewResolver(variableProvider VariableProvider, secretProvider SecretProvider, tenantID model.GlobalID, logger zerolog.Logger, secretEnabled bool) *Resolver { |
| 40 | + return &Resolver{ |
| 41 | + variableProvider: variableProvider, |
| 42 | + secretProvider: secretProvider, |
| 43 | + tenantID: tenantID, |
| 44 | + logger: logger, |
| 45 | + secretEnabled: secretEnabled, |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// Resolve performs string interpolation, replacing both variables and secrets |
| 50 | +func (r *Resolver) Resolve(ctx context.Context, value string) (string, error) { |
| 51 | + if value == "" { |
| 52 | + return "", nil |
| 53 | + } |
| 54 | + |
| 55 | + // First resolve secrets if enabled |
| 56 | + if r.secretEnabled { |
| 57 | + resolvedValue, err := r.resolveSecrets(ctx, value) |
| 58 | + if err != nil { |
| 59 | + return "", err |
| 60 | + } |
| 61 | + value = resolvedValue |
| 62 | + } |
| 63 | + |
| 64 | + // Then resolve variables |
| 65 | + if r.variableProvider != nil { |
| 66 | + resolvedValue, err := r.resolveVariables(value) |
| 67 | + if err != nil { |
| 68 | + return "", err |
| 69 | + } |
| 70 | + value = resolvedValue |
| 71 | + } |
| 72 | + |
| 73 | + return value, nil |
| 74 | +} |
| 75 | + |
| 76 | +// resolveSecrets resolves ${secrets.secret_name} patterns |
| 77 | +func (r *Resolver) resolveSecrets(ctx context.Context, value string) (string, error) { |
| 78 | + matches := SecretRegex.FindAllStringSubmatch(value, -1) |
| 79 | + if len(matches) == 0 { |
| 80 | + return value, nil |
| 81 | + } |
| 82 | + |
| 83 | + result := value |
| 84 | + for _, match := range matches { |
| 85 | + if len(match) < 2 { |
| 86 | + continue |
| 87 | + } |
| 88 | + |
| 89 | + secretName := match[1] |
| 90 | + placeholder := match[0] // ${secrets.secret_name} |
| 91 | + |
| 92 | + // Validate secret name follows Kubernetes DNS subdomain convention |
| 93 | + if !isValidSecretName(secretName) { |
| 94 | + return "", fmt.Errorf("invalid secret name '%s': must follow Kubernetes DNS subdomain naming convention", secretName) |
| 95 | + } |
| 96 | + |
| 97 | + r.logger.Debug().Str("secretName", secretName).Int64("tenantId", int64(r.tenantID)).Msg("resolving secret from GSM") |
| 98 | + |
| 99 | + secretValue, err := r.secretProvider.GetSecretValue(ctx, r.tenantID, secretName) |
| 100 | + if err != nil { |
| 101 | + return "", fmt.Errorf("failed to get secret '%s' from GSM: %w", secretName, err) |
| 102 | + } |
| 103 | + |
| 104 | + // Replace the placeholder with the actual secret value |
| 105 | + result = strings.ReplaceAll(result, placeholder, secretValue) |
| 106 | + } |
| 107 | + |
| 108 | + return result, nil |
| 109 | +} |
| 110 | + |
| 111 | +// resolveVariables resolves ${variable_name} patterns |
| 112 | +func (r *Resolver) resolveVariables(value string) (string, error) { |
| 113 | + // If no variable provider is set, return the value as-is |
| 114 | + if r.variableProvider == nil { |
| 115 | + return value, nil |
| 116 | + } |
| 117 | + |
| 118 | + matches := VariableRegex.FindAllStringSubmatch(value, -1) |
| 119 | + if len(matches) == 0 { |
| 120 | + return value, nil |
| 121 | + } |
| 122 | + |
| 123 | + result := value |
| 124 | + for _, match := range matches { |
| 125 | + if len(match) < 2 { |
| 126 | + continue |
| 127 | + } |
| 128 | + |
| 129 | + varName := match[1] |
| 130 | + placeholder := match[0] // ${variable_name} |
| 131 | + |
| 132 | + varValue, err := r.variableProvider.GetVariable(varName) |
| 133 | + if err != nil { |
| 134 | + return "", fmt.Errorf("failed to get variable '%s': %w", varName, err) |
| 135 | + } |
| 136 | + |
| 137 | + // Replace the placeholder with the actual variable value |
| 138 | + result = strings.ReplaceAll(result, placeholder, varValue) |
| 139 | + } |
| 140 | + |
| 141 | + return result, nil |
| 142 | +} |
| 143 | + |
| 144 | +// isValidSecretName validates that a secret name follows Kubernetes DNS subdomain naming convention. |
| 145 | +// See: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names |
| 146 | +func isValidSecretName(name string) bool { |
| 147 | + if len(name) == 0 || len(name) > 253 { |
| 148 | + return false |
| 149 | + } |
| 150 | + |
| 151 | + // Must consist of lowercase alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character |
| 152 | + if !regexp.MustCompile(`^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$`).MatchString(name) { |
| 153 | + return false |
| 154 | + } |
| 155 | + |
| 156 | + return true |
| 157 | +} |
| 158 | + |
| 159 | +// ToJavaScript converts a string with variable interpolation to JavaScript code |
| 160 | +// This is used by multihttp to generate JavaScript that references variables |
| 161 | +func ToJavaScript(value string) string { |
| 162 | + if len(value) == 0 { |
| 163 | + return `''` |
| 164 | + } |
| 165 | + |
| 166 | + var s strings.Builder |
| 167 | + buf := []byte(value) |
| 168 | + locs := VariableRegex.FindAllSubmatchIndex(buf, -1) |
| 169 | + |
| 170 | + p := 0 |
| 171 | + for _, loc := range locs { |
| 172 | + if len(loc) < 4 { // put the bounds checker at ease |
| 173 | + panic("unexpected result while building JavaScript") |
| 174 | + } |
| 175 | + |
| 176 | + if s.Len() > 0 { |
| 177 | + s.WriteRune('+') |
| 178 | + } |
| 179 | + |
| 180 | + if pre := buf[p:loc[0]]; len(pre) > 0 { |
| 181 | + s.WriteRune('\'') |
| 182 | + escapeJavaScript(&s, pre) |
| 183 | + s.WriteRune('\'') |
| 184 | + s.WriteRune('+') |
| 185 | + } |
| 186 | + |
| 187 | + s.WriteString(`vars['`) |
| 188 | + // Because of the capture in the regular expression, the result |
| 189 | + // has two indices that represent the matched substring, and |
| 190 | + // two more indices that represent the capture group. |
| 191 | + s.Write(buf[loc[2]:loc[3]]) |
| 192 | + s.WriteString(`']`) |
| 193 | + |
| 194 | + p = loc[1] |
| 195 | + } |
| 196 | + |
| 197 | + if len(buf[p:]) > 0 { |
| 198 | + if s.Len() > 0 { |
| 199 | + s.WriteRune('+') |
| 200 | + } |
| 201 | + |
| 202 | + s.WriteRune('\'') |
| 203 | + escapeJavaScript(&s, buf[p:]) |
| 204 | + s.WriteRune('\'') |
| 205 | + } |
| 206 | + |
| 207 | + return s.String() |
| 208 | +} |
| 209 | + |
| 210 | +// escapeJavaScript escapes a byte slice for use in JavaScript strings |
| 211 | +func escapeJavaScript(s *strings.Builder, buf []byte) { |
| 212 | + for _, b := range buf { |
| 213 | + switch b { |
| 214 | + case '\'': |
| 215 | + s.WriteString(`\'`) |
| 216 | + case '"': |
| 217 | + s.WriteString(`\"`) |
| 218 | + case '\\': |
| 219 | + s.WriteString(`\\`) |
| 220 | + case '\n': |
| 221 | + s.WriteString(`\n`) |
| 222 | + case '\r': |
| 223 | + s.WriteString(`\r`) |
| 224 | + case '\t': |
| 225 | + s.WriteString(`\t`) |
| 226 | + default: |
| 227 | + if b < 32 || b > 126 { |
| 228 | + // Escape non-printable characters |
| 229 | + fmt.Fprintf(s, `\x%02x`, b) |
| 230 | + } else { |
| 231 | + s.WriteByte(b) |
| 232 | + } |
| 233 | + } |
| 234 | + } |
| 235 | +} |
0 commit comments