|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "log/slog" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/markussiebert/cdk-sops-secrets/internal/client" |
| 12 | + "github.com/markussiebert/cdk-sops-secrets/internal/event" |
| 13 | +) |
| 14 | + |
| 15 | +const defaultExpirationSuffix = "_expiration" |
| 16 | +const defaultDaysBeforeExpiration = 14 |
| 17 | + |
| 18 | +// expirationMessage is the payload published to the SNS topic. |
| 19 | +type expirationMessage struct { |
| 20 | + SecretArn string `json:"secretArn"` |
| 21 | + KeyName string `json:"keyName"` |
| 22 | + ExpirationDate string `json:"expirationDate"` |
| 23 | + NotificationDate string `json:"notificationDate"` |
| 24 | + DaysBeforeExpiration int `json:"daysBeforeExpiration"` |
| 25 | +} |
| 26 | + |
| 27 | +// sanitizeScheduleName converts a key name into a valid EventBridge Scheduler |
| 28 | +// schedule name: only [a-zA-Z0-9_-], max 64 characters. |
| 29 | +func sanitizeScheduleName(name string) string { |
| 30 | + re := regexp.MustCompile(`[^a-zA-Z0-9_-]`) |
| 31 | + sanitized := re.ReplaceAllString(name, "-") |
| 32 | + if len(sanitized) > 64 { |
| 33 | + sanitized = sanitized[:64] |
| 34 | + } |
| 35 | + return sanitized |
| 36 | +} |
| 37 | + |
| 38 | +// parseExpirationDate attempts to parse a date string in ISO 8601 / RFC 3339 |
| 39 | +// formats. Accepted formats: "2006-01-02", "2006-01-02T15:04:05Z07:00". |
| 40 | +func parseExpirationDate(value string) (time.Time, error) { |
| 41 | + value = strings.TrimSpace(value) |
| 42 | + formats := []string{ |
| 43 | + "2006-01-02", |
| 44 | + time.RFC3339, |
| 45 | + } |
| 46 | + for _, format := range formats { |
| 47 | + if t, err := time.Parse(format, value); err == nil { |
| 48 | + return t, nil |
| 49 | + } |
| 50 | + } |
| 51 | + return time.Time{}, fmt.Errorf("unsupported date format: %q", value) |
| 52 | +} |
| 53 | + |
| 54 | +// scanExpirationKeys scans the flattened secret map for keys that end with the |
| 55 | +// given suffix and returns a map of base key → expiration time. |
| 56 | +func scanExpirationKeys(secretMap map[string]string, suffix string) map[string]time.Time { |
| 57 | + result := make(map[string]time.Time) |
| 58 | + for key, value := range secretMap { |
| 59 | + if !strings.HasSuffix(key, suffix) { |
| 60 | + continue |
| 61 | + } |
| 62 | + baseKey := strings.TrimSuffix(key, suffix) |
| 63 | + t, err := parseExpirationDate(value) |
| 64 | + if err != nil { |
| 65 | + slog.Warn("Skipping unparseable expiration date", |
| 66 | + "key", key, "value", value, "error", err) |
| 67 | + continue |
| 68 | + } |
| 69 | + result[baseKey] = t |
| 70 | + } |
| 71 | + return result |
| 72 | +} |
| 73 | + |
| 74 | +// handleExpirationUpsert creates or updates EventBridge Scheduler schedules for |
| 75 | +// all expiration keys found in the decrypted secret. |
| 76 | +func handleExpirationUpsert( |
| 77 | + props *event.SopsSyncResourcePropertys, |
| 78 | + clients client.AwsClient, |
| 79 | + secretMap map[string]string, |
| 80 | + secretArn string, |
| 81 | +) error { |
| 82 | + logger := slog.With("Package", "main", "Function", "handleExpirationUpsert") |
| 83 | + exp := props.Expiration |
| 84 | + |
| 85 | + suffix := defaultExpirationSuffix |
| 86 | + if exp.ExpirationSuffix != nil && *exp.ExpirationSuffix != "" { |
| 87 | + suffix = *exp.ExpirationSuffix |
| 88 | + } |
| 89 | + |
| 90 | + days := defaultDaysBeforeExpiration |
| 91 | + if exp.DaysBeforeExpiration != nil { |
| 92 | + days = *exp.DaysBeforeExpiration |
| 93 | + } |
| 94 | + |
| 95 | + expirations := scanExpirationKeys(secretMap, suffix) |
| 96 | + if len(expirations) == 0 { |
| 97 | + logger.Info("No expiration keys found in secret", "Suffix", suffix) |
| 98 | + return nil |
| 99 | + } |
| 100 | + |
| 101 | + for baseKey, expiresAt := range expirations { |
| 102 | + notifyAt := expiresAt.UTC().AddDate(0, 0, -days) |
| 103 | + // Skip schedules whose notification time is already in the past. |
| 104 | + if notifyAt.Before(time.Now().UTC()) { |
| 105 | + logger.Warn("Notification time is in the past, skipping schedule", |
| 106 | + "baseKey", baseKey, |
| 107 | + "expiresAt", expiresAt.Format("2006-01-02"), |
| 108 | + "notifyAt", notifyAt.Format("2006-01-02"), |
| 109 | + ) |
| 110 | + continue |
| 111 | + } |
| 112 | + |
| 113 | + scheduleName := sanitizeScheduleName(baseKey) |
| 114 | + // EventBridge Scheduler at() expression format: at(YYYY-MM-DDTHH:mm:ss) |
| 115 | + scheduleExpr := fmt.Sprintf("at(%s)", notifyAt.Format("2006-01-02T15:04:05")) |
| 116 | + |
| 117 | + msg := expirationMessage{ |
| 118 | + SecretArn: secretArn, |
| 119 | + KeyName: baseKey, |
| 120 | + ExpirationDate: expiresAt.UTC().Format("2006-01-02"), |
| 121 | + NotificationDate: notifyAt.UTC().Format("2006-01-02"), |
| 122 | + DaysBeforeExpiration: days, |
| 123 | + } |
| 124 | + msgJSON, err := json.Marshal(msg) |
| 125 | + if err != nil { |
| 126 | + return fmt.Errorf("failed to marshal expiration message for key %s: %v", baseKey, err) |
| 127 | + } |
| 128 | + |
| 129 | + logger.Info("Upserting expiration schedule", |
| 130 | + "scheduleName", scheduleName, |
| 131 | + "group", exp.ScheduleGroupName, |
| 132 | + "expression", scheduleExpr, |
| 133 | + ) |
| 134 | + |
| 135 | + if err := clients.SchedulerCreateOrUpdateSchedule( |
| 136 | + scheduleName, |
| 137 | + exp.ScheduleGroupName, |
| 138 | + scheduleExpr, |
| 139 | + exp.TopicArn, |
| 140 | + exp.SchedulerRoleArn, |
| 141 | + string(msgJSON), |
| 142 | + ); err != nil { |
| 143 | + return fmt.Errorf("failed to upsert schedule for key %s: %v", baseKey, err) |
| 144 | + } |
| 145 | + } |
| 146 | + return nil |
| 147 | +} |
| 148 | + |
| 149 | +// handleExpirationDelete removes all expiration schedules for a secret by |
| 150 | +// listing and deleting every schedule in the group. |
| 151 | +func handleExpirationDelete( |
| 152 | + props *event.SopsSyncResourcePropertys, |
| 153 | + clients client.AwsClient, |
| 154 | +) error { |
| 155 | + logger := slog.With("Package", "main", "Function", "handleExpirationDelete") |
| 156 | + exp := props.Expiration |
| 157 | + |
| 158 | + names, err := clients.SchedulerListSchedules(exp.ScheduleGroupName) |
| 159 | + if err != nil { |
| 160 | + // If the group doesn't exist yet (e.g. stack was never fully deployed) |
| 161 | + // treat it as a no-op rather than a hard failure. |
| 162 | + logger.Warn("Could not list schedules, assuming group does not exist", |
| 163 | + "Group", exp.ScheduleGroupName, "Error", err) |
| 164 | + return nil |
| 165 | + } |
| 166 | + |
| 167 | + for _, name := range names { |
| 168 | + logger.Info("Deleting expiration schedule", "Name", name, "Group", exp.ScheduleGroupName) |
| 169 | + if err := clients.SchedulerDeleteSchedule(name, exp.ScheduleGroupName); err != nil { |
| 170 | + // Log and continue so we attempt to delete all schedules even if one fails. |
| 171 | + logger.Error("Failed to delete schedule", "Name", name, "Error", err) |
| 172 | + } |
| 173 | + } |
| 174 | + return nil |
| 175 | +} |
0 commit comments