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.shiro.authz.permission;
020
021import org.apache.shiro.authz.Permission;
022import org.apache.shiro.util.CollectionUtils;
023import org.apache.shiro.util.StringUtils;
024
025import java.io.Serializable;
026import java.util.ArrayList;
027import java.util.Iterator;
028import java.util.LinkedHashSet;
029import java.util.List;
030import java.util.Set;
031
032/**
033 * A <code>WildcardPermission</code> is a very flexible permission construct supporting multiple levels of
034 * permission matching. However, most people will probably follow some standard conventions as explained below.
035 * <p/>
036 * <h3>Simple Usage</h3>
037 * <p/>
038 * In the simplest form, <code>WildcardPermission</code> can be used as a simple permission string. You could grant a
039 * user an &quot;editNewsletter&quot; permission and then check to see if the user has the editNewsletter
040 * permission by calling
041 * <p/>
042 * <code>subject.isPermitted(&quot;editNewsletter&quot;)</code>
043 * <p/>
044 * This is (mostly) equivalent to
045 * <p/>
046 * <code>subject.isPermitted( new WildcardPermission(&quot;editNewsletter&quot;) )</code>
047 * <p/>
048 * but more on that later.
049 * <p/>
050 * The simple permission string may work for simple applications, but it requires you to have permissions like
051 * <code>&quot;viewNewsletter&quot;</code>, <code>&quot;deleteNewsletter&quot;</code>,
052 * <code>&quot;createNewsletter&quot;</code>, etc. You can also grant a user <code>&quot;*&quot;</code> permissions
053 * using the wildcard character (giving this class its name), which means they have <em>all</em> permissions. But
054 * using this approach there's no way to just say a user has &quot;all newsletter permissions&quot;.
055 * <p/>
056 * For this reason, <code>WildcardPermission</code> supports multiple <em>levels</em> of permissioning.
057 * <p/>
058 * <h3>Multiple Levels</h3>
059 * <p/>
060 * WildcardPermission</code> also supports the concept of multiple <em>levels</em>.  For example, you could
061 * restructure the previous simple example by granting a user the permission <code>&quot;newsletter:edit&quot;</code>.
062 * The colon in this example is a special character used by the <code>WildcardPermission</code> that delimits the
063 * next token in the permission.
064 * <p/>
065 * In this example, the first token is the <em>domain</em> that is being operated on
066 * and the second token is the <em>action</em> being performed. Each level can contain multiple values.  So you
067 * could simply grant a user the permission <code>&quot;newsletter:view,edit,create&quot;</code> which gives them
068 * access to perform <code>view</code>, <code>edit</code>, and <code>create</code> actions in the <code>newsletter</code>
069 * <em>domain</em>. Then you could check to see if the user has the <code>&quot;newsletter:create&quot;</code>
070 * permission by calling
071 * <p/>
072 * <code>subject.isPermitted(&quot;newsletter:create&quot;)</code>
073 * <p/>
074 * (which would return true).
075 * <p/>
076 * In addition to granting multiple permissions via a single string, you can grant all permission for a particular
077 * level. So if you wanted to grant a user all actions in the <code>newsletter</code> domain, you could simply give
078 * them <code>&quot;newsletter:*&quot;</code>. Now, any permission check for <code>&quot;newsletter:XXX&quot;</code>
079 * will return <code>true</code>. It is also possible to use the wildcard token at the domain level (or both): so you
080 * could grant a user the <code>&quot;view&quot;</code> action across all domains <code>&quot;*:view&quot;</code>.
081 * <p/>
082 * <h3>Instance-level Access Control</h3>
083 * <p/>
084 * Another common usage of the <code>WildcardPermission</code> is to model instance-level Access Control Lists.
085 * In this scenario you use three tokens - the first is the <em>domain</em>, the second is the <em>action</em>, and
086 * the third is the <em>instance</em> you are acting on.
087 * <p/>
088 * So for example you could grant a user <code>&quot;newsletter:edit:12,13,18&quot;</code>.  In this example, assume
089 * that the third token is the system's ID of the newsletter. That would allow the user to edit newsletters
090 * <code>12</code>, <code>13</code>, and <code>18</code>. This is an extremely powerful way to express permissions,
091 * since you can now say things like <code>&quot;newsletter:*:13&quot;</code> (grant a user all actions for newsletter
092 * <code>13</code>), <code>&quot;newsletter:view,create,edit:*&quot;</code> (allow the user to
093 * <code>view</code>, <code>create</code>, or <code>edit</code> <em>any</em> newsletter), or
094 * <code>&quot;newsletter:*:*</code> (allow the user to perform <em>any</em> action on <em>any</em> newsletter).
095 * <p/>
096 * To perform checks against these instance-level permissions, the application should include the instance ID in the
097 * permission check like so:
098 * <p/>
099 * <code>subject.isPermitted( &quot;newsletter:edit:13&quot; )</code>
100 * <p/>
101 * There is no limit to the number of tokens that can be used, so it is up to your imagination in terms of ways that
102 * this could be used in your application.  However, the Shiro team likes to standardize some common usages shown
103 * above to help people get started and provide consistency in the Shiro community.
104 *
105 * @since 0.9
106 */
107public class WildcardPermission implements Permission, Serializable {
108
109    //TODO - JavaDoc methods
110
111    /*--------------------------------------------
112    |             C O N S T A N T S             |
113    ============================================*/
114    protected static final String WILDCARD_TOKEN = "*";
115    protected static final String PART_DIVIDER_TOKEN = ":";
116    protected static final String SUBPART_DIVIDER_TOKEN = ",";
117    protected static final boolean DEFAULT_CASE_SENSITIVE = false;
118
119    /*--------------------------------------------
120    |    I N S T A N C E   V A R I A B L E S    |
121    ============================================*/
122    private List<Set<String>> parts;
123
124    /*--------------------------------------------
125    |         C O N S T R U C T O R S           |
126    ============================================*/
127    /**
128     * Default no-arg constructor for subclasses only - end-user developers instantiating Permission instances must
129     * provide a wildcard string at a minimum, since Permission instances are immutable once instantiated.
130     * <p/>
131     * Note that the WildcardPermission class is very robust and typically subclasses are not necessary unless you
132     * wish to create type-safe Permission objects that would be used in your application, such as perhaps a
133     * {@code UserPermission}, {@code SystemPermission}, {@code PrinterPermission}, etc.  If you want such type-safe
134     * permission usage, consider subclassing the {@link DomainPermission DomainPermission} class for your needs.
135     */
136    protected WildcardPermission() {
137    }
138
139    public WildcardPermission(String wildcardString) {
140        this(wildcardString, DEFAULT_CASE_SENSITIVE);
141    }
142
143    public WildcardPermission(String wildcardString, boolean caseSensitive) {
144        setParts(wildcardString, caseSensitive);
145    }
146
147    protected void setParts(String wildcardString) {
148        setParts(wildcardString, DEFAULT_CASE_SENSITIVE);
149    }
150
151    protected void setParts(String wildcardString, boolean caseSensitive) {
152        wildcardString = StringUtils.clean(wildcardString);
153
154        if (wildcardString == null || wildcardString.isEmpty()) {
155            throw new IllegalArgumentException("Wildcard string cannot be null or empty. Make sure permission strings are properly formatted.");
156        }
157
158        if (!caseSensitive) {
159            wildcardString = wildcardString.toLowerCase();
160        }
161
162        List<String> parts = CollectionUtils.asList(wildcardString.split(PART_DIVIDER_TOKEN));
163
164        this.parts = new ArrayList<Set<String>>();
165        for (String part : parts) {
166            Set<String> subparts = CollectionUtils.asSet(part.split(SUBPART_DIVIDER_TOKEN));
167
168            if (subparts.isEmpty()) {
169                throw new IllegalArgumentException("Wildcard string cannot contain parts with only dividers. Make sure permission strings are properly formatted.");
170            }
171            this.parts.add(subparts);
172        }
173
174        if (this.parts.isEmpty()) {
175            throw new IllegalArgumentException("Wildcard string cannot contain only dividers. Make sure permission strings are properly formatted.");
176        }
177    }
178
179    /*--------------------------------------------
180    |  A C C E S S O R S / M O D I F I E R S    |
181    ============================================*/
182    protected List<Set<String>> getParts() {
183        return this.parts;
184    }
185
186    /**
187     * Sets the pre-split String parts of this <code>WildcardPermission</code>.
188     * @since 1.3.0
189     * @param parts pre-split String parts.
190     */
191    protected void setParts(List<Set<String>> parts) {
192        this.parts = parts;
193    }
194
195    /*--------------------------------------------
196    |               M E T H O D S               |
197    ============================================*/
198
199    public boolean implies(Permission p) {
200        // By default only supports comparisons with other WildcardPermissions
201        if (!(p instanceof WildcardPermission)) {
202            return false;
203        }
204
205        WildcardPermission wp = (WildcardPermission) p;
206
207        List<Set<String>> otherParts = wp.getParts();
208
209        int i = 0;
210        for (Set<String> otherPart : otherParts) {
211            // If this permission has less parts than the other permission, everything after the number of parts contained
212            // in this permission is automatically implied, so return true
213            if (getParts().size() - 1 < i) {
214                return true;
215            } else {
216                Set<String> part = getParts().get(i);
217                if (!part.contains(WILDCARD_TOKEN) && !part.containsAll(otherPart)) {
218                    return false;
219                }
220                i++;
221            }
222        }
223
224        // If this permission has more parts than the other parts, only imply it if all of the other parts are wildcards
225        for (; i < getParts().size(); i++) {
226            Set<String> part = getParts().get(i);
227            if (!part.contains(WILDCARD_TOKEN)) {
228                return false;
229            }
230        }
231
232        return true;
233    }
234
235    public String toString() {
236        StringBuilder buffer = new StringBuilder();
237        for (Set<String> part : parts) {
238            if (buffer.length() > 0) {
239                buffer.append(PART_DIVIDER_TOKEN);
240            }
241            Iterator<String> partIt = part.iterator();
242            while(partIt.hasNext()) {
243                buffer.append(partIt.next());
244                if (partIt.hasNext()) {
245                    buffer.append(SUBPART_DIVIDER_TOKEN);
246                }
247            }
248        }
249        return buffer.toString();
250    }
251
252    public boolean equals(Object o) {
253        if (o instanceof WildcardPermission) {
254            WildcardPermission wp = (WildcardPermission) o;
255            return parts.equals(wp.parts);
256        }
257        return false;
258    }
259
260    public int hashCode() {
261        return parts.hashCode();
262    }
263
264}