Joaquín Reñé
2026-03-27 4ee50e257b32f6ec0f72907305d1f2b1212808a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
* Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
*/
package net.curisit.securis.ioc;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.Provider;
import jakarta.ws.rs.ext.WriterInterceptor;
import jakarta.ws.rs.ext.WriterInterceptorContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.curisit.securis.db.User;
import net.curisit.securis.security.BasicSecurityContext;
import net.curisit.securis.security.Securable;
import net.curisit.securis.utils.CacheTTL;
import net.curisit.securis.utils.TokenHelper;
/**
* RequestsInterceptor
* <p>
* Authentication/authorization interceptor that:
* <ul>
*   <li>Loads and stores the {@link EntityManager} in the request context.</li>
*   <li>Validates tokens for methods annotated with {@link Securable}.</li>
*   <li>Builds a {@link BasicSecurityContext} with roles and scoped organization/application IDs.</li>
*   <li>Manages transactions when {@code @EnsureTransaction} is present.</li>
* </ul>
*
* <p><b>Cache usage:</b> Uses {@link CacheTTL} to cache roles and scope sets.
* The new {@link CacheTTL#getSet(String, Class)} helper removes unchecked
* conversion warnings when retrieving {@code Set<Integer>} from the cache.
* @author JRA
* Last reviewed by JRA on Oct 5, 2025.
*/
@Provider
@Priority(Priorities.AUTHENTICATION)
public class RequestsInterceptor implements ContainerRequestFilter, WriterInterceptor {
    private static final Logger LOG = LogManager.getLogger(RequestsInterceptor.class);
    @Inject private CacheTTL cache;
    @Inject private TokenHelper tokenHelper;
    @Inject private EntityManagerProvider emProvider;
    @Context private HttpServletResponse servletResponse;
    @Context private HttpServletRequest servletRequest;
    @Context private ResourceInfo resourceInfo;
    private static final String EM_CONTEXT_PROPERTY = "curisit.entitymanager";
    // -------------------------------------------------------------
    // Request filter (authN/authZ + EM handling)
    // -------------------------------------------------------------
    /** 
     * filter<p>
     * Entry point before resource method invocation. 
     * 
     * @param requestContext
     * @throws IOException
     */
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        
        Method method = resourceInfo != null ? resourceInfo.getResourceMethod() : null;
        if (method == null) {
            LOG.warn("RequestsInterceptor: resource method is null");
            return;
        }
        boolean securable = method.isAnnotationPresent(Securable.class);
        boolean ensureTransaction = method.isAnnotationPresent(EnsureTransaction.class);
        // Only require injected helpers when the endpoint actually needs them
        if (securable) {
            if (tokenHelper == null || cache == null || emProvider == null) {
                LOG.error(
                    "RequestsInterceptor is not fully initialized for secured endpoint '{}'. " +
                    "tokenHelper={}, cache={}, emProvider={}",
                    method.getName(), tokenHelper, cache, emProvider
                );
                requestContext.abortWith(
                    Response.status(Status.INTERNAL_SERVER_ERROR)
                            .entity("Security infrastructure not initialized")
                            .build()
                );
                return;
            }
            if (!checkSecurableMethods(requestContext, method)) {
                return;
            }
        }
        // Only open/use EM when needed
        if (ensureTransaction || securable) {
            EntityManager em = getEntityManagerSafely();
            if (em == null) {
                LOG.error("No EntityManager available for method '{}'", method.getName());
                requestContext.abortWith(
                    Response.status(Status.INTERNAL_SERVER_ERROR)
                            .entity("Persistence infrastructure not initialized")
                            .build()
                );
                return;
            }
            LOG.debug("GETTING EM: {}", em);
            requestContext.setProperty(EM_CONTEXT_PROPERTY, em);
            if (ensureTransaction) {
                try {
                    if (!em.getTransaction().isActive()) {
                        LOG.debug("Beginning transaction");
                        em.getTransaction().begin();
                    }
                } catch (Exception e) {
                    LOG.error("Error beginning transaction for method '{}'", method.getName(), e);
                    requestContext.abortWith(
                        Response.status(Status.INTERNAL_SERVER_ERROR)
                                .entity("Could not begin transaction")
                                .build()
                    );
                }
            }
        }
    }
    /**
    * checkSecurableMethods<p>
    * Enforce security checks for methods annotated with {@link Securable}.
    * Builds {@link BasicSecurityContext} when authorized.
    *
    * @param ctx
    * @param method
    * @return true if request can proceed; false when aborted
    */
    private boolean checkSecurableMethods(ContainerRequestContext ctx, Method method) {
        if (!method.isAnnotationPresent(Securable.class)) {
            return true;
        }
        String token = servletRequest != null ? servletRequest.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM) : null;
        if (token == null || !tokenHelper.isTokenValid(token)) {
            LOG.warn("Access denied, invalid token");
            ctx.abortWith(Response.status(Status.UNAUTHORIZED).build());
            return false;
        }
        String username = tokenHelper.extractUserFromToken(token);
        int roles = getUserRoles(username);
        Securable securable = method.getAnnotation(Securable.class);
        if (securable.roles() != 0 && (securable.roles() & roles) == 0) {
            LOG.warn("User {} lacks required roles for method {}", username, method.getName());
            ctx.abortWith(Response.status(Status.UNAUTHORIZED).build());
            return false;
        }
        boolean secure = servletRequest != null && servletRequest.isSecure();
        BasicSecurityContext sc = new BasicSecurityContext(username, roles, secure);
        sc.setOrganizationsIds(getUserOrganizations(username));
        sc.setApplicationsIds(getUserApplications(username));
        ctx.setSecurityContext(sc);
        return true;
    }
    /**
     * getEntityManagerSafely<p>
     * Get the entity manager in a safely way
     * 
     * @return entityManager
     */
    private EntityManager getEntityManagerSafely() {
        try {
            if (emProvider == null) {
                return null;
            }
            return emProvider.getEntityManager();
        } catch (Exception e) {
            LOG.error("Error obtaining EntityManager from provider", e);
            return null;
        }
    }
    // -------------------------------------------------------------
    // Cached lookups (roles/orgs/apps)
    // -------------------------------------------------------------
    /**
    * getUserRoles<p>
    * Retrieve roles bitmask for the given user (cached).
    * 
    * @param username
    * @return userRoles
    */
    private int getUserRoles(String username) {
        if (username == null || cache == null) {
            return 0;
        }
        Integer cached = cache.get("roles_" + username, Integer.class);
        if (cached != null) {
            return cached;
        }
        EntityManager em = getEntityManagerSafely();
        if (em == null) {
            LOG.error("Cannot resolve user roles: EntityManager is not available");
            return 0;
        }
        User user = em.find(User.class, username);
        int roles = 0;
        if (user != null) {
            List<Integer> r = user.getRoles();
            if (r != null) {
                for (Integer role : r) {
                    roles += role;
                }
            }
            cache.set("roles_" + username, roles, 3600);
            cache.set("orgs_" + username, user.getOrgsIds(), 3600);
        }
        return roles;
    }
    /**
    * getUserOrganizations<p>
    * Retrieve organization scope for the user as a typed {@code Set<Integer>}
    * using the cache helper that validates element types.
    * 
    * @param username
    * @return userOrganizations
    */
    private Set<Integer> getUserOrganizations(String username) {
        if (username == null || cache == null) {
            return Set.of();
        }
        Set<Integer> cached = cache.getSet("orgs_" + username, Integer.class);
        if (cached != null) {
            return cached;
        }
        EntityManager em = getEntityManagerSafely();
        if (em == null) {
            LOG.error("Cannot resolve user organizations: EntityManager is not available");
            return Set.of();
        }
        User user = em.find(User.class, username);
        if (user != null) {
            Set<Integer> result = user.getAllOrgsIds();
            cache.set("orgs_" + username, result, 3600);
            return result;
        }
        return Set.of();
    }
    /**
    * getUserApplications<p>
    * Retrieve application scope for the user as a typed {@code Set<Integer>}
    * using the cache helper that validates element types.
    * 
    * @param username
    * @return userApplications
    */
    private Set<Integer> getUserApplications(String username) {
        if (username == null || cache == null) {
            return Set.of();
        }
        Set<Integer> cached = cache.getSet("apps_" + username, Integer.class);
        if (cached != null) {
            return cached;
        }
        EntityManager em = getEntityManagerSafely();
        if (em == null) {
            LOG.error("Cannot resolve user applications: EntityManager is not available");
            return Set.of();
        }
        User user = em.find(User.class, username);
        if (user != null) {
            Set<Integer> result = user.getAllAppsIds();
            cache.set("apps_" + username, result, 3600);
            return result;
        }
        return Set.of();
    }
    // -------------------------------------------------------------
    // Writer interceptor (transaction finalize)
    // -------------------------------------------------------------
    /** 
     * aroundWriteTo<p>
     * Commit/rollback and close EM after response writing. 
     * 
     * @param context
     * @throws IOException
     * @throws WebApplicationException
     */
    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        try {
            context.proceed();
        } finally {
            EntityManager em = (EntityManager) context.getProperty(EM_CONTEXT_PROPERTY);
            if (em == null) {
                return;
            }
            try {
                if (em.getTransaction() != null && em.getTransaction().isActive()) {
                    int status = servletResponse != null ? servletResponse.getStatus() : Status.INTERNAL_SERVER_ERROR.getStatusCode();
                    if (status >= 200 && status < 300) {
                        em.getTransaction().commit();
                        LOG.debug("Transaction committed");
                    } else {
                        em.getTransaction().rollback();
                        LOG.debug("Transaction rolled back");
                    }
                }
            } catch (Exception e) {
                LOG.error("Error finalizing transaction", e);
                try {
                    if (em.getTransaction() != null && em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                } catch (Exception rollbackEx) {
                    LOG.error("Error rolling back transaction", rollbackEx);
                }
            } finally {
                try {
                    if (em.isOpen()) {
                        em.close();
                    }
                } catch (Exception e) {
                    LOG.error("Error closing EntityManager", e);
                }
            }
        }
    }
}