blob: 9fc6f5dade8c6c7917c6b4137b0dade54ed5bca6 [file] [log] [blame]
Akron49ceeb42025-05-23 17:46:01 +02001package main
2
3import (
Akrond8a76b32026-02-20 09:31:56 +01004 "bytes"
5 "embed"
Akron49ceeb42025-05-23 17:46:01 +02006 "fmt"
Akrond8a76b32026-02-20 09:31:56 +01007 "html/template"
8 "io/fs"
Akron80067202025-06-06 14:16:25 +02009 "net/url"
Akron49ceeb42025-05-23 17:46:01 +020010 "os"
11 "os/signal"
Akron80067202025-06-06 14:16:25 +020012 "path"
Akron14678dc2025-06-05 13:01:38 +020013 "path/filepath"
Akrond8a76b32026-02-20 09:31:56 +010014 "strconv"
Akron49ceeb42025-05-23 17:46:01 +020015 "strings"
16 "syscall"
Akron3caee162025-07-01 17:44:58 +020017 "time"
Akron49ceeb42025-05-23 17:46:01 +020018
Akron2ef703c2025-07-03 15:57:42 +020019 "github.com/KorAP/Koral-Mapper/config"
20 "github.com/KorAP/Koral-Mapper/mapper"
Akron1fc750e2025-05-26 16:54:18 +020021 "github.com/alecthomas/kong"
Akron49ceeb42025-05-23 17:46:01 +020022 "github.com/gofiber/fiber/v2"
Akrone6767de2026-05-20 10:06:24 +020023 "github.com/gofiber/fiber/v2/middleware/limiter"
Akron49ceeb42025-05-23 17:46:01 +020024 "github.com/rs/zerolog"
25 "github.com/rs/zerolog/log"
26)
27
Akrond8a76b32026-02-20 09:31:56 +010028//go:embed static/*
29var staticFS embed.FS
30
Akron74e1c072025-05-26 14:38:25 +020031const (
32 maxInputLength = 1024 * 1024 // 1MB
33 maxParamLength = 1024 // 1KB
34)
35
Akrona00d4752025-05-26 17:34:36 +020036type appConfig struct {
Akrona8a66ce2025-06-05 10:50:17 +020037 Port *int `kong:"short='p',help='Port to listen on'"`
Akrone1cff7c2025-06-04 18:43:32 +020038 Config string `kong:"short='c',help='YAML configuration file containing mapping directives and global settings'"`
Akron14678dc2025-06-05 13:01:38 +020039 Mappings []string `kong:"short='m',help='Individual YAML mapping files to load (supports glob patterns like dir/*.yaml)'"`
Akrona8a66ce2025-06-05 10:50:17 +020040 LogLevel *string `kong:"short='l',help='Log level (debug, info, warn, error)'"`
Akron49ceeb42025-05-23 17:46:01 +020041}
42
Akrond8a76b32026-02-20 09:31:56 +010043type BasePageData struct {
Akron40aaa632025-06-03 17:57:52 +020044 Title string
45 Version string
Akronfc77b5e2025-06-04 11:44:43 +020046 Hash string
47 Date string
Akron40aaa632025-06-03 17:57:52 +020048 Description string
Akron06d21f02025-06-04 14:36:07 +020049 Server string
50 SDK string
Akron43fb1022026-02-20 11:38:49 +010051 Stylesheet string
Akron2ac2ec02025-06-05 15:26:42 +020052 ServiceURL string
Akron43fb1022026-02-20 11:38:49 +010053 CookieName string
Akrond8a76b32026-02-20 09:31:56 +010054}
55
56type SingleMappingPageData struct {
57 BasePageData
Akronc376dcc2025-06-04 17:00:18 +020058 MapID string
Akrond8a76b32026-02-20 09:31:56 +010059 Mappings []config.MappingList
60 QueryURL string
61 ResponseURL string
Akron40aaa632025-06-03 17:57:52 +020062}
63
Akroncb51f812025-06-30 15:24:20 +020064type QueryParams struct {
65 Dir string
66 FoundryA string
67 FoundryB string
68 LayerA string
69 LayerB string
70}
71
Akron49b525c2025-07-03 15:17:06 +020072// requestParams holds common request parameters
73type requestParams struct {
74 MapID string
75 Dir string
76 FoundryA string
77 FoundryB string
78 LayerA string
79 LayerB string
Akron8414ae52026-05-19 13:31:14 +020080 Rewrites *bool // nil = use mapping list default; non-nil = override
Akron49b525c2025-07-03 15:17:06 +020081}
82
Akron247a93a2026-02-20 16:28:40 +010083// MappingSectionData contains per-section UI metadata so request and response
84// rows can be rendered from one shared template block.
85type MappingSectionData struct {
86 Title string
87 Mode string
88 CheckboxClass string
89 CheckboxName string
90 FieldsClass string
91 ArrowClass string
92 ArrowDirection string
93 ArrowLabel string
94 AnnotationLabel string
95}
96
Akrond8a76b32026-02-20 09:31:56 +010097// ConfigPageData holds all data passed to the configuration page template.
98type ConfigPageData struct {
99 BasePageData
100 AnnotationMappings []config.MappingList
101 CorpusMappings []config.MappingList
Akron247a93a2026-02-20 16:28:40 +0100102 MappingSections []MappingSectionData
Akrond8a76b32026-02-20 09:31:56 +0100103}
104
Akrona00d4752025-05-26 17:34:36 +0200105func parseConfig() *appConfig {
106 cfg := &appConfig{}
Akronfc77b5e2025-06-04 11:44:43 +0200107
108 desc := config.Description
109 desc += " [" + config.Version + "]"
110
Akron1fc750e2025-05-26 16:54:18 +0200111 ctx := kong.Parse(cfg,
Akronfc77b5e2025-06-04 11:44:43 +0200112 kong.Description(desc),
Akron1fc750e2025-05-26 16:54:18 +0200113 kong.UsageOnError(),
114 )
115 if ctx.Error != nil {
116 fmt.Fprintln(os.Stderr, ctx.Error)
Akron49ceeb42025-05-23 17:46:01 +0200117 os.Exit(1)
118 }
Akron49ceeb42025-05-23 17:46:01 +0200119 return cfg
120}
121
122func setupLogger(level string) {
123 // Parse log level
124 lvl, err := zerolog.ParseLevel(strings.ToLower(level))
125 if err != nil {
126 log.Error().Err(err).Str("level", level).Msg("Invalid log level, defaulting to info")
127 lvl = zerolog.InfoLevel
128 }
129
130 // Configure zerolog
131 zerolog.SetGlobalLevel(lvl)
132 log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
133}
134
Akron3caee162025-07-01 17:44:58 +0200135// setupFiberLogger configures fiber's logger middleware to integrate with zerolog
136func setupFiberLogger() fiber.Handler {
137 // Check if HTTP request logging should be enabled based on current log level
138 currentLevel := zerolog.GlobalLevel()
139
140 // Only enable HTTP request logging if log level is debug or info
141 if currentLevel > zerolog.InfoLevel {
142 return func(c *fiber.Ctx) error {
143 return c.Next()
144 }
145 }
146
147 return func(c *fiber.Ctx) error {
148 // Record start time
149 start := time.Now()
150
151 // Process request
152 err := c.Next()
153
154 // Calculate latency
155 latency := time.Since(start)
156 status := c.Response().StatusCode()
157
158 // Determine log level based on status code
159 logEvent := log.Info()
160 if status >= 400 && status < 500 {
161 logEvent = log.Warn()
162 } else if status >= 500 {
163 logEvent = log.Error()
164 }
165
166 // Log the request
167 logEvent.
168 Int("status", status).
169 Dur("latency", latency).
170 Str("method", c.Method()).
171 Str("path", c.Path()).
172 Str("ip", c.IP()).
173 Str("user_agent", c.Get("User-Agent")).
174 Msg("HTTP request")
175
176 return err
177 }
178}
179
Akron49b525c2025-07-03 15:17:06 +0200180// extractRequestParams extracts and validates common request parameters
181func extractRequestParams(c *fiber.Ctx) (*requestParams, error) {
182 params := &requestParams{
183 MapID: c.Params("map"),
184 Dir: c.Query("dir", "atob"),
185 FoundryA: c.Query("foundryA", ""),
186 FoundryB: c.Query("foundryB", ""),
187 LayerA: c.Query("layerA", ""),
188 LayerB: c.Query("layerB", ""),
189 }
190
Akron8414ae52026-05-19 13:31:14 +0200191 if rewrites := c.Query("rewrites", ""); rewrites != "" {
192 v := rewrites == "true"
193 params.Rewrites = &v
194 }
195
Akron49b525c2025-07-03 15:17:06 +0200196 // Validate input parameters
197 if err := validateInput(params.MapID, params.Dir, params.FoundryA, params.FoundryB, params.LayerA, params.LayerB, c.Body()); err != nil {
198 return nil, err
199 }
200
201 // Validate direction
202 if params.Dir != "atob" && params.Dir != "btoa" {
203 return nil, fmt.Errorf("invalid direction, must be 'atob' or 'btoa'")
204 }
205
206 return params, nil
207}
208
209// parseRequestBody parses JSON request body and direction
210func parseRequestBody(c *fiber.Ctx, dir string) (any, mapper.Direction, error) {
211 var jsonData any
212 if err := c.BodyParser(&jsonData); err != nil {
213 return nil, mapper.BtoA, fmt.Errorf("invalid JSON in request body")
214 }
215
216 direction, err := mapper.ParseDirection(dir)
217 if err != nil {
218 return nil, mapper.BtoA, err
219 }
220
221 return jsonData, direction, nil
222}
223
Akron49ceeb42025-05-23 17:46:01 +0200224func main() {
225 // Parse command line flags
Akron1fc750e2025-05-26 16:54:18 +0200226 cfg := parseConfig()
Akron49ceeb42025-05-23 17:46:01 +0200227
Akrone1cff7c2025-06-04 18:43:32 +0200228 // Validate command line arguments
229 if cfg.Config == "" && len(cfg.Mappings) == 0 {
230 log.Fatal().Msg("At least one configuration source must be provided: use -c for main config file or -m for mapping files")
231 }
232
Akron14678dc2025-06-05 13:01:38 +0200233 // Expand glob patterns in mapping files
234 expandedMappings, err := expandGlobs(cfg.Mappings)
235 if err != nil {
236 log.Fatal().Err(err).Msg("Failed to expand glob patterns in mapping files")
237 }
238
Akrone1cff7c2025-06-04 18:43:32 +0200239 // Load configuration from multiple sources
Akron14678dc2025-06-05 13:01:38 +0200240 yamlConfig, err := config.LoadFromSources(cfg.Config, expandedMappings)
Akrona00d4752025-05-26 17:34:36 +0200241 if err != nil {
242 log.Fatal().Err(err).Msg("Failed to load configuration")
243 }
244
Akrona8a66ce2025-06-05 10:50:17 +0200245 finalPort := yamlConfig.Port
246 finalLogLevel := yamlConfig.LogLevel
247
248 // Use command line values if provided (they override config file)
249 if cfg.Port != nil {
250 finalPort = *cfg.Port
251 }
252 if cfg.LogLevel != nil {
253 finalLogLevel = *cfg.LogLevel
254 }
255
256 // Set up logging with the final log level
257 setupLogger(finalLogLevel)
258
Akron49ceeb42025-05-23 17:46:01 +0200259 // Create a new mapper instance
Akrona00d4752025-05-26 17:34:36 +0200260 m, err := mapper.NewMapper(yamlConfig.Lists)
Akron49ceeb42025-05-23 17:46:01 +0200261 if err != nil {
262 log.Fatal().Err(err).Msg("Failed to create mapper")
263 }
264
265 // Create fiber app
266 app := fiber.New(fiber.Config{
267 DisableStartupMessage: true,
Akron74e1c072025-05-26 14:38:25 +0200268 BodyLimit: maxInputLength,
Akronafbe86d2025-07-01 08:45:13 +0200269 ReadBufferSize: 64 * 1024, // 64KB - increase header size limit
270 WriteBufferSize: 64 * 1024, // 64KB - increase response buffer size
Akron49ceeb42025-05-23 17:46:01 +0200271 })
272
Akron3caee162025-07-01 17:44:58 +0200273 // Add zerolog-integrated logger middleware
274 app.Use(setupFiberLogger())
275
Akron49ceeb42025-05-23 17:46:01 +0200276 // Set up routes
Akron40aaa632025-06-03 17:57:52 +0200277 setupRoutes(app, m, yamlConfig)
Akron49ceeb42025-05-23 17:46:01 +0200278
279 // Start server
280 go func() {
Akrona8a66ce2025-06-05 10:50:17 +0200281 log.Info().Int("port", finalPort).Msg("Starting server")
Akrond8a76b32026-02-20 09:31:56 +0100282 fmt.Printf("Starting server port=%d\n", finalPort)
Akronae3ffde2025-06-05 14:04:06 +0200283
284 for _, list := range yamlConfig.Lists {
285 log.Info().Str("id", list.ID).Str("desc", list.Description).Msg("Loaded mapping")
Akrond8a76b32026-02-20 09:31:56 +0100286 fmt.Printf("Loaded mapping desc=%s id=%s\n",
287 formatConsoleField(list.Description),
288 list.ID,
289 )
Akronae3ffde2025-06-05 14:04:06 +0200290 }
291
Akrona8a66ce2025-06-05 10:50:17 +0200292 if err := app.Listen(fmt.Sprintf(":%d", finalPort)); err != nil {
Akron49ceeb42025-05-23 17:46:01 +0200293 log.Fatal().Err(err).Msg("Server error")
294 }
295 }()
296
297 // Wait for interrupt signal
298 sigChan := make(chan os.Signal, 1)
299 signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
300 <-sigChan
301
302 // Graceful shutdown
303 log.Info().Msg("Shutting down server")
304 if err := app.Shutdown(); err != nil {
305 log.Error().Err(err).Msg("Error during shutdown")
306 }
307}
308
Akron06d21f02025-06-04 14:36:07 +0200309func setupRoutes(app *fiber.App, m *mapper.Mapper, yamlConfig *config.MappingConfig) {
Akrond8a76b32026-02-20 09:31:56 +0100310 configTmpl := template.Must(template.ParseFS(staticFS, "static/config.html"))
Akronbeee5052026-05-20 09:39:45 +0200311 pluginTmpl := template.Must(template.ParseFS(staticFS, "static/plugin.html"))
Akrond8a76b32026-02-20 09:31:56 +0100312
Akrone6767de2026-05-20 10:06:24 +0200313 // Security headers middleware to mitigate MIME-sniffing and referrer
314 // information leaks (OWASP Secure Headers). X-Frame-Options is
315 // intentionally omitted because the service is designed to be embedded
316 // in cross-origin iframes (Kalamar plugin).
317 app.Use(func(c *fiber.Ctx) error {
318 c.Set("X-Content-Type-Options", "nosniff")
319 c.Set("Referrer-Policy", "strict-origin-when-cross-origin")
320 return c.Next()
321 })
322
323 // Rate limiting middleware to prevent resource exhaustion from
324 // request floods. The maximum number of requests per minute
325 // per IP is configurable via the "rateLimit" YAML key or the
326 // KORAL_MAPPER_RATE_LIMIT environment variable (default: 100).
327 rateLimit := yamlConfig.RateLimit
328 if rateLimit <= 0 {
329 rateLimit = 100
330 }
331 app.Use(limiter.New(limiter.Config{
332 Max: rateLimit,
333 Expiration: 1 * time.Minute,
334 LimiterMiddleware: limiter.SlidingWindow{},
335 }))
336
Akron49ceeb42025-05-23 17:46:01 +0200337 // Health check endpoint
338 app.Get("/health", func(c *fiber.Ctx) error {
339 return c.SendString("OK")
340 })
341
Akrond8a76b32026-02-20 09:31:56 +0100342 // Static file serving from embedded FS
343 app.Get("/static/*", handleStaticFile())
344
Akronbf73a122026-02-27 15:02:16 +0100345 // Composite cascade transformation endpoints (cfg in path)
346 app.Post("/query/:cfg", handleCompositeQueryTransform(m, yamlConfig.Lists))
347 app.Post("/response/:cfg", handleCompositeResponseTransform(m, yamlConfig.Lists))
Akron512aab62026-02-20 08:36:12 +0100348
Akron49ceeb42025-05-23 17:46:01 +0200349 // Transformation endpoint
Akron8414ae52026-05-19 13:31:14 +0200350 app.Post("/:map/query", handleTransform(m, yamlConfig.Lists))
Akron40aaa632025-06-03 17:57:52 +0200351
Akron4de47a92025-06-27 11:58:11 +0200352 // Response transformation endpoint
Akron8414ae52026-05-19 13:31:14 +0200353 app.Post("/:map/response", handleResponseTransform(m, yamlConfig.Lists))
Akron4de47a92025-06-27 11:58:11 +0200354
Akron40aaa632025-06-03 17:57:52 +0200355 // Kalamar plugin endpoint
Akrond8a76b32026-02-20 09:31:56 +0100356 app.Get("/", handleKalamarPlugin(yamlConfig, configTmpl, pluginTmpl))
357 app.Get("/:map", handleKalamarPlugin(yamlConfig, configTmpl, pluginTmpl))
358}
359
360func handleStaticFile() fiber.Handler {
361 return func(c *fiber.Ctx) error {
362 name := c.Params("*")
363 data, err := fs.ReadFile(staticFS, "static/"+name)
364 if err != nil {
365 return c.Status(fiber.StatusNotFound).SendString("not found")
366 }
367 switch {
368 case strings.HasSuffix(name, ".js"):
369 c.Set("Content-Type", "text/javascript; charset=utf-8")
370 case strings.HasSuffix(name, ".css"):
371 c.Set("Content-Type", "text/css; charset=utf-8")
372 case strings.HasSuffix(name, ".html"):
373 c.Set("Content-Type", "text/html; charset=utf-8")
374 }
375 return c.Send(data)
376 }
377}
378
379func buildBasePageData(yamlConfig *config.MappingConfig) BasePageData {
380 return BasePageData{
381 Title: config.Title,
382 Version: config.Version,
383 Hash: config.Buildhash,
384 Date: config.Buildtime,
385 Description: config.Description,
386 Server: yamlConfig.Server,
387 SDK: yamlConfig.SDK,
Akron43fb1022026-02-20 11:38:49 +0100388 Stylesheet: yamlConfig.Stylesheet,
Akrond8a76b32026-02-20 09:31:56 +0100389 ServiceURL: yamlConfig.ServiceURL,
Akron43fb1022026-02-20 11:38:49 +0100390 CookieName: yamlConfig.CookieName,
Akrond8a76b32026-02-20 09:31:56 +0100391 }
392}
393
394func buildConfigPageData(yamlConfig *config.MappingConfig) ConfigPageData {
395 data := ConfigPageData{
396 BasePageData: buildBasePageData(yamlConfig),
397 }
398
399 for _, list := range yamlConfig.Lists {
400 normalized := list
401 if normalized.Type == "" {
402 normalized.Type = "annotation"
403 }
404 if list.IsCorpus() {
405 data.CorpusMappings = append(data.CorpusMappings, normalized)
406 } else {
407 data.AnnotationMappings = append(data.AnnotationMappings, normalized)
408 }
409 }
Akron247a93a2026-02-20 16:28:40 +0100410
411 data.MappingSections = []MappingSectionData{
412 {
Akron8bdf5202026-02-24 10:01:15 +0100413 Title: "Request",
414 Mode: "request",
415 CheckboxClass: "request-cb",
416 CheckboxName: "request",
417 FieldsClass: "request-fields",
418 ArrowClass: "request-dir-arrow",
419 ArrowDirection: "atob",
420 ArrowLabel: "\u2192",
Akron247a93a2026-02-20 16:28:40 +0100421 },
422 {
Akron8bdf5202026-02-24 10:01:15 +0100423 Title: "Response",
424 Mode: "response",
425 CheckboxClass: "response-cb",
426 CheckboxName: "response",
427 FieldsClass: "response-fields",
428 ArrowClass: "response-dir-arrow",
429 ArrowDirection: "btoa",
430 ArrowLabel: "\u2190",
Akron247a93a2026-02-20 16:28:40 +0100431 },
432 }
433
Akrond8a76b32026-02-20 09:31:56 +0100434 return data
Akron49ceeb42025-05-23 17:46:01 +0200435}
436
Akron512aab62026-02-20 08:36:12 +0100437func handleCompositeQueryTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler {
Akron8414ae52026-05-19 13:31:14 +0200438 listsByID := make(map[string]*config.MappingList, len(lists))
439 for i := range lists {
440 listsByID[lists[i].ID] = &lists[i]
441 }
442
Akron512aab62026-02-20 08:36:12 +0100443 return func(c *fiber.Ctx) error {
Akronbf73a122026-02-27 15:02:16 +0100444 cfgRaw := c.Params("cfg")
Akron512aab62026-02-20 08:36:12 +0100445 if len(cfgRaw) > maxParamLength {
446 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
447 "error": fmt.Sprintf("cfg too long (max %d bytes)", maxParamLength),
448 })
449 }
450
451 var jsonData any
452 if err := c.BodyParser(&jsonData); err != nil {
453 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
454 "error": "invalid JSON in request body",
455 })
456 }
457
458 entries, err := ParseCfgParam(cfgRaw, lists)
459 if err != nil {
460 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
461 "error": err.Error(),
462 })
463 }
464
465 if len(entries) == 0 {
466 return c.JSON(jsonData)
467 }
468
Akron8414ae52026-05-19 13:31:14 +0200469 rewrites := c.Query("rewrites", "")
470 var rewritesOverride *bool
471 if rewrites != "" {
472 v := rewrites == "true"
473 rewritesOverride = &v
474 }
475
Akron512aab62026-02-20 08:36:12 +0100476 orderedIDs := make([]string, 0, len(entries))
477 opts := make([]mapper.MappingOptions, 0, len(entries))
478 for _, entry := range entries {
479 dir := mapper.AtoB
480 if entry.Direction == "btoa" {
481 dir = mapper.BtoA
482 }
483
Akron8414ae52026-05-19 13:31:14 +0200484 addRewrites := false
485 if list, ok := listsByID[entry.ID]; ok {
486 addRewrites = list.Rewrites
487 }
488 if rewritesOverride != nil {
489 addRewrites = *rewritesOverride
490 }
491
Akron512aab62026-02-20 08:36:12 +0100492 orderedIDs = append(orderedIDs, entry.ID)
493 opts = append(opts, mapper.MappingOptions{
Akron8414ae52026-05-19 13:31:14 +0200494 Direction: dir,
495 FoundryA: entry.FoundryA,
496 LayerA: entry.LayerA,
497 FoundryB: entry.FoundryB,
498 LayerB: entry.LayerB,
499 FieldA: entry.FieldA,
500 FieldB: entry.FieldB,
501 AddRewrites: addRewrites,
Akron512aab62026-02-20 08:36:12 +0100502 })
503 }
504
505 result, err := m.CascadeQueryMappings(orderedIDs, opts, jsonData)
506 if err != nil {
507 log.Error().Err(err).Str("cfg", cfgRaw).Msg("Failed to apply composite query mappings")
508 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
509 "error": err.Error(),
510 })
511 }
512
513 return c.JSON(result)
514 }
515}
516
517func handleCompositeResponseTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler {
Akron8414ae52026-05-19 13:31:14 +0200518 listsByID := make(map[string]*config.MappingList, len(lists))
519 for i := range lists {
520 listsByID[lists[i].ID] = &lists[i]
521 }
522
Akron512aab62026-02-20 08:36:12 +0100523 return func(c *fiber.Ctx) error {
Akronbf73a122026-02-27 15:02:16 +0100524 cfgRaw := c.Params("cfg")
Akron512aab62026-02-20 08:36:12 +0100525 if len(cfgRaw) > maxParamLength {
526 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
527 "error": fmt.Sprintf("cfg too long (max %d bytes)", maxParamLength),
528 })
529 }
530
531 var jsonData any
532 if err := c.BodyParser(&jsonData); err != nil {
533 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
534 "error": "invalid JSON in request body",
535 })
536 }
537
538 entries, err := ParseCfgParam(cfgRaw, lists)
539 if err != nil {
540 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
541 "error": err.Error(),
542 })
543 }
544
545 if len(entries) == 0 {
546 return c.JSON(jsonData)
547 }
548
Akron8414ae52026-05-19 13:31:14 +0200549 rewrites := c.Query("rewrites", "")
550 var rewritesOverride *bool
551 if rewrites != "" {
552 v := rewrites == "true"
553 rewritesOverride = &v
554 }
555
Akron512aab62026-02-20 08:36:12 +0100556 orderedIDs := make([]string, 0, len(entries))
557 opts := make([]mapper.MappingOptions, 0, len(entries))
558 for _, entry := range entries {
559 dir := mapper.AtoB
560 if entry.Direction == "btoa" {
561 dir = mapper.BtoA
562 }
563
Akron8414ae52026-05-19 13:31:14 +0200564 addRewrites := false
565 if list, ok := listsByID[entry.ID]; ok {
566 addRewrites = list.Rewrites
567 }
568 if rewritesOverride != nil {
569 addRewrites = *rewritesOverride
570 }
571
Akron512aab62026-02-20 08:36:12 +0100572 orderedIDs = append(orderedIDs, entry.ID)
573 opts = append(opts, mapper.MappingOptions{
Akron8414ae52026-05-19 13:31:14 +0200574 Direction: dir,
575 FoundryA: entry.FoundryA,
576 LayerA: entry.LayerA,
577 FoundryB: entry.FoundryB,
578 LayerB: entry.LayerB,
579 FieldA: entry.FieldA,
580 FieldB: entry.FieldB,
581 AddRewrites: addRewrites,
Akron512aab62026-02-20 08:36:12 +0100582 })
583 }
584
585 result, err := m.CascadeResponseMappings(orderedIDs, opts, jsonData)
586 if err != nil {
587 log.Error().Err(err).Str("cfg", cfgRaw).Msg("Failed to apply composite response mappings")
588 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
589 "error": err.Error(),
590 })
591 }
592
593 return c.JSON(result)
594 }
595}
596
Akron8414ae52026-05-19 13:31:14 +0200597func handleTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler {
598 listsByID := make(map[string]*config.MappingList, len(lists))
599 for i := range lists {
600 listsByID[lists[i].ID] = &lists[i]
601 }
602
Akron49ceeb42025-05-23 17:46:01 +0200603 return func(c *fiber.Ctx) error {
Akron49b525c2025-07-03 15:17:06 +0200604 // Extract and validate parameters
605 params, err := extractRequestParams(c)
606 if err != nil {
Akron74e1c072025-05-26 14:38:25 +0200607 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
608 "error": err.Error(),
609 })
610 }
611
Akron49ceeb42025-05-23 17:46:01 +0200612 // Parse request body
Akron49b525c2025-07-03 15:17:06 +0200613 jsonData, direction, err := parseRequestBody(c, params.Dir)
Akrona1a183f2025-05-26 17:47:33 +0200614 if err != nil {
615 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
616 "error": err.Error(),
617 })
618 }
619
Akron8414ae52026-05-19 13:31:14 +0200620 // Determine rewrites: query param overrides YAML default
621 addRewrites := false
622 if list, ok := listsByID[params.MapID]; ok {
623 addRewrites = list.Rewrites
624 }
625 if params.Rewrites != nil {
626 addRewrites = *params.Rewrites
627 }
628
Akron49ceeb42025-05-23 17:46:01 +0200629 // Apply mappings
Akron49b525c2025-07-03 15:17:06 +0200630 result, err := m.ApplyQueryMappings(params.MapID, mapper.MappingOptions{
Akron8414ae52026-05-19 13:31:14 +0200631 Direction: direction,
632 FoundryA: params.FoundryA,
633 FoundryB: params.FoundryB,
634 LayerA: params.LayerA,
635 LayerB: params.LayerB,
636 AddRewrites: addRewrites,
Akron49ceeb42025-05-23 17:46:01 +0200637 }, jsonData)
638
639 if err != nil {
640 log.Error().Err(err).
Akron49b525c2025-07-03 15:17:06 +0200641 Str("mapID", params.MapID).
642 Str("direction", params.Dir).
Akron49ceeb42025-05-23 17:46:01 +0200643 Msg("Failed to apply mappings")
644
645 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
646 "error": err.Error(),
647 })
648 }
649
650 return c.JSON(result)
651 }
652}
Akron74e1c072025-05-26 14:38:25 +0200653
Akron8414ae52026-05-19 13:31:14 +0200654func handleResponseTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler {
655 listsByID := make(map[string]*config.MappingList, len(lists))
656 for i := range lists {
657 listsByID[lists[i].ID] = &lists[i]
658 }
659
Akron4de47a92025-06-27 11:58:11 +0200660 return func(c *fiber.Ctx) error {
Akron49b525c2025-07-03 15:17:06 +0200661 // Extract and validate parameters
662 params, err := extractRequestParams(c)
663 if err != nil {
Akron4de47a92025-06-27 11:58:11 +0200664 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
665 "error": err.Error(),
666 })
667 }
668
Akron4de47a92025-06-27 11:58:11 +0200669 // Parse request body
Akron49b525c2025-07-03 15:17:06 +0200670 jsonData, direction, err := parseRequestBody(c, params.Dir)
Akron4de47a92025-06-27 11:58:11 +0200671 if err != nil {
672 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
673 "error": err.Error(),
674 })
675 }
676
Akron8414ae52026-05-19 13:31:14 +0200677 // Determine rewrites: query param overrides YAML default
678 addRewrites := false
679 if list, ok := listsByID[params.MapID]; ok {
680 addRewrites = list.Rewrites
681 }
682 if params.Rewrites != nil {
683 addRewrites = *params.Rewrites
684 }
685
Akron4de47a92025-06-27 11:58:11 +0200686 // Apply response mappings
Akron49b525c2025-07-03 15:17:06 +0200687 result, err := m.ApplyResponseMappings(params.MapID, mapper.MappingOptions{
Akron8414ae52026-05-19 13:31:14 +0200688 Direction: direction,
689 FoundryA: params.FoundryA,
690 FoundryB: params.FoundryB,
691 LayerA: params.LayerA,
692 LayerB: params.LayerB,
693 AddRewrites: addRewrites,
Akron4de47a92025-06-27 11:58:11 +0200694 }, jsonData)
695
696 if err != nil {
697 log.Error().Err(err).
Akron49b525c2025-07-03 15:17:06 +0200698 Str("mapID", params.MapID).
699 Str("direction", params.Dir).
Akron4de47a92025-06-27 11:58:11 +0200700 Msg("Failed to apply response mappings")
701
702 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
703 "error": err.Error(),
704 })
705 }
706
707 return c.JSON(result)
708 }
709}
710
Akron74e1c072025-05-26 14:38:25 +0200711// validateInput checks if the input parameters are valid
712func validateInput(mapID, dir, foundryA, foundryB, layerA, layerB string, body []byte) error {
Akron69d43bf2025-05-26 17:09:00 +0200713 // Define parameter checks
714 params := []struct {
Akron74e1c072025-05-26 14:38:25 +0200715 name string
716 value string
717 }{
718 {"mapID", mapID},
719 {"dir", dir},
720 {"foundryA", foundryA},
721 {"foundryB", foundryB},
722 {"layerA", layerA},
723 {"layerB", layerB},
Akron69d43bf2025-05-26 17:09:00 +0200724 }
725
726 for _, param := range params {
Akron49b525c2025-07-03 15:17:06 +0200727 // Check input lengths and invalid characters in one combined condition
Akron69d43bf2025-05-26 17:09:00 +0200728 if len(param.value) > maxParamLength {
729 return fmt.Errorf("%s too long (max %d bytes)", param.name, maxParamLength)
730 }
Akron74e1c072025-05-26 14:38:25 +0200731 if strings.ContainsAny(param.value, "<>{}[]\\") {
732 return fmt.Errorf("%s contains invalid characters", param.name)
733 }
734 }
735
Akron69d43bf2025-05-26 17:09:00 +0200736 if len(body) > maxInputLength {
737 return fmt.Errorf("request body too large (max %d bytes)", maxInputLength)
738 }
739
Akron74e1c072025-05-26 14:38:25 +0200740 return nil
741}
Akron40aaa632025-06-03 17:57:52 +0200742
Akronbeee5052026-05-20 09:39:45 +0200743func handleKalamarPlugin(yamlConfig *config.MappingConfig, configTmpl *template.Template, pluginTmpl *template.Template) fiber.Handler {
Akron40aaa632025-06-03 17:57:52 +0200744 return func(c *fiber.Ctx) error {
Akronc376dcc2025-06-04 17:00:18 +0200745 mapID := c.Params("map")
746
Akrond8a76b32026-02-20 09:31:56 +0100747 // Config page (GET /)
748 if mapID == "" {
749 data := buildConfigPageData(yamlConfig)
750 var buf bytes.Buffer
751 if err := configTmpl.Execute(&buf, data); err != nil {
752 log.Error().Err(err).Msg("Failed to execute config template")
753 return c.Status(fiber.StatusInternalServerError).SendString("internal error")
754 }
755 c.Set("Content-Type", "text/html")
756 return c.Send(buf.Bytes())
757 }
758
759 // Single-mapping page (GET /:map) — existing behavior
Akroncb51f812025-06-30 15:24:20 +0200760 // Get query parameters
761 dir := c.Query("dir", "atob")
762 foundryA := c.Query("foundryA", "")
763 foundryB := c.Query("foundryB", "")
764 layerA := c.Query("layerA", "")
765 layerB := c.Query("layerB", "")
766
Akron49b525c2025-07-03 15:17:06 +0200767 // Validate input parameters and direction in one step
Akroncb51f812025-06-30 15:24:20 +0200768 if err := validateInput(mapID, dir, foundryA, foundryB, layerA, layerB, []byte{}); err != nil {
769 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
770 "error": err.Error(),
771 })
772 }
773
Akroncb51f812025-06-30 15:24:20 +0200774 if dir != "atob" && dir != "btoa" {
775 return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
776 "error": "invalid direction, must be 'atob' or 'btoa'",
777 })
778 }
779
Akroncb51f812025-06-30 15:24:20 +0200780 queryParams := QueryParams{
781 Dir: dir,
782 FoundryA: foundryA,
783 FoundryB: foundryB,
784 LayerA: layerA,
785 LayerB: layerB,
786 }
787
Akrond8a76b32026-02-20 09:31:56 +0100788 queryURL, err := buildMapServiceURL(yamlConfig.ServiceURL, mapID, "query", queryParams)
789 if err != nil {
790 log.Warn().Err(err).Msg("Failed to build query service URL")
791 return c.Status(fiber.StatusInternalServerError).SendString("internal error")
792 }
793 reversed := queryParams
794 if queryParams.Dir == "btoa" {
795 reversed.Dir = "atob"
796 } else {
797 reversed.Dir = "btoa"
798 }
799 responseURL, err := buildMapServiceURL(yamlConfig.ServiceURL, mapID, "response", reversed)
800 if err != nil {
801 log.Warn().Err(err).Msg("Failed to build response service URL")
802 return c.Status(fiber.StatusInternalServerError).SendString("internal error")
803 }
Akron40aaa632025-06-03 17:57:52 +0200804
Akrond8a76b32026-02-20 09:31:56 +0100805 data := SingleMappingPageData{
806 BasePageData: buildBasePageData(yamlConfig),
807 MapID: mapID,
808 Mappings: yamlConfig.Lists,
809 QueryURL: queryURL,
810 ResponseURL: responseURL,
811 }
812
813 var buf bytes.Buffer
814 if err := pluginTmpl.Execute(&buf, data); err != nil {
815 log.Error().Err(err).Msg("Failed to execute plugin template")
816 return c.Status(fiber.StatusInternalServerError).SendString("internal error")
817 }
Akron40aaa632025-06-03 17:57:52 +0200818 c.Set("Content-Type", "text/html")
Akrond8a76b32026-02-20 09:31:56 +0100819 return c.Send(buf.Bytes())
Akron40aaa632025-06-03 17:57:52 +0200820 }
821}
822
Akrond8a76b32026-02-20 09:31:56 +0100823func buildMapServiceURL(serviceURL, mapID, endpoint string, params QueryParams) (string, error) {
824 service, err := url.Parse(serviceURL)
825 if err != nil {
826 return "", err
Akronc376dcc2025-06-04 17:00:18 +0200827 }
Akrond8a76b32026-02-20 09:31:56 +0100828 service.Path = path.Join(service.Path, mapID, endpoint)
829 service.RawQuery = buildQueryParams(params.Dir, params.FoundryA, params.FoundryB, params.LayerA, params.LayerB)
830 return service.String(), nil
831}
Akronc376dcc2025-06-04 17:00:18 +0200832
Akrond8a76b32026-02-20 09:31:56 +0100833func formatConsoleField(value string) string {
834 if strings.ContainsAny(value, " \t") {
835 return strconv.Quote(value)
Akron40aaa632025-06-03 17:57:52 +0200836 }
Akrond8a76b32026-02-20 09:31:56 +0100837 return value
Akron40aaa632025-06-03 17:57:52 +0200838}
Akron14678dc2025-06-05 13:01:38 +0200839
Akroncb51f812025-06-30 15:24:20 +0200840// buildQueryParams builds a query string from the provided parameters
841func buildQueryParams(dir, foundryA, foundryB, layerA, layerB string) string {
842 params := url.Values{}
843 if dir != "" {
844 params.Add("dir", dir)
845 }
846 if foundryA != "" {
847 params.Add("foundryA", foundryA)
848 }
849 if foundryB != "" {
850 params.Add("foundryB", foundryB)
851 }
852 if layerA != "" {
853 params.Add("layerA", layerA)
854 }
855 if layerB != "" {
856 params.Add("layerB", layerB)
857 }
858 return params.Encode()
859}
860
Akron14678dc2025-06-05 13:01:38 +0200861// expandGlobs expands glob patterns in the slice of file paths
862// Returns the expanded list of files or an error if glob expansion fails
863func expandGlobs(patterns []string) ([]string, error) {
864 var expanded []string
865
866 for _, pattern := range patterns {
867 // Use filepath.Glob which works cross-platform
868 matches, err := filepath.Glob(pattern)
869 if err != nil {
870 return nil, fmt.Errorf("failed to expand glob pattern '%s': %w", pattern, err)
871 }
872
873 // If no matches found, treat as literal filename (consistent with shell behavior)
874 if len(matches) == 0 {
875 log.Warn().Str("pattern", pattern).Msg("Glob pattern matched no files, treating as literal filename")
876 expanded = append(expanded, pattern)
877 } else {
878 expanded = append(expanded, matches...)
879 }
880 }
881
882 return expanded, nil
883}