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

openmrs / openmrs-core / 43497228006

13 Nov 2026 07:48PM UTC coverage: 69.295% (+0.3%) from 68.956%
43497228006

push

github

ibacher
Refine how UserService saves users, roles and user properties (#6831)

552 of 595 new or added lines in 14 files covered. (92.77%)

9 existing lines in 5 files now uncovered.

26888 of 38802 relevant lines covered (69.3%)

0.69 hits per line

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

90.48
/api/src/main/java/org/openmrs/api/impl/RoleAssignments.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.api.impl;
11

12
import java.util.ArrayDeque;
13
import java.util.Collection;
14
import java.util.Deque;
15
import java.util.HashSet;
16
import java.util.Objects;
17
import java.util.Set;
18
import java.util.SortedSet;
19
import java.util.TreeSet;
20
import java.util.function.Function;
21

22
import org.openmrs.api.APIException;
23
import org.openmrs.api.cache.RolePrivilegeCache;
24
import org.openmrs.api.cache.RolePrivileges;
25
import org.openmrs.api.context.Context;
26
import org.openmrs.api.context.Daemon;
27
import org.openmrs.api.db.StoredRole;
28
import org.openmrs.util.PrivilegeConstants;
29
import org.openmrs.util.RoleConstants;
30

31
/**
32
 * The rule for handing out roles, whether assigning them to a user or making a role inherit them:
33
 * each role must be stored under exactly the given name, the authenticated user must hold every
34
 * privilege the roles grant, including through inheritance, and
35
 * {@link PrivilegeConstants#ASSIGN_SYSTEM_DEVELOPER_ROLE} if any of them is or inherits
36
 * {@link RoleConstants#SUPERUSER}. Roles are read as stored, never from a loaded
37
 * {@link org.openmrs.Role}, which may hold unsaved changes.
38
 * <p>
39
 * Superuser status can only be taken away by someone who could hand it out: changing a user or a
40
 * role that, as stored, is or inherits {@link RoleConstants#SUPERUSER} requires
41
 * {@link PrivilegeConstants#ASSIGN_SYSTEM_DEVELOPER_ROLE} (see {@link #grantsSuperuser}).
42
 * <p>
43
 * Proxy privileges don't count: they let internal calls do work the user can't, but must never let
44
 * the user hand out more than they hold. Daemon threads hold every privilege.
45
 *
46
 * @since 2.8.11
47
 */
48
public final class RoleAssignments {
49

50
        private RoleAssignments() {
51
        }
52

53
        /**
54
         * @param roleNames names of the roles being handed out
55
         * @param reader reads a role as stored, returning null if there is no such role
56
         * @return the privileges the roles grant that the authenticated user doesn't hold, sorted
57
         * @throws APIException if a name isn't exactly the name of a stored role, or if the roles grant
58
         *             System Developer and the user can't assign it
59
         */
60
        public static SortedSet<String> missingPrivileges(Collection<String> roleNames, Function<String, StoredRole> reader) {
61
                SortedSet<String> missing = new TreeSet<>();
1 ✔
62
                if (roleNames == null || Daemon.isDaemonThread()) {
1 ✔
63
                        return missing;
1 ✔
64
                }
65
                for (String roleName : roleNames) {
1 ✔
66
                        if (roleName == null) {
1 ✔
NEW
67
                                continue;
×
68
                        }
69
                        requireStored(roleName, reader);
1 ✔
70
                        RolePrivileges granted = RolePrivilegeCache.resolve(roleName, reader);
1 ✔
71
                        if (granted.grantsSuperuser() && !holds(PrivilegeConstants.ASSIGN_SYSTEM_DEVELOPER_ROLE)) {
1 ✔
72
                                throw new APIException("User.you.must.have.role", new Object[] { RoleConstants.SUPERUSER });
1 ✔
73
                        }
74
                        granted.getPrivilegeNames().stream().filter(p -> !holds(p)).forEach(missing::add);
1 ✔
75
                }
1 ✔
76
                return missing;
1 ✔
77
        }
78

79
        /**
80
         * Requires a role stored under exactly the given name. A name the database only matches loosely,
81
         * for example with different case or trailing spaces, is refused, since privilege checks resolve
82
         * roles by their exact name.
83
         *
84
         * @param roleName a role name
85
         * @param reader reads a role as stored, returning null if there is no such role
86
         * @return the stored role
87
         * @throws APIException if there is no role stored under exactly that name
88
         */
89
        public static StoredRole requireStored(String roleName, Function<String, StoredRole> reader) {
90
                StoredRole stored = reader.apply(roleName);
1 ✔
91
                if (stored == null || !stored.getName().equals(roleName)) {
1 ✔
NEW
92
                        throw new APIException("Role.unknown", new Object[] { roleName });
×
93
                }
94
                return stored;
1 ✔
95
        }
96

97
        /**
98
         * Requires that a role inheriting the given parents would not inherit itself, directly or through
99
         * the parents' stored inheritance.
100
         *
101
         * @param roleName the name of the role, or null for a role not yet named
102
         * @param parentNames names of the roles it is to inherit from
103
         * @param reader reads a role as stored, returning null if there is no such role
104
         * @throws APIException if the role would inherit itself
105
         */
106
        public static void requireNoInheritanceCycle(String roleName, Collection<String> parentNames,
107
                Function<String, StoredRole> reader) {
108
                if (roleName == null || parentNames == null) {
1 ✔
NEW
109
                        return;
×
110
                }
111
                Set<String> visited = new HashSet<>();
1 ✔
112
                Deque<String> pending = new ArrayDeque<>(parentNames);
1 ✔
113
                while (!pending.isEmpty()) {
1 ✔
114
                        String name = pending.pop();
1 ✔
115
                        if (name == null || !visited.add(name)) {
1 ✔
NEW
116
                                continue;
×
117
                        }
118
                        StoredRole stored = reader.apply(name);
1 ✔
119
                        // case-insensitive, since the database may match a differently cased name to the same row
120
                        if (name.equalsIgnoreCase(roleName) || (stored != null && stored.getName().equalsIgnoreCase(roleName))) {
1 ✔
121
                                throw new APIException("Role.cannot.inherit.descendant", (Object[]) null);
1 ✔
122
                        }
123
                        if (stored != null) {
1 ✔
124
                                pending.addAll(stored.getParentRoles());
1 ✔
125
                        }
126
                }
1 ✔
127
        }
1 ✔
128

129
        /**
130
         * @param roleNames names of roles as stored, such as a user's roles or a single role
131
         * @param reader reads a role as stored, returning null if there is no such role; it must read what
132
         *            is stored, never pending changes, since the result decides who may change the roles
133
         * @return true if any of the roles is or inherits {@link RoleConstants#SUPERUSER}
134
         */
135
        public static boolean grantsSuperuser(Collection<String> roleNames, Function<String, StoredRole> reader) {
136
                return roleNames != null && roleNames.stream().filter(Objects::nonNull)
1 ✔
137
                        .anyMatch(name -> RolePrivilegeCache.resolve(name, reader).grantsSuperuser());
1 ✔
138
        }
139

140
        /**
141
         * Requires that the authenticated user may change a user or role holding the given roles: if any of
142
         * them is or inherits {@link RoleConstants#SUPERUSER}, only a holder of
143
         * {@link PrivilegeConstants#ASSIGN_SYSTEM_DEVELOPER_ROLE} may.
144
         *
145
         * @param messageKey the message for the exception, given the privilege and role names
146
         * @param roleNames names of roles as stored, such as a user's roles or a single role
147
         * @param reader reads a role as stored, as for {@link #grantsSuperuser}
148
         * @throws APIException if the roles grant superuser status and the user can't assign it
149
         */
150
        public static void requireCanChangeSuperuser(String messageKey, Collection<String> roleNames,
151
                Function<String, StoredRole> reader) {
152
                if (!holds(PrivilegeConstants.ASSIGN_SYSTEM_DEVELOPER_ROLE) && grantsSuperuser(roleNames, reader)) {
1 ✔
153
                        throw new APIException(messageKey,
1 ✔
154
                                new Object[] { PrivilegeConstants.ASSIGN_SYSTEM_DEVELOPER_ROLE, RoleConstants.SUPERUSER });
155
                }
156
        }
1 ✔
157

158
        /**
159
         * @param privileges privilege names being handed out directly, such as a role's own privileges
160
         * @return those the authenticated user doesn't hold, sorted
161
         */
162
        public static SortedSet<String> notHeld(Collection<String> privileges) {
163
                SortedSet<String> missing = new TreeSet<>();
1 ✔
164
                if (privileges != null) {
1 ✔
165
                        privileges.stream().filter(p -> !holds(p)).forEach(missing::add);
1 ✔
166
                }
167
                return missing;
1 ✔
168
        }
169

170
        /**
171
         * @param privilege a privilege name
172
         * @return true if the authenticated user holds the privilege through their roles, not a proxy
173
         */
174
        public static boolean holds(String privilege) {
175
                return Context.hasPrivilege(privilege, false);
1 ✔
176
        }
177
}
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