• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 40546195274

27 Oct 2026 04:52PM UTC coverage: 66.668% (-0.02%) from 66.688%
40546195274

push

github

ibacher
Scope the Get Roles proxy privilege to the implicit role read (#6756)

12 of 14 new or added lines in 2 files covered. (85.71%)

8 existing lines in 4 files now uncovered.

26178 of 39266 relevant lines covered (66.67%)

0.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.5
/api/src/main/java/org/openmrs/aop/AuthorizationAdvice.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.aop;
11

12
import java.lang.reflect.Method;
13
import java.lang.reflect.Modifier;
14
import java.util.Arrays;
15
import java.util.Collection;
16
import java.util.Collections;
17
import java.util.LinkedHashSet;
18
import java.util.Map;
19
import java.util.Set;
20
import java.util.concurrent.ConcurrentHashMap;
21

22
import org.apache.commons.lang3.StringUtils;
23
import org.openmrs.User;
24
import org.openmrs.annotation.Authorized;
25
import org.openmrs.api.APIAuthenticationException;
26
import org.openmrs.api.context.Context;
27
import org.openmrs.api.context.Daemon;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30
import org.springframework.aop.MethodBeforeAdvice;
31
import org.springframework.core.annotation.AnnotationUtils;
32

33
/**
34
 * This class provides the authorization AOP advice performed before every service layer method
35
 * call.
36
 */
37
public class AuthorizationAdvice implements MethodBeforeAdvice {
1 ✔
38
        
39
        /**
40
         * Logger for this class and subclasses
41
         */
42
        private static final Logger log = LoggerFactory.getLogger(AuthorizationAdvice.class);
1 ✔
43
        private static final String USER_IS_NOT_AUTHORIZED_TO_ACCESS = "User {} is not authorized to access {}";
44

45
        /**
46
         * Resolved {@link Authorized} metadata per advised method. Which privileges a method requires never
47
         * changes, but working it out means walking every supertype of the declaring class, and this advice
48
         * runs ahead of every service call.
49
         */
50
        private final Map<Method, AuthorizationMetadata> metadataCache = new ConcurrentHashMap<>();
1 ✔
51

52
        /**
53
         * Allows us to check whether a user is authorized to access a particular method.
54
         * 
55
         * @param method
56
         * @param args
57
         * @param target
58
         * @throws Throwable
59
         * <strong>Should</strong> notify listeners about checked privileges
60
         */
61
        @Override
62
        public void before(Method method, Object[] args, Object target) throws Throwable {
63
                log.debug("Calling authorization advice before {}", method.getName());
1 ✔
64

65
                if (Daemon.isDaemonThread()) {
1 ✔
66
                        return;
1 ✔
67
                }
68

69
                // computeIfAbsent will always obtain a lock while get will not, hence this construction
70
                // we can't rely on the key not existing because multiple threads could hit this at once
71
                // and we don't synchronize
72
                AuthorizationMetadata metadata = metadataCache.get(method);
1 ✔
73
                if (metadata == null) {
1 ✔
74
                        metadata = metadataCache.computeIfAbsent(method, AuthorizationAdvice::resolveMetadata);
1 ✔
75
                }
76

77
                if (!metadata.annotated()) {
1 ✔
78
                        return;
1 ✔
79
                }
80

81
                if (log.isDebugEnabled()) {
1 ✔
82
                        User user = Context.getAuthenticatedUser();
×
83
                        log.debug("User {}", user);
×
84
                        if (user != null) {
×
85
                                log.debug("has roles {}", user.getAllRoles());
×
86
                        }
87
                }
88

89
                Collection<String> privileges = metadata.privileges();
1 ✔
90
                boolean requireAll = metadata.requireAll();
1 ✔
91

92
                // Only execute if the "secure" method has authorization attributes
93
                // Iterate through required privileges and return only if the user has
94
                // one of them
95
                if (!privileges.isEmpty()) {
1 ✔
96
                        for (String privilege : privileges) {
1 ✔
97
                                // skip null privileges
98
                                if (privilege == null || privilege.isEmpty()) {
1 ✔
NEW
99
                                        return;
×
100
                                }
101
                                boolean hasPrivilege  = Context.hasPrivilege(privilege);
1 ✔
102
                                log.debug("User has privilege {}? {}", privilege, hasPrivilege);
1 ✔
103

104
                                if (hasPrivilege) {
1 ✔
105
                                        if (!requireAll) {
1 ✔
106
                                                // if not all required, the first one that they have
107
                                                // causes them to "pass"
108
                                                return;
1 ✔
109
                                        }
110
                                } else {
111
                                        if (requireAll) {
1 ✔
112
                                                // if all are required, the first miss causes them
113
                                                // to "fail"
NEW
114
                                                throwUnauthorized(Context.getAuthenticatedUser(), method, privilege);
×
115
                                        }
116
                                }
117
                        }
1 ✔
118
                        
119
                        if (!requireAll) {
1 ✔
120
                                // If there's no match, then we know there are privileges and
121
                                // that the user didn't have any of them. The user is not
122
                                // authorized to access the method
123
                                throwUnauthorized(Context.getAuthenticatedUser(), method, privileges);
×
124
                        }
125
                        
126
                } else if (!(Context.isAuthenticated() || Context.hasProxyPrivileges())) {
1 ✔
127
                        // an @Authorized that names no privilege only asks that the caller be authenticated
128
                        throwUnauthorized(Context.getAuthenticatedUser(), method);
×
129
                }
130
        }
1 ✔
131

132
        /**
133
         * Works out which {@link Authorized} annotation, if any, governs a method.
134
         * <p>
135
         * Java does not inherit method annotations, so reading the method's own would let a subtype that
136
         * redeclares an annotated method — usually only to narrow the return type — silently drop its
137
         * privilege requirement. {@link AnnotationUtils#findAnnotation(Method, Class)} instead searches the
138
         * supertypes of the declaring class and follows synthetic bridge methods, preferring an annotation
139
         * on the method's own declaration over an inherited one. Which of two annotated supertype branches
140
         * wins is not documented, so a service hierarchy should not depend on it.
141
         * <p>
142
         * Runs inside {@link Map#computeIfAbsent}, so it must not call back into a service: the advice on
143
         * that call would re-enter this map, which {@link ConcurrentHashMap} forbids. Reflection and
144
         * logging only.
145
         */
146
        private static AuthorizationMetadata resolveMetadata(Method method) {
147
                Authorized authorized = AnnotationUtils.findAnnotation(method, Authorized.class);
1 ✔
148
                if (authorized == null) {
1 ✔
149
                        warnMethodIsUnguarded(method);
1 ✔
150
                        return AuthorizationMetadata.UNGUARDED;
1 ✔
151
                }
152

153
                return AuthorizationMetadata.of(authorized);
1 ✔
154
        }
155

156
        /**
157
         * Reports, once per method thanks to the cache, that nothing guards a proxied method. Plenty of
158
         * service methods are unannotated by design, so this flags something to look at rather than
159
         * something necessarily wrong.
160
         * <p>
161
         * Bridge and synthetic methods are skipped because a bridge duplicates a declaration reported in
162
         * its own right; non-public methods and {@link Object}'s are not part of the service API a caller
163
         * reaches through the proxy.
164
         */
165
        private static void warnMethodIsUnguarded(Method method) {
166
                if (method.isBridge() || method.isSynthetic() || !Modifier.isPublic(method.getModifiers())
1 ✔
167
                        || method.getDeclaringClass() == Object.class) {
1 ✔
168
                        return;
1 ✔
169
                }
170

171
                log.warn("No @Authorized annotation applies to {}.{}(), directly or through any method it overrides, "
1 ✔
172
                        + "so calls to it are not privilege checked",
173
                    method.getDeclaringClass().getName(), method.getName());
1 ✔
174
        }
1 ✔
175

176
        /**
177
         * Throws an APIAuthorization exception stating why the user failed
178
         *
179
         * @param user authenticated user
180
         * @param method acting method
181
         * @param attrs Collection of String privilege names that the user must have
182
         */
183
        private void throwUnauthorized(User user, Method method, Collection<String> attrs) {
184
                log.debug(USER_IS_NOT_AUTHORIZED_TO_ACCESS, user, method.getName());
1 ✔
185
                throw new APIAuthenticationException(Context.getMessageSourceService().getMessage("error.privilegesRequired",
1 ✔
186
                    new Object[] { StringUtils.join(attrs, ",") }, null));
1 ✔
187
        }
188
        
189
        /**
190
         * Throws an APIAuthorization exception stating why the user failed
191
         * 
192
         * @param user authenticated user
193
         * @param method acting method
194
         * @param attr privilege names that the user must have
195
         */
196
        private void throwUnauthorized(User user, Method method, String attr) {
197
                log.debug(USER_IS_NOT_AUTHORIZED_TO_ACCESS, user, method.getName());
1 ✔
198
                throw new APIAuthenticationException(Context.getMessageSourceService().getMessage("error.privilegesRequired",
1 ✔
199
                    new Object[] { attr }, null));
200
        }
201
        
202
        /**
203
         * Throws an APIAuthorization exception stating why the user failed
204
         * 
205
         * @param user authenticated user
206
         * @param method acting method
207
         */
208
        private void throwUnauthorized(User user, Method method) {
209
                log.debug(USER_IS_NOT_AUTHORIZED_TO_ACCESS, user, method.getName());
1 ✔
210
                throw new APIAuthenticationException(Context.getMessageSourceService().getMessage("error.aunthenticationRequired"));
1 ✔
211
        }
212

213
        /**
214
         * The {@link Authorized} configuration governing a single method. Privileges and
215
         * {@code requireAll} always come from one annotation, so a redeclaration replaces the inherited
216
         * configuration outright rather than merging with it.
217
         * <p>
218
         * {@code annotated} records whether an annotation was found at all, which
219
         * {@code privileges.isEmpty()} cannot tell apart from an {@code @Authorized} naming no privilege.
220
         * It is carried in band because {@link ConcurrentHashMap} will not store a null value.
221
         */
222
        private static final class AuthorizationMetadata {
223

224
                private static final AuthorizationMetadata UNGUARDED = new AuthorizationMetadata(false, Collections.emptyList(),
1 ✔
225
                        false);
226

227
                private final boolean annotated;
228

229
                private final Collection<String> privileges;
230

231
                private final boolean requireAll;
232

233
                private AuthorizationMetadata(boolean annotated, Collection<String> privileges, boolean requireAll) {
1 ✔
234
                        this.annotated = annotated;
1 ✔
235
                        this.privileges = privileges;
1 ✔
236
                        this.requireAll = requireAll;
1 ✔
237
                }
1 ✔
238

239
                private static AuthorizationMetadata of(Authorized authorized) {
240
                        // drop duplicate privileges
241
                        Set<String> privileges = new LinkedHashSet<>(Arrays.asList(authorized.value()));
1 ✔
242
                        return new AuthorizationMetadata(true, Collections.unmodifiableSet(privileges), authorized.requireAll());
1 ✔
243
                }
244

245
                private boolean annotated() {
246
                        return annotated;
1 ✔
247
                }
248

249
                private Collection<String> privileges() {
250
                        return privileges;
1 ✔
251
                }
252

253
                private boolean requireAll() {
254
                        return requireAll;
1 ✔
255
                }
256
        }
257
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc