blob: 6c4c9bf17bc7638c1e25cbf4f4f8fe1e7b375f54 [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
Akronf1ca8822026-05-20 15:44:00 +020023 defaultLogLevel = "warn"
24 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 {
Akronf1ca8822026-05-20 15:44:00 +020095 SDK string `yaml:"sdk,omitempty"`
96 Stylesheet string `yaml:"stylesheet,omitempty"`
97 Server string `yaml:"server,omitempty"`
98 ServiceURL string `yaml:"serviceURL,omitempty"`
99 CookieName string `yaml:"cookieName,omitempty"`
100 BasePath string `yaml:"basePath,omitempty"` // restricts config file loading to this directory tree
101 AllowOrigins string `yaml:"allowOrigins,omitempty"` // comma-separated list of allowed CORS origins
102 Port int `yaml:"port,omitempty"`
103 LogLevel string `yaml:"loglevel,omitempty"`
104 RateLimit int `yaml:"rateLimit,omitempty"` // max requests per minute per IP (0 = use default 100)
105 Lists []MappingList `yaml:"lists,omitempty"`
Akron57ee5582025-05-21 15:25:13 +0200106}
107
Akroned787d02026-05-20 12:31:07 +0200108// AllowedBasePath restricts file loading to a specific directory tree.
109// When set, all file paths must resolve to a location at or below this
110// directory (or under the system temp directory). Defaults to the CWD at
111// application startup; can be overridden via the "basePath" YAML config
112// field or the KORAL_MAPPER_BASE_PATH environment variable. In Docker
113// (WORKDIR /), the default "/" naturally allows all paths.
114var AllowedBasePath string
115
116// isWithinDir checks whether absPath is at or below the given directory.
117// Uses a trailing-separator comparison to avoid prefix false positives
118// (e.g. /home/user must not match /home/username).
119func isWithinDir(absPath, dir string) bool {
120 if dir == "/" {
121 return true
122 }
123 return absPath == dir || strings.HasPrefix(absPath, dir+string(filepath.Separator))
124}
125
126// sanitizeFilePath cleans a file path, resolves it to an absolute path, and
127// (when AllowedBasePath is set) verifies it resides at or below the allowed
128// base directory or the system temp directory. This prevents path
129// traversal attacks by ensuring os.ReadFile never receives
130// unsanitized user input and cannot access files outside the application's
131// working tree.
132func sanitizeFilePath(path string) (string, error) {
133 if path == "" {
134 return "", fmt.Errorf("empty file path")
135 }
136
137 // Clean the path to remove redundant separators and resolve "." and ".."
138 cleaned := filepath.Clean(path)
139
140 // Convert to absolute path so all traversal is resolved against the CWD
141 absPath, err := filepath.Abs(cleaned)
142 if err != nil {
143 return "", fmt.Errorf("failed to resolve absolute path for '%s': %w", path, err)
144 }
145
146 // If a base path is configured, confine access to that tree or temp dir
147 if AllowedBasePath != "" {
148 base := filepath.Clean(AllowedBasePath)
149 tmpDir := filepath.Clean(os.TempDir())
150
151 if !isWithinDir(absPath, base) && !isWithinDir(absPath, tmpDir) {
152 return "", fmt.Errorf(
153 "path traversal detected: '%s' resolves to '%s' which is outside the allowed base '%s'",
154 path, absPath, base)
155 }
156 }
157
158 return absPath, nil
159}
160
Akrone1cff7c2025-06-04 18:43:32 +0200161// LoadFromSources loads configuration from multiple sources and merges them:
162// - A main configuration file (optional) containing global settings and lists
163// - Individual mapping files (optional) containing single mapping lists each
164// At least one source must be provided
165func LoadFromSources(configFile string, mappingFiles []string) (*MappingConfig, error) {
166 var allLists []MappingList
167 var globalConfig MappingConfig
Akron57ee5582025-05-21 15:25:13 +0200168
Akrone1cff7c2025-06-04 18:43:32 +0200169 // Track seen IDs across all sources to detect duplicates
170 seenIDs := make(map[string]bool)
Akrona5d88142025-05-22 14:42:09 +0200171
Akrone1cff7c2025-06-04 18:43:32 +0200172 // Load main configuration file if provided
173 if configFile != "" {
Akroned787d02026-05-20 12:31:07 +0200174 safePath, err := sanitizeFilePath(configFile)
175 if err != nil {
176 return nil, err
177 }
178 data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above
Akrone1cff7c2025-06-04 18:43:32 +0200179 if err != nil {
180 return nil, fmt.Errorf("failed to read config file '%s': %w", configFile, err)
Akron06d21f02025-06-04 14:36:07 +0200181 }
Akrone1cff7c2025-06-04 18:43:32 +0200182
183 if len(data) == 0 {
184 return nil, fmt.Errorf("EOF: config file '%s' is empty", configFile)
185 }
186
187 // Try to unmarshal as new format first (object with optional sdk/server and lists)
Akron813780f2025-06-05 15:44:28 +0200188 if err := yaml.Unmarshal(data, &globalConfig); err == nil {
189 // Successfully parsed as new format - accept it regardless of whether it has lists
Akrone1cff7c2025-06-04 18:43:32 +0200190 for _, list := range globalConfig.Lists {
191 if seenIDs[list.ID] {
192 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
193 }
194 seenIDs[list.ID] = true
195 }
196 allLists = append(allLists, globalConfig.Lists...)
197 } else {
198 // Fall back to old format (direct list)
199 var lists []MappingList
200 if err := yaml.Unmarshal(data, &lists); err != nil {
201 return nil, fmt.Errorf("failed to parse YAML config file '%s': %w", configFile, err)
202 }
203
204 for _, list := range lists {
205 if seenIDs[list.ID] {
206 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
207 }
208 seenIDs[list.ID] = true
209 }
210 allLists = append(allLists, lists...)
211 // Clear the lists from globalConfig since we got them from the old format
212 globalConfig.Lists = nil
213 }
Akron06d21f02025-06-04 14:36:07 +0200214 }
215
Akrone1cff7c2025-06-04 18:43:32 +0200216 // Load individual mapping files
217 for _, file := range mappingFiles {
Akroned787d02026-05-20 12:31:07 +0200218 safePath, err := sanitizeFilePath(file)
219 if err != nil {
220 return nil, err
221 }
222 data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above
Akrone1cff7c2025-06-04 18:43:32 +0200223 if err != nil {
Akron7e8da932025-07-01 11:56:46 +0200224 log.Error().Err(err).Str("file", file).Msg("Failed to read mapping file")
225 continue
Akrone1cff7c2025-06-04 18:43:32 +0200226 }
227
228 if len(data) == 0 {
Akron7e8da932025-07-01 11:56:46 +0200229 log.Error().Err(err).Str("file", file).Msg("EOF: mapping file is empty")
230 continue
Akrone1cff7c2025-06-04 18:43:32 +0200231 }
232
233 var list MappingList
234 if err := yaml.Unmarshal(data, &list); err != nil {
Akron7e8da932025-07-01 11:56:46 +0200235 log.Error().Err(err).Str("file", file).Msg("Failed to parse YAML mapping file")
236 continue
Akrone1cff7c2025-06-04 18:43:32 +0200237 }
238
239 if seenIDs[list.ID] {
Akron7e8da932025-07-01 11:56:46 +0200240 log.Error().Err(err).Str("file", file).Str("list-id", list.ID).Msg("Duplicate mapping list ID found")
241 continue
Akrone1cff7c2025-06-04 18:43:32 +0200242 }
243 seenIDs[list.ID] = true
244 allLists = append(allLists, list)
Akron57ee5582025-05-21 15:25:13 +0200245 }
246
Akrone1cff7c2025-06-04 18:43:32 +0200247 // Ensure we have at least some configuration
248 if len(allLists) == 0 {
249 return nil, fmt.Errorf("no mapping lists found: provide either a config file (-c) with lists or mapping files (-m)")
250 }
251
Akron585f50f2025-07-03 13:55:47 +0200252 // Validate all mapping lists (skip duplicate ID check since we already did it)
Akrone1cff7c2025-06-04 18:43:32 +0200253 if err := validateMappingLists(allLists); err != nil {
Akron06d21f02025-06-04 14:36:07 +0200254 return nil, err
255 }
256
Akrone1cff7c2025-06-04 18:43:32 +0200257 // Create final configuration
258 result := &MappingConfig{
Akronf1ca8822026-05-20 15:44:00 +0200259 SDK: globalConfig.SDK,
260 Stylesheet: globalConfig.Stylesheet,
261 Server: globalConfig.Server,
262 ServiceURL: globalConfig.ServiceURL,
263 BasePath: globalConfig.BasePath,
264 AllowOrigins: globalConfig.AllowOrigins,
265 Port: globalConfig.Port,
266 LogLevel: globalConfig.LogLevel,
267 RateLimit: globalConfig.RateLimit,
268 Lists: allLists,
Akrone1cff7c2025-06-04 18:43:32 +0200269 }
270
Akronf98ba282026-02-24 11:13:30 +0100271 // Apply environment variable overrides (ENV > config file)
272 ApplyEnvOverrides(result)
273
Akron06d21f02025-06-04 14:36:07 +0200274 // Apply defaults if not specified
Akron2ac2ec02025-06-05 15:26:42 +0200275 ApplyDefaults(result)
Akrone1cff7c2025-06-04 18:43:32 +0200276
277 return result, nil
278}
279
Akron585f50f2025-07-03 13:55:47 +0200280// ApplyDefaults sets default values for configuration fields if they are empty
Akron2ac2ec02025-06-05 15:26:42 +0200281func ApplyDefaults(config *MappingConfig) {
Akron585f50f2025-07-03 13:55:47 +0200282 defaults := map[*string]string{
283 &config.SDK: defaultSDK,
Akron43fb1022026-02-20 11:38:49 +0100284 &config.Stylesheet: defaultStylesheet,
Akron585f50f2025-07-03 13:55:47 +0200285 &config.Server: defaultServer,
286 &config.ServiceURL: defaultServiceURL,
Akron43fb1022026-02-20 11:38:49 +0100287 &config.CookieName: defaultCookieName,
Akron585f50f2025-07-03 13:55:47 +0200288 &config.LogLevel: defaultLogLevel,
Akron06d21f02025-06-04 14:36:07 +0200289 }
Akron585f50f2025-07-03 13:55:47 +0200290
291 for field, defaultValue := range defaults {
292 if *field == "" {
293 *field = defaultValue
294 }
Akron06d21f02025-06-04 14:36:07 +0200295 }
Akron585f50f2025-07-03 13:55:47 +0200296
Akronf1ca8822026-05-20 15:44:00 +0200297 // AllowOrigins defaults to the Server value (with trailing slash
298 // stripped to form a proper origin). This avoids duplicating the
299 // server URL string and keeps CORS in sync with the deployment.
300 if config.AllowOrigins == "" {
301 config.AllowOrigins = strings.TrimRight(config.Server, "/")
302 }
303
Akrona8a66ce2025-06-05 10:50:17 +0200304 if config.Port == 0 {
305 config.Port = defaultPort
306 }
Akrone6767de2026-05-20 10:06:24 +0200307 if config.RateLimit == 0 {
308 config.RateLimit = defaultRateLimit
309 }
Akron06d21f02025-06-04 14:36:07 +0200310}
311
Akronf98ba282026-02-24 11:13:30 +0100312// ApplyEnvOverrides overrides configuration fields from environment variables.
313// All environment variables are uppercase and prefixed with KORAL_MAPPER_.
314// Non-empty environment values override any previously loaded config values.
315func ApplyEnvOverrides(config *MappingConfig) {
316 envMappings := map[string]*string{
Akronf1ca8822026-05-20 15:44:00 +0200317 "KORAL_MAPPER_SERVER": &config.Server,
318 "KORAL_MAPPER_SDK": &config.SDK,
319 "KORAL_MAPPER_STYLESHEET": &config.Stylesheet,
320 "KORAL_MAPPER_SERVICE_URL": &config.ServiceURL,
321 "KORAL_MAPPER_COOKIE_NAME": &config.CookieName,
322 "KORAL_MAPPER_LOG_LEVEL": &config.LogLevel,
323 "KORAL_MAPPER_BASE_PATH": &config.BasePath,
324 "KORAL_MAPPER_ALLOW_ORIGINS": &config.AllowOrigins,
Akronf98ba282026-02-24 11:13:30 +0100325 }
326
327 for envKey, field := range envMappings {
328 if val := os.Getenv(envKey); val != "" {
329 *field = val
330 }
331 }
332
333 if val := os.Getenv("KORAL_MAPPER_PORT"); val != "" {
334 if port, err := strconv.Atoi(val); err == nil {
335 config.Port = port
336 }
337 }
Akrone6767de2026-05-20 10:06:24 +0200338
339 if val := os.Getenv("KORAL_MAPPER_RATE_LIMIT"); val != "" {
340 if rl, err := strconv.Atoi(val); err == nil {
341 config.RateLimit = rl
342 }
343 }
Akronf98ba282026-02-24 11:13:30 +0100344}
345
Akron585f50f2025-07-03 13:55:47 +0200346// validateMappingLists validates a slice of mapping lists (without duplicate ID checking)
Akron06d21f02025-06-04 14:36:07 +0200347func validateMappingLists(lists []MappingList) error {
Akron57ee5582025-05-21 15:25:13 +0200348 for i, list := range lists {
349 if list.ID == "" {
Akron06d21f02025-06-04 14:36:07 +0200350 return fmt.Errorf("mapping list at index %d is missing an ID", i)
Akron57ee5582025-05-21 15:25:13 +0200351 }
Akrona5d88142025-05-22 14:42:09 +0200352
Akron57ee5582025-05-21 15:25:13 +0200353 if len(list.Mappings) == 0 {
Akron06d21f02025-06-04 14:36:07 +0200354 return fmt.Errorf("mapping list '%s' has no mapping rules", list.ID)
Akron57ee5582025-05-21 15:25:13 +0200355 }
356
357 // Validate each mapping rule
358 for j, rule := range list.Mappings {
359 if rule == "" {
Akron06d21f02025-06-04 14:36:07 +0200360 return fmt.Errorf("mapping list '%s' rule at index %d is empty", list.ID, j)
Akron57ee5582025-05-21 15:25:13 +0200361 }
362 }
363 }
Akron06d21f02025-06-04 14:36:07 +0200364 return nil
Akron57ee5582025-05-21 15:25:13 +0200365}
366
367// ParseMappings parses all mapping rules in a list and returns a slice of parsed rules
368func (list *MappingList) ParseMappings() ([]*parser.MappingResult, error) {
369 // Create a grammar parser with the list's default foundries and layers
370 grammarParser, err := parser.NewGrammarParser("", "")
371 if err != nil {
372 return nil, fmt.Errorf("failed to create grammar parser: %w", err)
373 }
374
375 results := make([]*parser.MappingResult, len(list.Mappings))
376 for i, rule := range list.Mappings {
Akrona5d88142025-05-22 14:42:09 +0200377 // Check for empty rules first
378 if rule == "" {
379 return nil, fmt.Errorf("empty mapping rule at index %d in list '%s'", i, list.ID)
380 }
381
Akron57ee5582025-05-21 15:25:13 +0200382 // Parse the mapping rule
383 result, err := grammarParser.ParseMapping(string(rule))
384 if err != nil {
385 return nil, fmt.Errorf("failed to parse mapping rule %d in list '%s': %w", i, list.ID, err)
386 }
387
388 // Apply default foundries and layers if not specified in the rule
389 if list.FoundryA != "" {
390 applyDefaultFoundryAndLayer(result.Upper.Wrap, list.FoundryA, list.LayerA)
391 }
392 if list.FoundryB != "" {
393 applyDefaultFoundryAndLayer(result.Lower.Wrap, list.FoundryB, list.LayerB)
394 }
395
396 results[i] = result
397 }
398
399 return results, nil
400}
401
402// applyDefaultFoundryAndLayer recursively applies default foundry and layer to terms that don't have them specified
403func applyDefaultFoundryAndLayer(node ast.Node, defaultFoundry, defaultLayer string) {
404 switch n := node.(type) {
405 case *ast.Term:
Akron585f50f2025-07-03 13:55:47 +0200406 if n.Foundry == "" && defaultFoundry != "" {
Akron57ee5582025-05-21 15:25:13 +0200407 n.Foundry = defaultFoundry
408 }
Akron585f50f2025-07-03 13:55:47 +0200409 if n.Layer == "" && defaultLayer != "" {
Akron57ee5582025-05-21 15:25:13 +0200410 n.Layer = defaultLayer
411 }
412 case *ast.TermGroup:
413 for _, op := range n.Operands {
414 applyDefaultFoundryAndLayer(op, defaultFoundry, defaultLayer)
415 }
416 }
417}