LCOV - code coverage report
Current view: top level - matchscore/utils - telegram_oidc.clj Coverage Total Hit
Test: lcov.info Lines: 82.5 % 97 80
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.utils.telegram-oidc
       2              :   "Validation for Telegram Login OIDC ID tokens."
       3              :   (:require
       4              :    [cheshire.core :as json]
       5              :    [clojure.string :as str])
       6              :   (:import
       7              :    (java.io            ByteArrayInputStream)
       8              :    (java.math          BigInteger)
       9              :    (java.net           URI)
      10              :    (java.net.http      HttpClient HttpRequest HttpResponse$BodyHandlers)
      11              :    (java.security      KeyFactory Signature)
      12              :    (java.security.spec RSAPublicKeySpec)
      13              :    (java.time          Duration Instant)
      14              :    (java.util          Base64)
      15              :    (java.util.zip      GZIPInputStream)))
      16              : 
      17              : 
      18            8 : (def ^:private issuer "https://oauth.telegram.org")
      19              : 
      20              : 
      21            8 : (def ^:private jwks-url "https://oauth.telegram.org/.well-known/jwks.json")
      22              : 
      23              : 
      24           36 : (defonce ^:private *jwks (atom nil))
      25              : 
      26              : 
      27           16 : (def ^:private jwks-ttl (Duration/ofMinutes 5))
      28              : 
      29              : 
      30           24 : (defonce ^:private http-client
      31            4 :   (->
      32            8 :     (HttpClient/newBuilder)
      33           16 :     (.connectTimeout (Duration/ofSeconds 5))
      34              :     (.build)))
      35              : 
      36              : 
      37            8 : (defn- b64url-decode [s] (.decode (Base64/getUrlDecoder) ^String s))
      38              : 
      39              : 
      40           12 : (defn- decode-json-part [part] (json/parse-string (String. (b64url-decode part) "UTF-8") keyword))
      41              : 
      42              : 
      43            4 : (defn- gzip-bytes?
      44              :   [^bytes body]
      45            8 :   (and
      46            4 :    (> (alength body) 1)
      47            7 :    (= (unchecked-byte 0x1f) (aget body 0))
      48            6 :    (= (unchecked-byte 0x8b) (aget body 1))))
      49              : 
      50              : 
      51            4 : (defn- decode-body
      52              :   "Response body as a UTF-8 string. Telegram's JWKS endpoint sometimes answers
      53              :   gzip even when the request doesn't ask for it, and java.net.http never
      54              :   decompresses, so gunzip by Content-Encoding or the gzip magic bytes."
      55              :   ^String [^bytes body content-encoding]
      56            6 :   (let [gzip? (or
      57            2 :                (=
      58              :                 "gzip"
      59           17 :                 (some->
      60            1 :                   content-encoding
      61            1 :                   str/trim
      62            1 :                   str/lower-case))
      63            2 :                (gzip-bytes? body))]
      64            2 :     (String.
      65            1 :      ^bytes
      66            1 :      (if gzip?
      67            8 :        (with-open [in (GZIPInputStream. (ByteArrayInputStream. body))] (.readAllBytes in))
      68            1 :        body)
      69              :      "UTF-8")))
      70              : 
      71              : 
      72            4 : (defn- fetch-jwks!
      73              :   []
      74            2 :   (let [request (->
      75            5 :                   (HttpRequest/newBuilder (URI/create jwks-url))
      76            4 :                   (.timeout (Duration/ofSeconds 10))
      77            1 :                   (.GET)
      78              :                   (.build))
      79            4 :         resp    (.send http-client request (HttpResponse$BodyHandlers/ofByteArray))]
      80            5 :     (when-not (= 200 (.statusCode resp))
      81            7 :       (throw (ex-info "Unable to fetch Telegram JWKS" {:status (.statusCode resp)})))
      82            0 :     (json/parse-string
      83            0 :      (decode-body (.body resp) (.orElse (.firstValue (.headers resp) "Content-Encoding") nil))
      84            0 :      keyword)))
      85              : 
      86              : 
      87            4 : (defn- expired?
      88              :   [{:keys [ts]}]
      89           12 :   (or (nil? ts) (.isBefore ^Instant ts (.minus (Instant/now) jwks-ttl))))
      90              : 
      91              : 
      92            4 : (defn- jwks
      93              :   []
      94            4 :   (let [cached @*jwks]
      95           12 :     (if (or (nil? cached) (expired? cached))
      96            2 :       (:keys
      97            3 :        (reset! *jwks
      98            5 :          {:keys (fetch-jwks!)
      99            2 :           :ts   (Instant/now)}))
     100            3 :       (:keys cached))))
     101              : 
     102              : 
     103            4 : (defn refresh-jwks!
     104              :  []
     105            0 :  (:keys
     106            0 :   (reset! *jwks
     107            0 :     {:keys (fetch-jwks!)
     108            0 :      :ts   (Instant/now)})))
     109              : 
     110              : 
     111           11 : (defn- key-by-kid [kid] (some #(when (= kid (:kid %)) %) (:keys (jwks))))
     112              : 
     113              : 
     114            4 : (defn- unsigned-bytes
     115              :   [b64url]
     116            0 :   (let [bytes (b64url-decode b64url)]
     117            0 :     (if (and (pos? (alength bytes)) (neg? (aget bytes 0))) (byte-array (cons 0 bytes)) bytes)))
     118              : 
     119              : 
     120            4 : (defn- rsa-public-key
     121              :   [{:keys [n e]}]
     122            0 :   (let [modulus  (BigInteger. (unsigned-bytes n))
     123            0 :         exponent (BigInteger. (unsigned-bytes e))
     124            0 :         spec     (RSAPublicKeySpec. modulus exponent)]
     125            0 :     (.generatePublic (KeyFactory/getInstance "RSA") spec)))
     126              : 
     127              : 
     128            4 : (defn- verify-signature?
     129              :   [signed-data signature key]
     130            0 :   (let [sig (Signature/getInstance "SHA256withRSA")]
     131            0 :     (.initVerify sig (rsa-public-key key))
     132            0 :     (.update sig (.getBytes ^String signed-data "UTF-8"))
     133            0 :     (.verify sig (b64url-decode signature))))
     134              : 
     135              : 
     136            4 : (defn- valid-audience?
     137              :   [aud client-id]
     138            4 :   (let [client-id' (str client-id)]
     139            9 :     (cond (string? aud)     (= client-id' aud)
     140            8 :           (number? aud)     (= client-id' (str aud))
     141            8 :           (sequential? aud) (some #{client-id'} aud)
     142              :           :else             false)))
     143              : 
     144              : 
     145            4 : (defn verify-id-token
     146              :  "Returns Telegram claims when the ID token is valid, otherwise throws."
     147              :  [id-token client-id]
     148            5 :  (let [[header-part payload-part sig-part :as parts] (str/split id-token #"\.")]
     149           12 :    (when-not (= 3 (count parts)) (throw (ex-info "Invalid Telegram ID token format" {})))
     150            4 :    (let [header      (decode-json-part header-part)
     151            3 :          claims      (decode-json-part payload-part)
     152            5 :          key         (key-by-kid (:kid header))
     153            5 :          signed-data (str header-part "." payload-part)
     154            3 :          now         (.getEpochSecond (Instant/now))]
     155            8 :      (when-not (= "RS256" (:alg header))
     156            9 :        (throw (ex-info "Unsupported Telegram ID token algorithm" {:alg (:alg header)})))
     157            4 :      (when-not key
     158            2 :        (refresh-jwks!)
     159            7 :        (when-not (key-by-kid (:kid header))
     160            9 :          (throw (ex-info "Telegram signing key not found" {:kid (:kid header)}))))
     161           12 :      (when-not (verify-signature? signed-data sig-part (key-by-kid (:kid header)))
     162            5 :        (throw (ex-info "Invalid Telegram ID token signature" {})))
     163            8 :      (when-not (= issuer (:iss claims))
     164            9 :        (throw (ex-info "Invalid Telegram ID token issuer" {:iss (:iss claims)})))
     165            9 :      (when-not (valid-audience? (:aud claims) client-id)
     166            9 :        (throw (ex-info "Invalid Telegram ID token audience" {:aud (:aud claims)})))
     167           15 :      (when-not (and (:exp claims) (< now (:exp claims)))
     168            9 :        (throw (ex-info "Expired Telegram ID token" {:exp (:exp claims)})))
     169            1 :      claims)))
        

Generated by: LCOV version 2.0-1