LCOV - code coverage report
Current view: top level - matchscore - routes.clj Coverage Total Hit
Test: lcov.info Lines: 76.6 % 492 377
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.routes
       2              :   (:require
       3              :    [bidi.ring :as bidi-ring]
       4              :    [clojure.data.json :as json]
       5              :    [clojure.java.io]
       6              :    [clojure.string]
       7              :    [goose.console :as goose-console]
       8              :    [matchscore.access.middleware :as access-middleware]
       9              :    [matchscore.api.account :as account-handlers]
      10              :    [matchscore.api.admin :as admin-handlers]
      11              :    [matchscore.api.admin-telegram :as admin-telegram-handlers]
      12              :    [matchscore.api.advancement-rules :as adv-rule-handlers]
      13              :    [matchscore.api.auth-telegram :as auth-telegram-handlers]
      14              :    [matchscore.api.banks :as bank-handlers]
      15              :    [matchscore.api.brackets :as brackets-handlers]
      16              :    [matchscore.api.class-templates :as class-templates-handlers]
      17              :    [matchscore.api.clubs :as clubs-handlers]
      18              :    [matchscore.api.draws :as draws-handlers]
      19              :    [matchscore.api.event-classes :as event-classes-handlers]
      20              :    [matchscore.api.event-creation-access :as event-creation-access-handlers]
      21              :    [matchscore.api.events :as events-handlers]
      22              :    [matchscore.api.graphql :as graphql-handlers]
      23              :    [matchscore.api.groups :as groups-handlers]
      24              :    [matchscore.api.health :as health-handlers]
      25              :    [matchscore.api.hosts :as hosts-handlers]
      26              :    [matchscore.api.media :as media-handlers]
      27              :    [matchscore.api.name-reminders :as name-reminder-handlers]
      28              :    [matchscore.api.payment-methods :as payment-method-handlers]
      29              :    [matchscore.api.player-follows :as player-follows-handlers]
      30              :    [matchscore.api.presence :as presence-handlers]
      31              :    [matchscore.api.resources :as resources-handlers]
      32              :    [matchscore.api.scoreboard :as scoreboard-handlers]
      33              :    [matchscore.api.stages :as stages-handlers]
      34              :    [matchscore.api.telegram-links :as telegram-links-handlers]
      35              :    [matchscore.api.telegram-notifications :as telegram-notifications-handlers]
      36              :    [matchscore.api.telegram-webhook :as telegram-handlers]
      37              :    [matchscore.api.templates :as templates-handlers]
      38              :    [matchscore.api.updates :as updates-handlers]
      39              :    [matchscore.utils.otel :as otel]
      40              :    [matchscore.utils.ring.case-transformers :as utils-ring-case-transformers]
      41              :    [matchscore.utils.ring.middleware :as utils-ring-middleware]
      42              :    [matchscore.utils.swagger :as swagger]
      43              :    [ring.middleware.content-type :as content-type]
      44              :    [ring.middleware.cookies :as cookies]
      45              :    [ring.middleware.cors :as cors]
      46              :    [ring.middleware.json :as middleware-json]
      47              :    [ring.middleware.keyword-params :as keyword-params]
      48              :    [ring.middleware.params :as params]
      49              :    [ring.middleware.resource :as resource]
      50              :    [ring.util.response :as res]
      51              :    [sentry-clj.core :as sentry]
      52              :    [taoensso.sente.server-adapters.community.jetty :as sente-jetty]
      53              :    [taoensso.telemere :as t]
      54              :    [taoensso.truss :as truss]))
      55              : 
      56              : 
      57            8 : (def ^:private dev-cookie-name "dev-auth")
      58              : 
      59              : 
      60              : ;; 30 days in seconds
      61           32 : (def ^:private dev-cookie-max-age (* 30 24 60 60))
      62              : 
      63              : 
      64            4 : (defn- dev-authorized?
      65              :   "Checks if the request is authorized to access dev tools.
      66              :   In dev env, always authorized. Otherwise checks for a valid
      67              :   dev-auth cookie or tg_id query param against allowed telegram IDs."
      68              :   [config request]
      69            4 :   (let [env          (:env config)
      70            3 :         allowed-ids  (:dev-telegram-ids config)
      71            9 :         cookie-tg-id (some->
      72            7 :                        (get-in request [:cookies dev-cookie-name :value])
      73            1 :                        parse-long)
      74            9 :         query-tg-id  (some->
      75            6 :                        (get-in request [:params "tg_id"])
      76            1 :                        parse-long)]
      77            7 :     (cond (= env "development")
      78            5 :           {:authorized? true
      79              :            :source      :dev-env}
      80              : 
      81            9 :           (and cookie-tg-id (contains? allowed-ids cookie-tg-id))
      82            5 :           {:authorized? true
      83              :            :source      :cookie}
      84              : 
      85            9 :           (and query-tg-id (contains? allowed-ids query-tg-id))
      86            6 :           {:authorized? true
      87              :            :source      :query-param
      88            1 :            :tg-id       query-tg-id}
      89              : 
      90            3 :           :else {:authorized? false})))
      91              : 
      92              : 
      93            4 : (defn- wrap-dev-auth
      94              :   "Wraps a handler with dev tool authorization.
      95              :   Sets a cookie when authorized via query param for convenience."
      96              :   [handler config]
      97            1 :   (fn [request]
      98            5 :    (let [{:keys [authorized? source tg-id]} (dev-authorized? config request)]
      99            4 :      (if-not authorized?
     100            2 :        (->
     101            3 :          (res/response "Not Found")
     102            3 :          (res/status 404)
     103            1 :          (res/content-type "text/plain"))
     104            4 :        (let [response (handler request)]
     105            4 :          (if (= source :query-param)
     106            3 :            (assoc-in response
     107            3 :             [:cookies dev-cookie-name]
     108           10 :             {:value     (str tg-id)
     109            1 :              :max-age   dev-cookie-max-age
     110              :              :path      "/"
     111              :              :same-site :lax})
     112            1 :            response))))))
     113              : 
     114              : 
     115              : ;; Serve index.html with explicit Content-Type
     116            4 : (defn index-handler
     117              :  [request]
     118            0 :  (t/log! :debug (str "Serving index.html for URI:" (:uri request)))
     119            0 :  (let [response (res/file-response "index.html" {:root "resources/public"})]
     120            0 :    (if response
     121            0 :      (assoc-in response [:headers "Content-Type"] "text/html")
     122            0 :      {:status 404
     123              :       :body   "index.html not found"})))
     124              : 
     125              : 
     126              : ;; Handle /__source_changed explicitly
     127            4 : (defn source-changed-handler
     128              :  [_request]
     129            0 :  (t/log! :debug "Ignoring /__source_changed request")
     130            0 :  {:status 404
     131              :   :body   "Source changed endpoint not supported"})
     132              : 
     133              : 
     134              : ;; Swagger UI handler
     135            4 : (defn swagger-ui-handler
     136              :  "Serves Swagger UI HTML page with auth token injected from config.
     137              :   Access controlled by wrap-dev-auth."
     138              :  [config]
     139            0 :  (fn [request]
     140            0 :   (t/log! :debug (str "Serving swagger.html for URI:" (:uri request)))
     141            0 :   (let [init-data (get-in config [:dev-auth :telegram-init-data] "")
     142            0 :         html      (->
     143            0 :                     (slurp (clojure.java.io/resource "public/swagger.html"))
     144            0 :                     (clojure.string/replace "{{TELEGRAM_INIT_DATA}}" init-data))]
     145            0 :     (->
     146            0 :       (res/response html)
     147            0 :       (res/content-type "text/html")
     148            0 :       (assoc-in [:headers "Cache-Control"] "no-store, no-cache, must-revalidate, max-age=0")
     149            0 :       (assoc-in [:headers "Pragma"] "no-cache")
     150            0 :       (assoc-in [:headers "Expires"] "0")))))
     151              : 
     152              : 
     153              : ;; GraphiQL handler
     154            4 : (defn graphiql-handler
     155              :  "Serves GraphiQL HTML page with auth token injected from config.
     156              :   Access controlled by wrap-dev-auth."
     157              :  [config]
     158            0 :  (fn [_request]
     159            0 :   (let [init-data (get-in config [:dev-auth :telegram-init-data] "")
     160            0 :         html      (->
     161            0 :                     (slurp (clojure.java.io/resource "public/graphiql.html"))
     162            0 :                     (clojure.string/replace "{{TELEGRAM_INIT_DATA}}" init-data))]
     163            0 :     (->
     164            0 :       (res/response html)
     165            0 :       (res/content-type "text/html")
     166            0 :       (assoc-in [:headers "Cache-Control"] "no-store, no-cache, must-revalidate, max-age=0")
     167            0 :       (assoc-in [:headers "Pragma"] "no-cache")
     168            0 :       (assoc-in [:headers "Expires"] "0")))))
     169              : 
     170              : 
     171              : ;; Helper to wrap all handlers in a route structure with middleware
     172            4 : (defn wrap-handlers-in-routes
     173              :  "Recursively walks through bidi route structure and wraps each handler function
     174              :    with extract-schema-from-meta (param/body validation) and then with
     175              :    wrap-authorize-with-meta (RBAC + ABAC enforcement) so the access check
     176              :    runs *before* schema decoding fires its handler invocation but *after*
     177              :    :auth-headers / :ctx are populated by the outer middleware stack. Every
     178              :    handler also runs with the authenticated user as the audit actor."
     179              :  [routes config]
     180           20 :  (cond
     181              :    ;; If it's a function (handler), wrap it (no :authz metadata possible on a bare fn).
     182           12 :    (fn? routes)
     183            2 :    (utils-ring-middleware/wrap-audit-actor
     184            4 :     (utils-ring-middleware/extract-schema-from-meta routes config))
     185              : 
     186              :    ;; If it's a var (like #'handler), wrap it with schema *and* authz.
     187           12 :    (var? routes)
     188           16 :    (let [authz-meta     (access-middleware/extract-authz-meta routes)
     189           16 :          schema-wrapped (utils-ring-middleware/extract-schema-from-meta routes config)
     190           16 :          authz-wrapped  (access-middleware/wrap-authorize-with-meta schema-wrapped authz-meta)
     191           12 :          entity-wrapped (access-middleware/wrap-resolve-entity-ids authz-wrapped)]
     192            8 :      (utils-ring-middleware/wrap-audit-actor
     193           12 :       (utils-ring-middleware/wrap-route-otel-attrs entity-wrapped)))
     194              : 
     195              :    ;; If it's a map, recursively process values
     196           12 :    (map? routes)
     197            8 :    (into
     198            4 :     {}
     199            8 :     (map
     200            4 :      (fn [[k v]]
     201           24 :       [k (wrap-handlers-in-routes v config)])
     202            4 :      routes))
     203              : 
     204              :    ;; If it's a vector, recursively process elements
     205           44 :    (vector? routes) (mapv #(wrap-handlers-in-routes % config) routes)
     206              : 
     207              :    ;; Otherwise return as-is (strings, keywords, etc.)
     208            4 :    :else routes))
     209              : 
     210              : 
     211              : ;; Bidi routes combining API and non-API
     212            4 : (defn make-api-routes-raw
     213              :  "Returns raw API routes without middleware wrapping (for OpenAPI spec generation)"
     214              :  [config]
     215           28 :  (let [webhook-url-prefix (get-in config [:telegram :webhook-url-prefix])
     216              :        base-routes
     217           92 :        {"/healthcheck" {:get #'health-handlers/health-handler}
     218           12 :         "/sentry-test" {:get #'health-handlers/sentry-test-handler}
     219           12 :         "/banks" {:get #'bank-handlers/banks-list-handler}
     220              :         "/account"
     221           40 :         {"" {:post #'account-handlers/account-create-handler
     222              :              :put  #'account-handlers/account-update-handler}
     223           12 :          "/telegram-bot-access" {:post #'name-reminder-handlers/account-telegram-bot-access-handler}
     224           28 :          "/payment-methods" {"" {:get  #'payment-method-handlers/payment-methods-list-handler
     225              :                                  :post #'payment-method-handlers/payment-methods-create-handler}
     226           12 :                              ["/" :payment-method-uuid]
     227           20 :                              {:put    #'payment-method-handlers/payment-methods-update-handler
     228              :                               :delete #'payment-method-handlers/payment-methods-delete-handler}}
     229           12 :          "/payment-method-order" {:put #'payment-method-handlers/payment-method-order-handler}}
     230           28 :         "/event-creation-access" {"" {:get #'event-creation-access-handlers/current-request-handler
     231              :                                       :post
     232              :                                       #'event-creation-access-handlers/create-request-handler}}
     233           12 :         "/updates" {:get #'updates-handlers/updates-handler}
     234           32 :         "/auth" {"/telegram" {""        {:post #'auth-telegram-handlers/telegram-login-handler}
     235           12 :                               "/logout" {:post #'auth-telegram-handlers/telegram-logout-handler}}}
     236           64 :         "/admin" {"/roles" {:get  #'admin-handlers/admin-roles-list-handler
     237              :                             :post #'admin-handlers/admin-roles-create-handler}
     238           32 :                   ["/roles/" :role-name] {:patch  #'admin-handlers/admin-roles-update-handler
     239              :                                           :delete #'admin-handlers/admin-roles-delete-handler}
     240           12 :                   "/users" {:get #'admin-handlers/admin-users-list-handler}
     241           32 :                   ["/users/" :user-uuid] {:get   #'admin-handlers/admin-user-handler
     242              :                                           :patch #'admin-handlers/admin-user-update-handler}
     243           28 :                   ["/users/" :user-uuid "/roles"] {:patch
     244              :                                                    #'admin-handlers/admin-user-roles-update-handler}
     245           16 :                   ["/users/" :user-uuid "/name-locks"]
     246           12 :                   {:put #'admin-handlers/admin-user-name-locks-update-handler}
     247           28 :                   "/policies" {:get    #'admin-handlers/admin-policies-list-handler
     248              :                                :post   #'admin-handlers/admin-policies-create-handler
     249              :                                :delete #'admin-handlers/admin-policies-delete-handler}
     250           12 :                   "/cache/clear" {:post #'admin-handlers/admin-cache-clear-handler}
     251              :                   "/telegram/posts"
     252           28 :                   {"/candidates" {:get #'admin-telegram-handlers/admin-telegram-candidates-handler}
     253           16 :                    ["/candidates/" :candidate-uuid "/archive"]
     254           12 :                    {:post #'admin-telegram-handlers/admin-telegram-archive-candidate-handler}
     255           12 :                    "/preview"    {:post #'admin-telegram-handlers/admin-telegram-preview-handler}
     256           12 :                    "/publish"    {:post #'admin-telegram-handlers/admin-telegram-publish-handler}}
     257           12 :                   "/telegram/links" {:get #'telegram-links-handlers/admin-telegram-links-handler}
     258           12 :                   "/events" {:get #'admin-handlers/admin-events-list-handler}
     259           12 :                   "/templates" {:get #'admin-handlers/admin-templates-list-handler}
     260              :                   "/event-creation-access-requests"
     261           20 :                   {"" {:get #'event-creation-access-handlers/admin-list-handler}
     262           16 :                    ["/" :request-uuid "/approve"]
     263           12 :                    {:post #'event-creation-access-handlers/admin-approve-handler}
     264           16 :                    ["/" :request-uuid "/decline"]
     265           12 :                    {:post #'event-creation-access-handlers/admin-decline-handler}}
     266           28 :                   "/clubs" {"" {:get  #'clubs-handlers/clubs-list-handler
     267              :                                 :post #'clubs-handlers/clubs-create-handler}
     268           40 :                             ["/" :club-uuid] {:get    #'clubs-handlers/clubs-get-handler
     269              :                                               :put    #'clubs-handlers/clubs-update-handler
     270              :                                               :delete #'clubs-handlers/clubs-deactivate-handler}
     271           16 :                             ["/" :club-uuid "/resources"]
     272           20 :                             {:get  #'resources-handlers/resources-list-handler
     273              :                              :post #'resources-handlers/resources-create-handler}
     274           20 :                             ["/" :club-uuid "/resources/" :resource-uuid]
     275           28 :                             {:get    #'resources-handlers/resources-get-handler
     276              :                              :put    #'resources-handlers/resources-update-handler
     277              :                              :delete #'resources-handlers/resources-deactivate-handler}}}
     278           12 :         "/graphql" {:post #'graphql-handlers/graphql-handler}
     279           24 :         "/media" {"/config" {:get #'media-handlers/media-config-handler}
     280           20 :                   "/images" {"" {:post #'media-handlers/media-upload-handler}
     281           28 :                              ["/" :asset-id "/focus"] {:put #'media-handlers/media-focus-handler}}}
     282           20 :         "/presence" {"/away" {:post #'presence-handlers/presence-away-handler}}
     283           20 :         "/psa" {["/players/" :player-id "/follow"]
     284           20 :                 {:put    #'player-follows-handlers/psa-player-follow-handler
     285              :                  :delete #'player-follows-handlers/psa-player-unfollow-handler}}
     286           20 :         "/esf" {["/players/" :player-id "/follow"]
     287           20 :                 {:put    #'player-follows-handlers/esf-player-follow-handler
     288              :                  :delete #'player-follows-handlers/esf-player-unfollow-handler}}
     289           16 :         "/telegram-links" {["/template/" :link-uuid]
     290           12 :                            {:delete #'telegram-links-handlers/template-link-delete-handler}
     291           16 :                            ["/template/" :link-uuid "/repost"]
     292           12 :                            {:post #'telegram-links-handlers/template-link-repost-handler}
     293           12 :                            ["/event/" :link-uuid]
     294           12 :                            {:delete #'telegram-links-handlers/event-link-delete-handler}
     295           16 :                            ["/event/" :link-uuid "/repost"]
     296           12 :                            {:post #'telegram-links-handlers/event-link-repost-handler}}
     297              :         "/events"
     298           28 :         {"" {:post #'events-handlers/event-create-handler
     299              :              :put  #'events-handlers/event-update-handler}
     300           24 :          ["/" :event-uuid] {:delete #'events-handlers/event-delete-handler}
     301           28 :          ["/" :event-uuid "/host"] {:put #'hosts-handlers/event-host-handler}
     302           28 :          ["/" :event-uuid "/images"] {:get #'events-handlers/event-images-handler}
     303           28 :          ["/" :event-uuid "/end"] {:post #'events-handlers/event-end-handler}
     304           16 :          ["/" :event-uuid "/payment-methods"]
     305           12 :          {:get #'payment-method-handlers/event-payment-methods-handler}
     306           16 :          ["/" :event-uuid "/payment-details-post"]
     307           12 :          {:post #'payment-method-handlers/event-send-payment-details-handler}
     308           16 :          ["/" :event-uuid "/name-reminder"]
     309           20 :          {:get  #'name-reminder-handlers/event-name-reminder-status-handler
     310              :           :post #'name-reminder-handlers/event-name-reminder-post-handler}
     311           28 :          ["/" :event-uuid "/state"] {:patch #'events-handlers/event-state-update-handler}
     312           28 :          ["/" :event-uuid "/join"] {:post #'events-handlers/event-join-handler}
     313           28 :          ["/" :event-uuid "/leave"] {:delete #'events-handlers/event-leave-handler}
     314           28 :          ["/" :event-uuid "/telegram-invite"] {:post
     315              :                                                #'events-handlers/event-telegram-invite-handler}
     316           16 :          ["/" :event-uuid "/post-participants-job"]
     317           12 :          {:post #'telegram-notifications-handlers/event-post-participants-job-handler}
     318           16 :          ["/" :event-uuid "/post-draws-job"]
     319           12 :          {:post #'telegram-notifications-handlers/event-post-draws-job-handler}
     320           16 :          ["/" :event-uuid "/post-results-job"]
     321           12 :          {:post #'telegram-notifications-handlers/event-post-results-job-handler}
     322           28 :          ["/" :event-uuid "/participants"] {:post #'events-handlers/event-add-participant-handler}
     323           20 :          ["/" :event-uuid "/participants/" :participant-uuid]
     324           20 :          {:delete #'events-handlers/event-remove-participant-handler
     325              :           :put    #'events-handlers/event-update-participant-handler}
     326           36 :          ["/" :event-uuid "/classes"] {:get
     327              :                                        #'event-classes-handlers/event-class-get-by-event-handler
     328              :                                        :post #'event-classes-handlers/event-class-create-handler}
     329           20 :          ["/" :event-uuid "/classes/" :class-uuid]
     330           20 :          {:put    #'event-classes-handlers/event-class-update-handler
     331              :           :delete #'event-classes-handlers/event-class-delete-handler}
     332           24 :          ["/" :event-uuid "/classes/" :class-uuid "/scoreboard"]
     333           12 :          {:get #'scoreboard-handlers/class-scoreboard-get-handler}
     334           24 :          ["/" :event-uuid "/classes/" :class-uuid "/participants"]
     335           12 :          {:post #'event-classes-handlers/event-class-participant-create-handler}
     336           24 :          ["/" :event-uuid "/classes/" :class-uuid "/participants/register-event"]
     337           12 :          {:post #'event-classes-handlers/event-class-participant-create-register-event-handler}
     338           24 :          ["/" :event-uuid "/classes/" :class-uuid "/participants/bulk-from-event"]
     339           12 :          {:post #'event-classes-handlers/event-class-bulk-add-participants-from-event-handler}
     340           28 :          ["/"
     341              :           :event-uuid
     342              :           "/classes/"
     343              :           :class-uuid
     344              :           "/participants/bulk-copy-from/"
     345              :           :source-class-uuid]
     346           12 :          {:post #'event-classes-handlers/event-class-bulk-copy-participants-handler}
     347           28 :          ["/"
     348              :           :event-uuid
     349              :           "/classes/"
     350              :           :class-uuid
     351              :           "/participants/bulk-move-from/"
     352              :           :source-class-uuid]
     353           12 :          {:post #'event-classes-handlers/event-class-bulk-move-participants-handler}
     354           28 :          ["/" :event-uuid "/classes/" :class-uuid "/participants/swap-with/" :other-class-uuid]
     355           12 :          {:post #'event-classes-handlers/event-class-swap-participants-handler}
     356           28 :          ["/" :event-uuid "/classes/" :class-uuid "/participants/" :participant-id]
     357           20 :          {:delete #'event-classes-handlers/event-class-participant-remove-handler
     358              :           :put    #'event-classes-handlers/event-class-participant-update-handler}
     359           32 :          ["/" :event-uuid "/classes/" :class-uuid "/participants/" :participant-id "/payment"]
     360           20 :          {:put    #'event-classes-handlers/event-class-participant-mark-payment-handler
     361              :           :delete #'event-classes-handlers/event-class-participant-revert-payment-handler}}
     362              :         "/templates"
     363           28 :         {"" {:post #'templates-handlers/template-create-handler
     364              :              :put  #'templates-handlers/template-update-handler}
     365           24 :          ["/" :template-uuid] {:delete #'templates-handlers/template-delete-handler}
     366           28 :          ["/" :template-uuid "/host"] {:put #'hosts-handlers/template-host-handler}
     367           28 :          ["/" :template-uuid "/images"] {:get #'templates-handlers/template-images-handler}
     368           28 :          ["/" :template-uuid "/join"] {:post #'templates-handlers/template-join-handler}
     369           16 :          ["/" :template-uuid "/payment-methods"]
     370           12 :          {:get #'payment-method-handlers/template-payment-methods-handler}
     371           28 :          ["/" :template-uuid "/leave"] {:delete #'templates-handlers/template-leave-handler}
     372           16 :          ["/" :template-uuid "/occurrence-exceptions"]
     373           20 :          {:get  #'templates-handlers/template-occurrence-exceptions-handler
     374              :           :post #'templates-handlers/template-occurrence-exception-create-handler}
     375           20 :          ["/" :template-uuid "/occurrence-exceptions/" :exception-uuid]
     376           12 :          {:delete #'templates-handlers/template-occurrence-exception-delete-handler}
     377           16 :          ["/" :template-uuid "/telegram-access"]
     378           12 :          {:post #'templates-handlers/template-telegram-access-handler}
     379           16 :          ["/" :template-uuid "/participants"]
     380           12 :          {:post #'templates-handlers/template-add-participant-handler}
     381           20 :          ["/" :template-uuid "/participants/" :participant-uuid]
     382           20 :          {:delete #'templates-handlers/template-remove-participant-handler
     383              :           :put    #'templates-handlers/template-update-participant-handler}
     384           16 :          ["/" :template-uuid "/post-participants-job"]
     385           12 :          {:post #'telegram-notifications-handlers/template-post-participants-job-handler}
     386           16 :          ["/" :template-uuid "/class-templates"]
     387           20 :          {:get  #'class-templates-handlers/class-template-get-by-template-handler
     388              :           :post #'class-templates-handlers/class-template-create-handler}
     389           20 :          ["/" :template-uuid "/class-templates/" :class-template-uuid]
     390           20 :          {:put    #'class-templates-handlers/class-template-update-handler
     391              :           :delete #'class-templates-handlers/class-template-delete-handler}
     392           28 :          ["/"
     393              :           :template-uuid
     394              :           "/class-templates/"
     395              :           :class-template-uuid
     396              :           "/participants/"
     397              :           :participant-id]
     398           20 :          {:delete #'class-templates-handlers/class-template-participant-remove-handler
     399              :           :put    #'class-templates-handlers/class-template-participant-update-handler}
     400           24 :          ["/"
     401              :           :template-uuid
     402              :           "/class-templates/"
     403              :           :class-template-uuid
     404              :           "/participants/bulk-from-template"]
     405           12 :          {:post
     406              :           #'class-templates-handlers/class-template-bulk-add-participants-from-template-handler}
     407           28 :          ["/"
     408              :           :template-uuid
     409              :           "/class-templates/"
     410              :           :class-template-uuid
     411              :           "/participants/bulk-copy-from/"
     412              :           :source-class-uuid]
     413           12 :          {:post #'class-templates-handlers/class-template-bulk-copy-participants-handler}
     414           28 :          ["/"
     415              :           :template-uuid
     416              :           "/class-templates/"
     417              :           :class-template-uuid
     418              :           "/participants/bulk-move-from/"
     419              :           :source-class-uuid]
     420           12 :          {:post #'class-templates-handlers/class-template-bulk-move-participants-handler}
     421           28 :          ["/"
     422              :           :template-uuid
     423              :           "/class-templates/"
     424              :           :class-template-uuid
     425              :           "/participants/swap-with/"
     426              :           :other-class-uuid]
     427           12 :          {:post #'class-templates-handlers/class-template-swap-participants-handler}}
     428           40 :         "/classes" {["/" :class-uuid "/stages"] {:get  #'stages-handlers/stages-get-by-class-handler
     429              :                                                  :post #'stages-handlers/stages-create-handler}
     430           16 :                     ["/" :class-uuid "/stages/by-template"]
     431           12 :                     {:post #'stages-handlers/stages-create-by-template-handler}
     432           20 :                     ["/" :class-uuid "/stages/" :stage-uuid]
     433           20 :                     {:put    #'stages-handlers/stages-update-handler
     434              :                      :delete #'stages-handlers/stages-delete-handler}
     435           24 :                     ["/" :class-uuid "/stages/" :stage-uuid "/play"]
     436           12 :                     {:post #'stages-handlers/stages-play-handler}}
     437           40 :         "/stages" {["/" :stage-uuid "/draws"] {:get  #'draws-handlers/draws-get-by-stage-handler
     438              :                                                :post #'draws-handlers/draws-create-handler}
     439           20 :                    ["/" :stage-uuid "/draws/" :draw-uuid]
     440           20 :                    {:put    #'draws-handlers/draws-update-handler
     441              :                     :delete #'draws-handlers/draws-delete-handler}
     442           16 :                    ["/" :stage-uuid "/advancement-rules"]
     443           28 :                    {:get    #'adv-rule-handlers/advancement-rules-get-by-stage-handler
     444              :                     :post   #'adv-rule-handlers/advancement-rules-create-handler
     445              :                     :delete #'adv-rule-handlers/advancement-rules-reset-handler}
     446           16 :                    ["/" :stage-uuid "/advancement-rules/swap"]
     447           12 :                    {:post #'adv-rule-handlers/advancement-rules-swap-handler}
     448           20 :                    ["/" :stage-uuid "/advancement-rules/" :rule-uuid]
     449           20 :                    {:put    #'adv-rule-handlers/advancement-rules-update-handler
     450              :                     :delete #'adv-rule-handlers/advancement-rules-delete-handler}
     451           24 :                    ["/" :stage-uuid "/advancement-rules/" :rule-uuid "/decompose"]
     452           12 :                    {:post #'adv-rule-handlers/advancement-rules-decompose-handler}
     453           24 :                    ["/" :stage-uuid "/advancement-rules/" :rule-uuid "/move"]
     454           12 :                    {:post #'adv-rule-handlers/advancement-rules-move-handler}}
     455              :         "/draws"
     456           40 :         {["/" :draw-uuid "/groups"] {:get  #'groups-handlers/groups-get-by-draw-handler
     457              :                                      :post #'groups-handlers/groups-create-handler}
     458           40 :          ["/" :draw-uuid "/groups/" :group-uuid] {:put    #'groups-handlers/groups-update-handler
     459              :                                                   :delete #'groups-handlers/groups-delete-handler}
     460           24 :          ["/" :draw-uuid "/groups/" :group-uuid "/participants"]
     461           12 :          {:put #'groups-handlers/groups-set-participants-handler}
     462           16 :          ["/" :draw-uuid "/groups/participants/fill"]
     463           12 :          {:post #'groups-handlers/groups-fill-all-from-class-handler}
     464           24 :          ["/" :draw-uuid "/groups/" :group-uuid "/participants/fill"]
     465           12 :          {:post #'groups-handlers/groups-fill-from-class-handler}
     466           28 :          ["/" :draw-uuid "/groups/" :group-uuid "/participants/" :group-participant-uuid]
     467           12 :          {:put #'groups-handlers/groups-update-participant-handler}
     468           36 :          ["/" :draw-uuid "/brackets"] {:get  #'brackets-handlers/brackets-get-by-draw-handler
     469              :                                        :post #'brackets-handlers/brackets-create-handler}
     470              :          ;; Nested so the literal "fill" segment is matched before the
     471              :          ;; :bracket-match-slot-uuid wildcard (both share a POST verb).
     472           16 :          ["/" :draw-uuid "/brackets/participants/"]
     473           20 :          {"fill" {:post #'brackets-handlers/brackets-fill-from-class-handler}
     474           28 :           [:bracket-match-slot-uuid] {:post #'brackets-handlers/brackets-add-participant-handler
     475              :                                       :put
     476              :                                       #'brackets-handlers/brackets-substitute-participant-handler}}
     477           20 :          ["/" :draw-uuid "/brackets/" :bracket-uuid]
     478           20 :          {:put    #'brackets-handlers/brackets-update-handler
     479              :           :delete #'brackets-handlers/brackets-delete-handler}
     480           24 :          ["/" :draw-uuid "/brackets/" :bracket-uuid "/participants/fill"]
     481           12 :          {:post #'brackets-handlers/brackets-fill-single-from-class-handler}}}]
     482            8 :    (if webhook-url-prefix
     483            8 :      ["/api"
     484           28 :       (assoc base-routes webhook-url-prefix {:post #'telegram-handlers/telegram-webhook-handler})]
     485            3 :      ["/api" base-routes])))
     486              : 
     487              : 
     488            4 : (defn make-api-routes
     489              :  "Returns wrapped API routes for request handling"
     490              :  [config]
     491           24 :  (wrap-handlers-in-routes (make-api-routes-raw config) config))
     492              : 
     493              : 
     494              : ;; Swagger/OpenAPI handlers
     495            4 : (defn openapi-spec-handler
     496              :  "Returns the OpenAPI specification as JSON. Access controlled by wrap-dev-auth."
     497              :  [config]
     498            0 :  (fn [_request]
     499            0 :   (let [routes (make-api-routes-raw config)
     500            0 :         spec   (swagger/generate-openapi-spec routes)]
     501            0 :     {:status  200
     502            0 :      :headers {"Content-Type"  "application/json"
     503              :                "Cache-Control" "no-store, no-cache, must-revalidate, max-age=0"
     504              :                "Pragma"        "no-cache"
     505              :                "Expires"       "0"}
     506            0 :      :body    (json/write-str spec)})))
     507              : 
     508              : 
     509            4 : (defn goose-console-handler
     510              :  "Serves Goose console. Access controlled by wrap-dev-auth."
     511              :  [goose]
     512            0 :  (fn [request]
     513            0 :   (let [response ((partial
     514            0 :                    goose-console/app-handler
     515            0 :                    (assoc goose-console/default-console-opts
     516              :                     :route-prefix "/goose/console"
     517              :                     :app-name     "Matchscore Goose"
     518            0 :                     :broker       (:producer goose)))
     519            0 :                   request)]
     520            0 :     (if (and response (string? (:body response)))
     521            0 :       (assoc-in response [:headers "Content-Type"] "text/html")
     522            0 :       response))))
     523              : 
     524              : 
     525            4 : (defn make-non-api-routes
     526              :  [goose config]
     527            0 :  (let [dev-auth (fn [handler]
     528            0 :                  (wrap-dev-auth handler config))]
     529            0 :    ["/"
     530            0 :     {"goose"            {true (dev-auth (goose-console-handler goose))}
     531            0 :      "swagger"          (dev-auth (swagger-ui-handler config))
     532            0 :      "graphiql"         (dev-auth (graphiql-handler config))
     533            0 :      "openapi.json"     (dev-auth (openapi-spec-handler config))
     534            0 :      "__source_changed" source-changed-handler
     535            0 :      "js/compiled"      source-changed-handler
     536            0 :      true               index-handler}]))
     537              : 
     538              : 
     539              : ;; Global exception handling middleware
     540            4 : (defn wrap-exception-handling
     541              :  "Catch and handle uncaught exceptions, logging and returning a 500 response."
     542              :  [handler]
     543            2 :  (fn [request]
     544            2 :   (truss/try*
     545            6 :    (handler request)
     546              :    (catch :ex-info e ;; RuntimeException subclass
     547            2 :      (let [{:keys [type humanized-errors]
     548              :             :as   error-data}
     549            6 :            (ex-data e)
     550           19 :            message (or (:message error-data) (ex-message e))]
     551           20 :        (cond (= type :validation-error)
     552            1 :              (do
     553            2 :                (otel/add-attrs!
     554            5 :                 {:error.type "validation-error"
     555              :                  :http.response.status_code "422"})
     556           92 :                (t/log!
     557              :                 :error
     558            4 :                 {:message   "Validation failed"
     559            1 :                  :exception e})
     560            5 :                {:status  422
     561            2 :                 :body    (json/write-str
     562            4 :                           {:message "Validation failed"
     563            1 :                            :errors  humanized-errors})
     564            3 :                 :headers {"Content-Type" "application/json"}})
     565              : 
     566            6 :              (= type :internal-validation-error)
     567            1 :              (do
     568            2 :                (otel/add-attrs!
     569            5 :                 {:error.type "internal-validation-error"
     570              :                  :http.response.status_code "422"})
     571           92 :                (t/log!
     572              :                 :error
     573            4 :                 {:message   "Internal validation failed"
     574            1 :                  :exception e})
     575            5 :                {:status  422
     576            2 :                 :body    (json/write-str
     577            4 :                           {:message "Internal validation failed"
     578            1 :                            :errors  humanized-errors})
     579            3 :                 :headers {"Content-Type" "application/json"}})
     580              : 
     581            6 :              (= type :api-not-found)
     582            1 :              (do
     583            2 :                (otel/add-attrs!
     584            5 :                 {:error.type "not-found"
     585              :                  :http.response.status_code "404"})
     586           95 :                (t/log! :info {:message "Not found"})
     587            5 :                {:status  404
     588            5 :                 :body    (json/write-str {:message message})
     589            3 :                 :headers {"Content-Type" "application/json"}})
     590              : 
     591            6 :              (= type :api-forbidden)
     592            2 :              (do
     593            4 :                (otel/add-attrs!
     594           10 :                 {:error.type "forbidden"
     595              :                  :http.response.status_code "403"})
     596              :                ;; Log full details server-side; never leak them to the client.
     597          184 :                (t/log!
     598              :                 :info
     599            8 :                 {:message "Forbidden"
     600            6 :                  :data    (ex-data e)})
     601           10 :                {:status  403
     602           10 :                 :body    (json/write-str {:message "Forbidden"})
     603            6 :                 :headers {"Content-Type" "application/json"}})
     604              : 
     605            6 :              (= type :media/version-conflict)
     606            5 :              {:status  409
     607            2 :               :body    (json/write-str
     608            4 :                         {:message         "Gallery has changed"
     609            5 :                          :current_version (:current-version (ex-data e))})
     610            3 :               :headers {"Content-Type" "application/json"}}
     611              : 
     612            6 :              (= type :media/unavailable)
     613           10 :              {:status  503
     614           10 :               :body    (json/write-str {:message message})
     615            6 :               :headers {"Content-Type" "application/json"}}
     616              : 
     617            6 :              (contains? #{:media/invalid-gallery :media/invalid-asset} type)
     618            0 :              {:status  422
     619            0 :               :body    (json/write-str {:message message})
     620            0 :               :headers {"Content-Type" "application/json"}}
     621              : 
     622              :              :else
     623            1 :              (do
     624            2 :                (otel/record-error!
     625            1 :                 e
     626            5 :                 {:error.type "server-error"
     627              :                  :http.response.status_code "500"})
     628           92 :                (t/log!
     629              :                 :error
     630            7 :                 {:message   (str "Exception: " (.getMessage e))
     631            1 :                  :exception e})
     632            1 :                (try
     633            5 :                  (sentry/send-event {:throwable e})
     634              :                  (catch Throwable _))
     635            5 :                {:status  500
     636            5 :                 :body    (json/write-str {:message "Internal server error"})
     637            3 :                 :headers {"Content-Type" "application/json"}}))))
     638              :    (catch Exception e
     639            2 :      (otel/record-error!
     640            1 :       e
     641            5 :       {:error.type "server-error"
     642              :        :http.response.status_code "500"})
     643           92 :      (t/log!
     644              :       :error
     645            7 :       {:message   (str "Exception: " (.getMessage e))
     646            1 :        :exception e})
     647            1 :      (try
     648            5 :        (sentry/send-event {:throwable e})
     649              :        (catch Throwable _))
     650            5 :      {:status  500
     651            5 :       :body    (json/write-str {:message "Internal server error"})
     652            3 :       :headers {"Content-Type" "application/json"}}))))
     653              : 
     654              : 
     655            4 : (defn wrap-response
     656              :  "Ensures the response map has a :headers key (initializing it to {} when absent).
     657              :   Preserves all other keys (e.g. :status, :body, :cookies) added by handlers or
     658              :   downstream middleware so they survive to outer middleware layers."
     659              :  [handler]
     660            1 :  (fn [request]
     661            4 :   (let [response (handler request)]
     662           15 :     (cond-> response (nil? (:headers response)) (assoc :headers {})))))
     663              : 
     664              : 
     665            4 : (defn- response-header
     666              :   [response header-name]
     667            4 :   (let [wanted (clojure.string/lower-case header-name)]
     668            2 :     (some
     669            1 :      (fn [[k v]]
     670           10 :       (when (= wanted (clojure.string/lower-case (name k))) v))
     671            3 :      (:headers response))))
     672              : 
     673              : 
     674            4 : (defn wrap-timing-allow-origin
     675              :  "Expose browser Resource Timing details for origins already allowed by CORS."
     676              :  [handler]
     677            1 :  (fn [request]
     678            4 :   (let [response     (handler request)
     679            4 :         allow-origin (response-header response "Access-Control-Allow-Origin")]
     680           12 :     (cond-> response allow-origin (assoc-in [:headers "Timing-Allow-Origin"] allow-origin)))))
     681              : 
     682              : 
     683              : ;; Build CORS origin patterns from config, ensuring all entries are regex patterns.
     684            8 : (def ^:private cors-preflight-max-age
     685              :   "Seconds a browser may reuse a preflight result instead of repeating the
     686              :   OPTIONS round trip. Browsers cap this themselves (Chromium at 2 hours)."
     687              :   "7200")
     688              : 
     689              : 
     690            4 : (defn- cors-origin-patterns
     691              :   [config]
     692            6 :   (let [base        [#"https://.*\.matchscore\.tech"
     693              :                      #"https://.*\.localhost"
     694              :                      #"https?://localhost(:\d+)?"
     695              :                      #"https?://127\.0\.0\.1(:\d+)?"]
     696            3 :         backend-url (:backend-url config)]
     697            4 :     (if (not-empty backend-url)
     698           10 :       (conj base (re-pattern (java.util.regex.Pattern/quote (clojure.string/trim backend-url))))
     699            1 :       base)))
     700              : 
     701              : 
     702              : ;; API middleware stack
     703            4 : (defn wrap-api-middleware
     704              :  [handler config redis pg telegram-bot goose repos casbin]
     705            1 :  (->
     706            1 :    handler
     707            9 :    (utils-ring-middleware/wrap-components config redis pg telegram-bot goose repos casbin)
     708            1 :    utils-ring-middleware/wrap-otel-attrs
     709            5 :    (utils-ring-middleware/wrap-parse-headers config repos)
     710            1 :    wrap-response
     711            3 :    (middleware-json/wrap-json-body
     712            5 :     {:keywords?    true
     713              :      :bigdecimals? true})
     714            1 :    utils-ring-case-transformers/wrap-snake-case-response
     715            1 :    middleware-json/wrap-json-response
     716              :    ;; cookies/params must run BEFORE wrap-parse-headers on inbound (so the
     717              :    ;; session cookie is parsed) and AFTER wrap-response on outbound (so the
     718              :    ;; Set-Cookie header survives).
     719            1 :    keyword-params/wrap-keyword-params
     720            1 :    params/wrap-params
     721            1 :    cookies/wrap-cookies
     722            1 :    content-type/wrap-content-type
     723            1 :    wrap-exception-handling
     724              :    ;; CORS must be outermost so headers are added even to error responses
     725           15 :    (cors/wrap-cors
     726            3 :     :access-control-allow-origin      (cors-origin-patterns config)
     727            7 :     :access-control-allow-methods     [:get :post :put :patch :delete :options]
     728            8 :     :access-control-allow-headers     ["Content-Type"
     729              :                                        "Authorization"
     730              :                                        "X-Requested-With"
     731              :                                        "X-Telegram-Init-Data"
     732              :                                        "traceparent"
     733              :                                        "tracestate"
     734              :                                        "baggage"]
     735              :     :access-control-allow-credentials "true"
     736            1 :     :access-control-max-age           cors-preflight-max-age)
     737            1 :    wrap-timing-allow-origin
     738              :    ;; wrap-refresh
     739              :  ))
     740              : 
     741              : 
     742              : ;; Non-API middleware stack
     743            4 : (defn wrap-non-api-middleware
     744              :  [handler]
     745            0 :  (->
     746            0 :    handler
     747            0 :    (resource/wrap-resource "public") ; Serve static files
     748            0 :    (resource/wrap-resource "public/assets") ; Additional static assets
     749            0 :    (resource/wrap-resource "public/js/compiled") ; Serve Webpack/CLJS
     750              :                                                  ; hot-reload files
     751            0 :    cookies/wrap-cookies
     752            0 :    params/wrap-params
     753            0 :    content-type/wrap-content-type
     754            0 :    wrap-exception-handling
     755              :    ;; wrap-refresh ; For development hot-reloading
     756              :  ))
     757              : 
     758              : 
     759              : ;; WebSocket middleware stack (for Sente /api/chsk route)
     760            4 : (defn wrap-ws-middleware
     761              :  [handler config redis pg telegram-bot goose repos casbin]
     762            0 :  (->
     763            0 :    handler
     764            0 :    (utils-ring-middleware/wrap-components config redis pg telegram-bot goose repos casbin)
     765            0 :    (utils-ring-middleware/wrap-parse-headers config repos)
     766            0 :    keyword-params/wrap-keyword-params
     767            0 :    params/wrap-params
     768            0 :    cookies/wrap-cookies
     769            0 :    content-type/wrap-content-type
     770            0 :    wrap-exception-handling
     771            0 :    middleware-json/wrap-json-response
     772              :    ;; CORS must be outermost so headers are added even to error responses
     773            0 :    (cors/wrap-cors
     774            0 :     :access-control-allow-origin      (cors-origin-patterns config)
     775            0 :     :access-control-allow-methods     [:get :post :put :delete :options]
     776            0 :     :access-control-allow-headers     ["Content-Type"
     777              :                                        "Authorization"
     778              :                                        "X-Requested-With"
     779              :                                        "X-Telegram-Init-Data"
     780              :                                        "traceparent"
     781              :                                        "tracestate"
     782              :                                        "baggage"]
     783              :     :access-control-allow-credentials "true")
     784            0 :    wrap-timing-allow-origin))
     785              : 
     786              : 
     787              : ;; ring-jetty9-adapter (Jetty 12) calls (.succeeded callback) immediately after
     788              : ;; writing the response, before Sente's async future can write the body.
     789              : ;; This middleware reads the Sente AJAX body synchronously (blocking the thread)
     790              : ;; so the body is available when the adapter writes the response.
     791            4 : (defn- wrap-sente-sync-body
     792              :   [handler]
     793            0 :   (fn [req]
     794            0 :    (let [resp (handler req)
     795            0 :          body (:body resp)]
     796            0 :      (if (satisfies? sente-jetty/ISenteJettyAjaxChannel body)
     797            0 :        (assoc resp :body (str (sente-jetty/ajax-read! body)))
     798            0 :        resp))))
     799              : 
     800              : 
     801              : ;; Combined handler with conditional middleware
     802            4 : (defn combined-handler
     803              :  [config redis pg telegram-bot goose repos sente casbin]
     804            0 :  (let [ws-handler (fn [req]
     805            0 :                    (case (:request-method req)
     806            0 :                      :get     ((:ajax-get-or-ws-handshake-fn sente) req)
     807            0 :                      :post    ((:ajax-post-fn sente) req)
     808            0 :                      :options {:status  200
     809            0 :                                :headers {}
     810              :                                :body    ""}
     811            0 :                      {:status 405
     812              :                       :body   "Method not allowed"}))
     813            0 :        ws-stack   (wrap-ws-middleware
     814            0 :                    (wrap-sente-sync-body ws-handler)
     815            0 :                    config
     816            0 :                    redis
     817            0 :                    pg
     818            0 :                    telegram-bot
     819            0 :                    goose
     820            0 :                    repos
     821            0 :                    casbin)]
     822            0 :    (fn [request]
     823            0 :     (let [uri     (:uri request)
     824            0 :           is-api? (.startsWith uri "/api")]
     825            0 :       (if (= uri "/api/chsk")
     826            0 :         (ws-stack request)
     827            0 :         (let [handler (if is-api?
     828            0 :                         (bidi-ring/make-handler (make-api-routes config))
     829            0 :                         (bidi-ring/make-handler (make-non-api-routes goose config)))]
     830            0 :           (if is-api?
     831            0 :             ((wrap-api-middleware handler config redis pg telegram-bot goose repos casbin) request)
     832            0 :             ((wrap-non-api-middleware handler) request))))))))
        

Generated by: LCOV version 2.0-1