├── .gitignore ├── .travis.yml ├── .github └── workflows │ ├── clojure.yml │ └── release.yml ├── src └── clj_github_app │ ├── webhook_signature.clj │ ├── client.clj │ └── token_manager.clj ├── test ├── example-private-key.pem └── clj_github_app │ ├── token_manager_test.clj │ ├── webhook_signature_test.clj │ └── client_test.clj ├── CHANGELOG.md ├── project.clj ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | /.idea 11 | /*.iml 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | script: 3 | - lein ancient 4 | - lein cloverage --codecov 5 | after_success: 6 | - bash <(curl -s https://codecov.io/bash) -f target/coverage/codecov.json 7 | -------------------------------------------------------------------------------- /.github/workflows/clojure.yml: -------------------------------------------------------------------------------- 1 | name: Clojure CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | test-clojure: 12 | 13 | strategy: 14 | matrix: 15 | java-version: [11, 17, 21] 16 | 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - uses: actions/setup-java@v4 23 | with: 24 | distribution: temurin 25 | java-version: ${{ matrix.java-version }} 26 | 27 | - name: Print java version 28 | run: java -version 29 | 30 | - name: Install dependencies 31 | run: lein deps 32 | 33 | - name: Run clj tests 34 | run: lein test 35 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | test-clojure: 10 | strategy: 11 | matrix: 12 | java-version: [11, 17, 21] 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - uses: actions/setup-java@v4 20 | with: 21 | distribution: temurin 22 | java-version: ${{ matrix.java-version }} 23 | 24 | - name: Print java version 25 | run: java -version 26 | 27 | - name: Install dependencies 28 | run: lein deps 29 | 30 | - name: Run clj tests 31 | run: lein test 32 | 33 | release: 34 | name: 'Publish on Clojars' 35 | runs-on: ubuntu-latest 36 | needs: [test-clojure] 37 | steps: 38 | - uses: actions/checkout@v4.2.2 39 | 40 | - name: Install dependencies 41 | run: lein deps 42 | 43 | - name: Publish on Clojars 44 | run: lein deploy publish 45 | env: 46 | CLOJARS_USERNAME: eng-prod-nubank 47 | CLOJARS_PASSWD: ${{ secrets.CLOJARS_DEPLOY_TOKEN }} 48 | -------------------------------------------------------------------------------- /src/clj_github_app/webhook_signature.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.webhook-signature 2 | (:require [clojure.string :as str] 3 | [crypto.equality] 4 | [pandect.algo.sha1 :as sha1] 5 | [pandect.algo.sha256 :as sha256])) 6 | 7 | (defn ^{:deprecated "Prefer using check-payload-signature-256."} check-payload-signature [webhook-secret x-hub-signature payload] 8 | (if (str/blank? webhook-secret) 9 | ::not-checked 10 | (if (str/blank? x-hub-signature) 11 | ::missing-signature 12 | (let [payload-signature (str "sha1=" (sha1/sha1-hmac payload webhook-secret))] 13 | (if-not (crypto.equality/eq? payload-signature x-hub-signature) 14 | ::wrong-signature 15 | ::ok))))) 16 | 17 | (defn check-payload-signature-256 [webhook-secret x-hub-signature-256 payload] 18 | (if (str/blank? webhook-secret) 19 | ::not-checked 20 | (if (str/blank? x-hub-signature-256) 21 | ::missing-signature 22 | (let [payload-signature (str "sha256=" (sha256/sha256-hmac payload webhook-secret))] 23 | (if-not (crypto.equality/eq? payload-signature x-hub-signature-256) 24 | ::wrong-signature 25 | ::ok))))) 26 | -------------------------------------------------------------------------------- /test/example-private-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEogIBAAKCAQEAxD7LShz5ruSEmdsOleoZ6Gtky7Jv8Y6fyvGaoHjLxFKb83Ah 3 | TR88dgmzGoRhUCP6ih1R824Tt3Ip4dYwbmDk8LO553crlHMQwOZKxxXUzjHXiEn7 4 | d1L4tKGjxYF4sFw9lplepR1kMFZLsZAqszYuJqB2n/NsAlKRqSVFfVP2g4y6lPcA 5 | ThyLzRiRL5kqp/PtpUGHqimpUcjUZuHTxxqSuyoxO+UbPcaBF7AwtLL2zNFTJlrb 6 | xjFelE3uxQ4QuOJ0R8cQAi7UeeT+VFlKM/wQztKwdYQKHiAcREnj/mn7T/9bxHdL 7 | wx0rNi1cHk9RDmHXvtr/j3cORtrMOjhSM2ZblQIDAQABAoIBACI2FDiCXqC3o8oy 8 | nxNRcVzMRBEitVM2GvNFNUCebl92S0ugE54fQOoO/NM1msVe0FF9lQjL+tHzLAv7 9 | zAuiBqdTnagVZVqGyLfoLccRLj0YAUv4IceGhmbu+t72mDSej/oOGKrOOeYXVTDK 10 | QjdlzZvcQ3HU/NJW1J/ZKIkVtxbthnJ5LPoopUNj7lFW3Rxs9hF53Q02LaZtjhhX 11 | ghdLnJ/nBoUUENprC7Io962U3Wrk+TdUea6keUdF09mxKYyJPVloMQimHpSnOODI 12 | EXGrhx+TH9b67UidWBhZQmhoWOs7r+SWysq1uEt8mVK83erUH9N1O99Bgl4U0lrO 13 | WFjHYw0CgYEA6ERZGsdtPGf6y7W0FGPN7RYe9N6zpK5s2dEBK8FrNnbXwsNTbuud 14 | W+kOXC+iRu7bkDimD6SLb9NuM3SVnIpdKxn8JknbzIOxmU3Sy2Uljdz8/Q5vOW30 15 | MEz2f7VQsi9QqtIITaf9+/r4nxxfh6iDe9jekx5ucvawBExPrUUFmCcCgYEA2Eww 16 | SzlYIy9nAQclAQpQeYwRG0Yt02sz50Xe/Q+pq7ulqgEJdmYa78ga8ZHB/l05F42Q 17 | kKNhl9HmoVr6p9BwOdDKnJ8AQSZEqJUf7vX7zSeEMn4qbpnAIM8HrxZrbCMFg/hP 18 | rnXQW0dgGaFs6kacIbHBA+biysfFfdZ0kpO5p+MCgYBiBm6Ascf1ZYDgNoiQzmpb 19 | dCmOeOriRscjymSvHctsyg1XYm408vWPk7V+zI+1VhuOK4pSMcSzZk0tJDf8QB0A 20 | EtBrLGK6Vp4+sCyVsNN/otOWzV+9oh0bwW+LCG/NM9DctxXQCGVV0l7Zb/UVYNZV 21 | D3soJgDBPkGdHsPFwcqRowKBgH9tk14d8JD6EkMGxIQyYWraXBGnbMQLek6cWVzZ 22 | Z2pnaJgZeEuqp9/wEf+Tkaibn1EC89JijtJ0tN0GznkjUZqeKV/QRMQdGYIAKQoN 23 | HUWmLDnbHoB+UDSEA9Dg8nSIxW0UU01C13ePO0yeT55N7xnisQXtdltlCjKyr4bT 24 | RSNlAoGAMwKFfEgOpk8DwzvVs/33ZIWeYje9YG+k10Y0t4whrXVv3Dc0D1LMPVnR 25 | m4mgvN4jBHDtE6Blm4iy9qbDQC0LvXMECaAPAv/6V12E+BxUwFPK3J3dN2CTDxm+ 26 | pnLMLUk9+rlj+eG0Vy7ayV/Qj46Yq5oFf4zhstMj6zoOkDfax5M= 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /test/clj_github_app/token_manager_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.token-manager-test 2 | (:require [clj-github-app.token-manager :refer :all :as tm] 3 | [clj-http.client :as http] 4 | [clojure.test :refer :all]) 5 | (:import (com.auth0.jwt JWT))) 6 | 7 | (def access-token-response {:body {:token "installation-token" 8 | :expires_at "2100-07-11T22:14:10Z"}}) 9 | 10 | (defn make-test-token-manager [] 11 | (make-token-manager "https://github-api.example.com" "app-id" (slurp "test/example-private-key.pem"))) 12 | 13 | (deftest works 14 | (testing "App token is a valid JWT with App ID included as issuer" 15 | (let [tm (make-test-token-manager)] 16 | (is (= "app-id" (-> (get-app-token tm) JWT/decode bean :issuer))))) 17 | 18 | (testing "Installation token is retrieved correctly" 19 | (with-redefs [tm/make-app-token (fn [_ _] "app-token") 20 | http/post (fn [url opts] 21 | (is (= url "https://github-api.example.com/app/installations/1/access_tokens")) 22 | (is (= (:oauth-token opts) "app-token")) 23 | access-token-response)] 24 | (let [tm (make-test-token-manager)] 25 | (is (= "installation-token" (get-installation-token tm "1")))))) 26 | 27 | (testing "Installation token is cached" 28 | (let [tm (make-test-token-manager) 29 | times-called (atom 0)] 30 | (with-redefs [tm/make-app-token (fn [_ _] "app-token") 31 | http/post (fn [_ _] 32 | (swap! times-called inc) 33 | access-token-response)] 34 | (get-installation-token tm "1") 35 | (get-installation-token tm "1") 36 | (is (= 1 @times-called)))))) 37 | -------------------------------------------------------------------------------- /test/clj_github_app/webhook_signature_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.webhook-signature-test 2 | (:require [clj-github-app.webhook-signature :refer :all :as ws] 3 | [clojure.test :refer :all] 4 | [pandect.algo.sha1 :as sha1] 5 | [pandect.algo.sha256 :as sha256])) 6 | 7 | (deftest works 8 | (testing "When webhook secret is blank, returns :clj-github-app.webhook-signature/not-checked" 9 | (are [?in] 10 | (= ::ws/not-checked (check-payload-signature ?in nil nil)) 11 | nil 12 | "" 13 | " ")) 14 | 15 | (testing "When X-Hub-Signature is blank or missing, returns :clj-github-app.webhook-signature/missing-signature" 16 | (are [?in] 17 | (= ::ws/missing-signature (check-payload-signature "secret" ?in nil)) 18 | nil 19 | "" 20 | " ")) 21 | 22 | (testing "" 23 | (are [?payload ?res] 24 | (= ?res (check-payload-signature "secret" (str "sha1=" (sha1/sha1-hmac "signed-payload" "secret")) ?payload)) 25 | "signed-payload" :clj-github-app.webhook-signature/ok 26 | "tampered-payload" :clj-github-app.webhook-signature/wrong-signature)) 27 | 28 | (testing "When webhook secret is blank, returns :clj-github-app.webhook-signature/not-checked" 29 | (are [?in] 30 | (= ::ws/not-checked (check-payload-signature-256 ?in nil nil)) 31 | nil 32 | "" 33 | " ")) 34 | 35 | (testing "When X-Hub-Signature-256 is blank or missing, returns :clj-github-app.webhook-signature/missing-signature" 36 | (are [?in] 37 | (= ::ws/missing-signature (check-payload-signature-256 "secret" ?in nil)) 38 | nil 39 | "" 40 | " ")) 41 | 42 | (testing "" 43 | (are [?payload ?res] 44 | (= ?res (check-payload-signature-256 "secret" (str "sha256=" (sha256/sha256-hmac "signed-payload" "secret")) ?payload)) 45 | "signed-payload" :clj-github-app.webhook-signature/ok 46 | "tampered-payload" :clj-github-app.webhook-signature/wrong-signature))) 47 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## [0.3.0] — 2024-12-06 11 | ### Changed 12 | * Upgrade dependencies 13 | * cheshire from 5.11.0 to 5.13.0 14 | * clj-http from 3.12.3 to 3.13.0 15 | * org.clojure/core.cache from 1.0.225 to 1.1.234 16 | * com.auth0/java-jwt from 4.0.0 to 4.4.0 17 | * org.bouncycastle/* from 1.78.1 to 1.79 18 | * Remove some dependencies 19 | * ring/ring-codec 20 | * org.bovinegenius/exploding-fish 21 | 22 | ## [0.2.2] — 2024-08-07 23 | ### Changed 24 | * Bump dependencies 25 | 26 | ## [0.2.1] — 2024-08-06 27 | 28 | ## [0.2.0] — 2022-10-03 29 | 30 | ## [0.1.4] — 2021-03-10 31 | ### Changed 32 | * Update github url to address deprecation 33 | 34 | ### Added 35 | * Include cheshire as a project dependency 36 | 37 | ## [0.1.3] — 2019-01-23 38 | ### Changed 39 | * Bump library versions 40 | 41 | ## [0.1.2] — 2018-11-11 42 | ### Changed 43 | * Bump library versions 44 | 45 | ## [0.1.1] — 2018-09-03 46 | ### Added 47 | * Development-related: 48 | * Use lein-ancient in CI to prevent outdated dependencies 49 | * Use lein-changelog to automate changelog tasks 50 | 51 | ## 0.1.0 — 2018-08-21 52 | ### Added 53 | * Webhook payload signature checker with secure comparison. 54 | * API client with HTTP connection pool. 55 | * Access token manager with caching 56 | 57 | [0.1.1]: https://github.com/nubank/clj-github-app/compare/0.1.0...0.1.1 58 | [0.1.2]: https://github.com/nubank/clj-github-app/compare/0.1.1...0.1.2 59 | [0.1.3]: https://github.com/nubank/clj-github-app/compare/0.1.2...0.1.3 60 | [0.1.4]: https://github.com/nubank/clj-github-app/compare/0.1.3...0.1.4 61 | [0.2.0]: https://github.com/nubank/clj-github-app/compare/0.1.4...0.2.0 62 | [0.2.1]: https://github.com/nubank/clj-github-app/compare/0.2.0...0.2.1 63 | [0.2.2]: https://github.com/nubank/clj-github-app/compare/0.2.1...0.2.2 64 | [Unreleased]: https://github.com/nubank/clj-github-app/compare/0.2.2...HEAD 65 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject nubank/clj-github-app "0.3.0" 2 | :description "A library to implement GitHub Apps in Clojure." 3 | :url "http://github.com/nubank/clj-github-app" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :repositories [["publish" {:url "https://clojars.org/repo" 7 | :username :env/clojars_username 8 | :password :env/clojars_passwd 9 | :sign-releases false}]] 10 | :dependencies [[cheshire/cheshire "5.13.0"] 11 | [clj-http/clj-http "3.13.0"] 12 | [org.clojure/core.cache "1.1.234"] 13 | [com.auth0/java-jwt "4.4.0"] 14 | [org.bouncycastle/bcpkix-jdk18on "1.79"] 15 | [org.bouncycastle/bcprov-jdk18on "1.79"] 16 | [pandect/pandect "1.0.2"] 17 | [crypto-equality/crypto-equality "1.0.1"]] 18 | :plugins [[lein-ancient "0.7.0"] 19 | [lein-changelog "0.3.2"] 20 | [lein-cljfmt "0.9.2" :exclusions [org.clojure/clojure]] 21 | [lein-cloverage "1.2.4"] 22 | [lein-nsorg "0.3.0" :exclusions [org.clojure/clojure]] 23 | [lein-shell "0.5.0"]] 24 | :profiles {:dev {:dependencies [[org.clojure/clojure "1.12.0"]]}} 25 | :deploy-repositories [["releases" :clojars]] 26 | :aliases {"update-readme-version" ["shell" "sed" "-i" "s|\\\\[nubank/clj-github-app \"[0-9.]*\"\\\\]|[nubank/clj-github-app \"${:version}\"]|" "README.md"] 27 | "lint" ["do" ["cljfmt" "check"] ["nsorg"]] 28 | "lint-fix" ["do" ["cljfmt" "fix"] ["nsorg" "--replace"]]} 29 | :release-tasks [["shell" "git" "diff" "--exit-code"] 30 | ["change" "version" "leiningen.release/bump-version"] 31 | ["change" "version" "leiningen.release/bump-version" "release"] 32 | ["changelog" "release"] 33 | ["update-readme-version"] 34 | ["vcs" "commit"] 35 | ["vcs" "tag"] 36 | ["deploy"] 37 | ["vcs" "push"]]) 38 | -------------------------------------------------------------------------------- /src/clj_github_app/client.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.client 2 | (:require [clj-github-app.token-manager :as token-manager] 3 | [clj-http.client :as http] 4 | [clj-http.conn-mgr :as conn-mgr] 5 | [clojure.string :as str]) 6 | (:import (java.lang AutoCloseable) 7 | (java.net URI))) 8 | 9 | (defprotocol AppClient 10 | (app-request* [_ opts]) 11 | (app-request [_ method url opts]) 12 | (request* [_ installation-id opts]) 13 | (request [_ installation-id method url opts])) 14 | 15 | (defn request-impl [connection-pool token opts] 16 | (http/request 17 | (merge {:oauth-token token 18 | :connection-manager connection-pool 19 | :as :json} 20 | opts))) 21 | 22 | (defn remove-leading-slash [url-or-path] 23 | (let [trimmed-url-or-path (str/trim url-or-path)] 24 | (if (= \/ (first trimmed-url-or-path)) 25 | (subs trimmed-url-or-path 1) 26 | trimmed-url-or-path))) 27 | 28 | (defn resolve-url [path-or-url ^String github-api-url] 29 | (-> (URI/create (str github-api-url "/")) 30 | (.resolve ^String (remove-leading-slash path-or-url)) 31 | .normalize 32 | .toString)) 33 | 34 | (defrecord AppClientImpl [github-api-url token-manager connection-pool] 35 | AppClient 36 | 37 | (app-request* [_ opts] 38 | (let [app-token (token-manager/get-app-token token-manager)] 39 | (request-impl connection-pool app-token (update opts :url resolve-url github-api-url)))) 40 | 41 | (app-request [this method path-or-url opts] 42 | (app-request* this (merge {:method method :url path-or-url} opts))) 43 | 44 | (request* [_ installation-id opts] 45 | (let [installation-token (token-manager/get-installation-token token-manager installation-id)] 46 | (request-impl connection-pool installation-token (update opts :url resolve-url github-api-url)))) 47 | 48 | (request [this installation-id method path-or-url opts] 49 | (request* this installation-id (merge {:method method :url path-or-url} opts))) 50 | 51 | AutoCloseable 52 | (close [_] 53 | (conn-mgr/shutdown-manager connection-pool))) 54 | 55 | (defn make-app-client [github-api-url github-app-id private-key-pem-str connection-pool-opts] 56 | (AppClientImpl. 57 | github-api-url 58 | (token-manager/make-token-manager github-api-url github-app-id private-key-pem-str) 59 | (conn-mgr/make-reusable-conn-manager connection-pool-opts))) 60 | -------------------------------------------------------------------------------- /test/clj_github_app/client_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.client-test 2 | (:require [clj-github-app.client :as client] 3 | [clj-http.client :as http] 4 | [clojure.test :refer :all])) 5 | 6 | (defn make-test-client [] 7 | (client/make-app-client "https://github.example.com/api/v3" "app-id" (slurp "test/example-private-key.pem") {})) 8 | 9 | (def access-token-response {:body {:token "installation-token" 10 | :expires_at "2100-07-11T22:14:10Z"}}) 11 | 12 | (deftest about-url-passing 13 | (testing "User is able to provide both full URL or just a path, which is resolved against the configured base API URL" 14 | 15 | (testing "with app-request and app-request*" 16 | (are [?path-or-url ?resulting-url] 17 | (let [resulting-url (atom nil)] 18 | (with-redefs [client/request-impl (fn [_ _ opts] 19 | (reset! resulting-url (:url opts)))] 20 | (with-open [c (make-test-client)] 21 | (client/app-request c :get ?path-or-url {}) 22 | (client/app-request* c {:method :get :url ?path-or-url}))) 23 | (= ?resulting-url @resulting-url)) 24 | "foo" "https://github.example.com/api/v3/foo" 25 | "https://github.example.com/api/v3/bar" "https://github.example.com/api/v3/bar" 26 | "https://api.github.com/bar" "https://api.github.com/bar")) 27 | 28 | (testing "with request and request*" 29 | (are [?path-or-url ?resulting-url] 30 | (let [resulting-url (atom nil)] 31 | (with-redefs [http/post (fn [_ _] 32 | access-token-response) 33 | client/request-impl (fn [_ _ opts] 34 | (reset! resulting-url (:url opts)))] 35 | (with-open [c (make-test-client)] 36 | (client/request c "inst-id" :get ?path-or-url {}) 37 | (client/request* c "inst-id" {:method :get :url ?path-or-url}))) 38 | (= ?resulting-url @resulting-url)) 39 | "foo" "https://github.example.com/api/v3/foo" 40 | "https://github.example.com/api/v3/bar" "https://github.example.com/api/v3/bar" 41 | "https://api.github.com/bar" "https://api.github.com/bar")))) 42 | 43 | (deftest about-resolve-url 44 | (testing "Handles correctly all slash combinations" 45 | (are [?github-api-url ?path-or-url] 46 | (= "https://github.example.com/api/v3/foo/bar" (client/resolve-url ?path-or-url ?github-api-url)) 47 | "https://github.example.com/api/v3" "foo/bar" 48 | "https://github.example.com/api/v3/" "foo/bar" 49 | "https://github.example.com/api/v3" "/foo/bar" 50 | "https://github.example.com/api/v3/" "/foo/bar"))) 51 | -------------------------------------------------------------------------------- /src/clj_github_app/token_manager.clj: -------------------------------------------------------------------------------- 1 | (ns clj-github-app.token-manager 2 | (:require [clj-http.client :as http] 3 | [clojure.core.cache :as cache]) 4 | (:import (clojure.core.cache CacheProtocol) 5 | (com.auth0.jwt JWT) 6 | (com.auth0.jwt.algorithms Algorithm) 7 | (java.io StringReader) 8 | (java.net URI URLEncoder) 9 | (java.nio.charset StandardCharsets) 10 | (java.security KeyFactory) 11 | (java.security.spec PKCS8EncodedKeySpec) 12 | (java.text SimpleDateFormat) 13 | (java.util Date) 14 | (org.bouncycastle.jce.provider BouncyCastleProvider) 15 | (org.bouncycastle.openssl PEMParser))) 16 | 17 | 18 | ;; See make-token-manager function below 19 | 20 | 21 | (defprotocol GitHubTokenManager 22 | (get-app-token [token-manager]) 23 | (get-installation-token [token-manager installation-id])) 24 | 25 | (defn- make-signing-algorithm [pem-str] 26 | (let [private-key (->> pem-str 27 | (StringReader.) 28 | (PEMParser.) 29 | (.readPemObject) 30 | (.getContent) 31 | (PKCS8EncodedKeySpec.) 32 | (.generatePrivate (KeyFactory/getInstance "RSA" (BouncyCastleProvider.))))] 33 | ;; Only private key given (only for signing, not for verifying) 34 | (Algorithm/RSA256 nil private-key))) 35 | 36 | (defn- make-app-token [signing-algorithm app-id] 37 | ;; If you get: 'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued 38 | ;; this means issuedAt is in the future according to GitHub's clock 39 | (let [now (Date.) 40 | now-30s (Date. ^long (-> now (.getTime) (- (* 1000 30)))) 41 | now+8m (Date. ^long (-> now (.getTime) (+ (* 1000 60 8))))] 42 | (-> (JWT/create) 43 | (.withIssuer (str app-id)) 44 | (.withIssuedAt now-30s) 45 | (.withExpiresAt now+8m) 46 | (.sign signing-algorithm)))) 47 | 48 | (cache/defcache GithubAppTokenCache [cache] 49 | CacheProtocol 50 | (lookup [this item] 51 | (let [ret (cache/lookup this item ::nope)] 52 | (when-not (= ::nope ret) ret))) 53 | (lookup [this item not-found] 54 | (if (cache/has? this item) 55 | (get cache item) 56 | not-found)) 57 | (has? [this item] 58 | (let [now (Date.) 59 | {:keys [expires-at-parsed]} (get cache item)] 60 | (when expires-at-parsed 61 | (.before now expires-at-parsed)))) 62 | (hit [this item] this) 63 | (miss [this item result] 64 | (let [now (Date.) 65 | expires-at-parsed (try 66 | (.parse (SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ssX") (:expires_at result)) 67 | (catch Exception _ 68 | now))] 69 | (GithubAppTokenCache. (assoc cache item (assoc result :expires-at-parsed expires-at-parsed))))) 70 | (seed [_ base] 71 | (GithubAppTokenCache. base)) 72 | (evict [_ item] 73 | (GithubAppTokenCache. (dissoc cache item))) 74 | Object 75 | (toString [_] 76 | (str cache))) 77 | 78 | (defrecord GitHubTokenManagerImpl [cache get-app-token-fn get-installation-token-fn] 79 | GitHubTokenManager 80 | (get-app-token [_] 81 | (get-app-token-fn)) 82 | (get-installation-token [_ installation-id] 83 | (:token (cache/lookup (swap! cache cache/through-cache installation-id get-installation-token-fn) 84 | installation-id)))) 85 | 86 | (defn- url-encode [^String s] 87 | (URLEncoder/encode s StandardCharsets/UTF_8)) 88 | 89 | (defn- installation-token-uri 90 | [github-api-url installation-id] 91 | (-> (URI/create (str github-api-url "/")) 92 | (.resolve (str "app/installations/" (url-encode (str installation-id)) "/access_tokens")) 93 | .normalize 94 | .toString)) 95 | 96 | (defn make-token-manager [github-api-url github-app-id private-key-pem-str] 97 | (let [signing-algorithm (make-signing-algorithm private-key-pem-str) 98 | cache (atom (GithubAppTokenCache. {}))] 99 | (GitHubTokenManagerImpl. 100 | cache 101 | (fn [] 102 | (make-app-token signing-algorithm github-app-id)) 103 | (fn [installation-id] 104 | (let [url (installation-token-uri github-api-url installation-id)] 105 | (:body (http/post url 106 | {:oauth-token (make-app-token signing-algorithm github-app-id) 107 | :as :json 108 | :accept "application/vnd.github.machine-man-preview+json"}))))))) 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clj-github-app 2 | [![Build Status](https://travis-ci.org/nubank/clj-github-app.svg?branch=master)](https://travis-ci.org/nubank/clj-github-app) 3 | [![codecov](https://codecov.io/gh/nubank/clj-github-app/branch/master/graph/badge.svg)](https://codecov.io/gh/nubank/clj-github-app) 4 | [![Clojars Project](https://img.shields.io/clojars/v/nubank/clj-github-app.svg)](https://clojars.org/nubank/clj-github-app) 5 | 6 | A library to implement [GitHub Apps] in Clojure. 7 | 8 | ```clj 9 | [nubank/clj-github-app "0.3.0"] 10 | ``` 11 | 12 | Includes: 13 | 14 | * [Webhook payload signature checker][webhook-signatures] with [secure comparison](https://github.com/weavejester/crypto-equality). 15 | * API client with HTTP connection pool. 16 | * Access token manager with caching ([Authenticating with GitHub Apps] is tricky). 17 | 18 | ## Usage 19 | 20 | ### Checking webhook signatures 21 | 22 | When implementing a webhook handler, it is recommended to check the webhook request signature before processing it. 23 | Please read the [official documentation][webhook-signatures] first. 24 | 25 | Imagine you have a webhook handler: 26 | 27 | ```clj 28 | (ns your-project.webhooks 29 | (:require [clj-github-app.webhook-signature :as webhook-signature])) 30 | 31 | (def GITHUB_WEBHOOK_SECRET (System/getenv "GITHUB_WEBHOOK_SECRET")) 32 | 33 | (defn post-github 34 | "Checks if the webhook is valid and handles it." 35 | [request] 36 | (let [{:strs [x-github-delivery x-github-event x-hub-signature-256]} (:headers request) 37 | payload (slurp (:body request))] 38 | (case (webhook-signature/check-payload-signature-256 GITHUB_WEBHOOK_SECRET x-hub-signature-256 payload) 39 | ::webhook-signature/missing-signature {:status 400 :body "x-hub-signature-256 header is missing"} 40 | ::webhook-signature/wrong-signature {:status 401 :body "x-hub-signature-256 does not match"} 41 | (let [parsed-payload (json/parse-string payload keyword)] 42 | ;; process your webhook here 43 | {:status 200 :body "This is fine."})))) 44 | ``` 45 | 46 | The key part here is the call to `check-payload-signature-256`. It takes 3 arguments: 47 | 48 | * `webhook-secret` — the exact secret string that you set when configuring webhook for your repo. 49 | If this argument is blank or nil, `check-payload-signature-256` will do nothing and return 50 | `:clj-github-app.webhook-signature/not-checked`. 51 | * `x-hub-signature-256` — contents of "X-Hub-Signature-256" request header. 52 | * `payload` — request body as a string. 53 | 54 | Possible return values: 55 | 56 | * `:clj-github-app.webhook-signature/ok` — signature matches the payload. 57 | * `:clj-github-app.webhook-signature/wrong-signature` — signature does not match the payload. 58 | * `:clj-github-app.webhook-signature/missing-signature` — `x-hub-signature` parameter was blank or nil. 59 | * `:clj-github-app.webhook-signature/not-checked` — no check was done because `webhook-secret` parameter was blank or nil. 60 | 61 | 62 | ### Authenticating as a GitHub App 63 | 64 | Please read [Authenticating with GitHub Apps] official documentation first. 65 | 66 | Example (uses [mount-lite]): 67 | 68 | ```clj 69 | (ns your-project.external.github 70 | (:require [mount.lite :as m] 71 | [clj-github-app.client :as client])) 72 | 73 | (def GITHUB_API_URL "https://api.github.com") 74 | (def GITHUB_APP_ID (System/getenv "GITHUB_APP_ID")) 75 | (def GITHUB_APP_PRIVATE_KEY_PEM (System/getenv "GITHUB_APP_PRIVATE_KEY_PEM")) 76 | 77 | (m/defstate client 78 | :start (client/make-app-client GITHUB_API_URL GITHUB_APP_ID GITHUB_APP_PRIVATE_KEY_PEM {}) 79 | :stop (.close @client)) 80 | ``` 81 | 82 | `clj-github-app.client/make-app-client` takes 4 parameters: 83 | 84 | * `github-api-url` — Base URL of GitHub API. Usually `https://api.github.com` or something like `https://github.example.com/api/v3` for GHE. 85 | * `github-app-id` — GitHub App ID as string (can be found on the app settings page). 86 | * `private-key-pem-str` — String contents of the private key file that you [generated when configuring the app](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#generating-a-private-key). 87 | * `connection-pool-opts` — [clj-http connection pool parameters](https://github.com/dakrone/clj-http#persistent-connections). 88 | Can be set to `{}` to use all defaults. 89 | 90 | It returns an object that implements `AutoCloseable` interface and `AppClient` protocol, which has the following functions: 91 | 92 | * `request*` — to [authenticate as an installation][as-installation]. 93 | Given `installation-id` and `opts`, makes an HTTP request to GitHub API, automatically retrieving an access token. 94 | Uses [clj-http], `opts` argument is given to `request` function as described [here](https://github.com/dakrone/clj-http#raw-request). 95 | `opts` is supposed to include `:method` and `:url` keys. 96 | This function is the main workhorse. 97 | * `request` — same as `request*`, but has separate arguments for method and URL. 98 | * `app-request*` — to [authenticate as a GitHub App][as-app]. 99 | This is only useful for querying app metadata. 100 | * `app-request` — same as `app-request*`, but has separate arguments for method and URL. 101 | 102 | You can [authenticate as a GitHub App][as-app]: 103 | 104 | ```clj 105 | (client/app-request* @client {:method :get :url "/app" :accept "application/vnd.github.machine-man-preview+json"}) 106 | (client/app-request @client :get "/app" {:accept "application/vnd.github.machine-man-preview+json"}) 107 | ``` 108 | 109 | You can also [authenticate as an installation][as-installation]. For this you need Installation ID, 110 | (which is usually given to you in webhook payloads): 111 | 112 | ```clj 113 | (client/request* @client 42 {:method :get :url "/repos/myname/myrepo/issues/123/comments") 114 | (client/request @client 42 :get "/repos/myname/myrepo/issues/123/comments" {}) 115 | ``` 116 | 117 | All these functions can accept either a full URL or just a relative path, which will be automatically appended to the base 118 | GitHub API URL, given earlier to `make-app-client`. 119 | The "path only" mode is useful when you are constructing the URL yourself and don't want to repeat the base API URL there. 120 | The path can start with a `/` or not, which makes no difference, both cases are handled the same way. 121 | The "full URL" mode is useful when you use a URL extracted from a webhook payload 122 | and don't want to strip the base URL part from there. 123 | 124 | ```clj 125 | ;; Use github-api-url (provided earlier to make-app-client) as base API URL 126 | (client/app-request @client :get "foo" {}) 127 | (client/app-request @client :get "/foo" {}) 128 | ;; The same call, but without relying on github-api-url 129 | (client/app-request @client :get "https://api.github.com/foo" {}) 130 | ``` 131 | 132 | #### Convenience wrappers for API endpoints 133 | 134 | This library does not provide any wrappers like 135 | 136 | ```clj 137 | (list-issue-comments "owner" "repo" "123" {:since "2018-01-01"}) 138 | ``` 139 | 140 | Such wrappers are really easy to implement on your own: 141 | 142 | ```clj 143 | (defn create-list-issue-comments-request [owner repo issue-number params] 144 | {:method :get 145 | :url (format "/repos/%s/%s/issues/%s/comments" owner repo issue-number) 146 | :query-params params}) 147 | ``` 148 | 149 | and then use like this: 150 | 151 | ```clj 152 | (client/request @client 42 (create-list-issue-comments-request "owner" "repo" "123" {:since "2018-01-01"})) 153 | ``` 154 | 155 | Full GitHub API reference can be found [here](https://developer.github.com/v3/). 156 | 157 | ## Development 158 | 159 | With every commit, add important changes from it to the "Unreleased" section of _CHANGELOG.md_. 160 | 161 | ### Release procedure 162 | 163 | Run `lein release` as described below, depending on how much changes are made since previous release. 164 | 165 | Library version will be updated in _project.clj_ and _README.md_ automatically after calling `lein release`. 166 | `## Unreleased` section int _CHANGELOG.md_ will be automatically changed into the version being released. 167 | 168 | lein release :patch 169 | # or 170 | lein release :minor 171 | # or 172 | lein release :major 173 | 174 | ## License 175 | 176 | Copyright © 2018 Dmitrii Balakhonskii 177 | 178 | Distributed under the Eclipse Public License version 1.0. 179 | 180 | 181 | [GitHub Apps]: https://developer.github.com/apps/about-apps/#about-github-apps 182 | [Authenticating with GitHub Apps]: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/ 183 | [webhook-signatures]: https://developer.github.com/webhooks/securing/#validating-payloads-from-github 184 | [as-app]: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#accessing-api-endpoints-as-a-github-app 185 | [as-installation]: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#accessing-api-endpoints-as-an-installation 186 | [clj-http]: https://github.com/dakrone/clj-http 187 | [mount-lite]: https://github.com/aroemers/mount-lite 188 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor to control, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | --------------------------------------------------------------------------------