blob: 7fa600e7aae640ef25d96a868fb109a0650ad842 [file] [log] [blame]
Akron57ee5582025-05-21 15:25:13 +02001package config
2
3import (
4 "fmt"
5 "os"
Akroned787d02026-05-20 12:31:07 +02006 "path/filepath"
Akronf98ba282026-02-24 11:13:30 +01007 "strconv"
Akroned787d02026-05-20 12:31:07 +02008 "strings"
Akron57ee5582025-05-21 15:25:13 +02009
Akron2ef703c2025-07-03 15:57:42 +020010 "github.com/KorAP/Koral-Mapper/ast"
11 "github.com/KorAP/Koral-Mapper/parser"
Akron7e8da932025-07-01 11:56:46 +020012 "github.com/rs/zerolog/log"
Akron57ee5582025-05-21 15:25:13 +020013 "gopkg.in/yaml.v3"
14)
15
Akron06d21f02025-06-04 14:36:07 +020016const (
Akron2ac2ec02025-06-05 15:26:42 +020017 defaultServer = "https://korap.ids-mannheim.de/"
18 defaultSDK = "https://korap.ids-mannheim.de/js/korap-plugin-latest.js"
Akron43fb1022026-02-20 11:38:49 +010019 defaultStylesheet = "https://korap.ids-mannheim.de/css/kalamar-plugin-latest.css"
Akron2ef703c2025-07-03 15:57:42 +020020 defaultServiceURL = "https://korap.ids-mannheim.de/plugin/koralmapper"
Akron43fb1022026-02-20 11:38:49 +010021 defaultCookieName = "km-config"
Akron14c13a52025-06-06 15:36:23 +020022 defaultPort = 5725
Akron2ac2ec02025-06-05 15:26:42 +020023 defaultLogLevel = "warn"
Akrone6767de2026-05-20 10:06:24 +020024 defaultRateLimit = 100
Akron06d21f02025-06-04 14:36:07 +020025)
26
Akron57ee5582025-05-21 15:25:13 +020027// MappingRule represents a single mapping rule in the configuration
28type MappingRule string
29
30// MappingList represents a list of mapping rules with metadata
31type MappingList struct {
Akrondab27112025-06-05 13:52:43 +020032 ID string `yaml:"id"`
Akron2f93c582026-02-19 16:49:13 +010033 Type string `yaml:"type,omitempty"` // "annotation" (default) or "corpus"
Akrondab27112025-06-05 13:52:43 +020034 Description string `yaml:"desc,omitempty"`
35 FoundryA string `yaml:"foundryA,omitempty"`
36 LayerA string `yaml:"layerA,omitempty"`
37 FoundryB string `yaml:"foundryB,omitempty"`
38 LayerB string `yaml:"layerB,omitempty"`
Akrona67de8f2026-02-23 17:54:26 +010039 FieldA string `yaml:"fieldA,omitempty"`
40 FieldB string `yaml:"fieldB,omitempty"`
Akron8414ae52026-05-19 13:31:14 +020041 Rewrites bool `yaml:"rewrites,omitempty"`
Akrondab27112025-06-05 13:52:43 +020042 Mappings []MappingRule `yaml:"mappings"`
Akron57ee5582025-05-21 15:25:13 +020043}
44
Akron2f93c582026-02-19 16:49:13 +010045// IsCorpus returns true if the mapping list type is "corpus".
46func (list *MappingList) IsCorpus() bool {
47 return list.Type == "corpus"
48}
49
50// ParseCorpusMappings parses all mapping rules as corpus rules.
Akrona67de8f2026-02-23 17:54:26 +010051// Bare values (without key=) are always allowed and receive the default
52// field name from the mapping list header (FieldA/FieldB) when set.
Akron2f93c582026-02-19 16:49:13 +010053func (list *MappingList) ParseCorpusMappings() ([]*parser.CorpusMappingResult, error) {
54 corpusParser := parser.NewCorpusParser()
Akrona67de8f2026-02-23 17:54:26 +010055 corpusParser.AllowBareValues = true
56
Akron2f93c582026-02-19 16:49:13 +010057 results := make([]*parser.CorpusMappingResult, len(list.Mappings))
58 for i, rule := range list.Mappings {
59 if rule == "" {
60 return nil, fmt.Errorf("empty corpus mapping rule at index %d in list '%s'", i, list.ID)
61 }
62 result, err := corpusParser.ParseMapping(string(rule))
63 if err != nil {
64 return nil, fmt.Errorf("failed to parse corpus mapping rule %d in list '%s': %w", i, list.ID, err)
65 }
Akrona67de8f2026-02-23 17:54:26 +010066
67 if list.FieldA != "" {
68 applyDefaultCorpusKey(result.Upper, list.FieldA)
69 }
70 if list.FieldB != "" {
71 applyDefaultCorpusKey(result.Lower, list.FieldB)
72 }
73
Akron2f93c582026-02-19 16:49:13 +010074 results[i] = result
75 }
76 return results, nil
77}
78
Akrona67de8f2026-02-23 17:54:26 +010079// applyDefaultCorpusKey recursively fills in empty keys on CorpusField nodes.
80func applyDefaultCorpusKey(node parser.CorpusNode, defaultKey string) {
81 switch n := node.(type) {
82 case *parser.CorpusField:
83 if n.Key == "" {
84 n.Key = defaultKey
85 }
86 case *parser.CorpusGroup:
87 for _, op := range n.Operands {
88 applyDefaultCorpusKey(op, defaultKey)
89 }
90 }
91}
92
Akron06d21f02025-06-04 14:36:07 +020093// MappingConfig represents the root configuration containing multiple mapping lists
94type MappingConfig struct {
Akron2ac2ec02025-06-05 15:26:42 +020095 SDK string `yaml:"sdk,omitempty"`
Akron43fb1022026-02-20 11:38:49 +010096 Stylesheet string `yaml:"stylesheet,omitempty"`
Akron2ac2ec02025-06-05 15:26:42 +020097 Server string `yaml:"server,omitempty"`
98 ServiceURL string `yaml:"serviceURL,omitempty"`
Akron43fb1022026-02-20 11:38:49 +010099 CookieName string `yaml:"cookieName,omitempty"`
Akroned787d02026-05-20 12:31:07 +0200100 BasePath string `yaml:"basePath,omitempty"` // restricts config file loading to this directory tree
Akron2ac2ec02025-06-05 15:26:42 +0200101 Port int `yaml:"port,omitempty"`
102 LogLevel string `yaml:"loglevel,omitempty"`
Akrone6767de2026-05-20 10:06:24 +0200103 RateLimit int `yaml:"rateLimit,omitempty"` // max requests per minute per IP (0 = use default 100)
Akron2ac2ec02025-06-05 15:26:42 +0200104 Lists []MappingList `yaml:"lists,omitempty"`
Akron57ee5582025-05-21 15:25:13 +0200105}
106
Akroned787d02026-05-20 12:31:07 +0200107// AllowedBasePath restricts file loading to a specific directory tree.
108// When set, all file paths must resolve to a location at or below this
109// directory (or under the system temp directory). Defaults to the CWD at
110// application startup; can be overridden via the "basePath" YAML config
111// field or the KORAL_MAPPER_BASE_PATH environment variable. In Docker
112// (WORKDIR /), the default "/" naturally allows all paths.
113var AllowedBasePath string
114
115// isWithinDir checks whether absPath is at or below the given directory.
116// Uses a trailing-separator comparison to avoid prefix false positives
117// (e.g. /home/user must not match /home/username).
118func isWithinDir(absPath, dir string) bool {
119 if dir == "/" {
120 return true
121 }
122 return absPath == dir || strings.HasPrefix(absPath, dir+string(filepath.Separator))
123}
124
125// sanitizeFilePath cleans a file path, resolves it to an absolute path, and
126// (when AllowedBasePath is set) verifies it resides at or below the allowed
127// base directory or the system temp directory. This prevents path
128// traversal attacks by ensuring os.ReadFile never receives
129// unsanitized user input and cannot access files outside the application's
130// working tree.
131func sanitizeFilePath(path string) (string, error) {
132 if path == "" {
133 return "", fmt.Errorf("empty file path")
134 }
135
136 // Clean the path to remove redundant separators and resolve "." and ".."
137 cleaned := filepath.Clean(path)
138
139 // Convert to absolute path so all traversal is resolved against the CWD
140 absPath, err := filepath.Abs(cleaned)
141 if err != nil {
142 return "", fmt.Errorf("failed to resolve absolute path for '%s': %w", path, err)
143 }
144
145 // If a base path is configured, confine access to that tree or temp dir
146 if AllowedBasePath != "" {
147 base := filepath.Clean(AllowedBasePath)
148 tmpDir := filepath.Clean(os.TempDir())
149
150 if !isWithinDir(absPath, base) && !isWithinDir(absPath, tmpDir) {
151 return "", fmt.Errorf(
152 "path traversal detected: '%s' resolves to '%s' which is outside the allowed base '%s'",
153 path, absPath, base)
154 }
155 }
156
157 return absPath, nil
158}
159
Akrone1cff7c2025-06-04 18:43:32 +0200160// LoadFromSources loads configuration from multiple sources and merges them:
161// - A main configuration file (optional) containing global settings and lists
162// - Individual mapping files (optional) containing single mapping lists each
163// At least one source must be provided
164func LoadFromSources(configFile string, mappingFiles []string) (*MappingConfig, error) {
165 var allLists []MappingList
166 var globalConfig MappingConfig
Akron57ee5582025-05-21 15:25:13 +0200167
Akrone1cff7c2025-06-04 18:43:32 +0200168 // Track seen IDs across all sources to detect duplicates
169 seenIDs := make(map[string]bool)
Akrona5d88142025-05-22 14:42:09 +0200170
Akrone1cff7c2025-06-04 18:43:32 +0200171 // Load main configuration file if provided
172 if configFile != "" {
Akroned787d02026-05-20 12:31:07 +0200173 safePath, err := sanitizeFilePath(configFile)
174 if err != nil {
175 return nil, err
176 }
177 data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above
Akrone1cff7c2025-06-04 18:43:32 +0200178 if err != nil {
179 return nil, fmt.Errorf("failed to read config file '%s': %w", configFile, err)
Akron06d21f02025-06-04 14:36:07 +0200180 }
Akrone1cff7c2025-06-04 18:43:32 +0200181
182 if len(data) == 0 {
183 return nil, fmt.Errorf("EOF: config file '%s' is empty", configFile)
184 }
185
186 // Try to unmarshal as new format first (object with optional sdk/server and lists)
Akron813780f2025-06-05 15:44:28 +0200187 if err := yaml.Unmarshal(data, &globalConfig); err == nil {
188 // Successfully parsed as new format - accept it regardless of whether it has lists
Akrone1cff7c2025-06-04 18:43:32 +0200189 for _, list := range globalConfig.Lists {
190 if seenIDs[list.ID] {
191 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
192 }
193 seenIDs[list.ID] = true
194 }
195 allLists = append(allLists, globalConfig.Lists...)
196 } else {
197 // Fall back to old format (direct list)
198 var lists []MappingList
199 if err := yaml.Unmarshal(data, &lists); err != nil {
200 return nil, fmt.Errorf("failed to parse YAML config file '%s': %w", configFile, err)
201 }
202
203 for _, list := range lists {
204 if seenIDs[list.ID] {
205 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
206 }
207 seenIDs[list.ID] = true
208 }
209 allLists = append(allLists, lists...)
210 // Clear the lists from globalConfig since we got them from the old format
211 globalConfig.Lists = nil
212 }
Akron06d21f02025-06-04 14:36:07 +0200213 }
214
Akrone1cff7c2025-06-04 18:43:32 +0200215 // Load individual mapping files
216 for _, file := range mappingFiles {
Akroned787d02026-05-20 12:31:07 +0200217 safePath, err := sanitizeFilePath(file)
218 if err != nil {
219 return nil, err
220 }
221 data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above
Akrone1cff7c2025-06-04 18:43:32 +0200222 if err != nil {
Akron7e8da932025-07-01 11:56:46 +0200223 log.Error().Err(err).Str("file", file).Msg("Failed to read mapping file")
224 continue
Akrone1cff7c2025-06-04 18:43:32 +0200225 }
226
227 if len(data) == 0 {
Akron7e8da932025-07-01 11:56:46 +0200228 log.Error().Err(err).Str("file", file).Msg("EOF: mapping file is empty")
229 continue
Akrone1cff7c2025-06-04 18:43:32 +0200230 }
231
232 var list MappingList
233 if err := yaml.Unmarshal(data, &list); err != nil {
Akron7e8da932025-07-01 11:56:46 +0200234 log.Error().Err(err).Str("file", file).Msg("Failed to parse YAML mapping file")
235 continue
Akrone1cff7c2025-06-04 18:43:32 +0200236 }
237
238 if seenIDs[list.ID] {
Akron7e8da932025-07-01 11:56:46 +0200239 log.Error().Err(err).Str("file", file).Str("list-id", list.ID).Msg("Duplicate mapping list ID found")
240 continue
Akrone1cff7c2025-06-04 18:43:32 +0200241 }
242 seenIDs[list.ID] = true
243 allLists = append(allLists, list)
Akron57ee5582025-05-21 15:25:13 +0200244 }
245
Akrone1cff7c2025-06-04 18:43:32 +0200246 // Ensure we have at least some configuration
247 if len(allLists) == 0 {
248 return nil, fmt.Errorf("no mapping lists found: provide either a config file (-c) with lists or mapping files (-m)")
249 }
250
Akron585f50f2025-07-03 13:55:47 +0200251 // Validate all mapping lists (skip duplicate ID check since we already did it)
Akrone1cff7c2025-06-04 18:43:32 +0200252 if err := validateMappingLists(allLists); err != nil {
Akron06d21f02025-06-04 14:36:07 +0200253 return nil, err
254 }
255
Akrone1cff7c2025-06-04 18:43:32 +0200256 // Create final configuration
257 result := &MappingConfig{
Akron2ac2ec02025-06-05 15:26:42 +0200258 SDK: globalConfig.SDK,
Akron43fb1022026-02-20 11:38:49 +0100259 Stylesheet: globalConfig.Stylesheet,
Akron2ac2ec02025-06-05 15:26:42 +0200260 Server: globalConfig.Server,
261 ServiceURL: globalConfig.ServiceURL,
Akroned787d02026-05-20 12:31:07 +0200262 BasePath: globalConfig.BasePath,
Akron2ac2ec02025-06-05 15:26:42 +0200263 Port: globalConfig.Port,
264 LogLevel: globalConfig.LogLevel,
Akrone6767de2026-05-20 10:06:24 +0200265 RateLimit: globalConfig.RateLimit,
Akron2ac2ec02025-06-05 15:26:42 +0200266 Lists: allLists,
Akrone1cff7c2025-06-04 18:43:32 +0200267 }
268
Akronf98ba282026-02-24 11:13:30 +0100269 // Apply environment variable overrides (ENV > config file)
270 ApplyEnvOverrides(result)
271
Akron06d21f02025-06-04 14:36:07 +0200272 // Apply defaults if not specified
Akron2ac2ec02025-06-05 15:26:42 +0200273 ApplyDefaults(result)
Akrone1cff7c2025-06-04 18:43:32 +0200274
275 return result, nil
276}
277
Akron585f50f2025-07-03 13:55:47 +0200278// ApplyDefaults sets default values for configuration fields if they are empty
Akron2ac2ec02025-06-05 15:26:42 +0200279func ApplyDefaults(config *MappingConfig) {
Akron585f50f2025-07-03 13:55:47 +0200280 defaults := map[*string]string{
281 &config.SDK: defaultSDK,
Akron43fb1022026-02-20 11:38:49 +0100282 &config.Stylesheet: defaultStylesheet,
Akron585f50f2025-07-03 13:55:47 +0200283 &config.Server: defaultServer,
284 &config.ServiceURL: defaultServiceURL,
Akron43fb1022026-02-20 11:38:49 +0100285 &config.CookieName: defaultCookieName,
Akron585f50f2025-07-03 13:55:47 +0200286 &config.LogLevel: defaultLogLevel,
Akron06d21f02025-06-04 14:36:07 +0200287 }
Akron585f50f2025-07-03 13:55:47 +0200288
289 for field, defaultValue := range defaults {
290 if *field == "" {
291 *field = defaultValue
292 }
Akron06d21f02025-06-04 14:36:07 +0200293 }
Akron585f50f2025-07-03 13:55:47 +0200294
Akrona8a66ce2025-06-05 10:50:17 +0200295 if config.Port == 0 {
296 config.Port = defaultPort
297 }
Akrone6767de2026-05-20 10:06:24 +0200298 if config.RateLimit == 0 {
299 config.RateLimit = defaultRateLimit
300 }
Akron06d21f02025-06-04 14:36:07 +0200301}
302
Akronf98ba282026-02-24 11:13:30 +0100303// ApplyEnvOverrides overrides configuration fields from environment variables.
304// All environment variables are uppercase and prefixed with KORAL_MAPPER_.
305// Non-empty environment values override any previously loaded config values.
306func ApplyEnvOverrides(config *MappingConfig) {
307 envMappings := map[string]*string{
308 "KORAL_MAPPER_SERVER": &config.Server,
309 "KORAL_MAPPER_SDK": &config.SDK,
310 "KORAL_MAPPER_STYLESHEET": &config.Stylesheet,
311 "KORAL_MAPPER_SERVICE_URL": &config.ServiceURL,
312 "KORAL_MAPPER_COOKIE_NAME": &config.CookieName,
313 "KORAL_MAPPER_LOG_LEVEL": &config.LogLevel,
Akroned787d02026-05-20 12:31:07 +0200314 "KORAL_MAPPER_BASE_PATH": &config.BasePath,
Akronf98ba282026-02-24 11:13:30 +0100315 }
316
317 for envKey, field := range envMappings {
318 if val := os.Getenv(envKey); val != "" {
319 *field = val
320 }
321 }
322
323 if val := os.Getenv("KORAL_MAPPER_PORT"); val != "" {
324 if port, err := strconv.Atoi(val); err == nil {
325 config.Port = port
326 }
327 }
Akrone6767de2026-05-20 10:06:24 +0200328
329 if val := os.Getenv("KORAL_MAPPER_RATE_LIMIT"); val != "" {
330 if rl, err := strconv.Atoi(val); err == nil {
331 config.RateLimit = rl
332 }
333 }
Akronf98ba282026-02-24 11:13:30 +0100334}
335
Akron585f50f2025-07-03 13:55:47 +0200336// validateMappingLists validates a slice of mapping lists (without duplicate ID checking)
Akron06d21f02025-06-04 14:36:07 +0200337func validateMappingLists(lists []MappingList) error {
Akron57ee5582025-05-21 15:25:13 +0200338 for i, list := range lists {
339 if list.ID == "" {
Akron06d21f02025-06-04 14:36:07 +0200340 return fmt.Errorf("mapping list at index %d is missing an ID", i)
Akron57ee5582025-05-21 15:25:13 +0200341 }
Akrona5d88142025-05-22 14:42:09 +0200342
Akron57ee5582025-05-21 15:25:13 +0200343 if len(list.Mappings) == 0 {
Akron06d21f02025-06-04 14:36:07 +0200344 return fmt.Errorf("mapping list '%s' has no mapping rules", list.ID)
Akron57ee5582025-05-21 15:25:13 +0200345 }
346
347 // Validate each mapping rule
348 for j, rule := range list.Mappings {
349 if rule == "" {
Akron06d21f02025-06-04 14:36:07 +0200350 return fmt.Errorf("mapping list '%s' rule at index %d is empty", list.ID, j)
Akron57ee5582025-05-21 15:25:13 +0200351 }
352 }
353 }
Akron06d21f02025-06-04 14:36:07 +0200354 return nil
Akron57ee5582025-05-21 15:25:13 +0200355}
356
357// ParseMappings parses all mapping rules in a list and returns a slice of parsed rules
358func (list *MappingList) ParseMappings() ([]*parser.MappingResult, error) {
359 // Create a grammar parser with the list's default foundries and layers
360 grammarParser, err := parser.NewGrammarParser("", "")
361 if err != nil {
362 return nil, fmt.Errorf("failed to create grammar parser: %w", err)
363 }
364
365 results := make([]*parser.MappingResult, len(list.Mappings))
366 for i, rule := range list.Mappings {
Akrona5d88142025-05-22 14:42:09 +0200367 // Check for empty rules first
368 if rule == "" {
369 return nil, fmt.Errorf("empty mapping rule at index %d in list '%s'", i, list.ID)
370 }
371
Akron57ee5582025-05-21 15:25:13 +0200372 // Parse the mapping rule
373 result, err := grammarParser.ParseMapping(string(rule))
374 if err != nil {
375 return nil, fmt.Errorf("failed to parse mapping rule %d in list '%s': %w", i, list.ID, err)
376 }
377
378 // Apply default foundries and layers if not specified in the rule
379 if list.FoundryA != "" {
380 applyDefaultFoundryAndLayer(result.Upper.Wrap, list.FoundryA, list.LayerA)
381 }
382 if list.FoundryB != "" {
383 applyDefaultFoundryAndLayer(result.Lower.Wrap, list.FoundryB, list.LayerB)
384 }
385
386 results[i] = result
387 }
388
389 return results, nil
390}
391
392// applyDefaultFoundryAndLayer recursively applies default foundry and layer to terms that don't have them specified
393func applyDefaultFoundryAndLayer(node ast.Node, defaultFoundry, defaultLayer string) {
394 switch n := node.(type) {
395 case *ast.Term:
Akron585f50f2025-07-03 13:55:47 +0200396 if n.Foundry == "" && defaultFoundry != "" {
Akron57ee5582025-05-21 15:25:13 +0200397 n.Foundry = defaultFoundry
398 }
Akron585f50f2025-07-03 13:55:47 +0200399 if n.Layer == "" && defaultLayer != "" {
Akron57ee5582025-05-21 15:25:13 +0200400 n.Layer = defaultLayer
401 }
402 case *ast.TermGroup:
403 for _, op := range n.Operands {
404 applyDefaultFoundryAndLayer(op, defaultFoundry, defaultLayer)
405 }
406 }
407}