ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

YAML Secret Reference Resolution

YAML

Goal -- WPM

Ready
Exercise Algorithm Area
1package main
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7 "gopkg.in/yaml.v3"
8)
9
10// secretPattern is a regex to find placeholders like ${SECRET_NAME}.
11var secretPattern = regexp.MustCompile(`\$\{([^}]+)\}`)
12
13// resolveSecrets processes a YAML structure and replaces secret placeholders.
14// It takes the data to process and a map of available secrets.
15func resolveSecrets(data interface{}, secrets map[string]string) (interface{}, error) {
16 // Use reflection to traverse the data structure.
17 val := reflect.ValueOf(data)
18
19 // Handle nil values.
20 if !val.IsValid() {
21 return nil, nil
22 }
23
24 // If the value is a string, attempt to resolve secrets.
25 if val.Kind() == reflect.String {
26 str := val.String()
27 resolvedStr := secretPattern.ReplaceAllStringFunc(str, func(match string) string {
28 // Extract the secret name from the placeholder (e.g., 'SECRET_NAME' from '${SECRET_NAME}').
29 secretName := strings.TrimPrefix(strings.TrimSuffix(match, "}"), "$")
30 secretName = strings.TrimPrefix(secretName, "{")
31
32 secretValue, ok := secrets[secretName]
33 if !ok {
34 // Return the original placeholder if the secret is not found, and potentially log a warning.
35 // For this example, we'll return an error to indicate resolution failure.
36 // In a real system, you might want to allow unresolvable secrets or have a default.
37 // To return an error, we need to signal it up the call stack.
38 // For simplicity here, we'll return a marker and handle it later.
39 // A better approach would be to return (interface{}, error) from ReplaceAllStringFunc.
40 // Let's adjust the approach to return an error from the main function.
41 return "__UNRESOLVED_SECRET__" // Placeholder for error signaling
42 }
43 return secretValue
44 })
45
46 // Check if any secret was unresolved.
47 if strings.Contains(resolvedStr, "__UNRESOLVED_SECRET__") {
48 return nil, fmt.Errorf("unresolved secret placeholder found in string: %s", str)
49 }
50 return resolvedStr, nil
51 }
52
53 // If the value is a map, recursively process its values.
54 if val.Kind() == reflect.Map {
55 // Create a new map to store the resolved data.
56 resolvedMap := make(map[string]interface{})
57 for _, key := range val.MapKeys() {
58 mapKey := key.String()
59 originalValue := val.MapIndex(key).Interface()
60 resolvedValue, err := resolveSecrets(originalValue, secrets)
61 if err != nil {
62 return nil, fmt.Errorf("error resolving secret in map key '%s': %w", mapKey, err)
63 }
64 resolvedMap[mapKey] = resolvedValue
65 }
66 return resolvedMap, nil
67 }
68
69 // If the value is a slice, recursively process its elements.
70 if val.Kind() == reflect.Slice {
71 // Create a new slice to store the resolved data.
72 resolvedSlice := make([]interface{}, val.Len())
73 for i := 0; i < val.Len(); i++ {
74 originalElement := val.Index(i).Interface()
75 resolvedElement, err := resolveSecrets(originalElement, secrets)
76 if err != nil {
77 return nil, fmt.Errorf("error resolving secret in slice element at index %d: %w", i, err)
78 }
79 resolvedSlice[i] = resolvedElement
80 }
81 return resolvedSlice, nil
82 }
83
84 // For other types (integers, booleans, etc.), return them as is.
85 return data, nil
86}
87
88func main() {
89 // Example secrets map.
90 secrets := map[string]string{
91 "DB_PASSWORD": "s3cr3tP@ssw0rd",
92 "API_KEY": "aBcDeFgHiJkLmNoPqRsT",
93 "SERVICE_URL": "https://api.example.com/v1",
94 }
95
96 // Example YAML configuration with secret placeholders.
97 yamlConfig := `
98service:
99name: my-app
100database:
101host: db.internal
102port: 5432
103password: "${DB_PASSWORD}"
104api:
105url: "${SERVICE_URL}"
106key: "${API_KEY}"
107logging:
108level: INFO
109file: /var/log/app.log
110`
111 var parsedConfig interface{}.
112 err := yaml.Unmarshal([]byte(yamlConfig), &parsedConfig)
113 if err != nil {
114 fmt.Printf("Error unmarshalling YAML: %v\n", err)
115 return
116 }
117
118 // Resolve secrets in the parsed configuration.
119 resolvedConfig, err := resolveSecrets(parsedConfig, secrets)
120 if err != nil {
121 fmt.Printf("Error resolving secrets: %v\n", err)
122 return
123 }
124
125 // Marshal the resolved configuration back to YAML for display.
126 outputYAML, err := yaml.Marshal(resolvedConfig)
127 if err != nil {
128 fmt.Printf("Error marshalling resolved YAML: %v\n", err)
129 return
130 }
131
132 fmt.Println("--- Resolved Configuration ---")
133 fmt.Println(string(outputYAML))
134
135 // Example with an unresolved secret.
136 yamlConfigUnresolved := `
137service:
138name: another-app
139api_token: "${UNRESOLVED_TOKEN}"
140`
141 err = yaml.Unmarshal([]byte(yamlConfigUnresolved), &parsedConfig)
142 if err != nil {
143 fmt.Printf("Error unmarshalling YAML (unresolved): %v\n", err)
144 return
145 }
146
147 _, err = resolveSecrets(parsedConfig, secrets)
148 if err != nil {
149 fmt.Printf("\n--- Expected Error: Unresolved Secret ---")
150 fmt.Printf("\nError resolving secrets: %v\n", err)
151 } else {
152 fmt.Println("\n--- Unexpected: Secret was resolved ---")
153 }
154
155 // Example with a secret in a list.
156 yamlConfigList := `
157servers:
158- url: "${SERVICE_URL}"
159auth_token: "${API_KEY}"
160- url: "http://backup.example.com"
161`
162 err = yaml.Unmarshal([]byte(yamlConfigList), &parsedConfig)
163 if err != nil {
164 fmt.Printf("Error unmarshalling YAML (list): %v\n", err)
165 return
166 }
167
168 resolvedConfigList, err := resolveSecrets(parsedConfig, secrets)
169 if err != nil {
170 fmt.Printf("Error resolving secrets in list: %v\n", err)
171 return
172 }
173
174 outputYAMLList, err := yaml.Marshal(resolvedConfigList)
175 if err != nil {
176 fmt.Printf("Error marshalling resolved YAML (list): %v\n", err)
177 return
178 }
179
180 fmt.Println("\n--- Resolved Configuration with List ---")
181 fmt.Println(string(outputYAMLList))
182}
Algorithm description viewbox

YAML Secret Reference Resolution

Algorithm description:

This function processes a YAML configuration, replacing placeholder strings like `${SECRET_NAME}` with actual secret values provided in a map. It recursively traverses nested YAML structures (maps, lists, strings) to find and substitute these placeholders. This is crucial for securely managing sensitive information like passwords, API keys, and connection strings in configuration files without exposing them directly.

Algorithm explanation:

The `resolveSecrets` function uses reflection to traverse the input data structure. If it encounters a string, it uses a regular expression (`secretPattern`) to find all occurrences of `${SECRET_NAME}`. For each match, it extracts the `SECRET_NAME`, looks it up in the provided `secrets` map, and replaces the placeholder with the corresponding value. If a secret is not found in the map, it returns an error. For maps and slices, it recursively calls `resolveSecrets` on their elements/values. Non-string primitive types are returned as is. The time complexity is roughly O(N*P), where N is the total number of string elements and P is the average number of placeholders per string, due to regex matching and recursion. Space complexity is O(N) for storing the resolved structure. Edge cases include missing secrets, empty secrets map, and placeholders within other placeholders (not handled by this simple regex).

Pseudocode:

function resolveSecrets(data, secretsMap):
  if data is nil:
    return nil

  if typeOf(data) is string:
    originalString = data
    resolvedString = originalString
    while resolvedString contains placeholder pattern `${SECRET_NAME}`:
      match = find first placeholder in resolvedString
      secretName = extract secret name from match
      if secretName is in secretsMap:
        secretValue = secretsMap[secretName]
        replace placeholder in resolvedString with secretValue
      else:
        return error "unresolved secret: " + secretName
    return resolvedString

  if typeOf(data) is map:
    resolvedMap = new map
    for each key, value in data:
      resolvedMap[key] = resolveSecrets(value, secretsMap)
      if error occurred during recursive call:
        return error
    return resolvedMap

  if typeOf(data) is list:
    resolvedList = new list
    for each element in data:
      resolvedElement = resolveSecrets(element, secretsMap)
      if error occurred during recursive call:
        return error
      add resolvedElement to resolvedList
    return resolvedList

  // For other types, return as is
  return data