001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.auth.authorize;
020
021import org.apache.wiki.auth.GroupPrincipal;
022import org.apache.wiki.util.Synchronizer;
023
024import java.security.Principal;
025import java.util.Date;
026import java.util.List;
027import java.util.concurrent.CopyOnWriteArrayList;
028import java.util.concurrent.atomic.AtomicReference;
029import java.util.concurrent.locks.ReentrantLock;
030
031/**
032 * <p>
033 * Groups are a specialized type of ad-hoc role used by the wiki system. Unlike
034 * externally-provided roles (such as those provided by an LDAP server or web
035 * container), JSPWiki groups can be created dynamically by wiki users, without
036 * requiring special container privileges or administrator intervention. They
037 * are designed to provide a lightweight role-based access control system that
038 * complements existing role systems.
039 * </p>
040 * <p>
041 * Group names are case-insensitive, and have a few naming restrictions, which
042 * are enforced by the {@link GroupManager}:
043 * </p>
044 * <ul>
045 * <li>Groups cannot have the same name as a built-in Role (e.g., "Admin",
046 * "Authenticated" etc.)</li>
047 * <li>Groups cannot have the same name as an existing user</li>
048 * </ul>
049 * <p>
050 * <em>Note: prior to JSPWiki 2.4.19, Group was an interface; it
051 * is now a concrete, final class.</em>
052 * </p>
053 * <p>
054 * Groups are related to {@link GroupPrincipal}s. A GroupPrincipal, when
055 * injected into the Principal set of a Session's Subject, means that the
056 * user is a member of a Group of the same name -- it is, in essence, an
057 * "authorization token." GroupPrincipals, unlike Groups, are thread-safe,
058 * lightweight and immutable. That's why we use them in Subjects rather than the
059 * Groups themselves.
060 * </p>
061 *
062 * @since 2.3
063 */
064public class Group {
065
066    static final String[]  RESTRICTED_GROUPNAMES = new String[] { "Anonymous", "All", "Asserted", "Authenticated" };
067
068    private final List<Principal> m_members = new CopyOnWriteArrayList<>();
069
070    private String          m_creator;
071
072    private Date            m_created;
073
074    private String          m_modifier;
075
076    private Date            m_modified;
077
078    private final String    m_name;
079
080    private final Principal m_principal;
081
082    private final String    m_wiki;
083
084    /**
085     * A lock used to ensure thread safety when accessing shared resources.
086     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
087     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
088     * waiting to acquire a lock.
089     *
090     * @see java.util.concurrent.locks.ReentrantLock
091     */
092    private final ReentrantLock lock = new ReentrantLock();
093
094    /**
095     * Protected constructor to prevent direct instantiation except by other
096     * package members. Callers should use
097     * {@link GroupManager#parseGroup(String, String, boolean)} or
098     * {@link GroupManager#parseGroup(org.apache.wiki.api.core.Context, boolean)}.
099     * instead.
100     * @param name the name of the group
101     * @param wiki the wiki the group belongs to
102     */
103    protected Group( final String name, final String wiki ) {
104        m_name = name;
105        m_wiki = wiki;
106        m_principal = new GroupPrincipal( name );
107    }
108
109    /**
110     * Adds a Principal to the group. 
111     * 
112     * @param user the principal to add
113     * @return <code>true</code> if the operation was successful
114     */
115    public boolean add( final Principal user ) {
116        return Synchronizer.synchronize(lock, () -> {
117            if( isMember( user ) ) {
118                return false;
119            }
120
121            m_members.add( user );
122            return true;
123        });
124    }
125
126    /**
127     * Clears all Principals from the group list. 
128     */
129    public void clear() {
130        Synchronizer.synchronize(lock, m_members::clear);
131    }
132
133    /**
134     * Two DefaultGroups are equal if they contain identical member Principals
135     * and have the same name.
136     * @param o the object to compare
137     * @return the comparison
138     */
139    @Override
140    public boolean equals( final Object o ) {
141        if( !( o instanceof Group ) ) {
142            return false;
143        }
144
145        final Group g = ( Group )o; // Just a shortcut.
146
147        if( g.m_members.size() != m_members.size() ) {
148            return false;
149        }
150
151        if( getName() != null && !getName().equals( g.getName() ) ) {
152            return false;
153        } else if( getName() == null && g.getName() != null ) {
154            return false;
155        }
156
157        return m_members.stream().allMatch(g::isMember);
158    }
159
160    /**
161     *  The hashcode is calculated as a XOR sum over all members of the Group.
162     *
163     *  @return the hash code
164     */
165    @Override
166    public int hashCode() {
167        return m_members.stream().mapToInt(Principal::hashCode).reduce(0, (a, b) -> a ^ b);
168    }
169    
170    /**
171     * Returns the creation date.
172     *
173     * @return the creation date
174     */
175    public Date getCreated() {
176        return Synchronizer.synchronize(lock, () -> m_created);
177    }
178
179    /**
180     * Returns the creator of this Group.
181     *
182     * @return the creator
183     */
184    public final String getCreator() {
185        return Synchronizer.synchronize(lock, () -> m_creator);
186    }
187
188    /**
189     * Returns the last-modified date.
190     *
191     * @return the date and time of last modification
192     */
193    public Date getLastModified() {
194        return Synchronizer.synchronize(lock, () -> m_modified);
195    }
196
197    /**
198     * Returns the name of the user who last modified this group.
199     *
200     * @return the modifier
201     */
202    public final String getModifier() {
203        return Synchronizer.synchronize(lock, () -> m_modifier);
204    }
205
206    /**
207     * The name of the group. This is set in the class constructor.
208     *
209     * @return the name of the Group
210     */
211    public String getName() {
212        return m_name;
213    }
214
215    /**
216     * Returns the GroupPrincipal that represents this Group.
217     *
218     * @return the group principal
219     */
220    public Principal getPrincipal() {
221        return m_principal;
222    }
223
224    /**
225     * Returns the wiki name.
226     *
227     * @return the wiki name
228     */
229    public String getWiki() {
230        return m_wiki;
231    }
232
233    /**
234     * Returns <code>true</code> if a Principal is a member of the group. Specifically, the Principal's <code>getName()</code> method must
235     * return the same value as one of the Principals in the group member list. The Principal's type does <em>not</em> need to match.
236     *
237     * @param principal the principal about whom membership status is sought
238     * @return the result of the operation
239     */
240    public boolean isMember( final Principal principal ) {
241        return findMember( principal.getName() ) != null;
242    }
243
244    /**
245     * Returns the members of the group as an array of Principal objects.
246     *
247     * @return the members
248     */
249    public Principal[] members() {
250        return m_members.toArray( new Principal[0] );
251    }
252
253    /**
254     * Removes a Principal from the group.
255     *
256     * @param user the principal to remove
257     * @return <code>true</code> if the operation was successful
258     */
259    public boolean remove(Principal user) {
260        final AtomicReference<Principal> userRef = new AtomicReference<>(user);
261        return Synchronizer.synchronize(lock, () -> {
262            Principal updatedUser = findMember(userRef.get().getName());
263            userRef.set(updatedUser);
264            if (updatedUser == null) {
265                return false;
266            }
267            m_members.remove(updatedUser);
268            return true;
269        });
270    }
271
272    /**
273     * Sets the created date.
274     *
275     * @param date the creation date
276     */
277    public void setCreated( final Date date ) {
278        Synchronizer.synchronize(lock, () -> {
279            m_created = date;
280        });
281    }
282
283    /**
284     * Sets the creator of this Group.
285     * @param creator the creator
286     */
287    public final void setCreator( final String creator ) {
288        Synchronizer.synchronize(lock, () -> {
289            this.m_creator = creator;
290        });
291    }
292
293    /**
294     * Sets the last-modified date
295     *
296     * @param date the last-modified date
297     */
298    public void setLastModified( final Date date ) {
299        Synchronizer.synchronize(lock, () -> {
300            m_modified = date;
301        });
302    }
303
304    /**
305     * Sets the name of the user who last modified this group.
306     *
307     * @param modifier the modifier
308     */
309    public final void setModifier( final String modifier ) {
310        Synchronizer.synchronize(lock, () -> {
311            this.m_modifier = modifier;
312        });
313    }
314
315    /**
316     * Returns a string representation of the Group.
317     *
318     * @return the string
319     * @see java.lang.Object#toString()
320     */
321    @Override
322    public String toString() {
323        return "(Group " + getName() + ")";
324    }
325
326    private Principal findMember( final String name ) {
327        return m_members.stream().filter(member -> member.getName().equals(name)).findFirst().orElse(null);
328
329    }
330
331}