Joaquín Reñé
2025-10-07 146a0fb8b0e90f9196e569152f649baf60d6cc8f
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
/*
* 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 {
        EntityManager em = emProvider.getEntityManager();
        LOG.debug("GETTING EM: {}", em);
        // Store EntityManager for later retrieval (writer interceptor)
        requestContext.setProperty(EM_CONTEXT_PROPERTY, em);
        Method method = resourceInfo.getResourceMethod();
        if (checkSecurableMethods(requestContext, method)) {
            if (method.isAnnotationPresent(EnsureTransaction.class)) {
                LOG.debug("Beginning transaction");
                em.getTransaction().begin();
            }
        }
    }
    /**
    * 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.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM);
        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;
        }
        BasicSecurityContext sc = new BasicSecurityContext(username, roles, servletRequest.isSecure());
        sc.setOrganizationsIds(getUserOrganizations(username));
        sc.setApplicationsIds(getUserApplications(username));
        ctx.setSecurityContext(sc);
        return true;
    }
    // -------------------------------------------------------------
    // 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) return 0;
        Integer cached = cache.get("roles_" + username, Integer.class);
        if (cached != null) return cached;
        EntityManager em = emProvider.getEntityManager();
        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);
            // also warm some caches
            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) {
        Set<Integer> cached = cache.getSet("orgs_" + username, Integer.class);
        if (cached != null) return cached;
        User user = emProvider.getEntityManager().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) {
        Set<Integer> cached = cache.getSet("apps_" + username, Integer.class);
        if (cached != null) return cached;
        User user = emProvider.getEntityManager().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 {
        context.proceed();
        EntityManager em = (EntityManager) context.getProperty(EM_CONTEXT_PROPERTY);
        if (em == null) return;
        try {
            if (em.getTransaction().isActive()) {
                if (servletResponse.getStatus() == Status.OK.getStatusCode()) {
                    em.getTransaction().commit();
                    LOG.debug("Transaction committed");
                } else {
                    em.getTransaction().rollback();
                    LOG.debug("Transaction rolled back");
                }
            }
        } finally {
            if (em.isOpen()) {
                try {
                    em.close();
                } catch (Exception e) {
                    LOG.error("Error closing EntityManager", e);
                }
            }
        }
    }
}