Line data Source code
1 4 : (ns matchscore.access.middleware
2 : "Ring middleware that reads `:authz` metadata off the handler var and
3 : calls the access core to authorize the request.
4 :
5 : Metadata shape (all keys optional except :obj and :act):
6 :
7 : {:authz {:obj :template ; resource type keyword
8 : :act :update ; action keyword
9 : :id :route-params/uuid ; where to read the resource id from
10 : :via :class ; optional traversal: resolve id via this parent
11 : :participant? false ; set false to skip participant join (join/leave)
12 : :create? true ; skip fetch, build create-obj instead
13 : :dom \"*\" ; literal domain (default \"*\")
14 : :dom-from \"*\" ; dynamic domain source
15 : :obj-resolver some.ns/fn ; (request) -> obj-map, wins over declarative keys
16 : :public? true}} ; opt-in public access (short-circuits check)
17 :
18 : - No `:authz` on the handler → request passes through (rollout is opt-in).
19 : - `:public? true` → request passes through (documents intent).
20 : - `:create? true` → obj-map built via resource/create-obj, no DB fetch.
21 : - `:id` namespaced keyword → resource id resolved from :route-params/<k> or :body/<k>.
22 : - `:via` keyword → id treated as parent; resolvers/via-fns walks to resource id.
23 : - `:obj-resolver` fn/var → custom resolver wins over all declarative keys.
24 : - Otherwise `wrap-authorize` → resolves domain + obj-map and calls
25 : `access.core/authorize!`, which throws `:api-forbidden` on deny.
26 : The exception is mapped to 403 by `wrap-exception-handling`.
27 :
28 : This wrapper is applied at route-build time around handlers already
29 : wrapped by `extract-schema-from-meta`, so `:auth-headers` and `:ctx`
30 : are present on the request when the check fires."
31 : (:require
32 : [matchscore.access.core :as access]
33 : [matchscore.access.resolvers :as resolvers]
34 : [matchscore.access.resource :as resource]
35 : [matchscore.domain.event.repository.postgres :as event-repo]
36 : [matchscore.domain.template.repository.postgres :as template-repo]
37 : [matchscore.utils.uuid :as uuid-utils]))
38 :
39 :
40 4 : (defn- -resolve-entity-uuid
41 : "Resolve a public UUID to an internal UUID by trying public ID first and then UUID.
42 : Returns nil when no row is found."
43 : [repo find-by-public-id find-by-id raw-id]
44 12 : (when raw-id
45 18 : (or
46 20 : (:uuid (find-by-public-id repo))
47 : (try
48 20 : (:uuid (find-by-id repo))
49 : (catch Exception _ nil)))))
50 :
51 :
52 4 : (defn- request-context
53 : [request]
54 12 : (assoc (select-keys request [:request-method :uri :path-info :route-params])
55 5 : :body-present? (some? (:body request))
56 6 : :auth-header-present? (boolean (seq (:auth-headers request)))))
57 :
58 :
59 4 : (defn- config-error!
60 : [message data request]
61 1 : (throw
62 2 : (ex-info
63 1 : message
64 6 : (assoc data
65 : :type :access/config-error
66 3 : :request (request-context request)))))
67 :
68 :
69 4 : (defn- resolve-dom
70 : [authz request]
71 16 : (let [dom-from (:dom-from authz)
72 12 : dom (:dom authz)]
73 16 : (cond
74 4 : dom dom
75 16 : (nil? dom-from) "*"
76 3 : (= "*" dom-from) "*"
77 3 : (keyword? dom-from)
78 4 : (let [ns* (namespace dom-from)
79 5 : name* (keyword (name dom-from))]
80 3 : (case ns*
81 10 : "route-params" (or (get-in request [:route-params name*]) "*")
82 0 : "body" (or (get-in request [:body name*]) "*")
83 0 : "auth" (or (get-in request [:auth-headers (keyword "user" (name name*))]) "*")
84 2 : (config-error!
85 4 : (str "Unknown :dom-from namespace: " dom-from)
86 3 : {:dom-from dom-from}
87 1 : request)))
88 :
89 : :else
90 10 : (config-error! (str "Invalid :dom-from metadata: " dom-from) {:dom-from dom-from} request))))
91 :
92 :
93 4 : (defn- resolve-id
94 : "Extracts a value from the request using a namespaced keyword like
95 : :route-params/template-uuid or :body/uuid. Returns nil if id-loc is nil."
96 : [request id-loc]
97 12 : (when id-loc
98 16 : (if (keyword? id-loc)
99 16 : (let [ns* (namespace id-loc)
100 20 : k (keyword (name id-loc))]
101 12 : (case ns*
102 24 : "route-params" (get-in request [:route-params k])
103 12 : "body" (get-in request [:body k])
104 0 : "auth" (get-in request [:auth-headers (keyword "user" (name k))])
105 10 : (config-error! (str "Unknown :id namespace: " id-loc) {:id id-loc} request)))
106 10 : (config-error! (str "Invalid :id metadata: " id-loc) {:id id-loc} request))))
107 :
108 :
109 4 : (defn- resolve-obj
110 : [authz request]
111 44 : (let [ctx (assoc (:ctx request) :auth-headers (:auth-headers request))
112 12 : obj-type (:obj authz)
113 12 : resolver (:obj-resolver authz)
114 34 : typed #(cond-> % (and % (not (contains? % :type))) (assoc :type (name obj-type)))]
115 12 : (cond
116 : ;; 1. Custom resolver wins (escape hatch).
117 28 : resolver (let [rfn (if (var? resolver) @resolver resolver)] (typed (rfn request)))
118 :
119 : ;; 2. Create path — no resource lookup needed.
120 36 : (:create? authz) (resource/create-obj ctx (name obj-type))
121 :
122 : ;; 3. Declarative fetch with optional :via traversal.
123 : :else
124 28 : (let [parent-id (resolve-id request (:id authz))
125 30 : actual-id (if-let [via (:via authz)]
126 12 : (let [via-fn (get resolvers/via-fns via)]
127 15 : (when (nil? via-fn)
128 0 : (config-error! (str "Unknown :via key: " via) {:via via} request))
129 12 : (via-fn ctx parent-id))
130 4 : parent-id)
131 12 : fetch-fn (get resolvers/fetch-fns obj-type)
132 41 : opts (cond-> {} (false? (:participant? authz)) (assoc :participant? false))
133 49 : obj-map (when (and fetch-fn actual-id) (fetch-fn ctx actual-id opts))]
134 8 : (if actual-id
135 20 : (resolvers/require-or-404! obj-map obj-type actual-id)
136 6 : (resource/create-obj ctx (name obj-type)))))))
137 :
138 :
139 4 : (defn wrap-authorize-with-meta
140 : "Wraps an already-schema-wrapped handler with `:authz` enforcement.
141 : `authz-meta` is the `:authz` map from the original handler var's
142 : metadata; nil / `:public? true` short-circuits to a pass-through."
143 : [handler authz-meta]
144 32 : (cond (nil? authz-meta) handler
145 16 : (:public? authz-meta) handler
146 : :else
147 4 : (fn [request]
148 28 : (let [user-uuid (get-in request [:auth-headers :user/uuid])
149 12 : ctx (:ctx request)
150 16 : dom (resolve-dom authz-meta request)
151 16 : obj (resolve-obj authz-meta request)
152 12 : act (:act authz-meta)]
153 28 : (access/authorize! ctx user-uuid dom obj act)
154 12 : (handler request)))))
155 :
156 :
157 4 : (defn extract-authz-meta
158 : "Pulls `:authz` from a handler var. Returns nil if `routes` is not a var
159 : or does not carry the metadata."
160 : [routes]
161 40 : (when (var? routes) (:authz (meta routes))))
162 :
163 :
164 4 : (defn wrap-resolve-entity-ids
165 : "Middleware that resolves public IDs in route params and body to UUIDs before
166 : authorization and schema validation run. Replaces :event-uuid and
167 : :template-uuid if present in route params. Also resolves :uuid in the request
168 : body for event and template update routes when the value is a public-id (not a
169 : UUID). Throws :api-not-found if the entity does not exist."
170 : [handler]
171 4 : (fn [request]
172 16 : (let [route-params (:route-params request)
173 24 : repos (get-in request [:ctx :repos])
174 12 : event-pub-id (:event-uuid route-params)
175 12 : tmpl-pub-id (:template-uuid route-params)]
176 20 : (if (nil? repos)
177 3 : (handler request)
178 16 : (let [event-uuid (when event-pub-id
179 16 : (-resolve-entity-uuid
180 12 : (:event-postgres-repo repos)
181 16 : #(event-repo/find-by-public-id % event-pub-id)
182 20 : #(event-repo/find-by-id % event-pub-id nil)
183 4 : event-pub-id))
184 11 : tmpl-uuid (when tmpl-pub-id
185 12 : (-resolve-entity-uuid
186 9 : (:template-postgres-repo repos)
187 12 : #(template-repo/find-by-public-id % tmpl-pub-id)
188 15 : #(template-repo/find-by-id % tmpl-pub-id nil)
189 3 : tmpl-pub-id))
190 24 : body-id (get-in request [:body :uuid])
191 37 : path (or (:path-info request) (:uri request))
192 : [body-entity-type body-uuid]
193 5 : (when
194 29 : (and
195 4 : body-id
196 15 : (not (uuid-utils/uuid-string? body-id))
197 6 : (#{:put :patch} (:request-method request)))
198 6 : (cond (re-find #"/events$" path)
199 2 : [:event
200 4 : (-resolve-entity-uuid
201 3 : (:event-postgres-repo repos)
202 4 : #(event-repo/find-by-public-id % body-id)
203 5 : #(event-repo/find-by-id % body-id nil)
204 1 : body-id)]
205 :
206 4 : (re-find #"/templates$" path)
207 2 : [:template
208 4 : (-resolve-entity-uuid
209 3 : (:template-postgres-repo repos)
210 4 : #(template-repo/find-by-public-id % body-id)
211 0 : #(template-repo/find-by-id % body-id nil)
212 1 : body-id)]))]
213 52 : (cond (and event-pub-id (nil? event-uuid))
214 1 : (throw
215 3 : (ex-info
216 : "Event not found"
217 5 : {:type :api-not-found
218 : :message "Event not found"}))
219 :
220 32 : (and tmpl-pub-id (nil? tmpl-uuid))
221 1 : (throw
222 3 : (ex-info
223 : "Template not found"
224 5 : {:type :api-not-found
225 : :message "Template not found"}))
226 :
227 24 : (and body-entity-type (nil? body-uuid))
228 1 : (throw
229 2 : (ex-info
230 6 : (str (name body-entity-type) " not found")
231 4 : {:type :api-not-found
232 6 : :message (str (name body-entity-type) " not found")}))
233 :
234 : :else
235 8 : (handler
236 14 : (->
237 16 : (update
238 4 : request
239 : :route-params
240 37 : #(cond-> %
241 20 : event-uuid (assoc :event-uuid event-uuid)
242 10 : tmpl-uuid (assoc :template-uuid tmpl-uuid)))
243 9 : (cond-> body-uuid (assoc-in [:body :uuid] body-uuid))))))))))
|