Line data Source code
1 4 : (ns matchscore.utils.ring.middleware
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [cheshire.core :as json]
6 : [clojure.string :as str]
7 : [clojure.walk :as walk]
8 : [malli.core :as m]
9 : [malli.error :as me]
10 : [malli.transform :as mt]
11 : [matchscore.domain.session.repository.redis :as session-repo]
12 : [matchscore.domain.user.command :as user-command]
13 : [matchscore.domain.user.query :as user-query]
14 : [matchscore.utils.audit :as audit]
15 : [matchscore.utils.otel :as otel]
16 : [matchscore.utils.ring.case-transformers :as utils-ring-case-transformers]
17 : [matchscore.utils.telegram-auth :as telegram-auth]
18 : [ring.util.codec :as codec]
19 : [ring.util.response :as res]
20 : [schemas.registry :as registry]
21 : [taoensso.telemere :as t])
22 : (:import
23 : (java.math BigInteger)
24 : (java.nio.charset StandardCharsets)
25 : (java.security MessageDigest)))
26 :
27 :
28 10 : (defn- current-repos [repos] (if (instance? clojure.lang.IDeref repos) (deref repos) repos))
29 :
30 :
31 4 : (defn- redact-presigned-urls
32 : [value]
33 0 : (walk/postwalk
34 0 : #(if (and (string? %) (re-find #"(?i)[?&]X-Amz-(Signature|Credential)=" %))
35 : "[REDACTED SIGNED URL]"
36 : %)
37 0 : value))
38 :
39 :
40 4 : (defn- auto-provision-telegram-user!
41 : "Auto-creates a MatchScore account for a Telegram Mini App identity that has
42 : none, from the initData profile, so the user does not face the registration
43 : form. Returns the new user UUID, or nil on failure (auth then proceeds with a
44 : nil uuid)."
45 : [repos telegram-id user-data]
46 1 : (try
47 3 : (let [result (user-command/create-from-telegram!
48 3 : {:repos repos}
49 7 : {:telegram-id telegram-id
50 3 : :first-name (:first_name user-data)
51 3 : :last-name (:last_name user-data)
52 3 : :username (:username user-data)
53 3 : :photo-url (:photo_url user-data)})]
54 4 : (if (either/right? result)
55 6 : (let [uuid (:uuid (c/extract result))]
56 92 : (t/log!
57 : :info
58 5 : {:message "Auto-provisioned Telegram user (mini-app open)"
59 1 : :telegram-id telegram-id
60 1 : :user-uuid uuid})
61 1 : uuid)
62 : ;; A concurrent insert may have won the unique telegram_id — re-resolve.
63 : ;; Any other Left (e.g. a validation/persistence failure) won't resolve,
64 : ;; so surface it rather than silently returning a nil uuid.
65 0 : (or
66 0 : (user-query/find-uuid-by-telegram-id
67 0 : (:user-postgres-repo repos)
68 0 : (:user-redis-repo repos)
69 0 : telegram-id)
70 : (do
71 0 : (t/log!
72 : :warn
73 0 : {:message "Failed to auto-provision Telegram user (mini-app open)"
74 0 : :telegram-id telegram-id
75 0 : :error (c/extract result)})
76 : nil))))
77 : (catch Exception e
78 0 : (t/log!
79 : :error
80 0 : {:message "Auto-provision of Telegram user failed"
81 0 : :telegram-id telegram-id
82 0 : :exception e})
83 : nil)))
84 :
85 :
86 4 : (defn- pseudonymize-id
87 : [id]
88 0 : (let [digest
89 0 : (.digest (MessageDigest/getInstance "SHA-256") (.getBytes (str id) StandardCharsets/UTF_8))]
90 0 : (subs (format "%064x" (BigInteger. 1 digest)) 0 32)))
91 :
92 :
93 4 : (defn wrap-otel-attrs
94 : "Decorate the request span (created by the OTel Java agent on the Jetty
95 : servlet) with MatchScore-specific attributes, and bind the trace/span IDs
96 : into telemere's context so every (t/log! ...) inside the handler carries
97 : them. This is what gives us free log\u2194trace correlation."
98 : [handler]
99 1 : (fn [request]
100 0 : (let [auth (:auth-headers request)
101 0 : tg-id (:telegram/id auth)
102 0 : user-id (:user/uuid auth)
103 0 : auth-source (:auth-source auth)
104 0 : trace-id (otel/current-trace-id)
105 0 : span-id (otel/current-span-id)]
106 0 : (when trace-id
107 0 : (otel/add-attrs!
108 0 : (cond-> {:http.route (:uri request)}
109 0 : tg-id (assoc :telegram.id (pseudonymize-id tg-id))
110 0 : user-id (assoc :user.uuid (pseudonymize-id user-id))
111 0 : auth-source (assoc :auth.source (name auth-source)))))
112 0 : (if trace-id
113 0 : (t/with-ctx+
114 0 : {:trace-id trace-id
115 0 : :span-id span-id}
116 0 : (handler request))
117 0 : (handler request)))))
118 :
119 :
120 4 : (defn wrap-route-otel-attrs
121 : "Add bidi route-params (entity UUIDs) as OTel span attributes for business
122 : context. Must be applied inside the bidi handler so :route-params is present."
123 : [handler]
124 4 : (fn [request]
125 44 : (when-let [rp (not-empty (:route-params request))]
126 8 : (otel/add-attrs!
127 8 : (reduce-kv
128 4 : (fn [m k v]
129 48 : (assoc m (str "route." (name k)) (str v)))
130 4 : {}
131 4 : rp)))
132 12 : (handler request)))
133 :
134 :
135 4 : (defn wrap-audit-actor
136 : "Makes the authenticated user the audit actor for everything the handler
137 : writes, so repositories can fill `created_by` / `updated_by`. Guests and
138 : credential-free routes run with no actor. Applied per route, where
139 : `:auth-headers` is already present on the request."
140 : [handler]
141 4 : (fn [request]
142 72 : (audit/with-actor (get-in request [:auth-headers :user/uuid]) (handler request))))
143 :
144 :
145 4 : (defn wrap-components
146 : "Middleware to add components to the request map."
147 : [handler config redis pg telegram-bot goose repos casbin]
148 1 : (fn [request]
149 0 : (let [repos' (current-repos repos)]
150 0 : (handler
151 0 : (assoc request
152 0 : :config config
153 0 : :pg (:datasource pg)
154 0 : :bot telegram-bot
155 0 : :redis redis
156 0 : :goose goose
157 0 : :repos repos'
158 0 : :casbin casbin
159 0 : :ctx {:repos repos'
160 0 : :config config
161 0 : :goose goose
162 0 : :pg (:datasource pg)
163 0 : :redis redis
164 0 : :auth-headers (:auth-headers request)
165 0 : :casbin casbin
166 0 : :enforcer (:enforcer casbin)})))))
167 :
168 :
169 4 : (defn- session-cookie-value
170 : [request cookie-name]
171 8 : (let [v (get-in request [:cookies cookie-name :value])]
172 15 : (when (and (string? v) (not (str/blank? v))) v)))
173 :
174 :
175 4 : (defn- unauthenticated-route?
176 : [request]
177 4 : (let [uri (:uri request)
178 3 : method (:request-method request)]
179 : ;; Telegram Login Widget — login and logout do not require prior auth
180 17 : (and (= method :post) (or (= uri "/api/auth/telegram") (= uri "/api/auth/telegram/logout")))))
181 :
182 :
183 9 : (defn- healthcheck-route? [request] (= (:uri request) "/api/healthcheck"))
184 :
185 :
186 4 : (defn- guest-route?
187 : "Read-only transports that support an unauthenticated guest context.
188 : Authorization and visibility are still enforced by their handlers/resolvers."
189 : [request]
190 4 : (let [uri (:uri request)
191 3 : method (:request-method request)]
192 17 : (or
193 10 : (and (= method :post) (= uri "/api/graphql"))
194 : (and
195 3 : (= method :get)
196 : (or
197 3 : (= uri "/api/media/config")
198 5 : (boolean (re-matches #"/api/events/[^/]+/classes/[^/]+/scoreboard" uri))
199 4 : (boolean (re-matches #"/api/(?:events|templates)/[^/]+/images" uri)))))))
200 :
201 :
202 : ;; Middleware to parse headers
203 4 : (defn wrap-parse-headers
204 : "Middleware to extract and parse auth credentials.
205 :
206 : Two auth modes are supported:
207 : 1. Telegram Mini App initData via `Authorization: twa <data>` header
208 : (or `?twa=<data>` query param for the WebSocket route).
209 : 2. Opaque session cookie issued by the Telegram Login Widget flow,
210 : backed by Redis via `session-redis-repo`.
211 :
212 : TWA wins if both are present. On success, `:auth-headers` is populated
213 : with `{:telegram/id ... :user/uuid ... :auth-source :twa | :session}`.
214 : Credential-free read transports receive `{:auth-source :guest}`; invalid
215 : credentials are always rejected instead of falling back to guest mode."
216 : [handler config repos]
217 2 : (fn [request]
218 6 : (when-not (healthcheck-route? request)
219 102 : (t/log! :info (str "=== === === === === " (:request-method request) " " (:uri request)))
220 6 : (when (= (:env config) "production")
221 0 : (t/log!
222 : :info
223 0 : {:request-body (:body request)
224 0 : :query-params (:params request)})))
225 7 : (when (= (:uri request) "/api/graphql")
226 92 : (t/log!
227 : :info
228 17 : (str "GraphQL query: " (or (get-in request [:body :query]) (get (:body request) "query")))))
229 4 : (let [repos' (current-repos repos)
230 6 : bot-token (get-in config [:telegram :bot-token])
231 6 : bot-api-secret-token (get-in config [:telegram :bot-api-secret-token])
232 8 : session-cookie-name (get-in config [:auth :session :cookie-name] "ms_session")
233 3 : headers (:headers request)
234 3 : bot-api-secret-token-header (get headers "x-telegram-bot-api-secret-token")
235 6 : webhook-url-prefix (get-in config [:telegram :webhook-url-prefix])
236 : ;; extract TWA auth token if present (header, or, for routes that can't set an
237 : ;; Authorization header, the `:twa` param — `wrap-params` merges both query and
238 : ;; urlencoded-body params, so this covers the WebSocket upgrade's `?twa=` query param
239 : ;; and the presence-away `navigator.sendBeacon`, which sends `twa` in the urlencoded
240 : ;; body to
241 : ;; keep the initData out of access logs and browser history)
242 5 : twa-auth (or
243 9 : (when-let [auth (get headers "authorization")]
244 10 : (when (re-matches #"twa .+" auth) (subs auth 4)))
245 8 : (when (contains? #{"/api/chsk" "/api/presence/away"} (:uri request))
246 0 : (get (:params request) :twa)))
247 4 : session-id (session-cookie-value request session-cookie-name)
248 6 : auth-enabled (get-in config [:options :telegram-auth-enabled?])
249 1 : twa-validation-failed? (fn []
250 6 : (not (telegram-auth/valid? twa-auth bot-token)))
251 1 : call-handler (fn [req]
252 4 : (let [resp (handler req)]
253 1 : (when
254 10 : (and
255 5 : (not (healthcheck-route? req))
256 6 : (not= (:request-method req) :options)
257 3 : (= (:env config) "production"))
258 0 : (t/log!
259 : :info
260 0 : {:response-status (:status resp)
261 0 : :response-body (redact-presigned-urls (:body resp))}))
262 1 : resp))
263 1 : attach-twa (fn []
264 4 : (let [decoded (codec/form-decode twa-auth)
265 6 : user-data (json/parse-string (get decoded "user") true)
266 3 : tg-id (:id user-data)
267 2 : existing-uuid (user-query/find-uuid-by-telegram-id
268 3 : (:user-postgres-repo repos')
269 3 : (:user-redis-repo repos')
270 1 : tg-id)
271 : ;; A Telegram Mini App caller is already authenticated and
272 : ;; carries their profile in initData, so auto-provision an
273 : ;; account on first open instead of forcing the
274 : ;; registration form.
275 5 : user-uuid (or
276 1 : existing-uuid
277 1 : (when tg-id
278 2 : (auto-provision-telegram-user!
279 1 : repos'
280 1 : tg-id
281 1 : user-data)))
282 7 : auth-headers {:twa-auth twa-auth
283 1 : :telegram/id tg-id
284 1 : :user/uuid user-uuid
285 : :auth-source :twa}
286 5 : modified-request (assoc request
287 1 : :parsed-headers auth-headers
288 1 : :auth-headers auth-headers)]
289 3 : (call-handler modified-request)))
290 1 : attach-session (fn [session]
291 9 : (let [auth-headers {:telegram/id (:telegram-id session)
292 3 : :user/uuid (:user-uuid session)
293 : :auth-source :session}
294 5 : modified-request (assoc request
295 1 : :parsed-headers auth-headers
296 1 : :auth-headers auth-headers)]
297 3 : (call-handler modified-request)))
298 1 : attach-guest (fn []
299 4 : (let [auth-headers {:auth-source :guest}]
300 2 : (call-handler
301 5 : (assoc request
302 1 : :parsed-headers auth-headers
303 1 : :auth-headers auth-headers))))]
304 8 : (cond
305 : ;; CORS preflight — no auth required (browser sends no credentials)
306 8 : (= (:request-method request) :options) (call-handler request)
307 :
308 : ;; Healthcheck — no auth required
309 6 : (healthcheck-route? request) (call-handler request)
310 :
311 : ;; Telegram Login Widget login/logout — no prior auth required
312 6 : (unauthenticated-route? request) (call-handler request)
313 :
314 : ;; Telegram webhook — verify secret token, skip user parsing
315 5 : (and
316 8 : (= (:uri request) (str "/api" webhook-url-prefix))
317 2 : (= bot-api-secret-token bot-api-secret-token-header))
318 3 : (call-handler request)
319 :
320 : ;; TWA present — validate and attach (TWA wins over session)
321 1 : twa-auth
322 9 : (cond (and auth-enabled (twa-validation-failed?))
323 1 : (do
324 93 : (t/log! :info "Unauthorized (invalid token)")
325 2 : (->
326 5 : (res/response {:errors "Unauthorized"})
327 3 : (res/status 401)
328 1 : (res/content-type "application/json")))
329 :
330 2 : :else (attach-twa))
331 :
332 : ;; No TWA — try session cookie
333 1 : session-id
334 4 : (let [repo (:session-redis-repo repos')]
335 2 : (if repo
336 9 : (if-let [session (session-repo/find-by-id repo session-id)]
337 3 : (attach-session session)
338 1 : (do
339 93 : (t/log! :info "Unauthorized (invalid session)")
340 2 : (->
341 5 : (res/response {:errors "Unauthorized"})
342 3 : (res/status 401)
343 1 : (res/content-type "application/json"))))
344 0 : (do
345 0 : (t/log! :info "Unauthorized (no session repo)")
346 0 : (->
347 0 : (res/response {:errors "Unauthorized"})
348 0 : (res/status 401)
349 0 : (res/content-type "application/json")))))
350 :
351 : ;; Selected read-only transports support guest access. This branch comes
352 : ;; after credential validation so a bad session/token can never downgrade
353 : ;; to guest mode.
354 5 : (guest-route? request) (attach-guest)
355 :
356 : ;; Neither — reject
357 : :else
358 1 : (do
359 93 : (t/log! :info "Unauthorized (missing credentials)")
360 2 : (->
361 5 : (res/response {:errors "Unauthorized"})
362 3 : (res/status 401)
363 1 : (res/content-type "application/json")))))))
364 :
365 :
366 4 : (defn- extract-cookie-values
367 : "Extracts :value from Ring cookie map structure.
368 : Ring cookies are {:cookie-name {:value \"cookie-value\"}}
369 : This converts to {:cookie-name \"cookie-value\"}"
370 : [cookies]
371 0 : (reduce-kv
372 0 : (fn [acc k v]
373 0 : (assoc acc k (if (map? v) (:value v) v)))
374 0 : {}
375 0 : cookies))
376 :
377 :
378 4 : (defn- validate-and-decode-params
379 : "Validates and decodes parameters (query, path, header, cookie) against schema.
380 : Returns [validated-params errors] tuple."
381 : [params schema param-type]
382 12 : (when schema
383 4 : (let [;; For cookies, extract :value from Ring's cookie map structure
384 20 : preprocessed-params (if (= param-type "cookie") (extract-cookie-values params) params)
385 8 : transformer (mt/transformer
386 8 : (utils-ring-case-transformers/snake-to-kebab-transformer)
387 8 : (mt/strip-extra-keys-transformer)
388 8 : (mt/default-value-transformer))
389 32 : decoded (m/decode schema preprocessed-params {:registry registry/registry} transformer)]
390 32 : (if (m/validate schema decoded {:registry registry/registry})
391 12 : [decoded nil]
392 11 : [nil (me/humanize (m/explain schema decoded {:registry registry/registry}))]))))
393 :
394 :
395 4 : (defn extract-schema-from-meta
396 : "Middleware that inspects the handler's malli schema to determine
397 : how many arguments it expects and validates input data and response:
398 : - If schema has 2 arguments in :cat (request, data), validates data and passes both
399 : - If schema has 1 argument in :cat (request), passes only request
400 : - If no schema, passes only request
401 : - If response schema is present, validates the response body
402 : - Validates query-params, path-params, header-params, cookie-params from :malli/parameters
403 : - Validation can be disabled via :options :runtime-validation? config flag"
404 8 : ([handler] (extract-schema-from-meta handler nil))
405 : ([handler config]
406 : ;; Extract schema information at middleware wrapping time, not request time
407 4 : (let [;; Check if runtime validation is enabled (default: true)
408 28 : validation-enabled? (get-in config [:options :runtime-validation?] true)
409 : ;; Get the actual function from var if needed
410 30 : actual-fn (if (var? handler) @handler handler)
411 : ;; Get metadata from either the var or the function
412 34 : handler-meta (if (var? handler) (meta handler) (meta actual-fn))
413 12 : fn-schema (:malli/schema handler-meta)
414 : ;; Extract parameter schemas
415 12 : param-schemas (:malli/parameters handler-meta)
416 12 : query-schema (:query param-schemas)
417 12 : path-schema (:path param-schemas)
418 12 : header-schema (:header param-schemas)
419 12 : cookie-schema (:cookie param-schemas)
420 : ;; Extract the :cat vector which contains argument schemas
421 : ;; Format: [:=> [:cat arg1-schema arg2-schema?] response-schema]
422 24 : args-schema (when fn-schema (get fn-schema 1))
423 20 : args-count (when args-schema (count args-schema))
424 32 : needs-two-args? (and args-count (>= args-count 3))
425 24 : data-schema (when needs-two-args? (get args-schema 2))
426 : ;; Extract response schema for validation
427 24 : response-schema (when fn-schema (get fn-schema 2))]
428 :
429 : ;(t/log! :info (str "Setting up middleware for handler: " handler))
430 : ;(t/log! :info (str "Handler is var?: " (var? handler)))
431 : ;(t/log! :info (str "Args count: " args-count ", needs 2 args?: "
432 : ;needs-two-args?))
433 :
434 4 : (fn [request]
435 4 : (letfn
436 : [(validate-response [response]
437 26 : (if (and validation-enabled? response-schema)
438 2 : (do
439 44 : (t/log! :debug (str "Validating response: " response))
440 16 : (if (m/validate response-schema response {:registry registry/registry})
441 48 : (do (t/log! :debug "Response validation passed") response)
442 0 : (let [errors (me/humanize
443 0 : (m/explain response-schema response {:registry registry/registry}))]
444 0 : (t/log! :error (str "Response validation failed: " errors))
445 0 : (t/log! :error (str "Response: " response))
446 0 : (->
447 0 : (res/response
448 0 : {:message "Response validation failed"
449 0 : :errors errors})
450 0 : (res/status 422)))))
451 4 : response))]
452 :
453 : ;; First, validate all parameter types
454 4 : (let [;; Validate query params
455 : [validated-query-params query-errors]
456 28 : (validate-and-decode-params (:params request) query-schema "query")
457 :
458 : ;; Validate path params
459 : [validated-path-params path-errors]
460 28 : (validate-and-decode-params (:route-params request) path-schema "path")
461 :
462 : ;; Validate headers (Ring already lowercases header keys)
463 : [validated-headers header-errors]
464 28 : (validate-and-decode-params (:headers request) header-schema "header")
465 :
466 : ;; Validate cookies
467 : [validated-cookies cookie-errors]
468 28 : (validate-and-decode-params (:cookies request) cookie-schema "cookie")
469 :
470 : ;; Collect all validation errors (only if validation is
471 : ;; enabled)
472 10 : all-errors (when validation-enabled?
473 4 : (merge
474 2 : {}
475 4 : (when query-errors {:query-params query-errors})
476 8 : (when path-errors {:path-params path-errors})
477 4 : (when header-errors {:headers header-errors})
478 4 : (when cookie-errors {:cookies cookie-errors})))]
479 :
480 : ;; If any parameter validation failed, return 400
481 16 : (if (seq all-errors)
482 1 : (do
483 96 : (t/log! :error (str "Parameter validation errors: " all-errors))
484 2 : (->
485 2 : (res/response
486 4 : {:message "Parameter validation failed"
487 1 : :errors all-errors})
488 1 : (res/status 400)))
489 :
490 : ;; Otherwise, add validated params to request and proceed
491 49 : (let [updated-request (cond-> request
492 8 : validated-query-params (assoc :params validated-query-params)
493 :
494 16 : validated-path-params (assoc :route-params
495 4 : validated-path-params)
496 :
497 4 : validated-headers (update :headers merge validated-headers)
498 :
499 4 : validated-cookies (assoc :cookies validated-cookies))]
500 :
501 8 : (cond
502 : ;; If :cat has 3 elements [:cat request-schema data-schema],
503 : ;; validate and pass 2 args
504 4 : needs-two-args?
505 16 : (let [data (:body updated-request)
506 8 : initial-transformer (mt/transformer
507 8 : (utils-ring-case-transformers/snake-to-kebab-transformer)
508 8 : (mt/strip-extra-keys-transformer)
509 8 : (mt/default-value-transformer))
510 : decoded-data
511 32 : (m/decode data-schema data {:registry registry/registry} initial-transformer)]
512 88 : (t/log! :debug (str "Input data:" data))
513 88 : (t/log! :debug (str "Decoded data (pre-validation):" decoded-data))
514 : ;; Skip validation if disabled
515 4 : (if
516 18 : (or
517 12 : (not validation-enabled?)
518 12 : (m/validate data-schema decoded-data {:registry registry/registry}))
519 4 : (do
520 88 : (t/log! :debug "Calling handler with 2 args")
521 24 : (validate-response (handler updated-request decoded-data)))
522 1 : (let [errors
523 2 : (me/humanize
524 7 : (m/explain data-schema decoded-data {:registry registry/registry}))]
525 96 : (t/log! :error (str "Validation errors:" errors))
526 96 : (t/log! :error (str "Decoded data (failed):" decoded-data))
527 2 : (->
528 2 : (res/response
529 4 : {:message "Validation failed"
530 1 : :errors errors})
531 1 : (res/status 400)))))
532 :
533 : ;; Otherwise, pass only request (includes no schema case)
534 : :else
535 4 : (do
536 88 : (t/log! :debug "Calling handler with 1 arg")
537 20 : (validate-response (handler updated-request))))))))))))
|