| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| Akron | daca314 | 2026-05-21 13:00:45 +0200 | [diff] [blame^] | 5 | "net/url" |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 6 | "os" |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 7 | "path/filepath" |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 8 | "strconv" |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 9 | "strings" |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 10 | |
| Akron | 2ef703c | 2025-07-03 15:57:42 +0200 | [diff] [blame] | 11 | "github.com/KorAP/Koral-Mapper/ast" |
| 12 | "github.com/KorAP/Koral-Mapper/parser" |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 13 | "github.com/rs/zerolog/log" |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 14 | "gopkg.in/yaml.v3" |
| 15 | ) |
| 16 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 17 | const ( |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 18 | defaultServer = "https://korap.ids-mannheim.de/" |
| 19 | defaultSDK = "https://korap.ids-mannheim.de/js/korap-plugin-latest.js" |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 20 | defaultStylesheet = "https://korap.ids-mannheim.de/css/kalamar-plugin-latest.css" |
| Akron | 2ef703c | 2025-07-03 15:57:42 +0200 | [diff] [blame] | 21 | defaultServiceURL = "https://korap.ids-mannheim.de/plugin/koralmapper" |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 22 | defaultCookieName = "km-config" |
| Akron | 14c13a5 | 2025-06-06 15:36:23 +0200 | [diff] [blame] | 23 | defaultPort = 5725 |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 24 | defaultLogLevel = "warn" |
| 25 | defaultRateLimit = 100 |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 26 | ) |
| 27 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 28 | // MappingRule represents a single mapping rule in the configuration |
| 29 | type MappingRule string |
| 30 | |
| 31 | // MappingList represents a list of mapping rules with metadata |
| 32 | type MappingList struct { |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 33 | ID string `yaml:"id"` |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 34 | Type string `yaml:"type,omitempty"` // "annotation" (default) or "corpus" |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 35 | Description string `yaml:"desc,omitempty"` |
| 36 | FoundryA string `yaml:"foundryA,omitempty"` |
| 37 | LayerA string `yaml:"layerA,omitempty"` |
| 38 | FoundryB string `yaml:"foundryB,omitempty"` |
| 39 | LayerB string `yaml:"layerB,omitempty"` |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 40 | FieldA string `yaml:"fieldA,omitempty"` |
| 41 | FieldB string `yaml:"fieldB,omitempty"` |
| Akron | f7bba07 | 2026-05-21 12:36:19 +0200 | [diff] [blame] | 42 | Rewrites *bool `yaml:"rewrites,omitempty"` |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 43 | Mappings []MappingRule `yaml:"mappings"` |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 44 | } |
| 45 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 46 | // IsCorpus returns true if the mapping list type is "corpus". |
| 47 | func (list *MappingList) IsCorpus() bool { |
| 48 | return list.Type == "corpus" |
| 49 | } |
| 50 | |
| Akron | f7bba07 | 2026-05-21 12:36:19 +0200 | [diff] [blame] | 51 | // EffectiveRewrites returns the resolved rewrites setting for this list. |
| 52 | // If the list has an explicit per-list override, it is used; otherwise the |
| 53 | // global default is returned. |
| 54 | func (list *MappingList) EffectiveRewrites(globalDefault bool) bool { |
| 55 | if list.Rewrites != nil { |
| 56 | return *list.Rewrites |
| 57 | } |
| 58 | return globalDefault |
| 59 | } |
| 60 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 61 | // ParseCorpusMappings parses all mapping rules as corpus rules. |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 62 | // Bare values (without key=) are always allowed and receive the default |
| 63 | // field name from the mapping list header (FieldA/FieldB) when set. |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 64 | func (list *MappingList) ParseCorpusMappings() ([]*parser.CorpusMappingResult, error) { |
| 65 | corpusParser := parser.NewCorpusParser() |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 66 | corpusParser.AllowBareValues = true |
| 67 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 68 | results := make([]*parser.CorpusMappingResult, len(list.Mappings)) |
| 69 | for i, rule := range list.Mappings { |
| 70 | if rule == "" { |
| 71 | return nil, fmt.Errorf("empty corpus mapping rule at index %d in list '%s'", i, list.ID) |
| 72 | } |
| 73 | result, err := corpusParser.ParseMapping(string(rule)) |
| 74 | if err != nil { |
| 75 | return nil, fmt.Errorf("failed to parse corpus mapping rule %d in list '%s': %w", i, list.ID, err) |
| 76 | } |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 77 | |
| 78 | if list.FieldA != "" { |
| 79 | applyDefaultCorpusKey(result.Upper, list.FieldA) |
| 80 | } |
| 81 | if list.FieldB != "" { |
| 82 | applyDefaultCorpusKey(result.Lower, list.FieldB) |
| 83 | } |
| 84 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 85 | results[i] = result |
| 86 | } |
| 87 | return results, nil |
| 88 | } |
| 89 | |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 90 | // applyDefaultCorpusKey recursively fills in empty keys on CorpusField nodes. |
| 91 | func applyDefaultCorpusKey(node parser.CorpusNode, defaultKey string) { |
| 92 | switch n := node.(type) { |
| 93 | case *parser.CorpusField: |
| 94 | if n.Key == "" { |
| 95 | n.Key = defaultKey |
| 96 | } |
| 97 | case *parser.CorpusGroup: |
| 98 | for _, op := range n.Operands { |
| 99 | applyDefaultCorpusKey(op, defaultKey) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 104 | // MappingConfig represents the root configuration containing multiple mapping lists |
| 105 | type MappingConfig struct { |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 106 | SDK string `yaml:"sdk,omitempty"` |
| 107 | Stylesheet string `yaml:"stylesheet,omitempty"` |
| 108 | Server string `yaml:"server,omitempty"` |
| 109 | ServiceURL string `yaml:"serviceURL,omitempty"` |
| 110 | CookieName string `yaml:"cookieName,omitempty"` |
| 111 | BasePath string `yaml:"basePath,omitempty"` // restricts config file loading to this directory tree |
| 112 | AllowOrigins string `yaml:"allowOrigins,omitempty"` // comma-separated list of allowed CORS origins |
| 113 | Port int `yaml:"port,omitempty"` |
| 114 | LogLevel string `yaml:"loglevel,omitempty"` |
| 115 | RateLimit int `yaml:"rateLimit,omitempty"` // max requests per minute per IP (0 = use default 100) |
| Akron | f7bba07 | 2026-05-21 12:36:19 +0200 | [diff] [blame] | 116 | Rewrites bool `yaml:"rewrites,omitempty"` // global default for koral:rewrite annotations |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 117 | Lists []MappingList `yaml:"lists,omitempty"` |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 118 | } |
| 119 | |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 120 | // AllowedBasePath restricts file loading to a specific directory tree. |
| 121 | // When set, all file paths must resolve to a location at or below this |
| 122 | // directory (or under the system temp directory). Defaults to the CWD at |
| 123 | // application startup; can be overridden via the "basePath" YAML config |
| 124 | // field or the KORAL_MAPPER_BASE_PATH environment variable. In Docker |
| 125 | // (WORKDIR /), the default "/" naturally allows all paths. |
| 126 | var AllowedBasePath string |
| 127 | |
| 128 | // isWithinDir checks whether absPath is at or below the given directory. |
| 129 | // Uses a trailing-separator comparison to avoid prefix false positives |
| 130 | // (e.g. /home/user must not match /home/username). |
| 131 | func isWithinDir(absPath, dir string) bool { |
| 132 | if dir == "/" { |
| 133 | return true |
| 134 | } |
| 135 | return absPath == dir || strings.HasPrefix(absPath, dir+string(filepath.Separator)) |
| 136 | } |
| 137 | |
| 138 | // sanitizeFilePath cleans a file path, resolves it to an absolute path, and |
| 139 | // (when AllowedBasePath is set) verifies it resides at or below the allowed |
| 140 | // base directory or the system temp directory. This prevents path |
| 141 | // traversal attacks by ensuring os.ReadFile never receives |
| 142 | // unsanitized user input and cannot access files outside the application's |
| 143 | // working tree. |
| 144 | func sanitizeFilePath(path string) (string, error) { |
| 145 | if path == "" { |
| 146 | return "", fmt.Errorf("empty file path") |
| 147 | } |
| 148 | |
| 149 | // Clean the path to remove redundant separators and resolve "." and ".." |
| 150 | cleaned := filepath.Clean(path) |
| 151 | |
| 152 | // Convert to absolute path so all traversal is resolved against the CWD |
| 153 | absPath, err := filepath.Abs(cleaned) |
| 154 | if err != nil { |
| 155 | return "", fmt.Errorf("failed to resolve absolute path for '%s': %w", path, err) |
| 156 | } |
| 157 | |
| 158 | // If a base path is configured, confine access to that tree or temp dir |
| 159 | if AllowedBasePath != "" { |
| 160 | base := filepath.Clean(AllowedBasePath) |
| 161 | tmpDir := filepath.Clean(os.TempDir()) |
| 162 | |
| 163 | if !isWithinDir(absPath, base) && !isWithinDir(absPath, tmpDir) { |
| 164 | return "", fmt.Errorf( |
| 165 | "path traversal detected: '%s' resolves to '%s' which is outside the allowed base '%s'", |
| 166 | path, absPath, base) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | return absPath, nil |
| 171 | } |
| 172 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 173 | // LoadFromSources loads configuration from multiple sources and merges them: |
| 174 | // - A main configuration file (optional) containing global settings and lists |
| 175 | // - Individual mapping files (optional) containing single mapping lists each |
| 176 | // At least one source must be provided |
| 177 | func LoadFromSources(configFile string, mappingFiles []string) (*MappingConfig, error) { |
| 178 | var allLists []MappingList |
| 179 | var globalConfig MappingConfig |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 180 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 181 | // Track seen IDs across all sources to detect duplicates |
| 182 | seenIDs := make(map[string]bool) |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 183 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 184 | // Load main configuration file if provided |
| 185 | if configFile != "" { |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 186 | safePath, err := sanitizeFilePath(configFile) |
| 187 | if err != nil { |
| 188 | return nil, err |
| 189 | } |
| 190 | data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 191 | if err != nil { |
| 192 | return nil, fmt.Errorf("failed to read config file '%s': %w", configFile, err) |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 193 | } |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 194 | |
| 195 | if len(data) == 0 { |
| 196 | return nil, fmt.Errorf("EOF: config file '%s' is empty", configFile) |
| 197 | } |
| 198 | |
| 199 | // Try to unmarshal as new format first (object with optional sdk/server and lists) |
| Akron | 813780f | 2025-06-05 15:44:28 +0200 | [diff] [blame] | 200 | if err := yaml.Unmarshal(data, &globalConfig); err == nil { |
| 201 | // Successfully parsed as new format - accept it regardless of whether it has lists |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 202 | for _, list := range globalConfig.Lists { |
| 203 | if seenIDs[list.ID] { |
| 204 | return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID) |
| 205 | } |
| 206 | seenIDs[list.ID] = true |
| 207 | } |
| 208 | allLists = append(allLists, globalConfig.Lists...) |
| 209 | } else { |
| 210 | // Fall back to old format (direct list) |
| 211 | var lists []MappingList |
| 212 | if err := yaml.Unmarshal(data, &lists); err != nil { |
| 213 | return nil, fmt.Errorf("failed to parse YAML config file '%s': %w", configFile, err) |
| 214 | } |
| 215 | |
| 216 | for _, list := range lists { |
| 217 | if seenIDs[list.ID] { |
| 218 | return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID) |
| 219 | } |
| 220 | seenIDs[list.ID] = true |
| 221 | } |
| 222 | allLists = append(allLists, lists...) |
| 223 | // Clear the lists from globalConfig since we got them from the old format |
| 224 | globalConfig.Lists = nil |
| 225 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 226 | } |
| 227 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 228 | // Load individual mapping files |
| 229 | for _, file := range mappingFiles { |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 230 | safePath, err := sanitizeFilePath(file) |
| 231 | if err != nil { |
| 232 | return nil, err |
| 233 | } |
| 234 | data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 235 | if err != nil { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 236 | log.Error().Err(err).Str("file", file).Msg("Failed to read mapping file") |
| 237 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 238 | } |
| 239 | |
| 240 | if len(data) == 0 { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 241 | log.Error().Err(err).Str("file", file).Msg("EOF: mapping file is empty") |
| 242 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 243 | } |
| 244 | |
| 245 | var list MappingList |
| 246 | if err := yaml.Unmarshal(data, &list); err != nil { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 247 | log.Error().Err(err).Str("file", file).Msg("Failed to parse YAML mapping file") |
| 248 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 249 | } |
| 250 | |
| 251 | if seenIDs[list.ID] { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 252 | log.Error().Err(err).Str("file", file).Str("list-id", list.ID).Msg("Duplicate mapping list ID found") |
| 253 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 254 | } |
| 255 | seenIDs[list.ID] = true |
| 256 | allLists = append(allLists, list) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 257 | } |
| 258 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 259 | // Ensure we have at least some configuration |
| 260 | if len(allLists) == 0 { |
| 261 | return nil, fmt.Errorf("no mapping lists found: provide either a config file (-c) with lists or mapping files (-m)") |
| 262 | } |
| 263 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 264 | // Validate all mapping lists (skip duplicate ID check since we already did it) |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 265 | if err := validateMappingLists(allLists); err != nil { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 266 | return nil, err |
| 267 | } |
| 268 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 269 | // Create final configuration |
| 270 | result := &MappingConfig{ |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 271 | SDK: globalConfig.SDK, |
| 272 | Stylesheet: globalConfig.Stylesheet, |
| 273 | Server: globalConfig.Server, |
| 274 | ServiceURL: globalConfig.ServiceURL, |
| 275 | BasePath: globalConfig.BasePath, |
| 276 | AllowOrigins: globalConfig.AllowOrigins, |
| 277 | Port: globalConfig.Port, |
| 278 | LogLevel: globalConfig.LogLevel, |
| 279 | RateLimit: globalConfig.RateLimit, |
| Akron | f7bba07 | 2026-05-21 12:36:19 +0200 | [diff] [blame] | 280 | Rewrites: globalConfig.Rewrites, |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 281 | Lists: allLists, |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 282 | } |
| 283 | |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 284 | // Apply environment variable overrides (ENV > config file) |
| 285 | ApplyEnvOverrides(result) |
| 286 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 287 | // Apply defaults if not specified |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 288 | ApplyDefaults(result) |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 289 | |
| 290 | return result, nil |
| 291 | } |
| 292 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 293 | // ApplyDefaults sets default values for configuration fields if they are empty |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 294 | func ApplyDefaults(config *MappingConfig) { |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 295 | defaults := map[*string]string{ |
| 296 | &config.SDK: defaultSDK, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 297 | &config.Stylesheet: defaultStylesheet, |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 298 | &config.Server: defaultServer, |
| 299 | &config.ServiceURL: defaultServiceURL, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 300 | &config.CookieName: defaultCookieName, |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 301 | &config.LogLevel: defaultLogLevel, |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 302 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 303 | |
| 304 | for field, defaultValue := range defaults { |
| 305 | if *field == "" { |
| 306 | *field = defaultValue |
| 307 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 308 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 309 | |
| Akron | daca314 | 2026-05-21 13:00:45 +0200 | [diff] [blame^] | 310 | // AllowOrigins defaults to the Server value. This avoids duplicating |
| 311 | // the server URL string and keeps CORS in sync with the deployment. |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 312 | if config.AllowOrigins == "" { |
| Akron | daca314 | 2026-05-21 13:00:45 +0200 | [diff] [blame^] | 313 | config.AllowOrigins = config.Server |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 314 | } |
| Akron | daca314 | 2026-05-21 13:00:45 +0200 | [diff] [blame^] | 315 | config.AllowOrigins = normalizeOrigins(config.AllowOrigins) |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 316 | |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 317 | if config.Port == 0 { |
| 318 | config.Port = defaultPort |
| 319 | } |
| Akron | e6767de | 2026-05-20 10:06:24 +0200 | [diff] [blame] | 320 | if config.RateLimit == 0 { |
| 321 | config.RateLimit = defaultRateLimit |
| 322 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 323 | } |
| 324 | |
| Akron | daca314 | 2026-05-21 13:00:45 +0200 | [diff] [blame^] | 325 | // normalizeOrigins takes a comma-separated list of origin URLs and strips |
| 326 | // any path components, returning only scheme + host (+ port when present). |
| 327 | // The CORS middleware requires bare origins without paths; URLs like |
| 328 | // "https://example.com/instance/test" are pruned to "https://example.com". |
| 329 | func normalizeOrigins(raw string) string { |
| 330 | parts := strings.Split(raw, ",") |
| 331 | for i, part := range parts { |
| 332 | part = strings.TrimSpace(part) |
| 333 | if u, err := url.Parse(part); err == nil && u.Host != "" { |
| 334 | parts[i] = u.Scheme + "://" + u.Host |
| 335 | } else { |
| 336 | parts[i] = strings.TrimRight(part, "/") |
| 337 | } |
| 338 | } |
| 339 | return strings.Join(parts, ",") |
| 340 | } |
| 341 | |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 342 | // ApplyEnvOverrides overrides configuration fields from environment variables. |
| 343 | // All environment variables are uppercase and prefixed with KORAL_MAPPER_. |
| 344 | // Non-empty environment values override any previously loaded config values. |
| 345 | func ApplyEnvOverrides(config *MappingConfig) { |
| 346 | envMappings := map[string]*string{ |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame] | 347 | "KORAL_MAPPER_SERVER": &config.Server, |
| 348 | "KORAL_MAPPER_SDK": &config.SDK, |
| 349 | "KORAL_MAPPER_STYLESHEET": &config.Stylesheet, |
| 350 | "KORAL_MAPPER_SERVICE_URL": &config.ServiceURL, |
| 351 | "KORAL_MAPPER_COOKIE_NAME": &config.CookieName, |
| 352 | "KORAL_MAPPER_LOG_LEVEL": &config.LogLevel, |
| 353 | "KORAL_MAPPER_BASE_PATH": &config.BasePath, |
| 354 | "KORAL_MAPPER_ALLOW_ORIGINS": &config.AllowOrigins, |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 355 | } |
| 356 | |
| 357 | for envKey, field := range envMappings { |
| 358 | if val := os.Getenv(envKey); val != "" { |
| 359 | *field = val |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | if val := os.Getenv("KORAL_MAPPER_PORT"); val != "" { |
| 364 | if port, err := strconv.Atoi(val); err == nil { |
| 365 | config.Port = port |
| 366 | } |
| 367 | } |
| Akron | e6767de | 2026-05-20 10:06:24 +0200 | [diff] [blame] | 368 | |
| 369 | if val := os.Getenv("KORAL_MAPPER_RATE_LIMIT"); val != "" { |
| 370 | if rl, err := strconv.Atoi(val); err == nil { |
| 371 | config.RateLimit = rl |
| 372 | } |
| 373 | } |
| Akron | f7bba07 | 2026-05-21 12:36:19 +0200 | [diff] [blame] | 374 | |
| 375 | if val := os.Getenv("KORAL_MAPPER_REWRITES"); val != "" { |
| 376 | config.Rewrites = val == "true" |
| 377 | } |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 378 | } |
| 379 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 380 | // validateMappingLists validates a slice of mapping lists (without duplicate ID checking) |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 381 | func validateMappingLists(lists []MappingList) error { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 382 | for i, list := range lists { |
| 383 | if list.ID == "" { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 384 | return fmt.Errorf("mapping list at index %d is missing an ID", i) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 385 | } |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 386 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 387 | if len(list.Mappings) == 0 { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 388 | return fmt.Errorf("mapping list '%s' has no mapping rules", list.ID) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 389 | } |
| 390 | |
| 391 | // Validate each mapping rule |
| 392 | for j, rule := range list.Mappings { |
| 393 | if rule == "" { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 394 | return fmt.Errorf("mapping list '%s' rule at index %d is empty", list.ID, j) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 395 | } |
| 396 | } |
| 397 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 398 | return nil |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 399 | } |
| 400 | |
| 401 | // ParseMappings parses all mapping rules in a list and returns a slice of parsed rules |
| 402 | func (list *MappingList) ParseMappings() ([]*parser.MappingResult, error) { |
| 403 | // Create a grammar parser with the list's default foundries and layers |
| 404 | grammarParser, err := parser.NewGrammarParser("", "") |
| 405 | if err != nil { |
| 406 | return nil, fmt.Errorf("failed to create grammar parser: %w", err) |
| 407 | } |
| 408 | |
| 409 | results := make([]*parser.MappingResult, len(list.Mappings)) |
| 410 | for i, rule := range list.Mappings { |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 411 | // Check for empty rules first |
| 412 | if rule == "" { |
| 413 | return nil, fmt.Errorf("empty mapping rule at index %d in list '%s'", i, list.ID) |
| 414 | } |
| 415 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 416 | // Parse the mapping rule |
| 417 | result, err := grammarParser.ParseMapping(string(rule)) |
| 418 | if err != nil { |
| 419 | return nil, fmt.Errorf("failed to parse mapping rule %d in list '%s': %w", i, list.ID, err) |
| 420 | } |
| 421 | |
| 422 | // Apply default foundries and layers if not specified in the rule |
| 423 | if list.FoundryA != "" { |
| 424 | applyDefaultFoundryAndLayer(result.Upper.Wrap, list.FoundryA, list.LayerA) |
| 425 | } |
| 426 | if list.FoundryB != "" { |
| 427 | applyDefaultFoundryAndLayer(result.Lower.Wrap, list.FoundryB, list.LayerB) |
| 428 | } |
| 429 | |
| 430 | results[i] = result |
| 431 | } |
| 432 | |
| 433 | return results, nil |
| 434 | } |
| 435 | |
| 436 | // applyDefaultFoundryAndLayer recursively applies default foundry and layer to terms that don't have them specified |
| 437 | func applyDefaultFoundryAndLayer(node ast.Node, defaultFoundry, defaultLayer string) { |
| 438 | switch n := node.(type) { |
| 439 | case *ast.Term: |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 440 | if n.Foundry == "" && defaultFoundry != "" { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 441 | n.Foundry = defaultFoundry |
| 442 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 443 | if n.Layer == "" && defaultLayer != "" { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 444 | n.Layer = defaultLayer |
| 445 | } |
| 446 | case *ast.TermGroup: |
| 447 | for _, op := range n.Operands { |
| 448 | applyDefaultFoundryAndLayer(op, defaultFoundry, defaultLayer) |
| 449 | } |
| 450 | } |
| 451 | } |