View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.authz.permission;
20  
21  import org.apache.shiro.authz.Permission;
22  import org.apache.shiro.util.CollectionUtils;
23  
24  import java.io.Serializable;
25  import java.util.ArrayList;
26  import java.util.LinkedHashSet;
27  import java.util.List;
28  import java.util.Set;
29  
30  /**
31   * A <code>WildcardPermission</code> is a very flexible permission construct supporting multiple levels of
32   * permission matching. However, most people will probably follow some standard conventions as explained below.
33   * <p/>
34   * <h3>Simple Usage</h3>
35   * <p/>
36   * In the simplest form, <code>WildcardPermission</code> can be used as a simple permission string. You could grant a
37   * user an &quot;editNewsletter&quot; permission and then check to see if the user has the editNewsletter
38   * permission by calling
39   * <p/>
40   * <code>subject.isPermitted(&quot;editNewsletter&quot;)</code>
41   * <p/>
42   * This is (mostly) equivalent to
43   * <p/>
44   * <code>subject.isPermitted( new WildcardPermission(&quot;editNewsletter&quot;) )</code>
45   * <p/>
46   * but more on that later.
47   * <p/>
48   * The simple permission string may work for simple applications, but it requires you to have permissions like
49   * <code>&quot;viewNewsletter&quot;</code>, <code>&quot;deleteNewsletter&quot;</code>,
50   * <code>&quot;createNewsletter&quot;</code>, etc. You can also grant a user <code>&quot;*&quot;</code> permissions
51   * using the wildcard character (giving this class its name), which means they have <em>all</em> permissions. But
52   * using this approach there's no way to just say a user has &quot;all newsletter permissions&quot;.
53   * <p/>
54   * For this reason, <code>WildcardPermission</code> supports multiple <em>levels</em> of permissioning.
55   * <p/>
56   * <h3>Multiple Levels</h3>
57   * <p/>
58   * WildcardPermission</code> also supports the concept of multiple <em>levels</em>.  For example, you could
59   * restructure the previous simple example by granting a user the permission <code>&quot;newsletter:edit&quot;</code>.
60   * The colon in this example is a special character used by the <code>WildcardPermission</code> that delimits the
61   * next token in the permission.
62   * <p/>
63   * In this example, the first token is the <em>domain</em> that is being operated on
64   * and the second token is the <em>action</em> being performed. Each level can contain multiple values.  So you
65   * could simply grant a user the permission <code>&quot;newsletter:view,edit,create&quot;</code> which gives them
66   * access to perform <code>view</code>, <code>edit</code>, and <code>create</code> actions in the <code>newsletter</code>
67   * <em>domain</em>. Then you could check to see if the user has the <code>&quot;newsletter:create&quot;</code>
68   * permission by calling
69   * <p/>
70   * <code>subject.isPermitted(&quot;newsletter:create&quot;)</code>
71   * <p/>
72   * (which would return true).
73   * <p/>
74   * In addition to granting multiple permissions via a single string, you can grant all permission for a particular
75   * level. So if you wanted to grant a user all actions in the <code>newsletter</code> domain, you could simply give
76   * them <code>&quot;newsletter:*&quot;</code>. Now, any permission check for <code>&quot;newsletter:XXX&quot;</code>
77   * will return <code>true</code>. It is also possible to use the wildcard token at the domain level (or both): so you
78   * could grant a user the <code>&quot;view&quot;</code> action across all domains <code>&quot;*:view&quot;</code>.
79   * <p/>
80   * <h3>Instance-level Access Control</h3>
81   * <p/>
82   * Another common usage of the <code>WildcardPermission</code> is to model instance-level Access Control Lists.
83   * In this scenario you use three tokens - the first is the <em>domain</em>, the second is the <em>action</em>, and
84   * the third is the <em>instance</em> you are acting on.
85   * <p/>
86   * So for example you could grant a user <code>&quot;newsletter:edit:12,13,18&quot;</code>.  In this example, assume
87   * that the third token is the system's ID of the newsletter. That would allow the user to edit newsletters
88   * <code>12</code>, <code>13</code>, and <code>18</code>. This is an extremely powerful way to express permissions,
89   * since you can now say things like <code>&quot;newsletter:*:13&quot;</code> (grant a user all actions for newsletter
90   * <code>13</code>), <code>&quot;newsletter:view,create,edit:*&quot;</code> (allow the user to
91   * <code>view</code>, <code>create</code>, or <code>edit</code> <em>any</em> newsletter), or
92   * <code>&quot;newsletter:*:*</code> (allow the user to perform <em>any</em> action on <em>any</em> newsletter).
93   * <p/>
94   * To perform checks against these instance-level permissions, the application should include the instance ID in the
95   * permission check like so:
96   * <p/>
97   * <code>subject.isPermitted( &quot;newsletter:edit:13&quot; )</code>
98   * <p/>
99   * 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
100  * this could be used in your application.  However, the Shiro team likes to standardize some common usages shown
101  * above to help people get started and provide consistency in the Shiro community.
102  *
103  * @since 0.9
104  */
105 public class WildcardPermission implements Permission, Serializable {
106 
107     //TODO - JavaDoc methods
108 
109     /*--------------------------------------------
110     |             C O N S T A N T S             |
111     ============================================*/
112     protected static final String WILDCARD_TOKEN = "*";
113     protected static final String PART_DIVIDER_TOKEN = ":";
114     protected static final String SUBPART_DIVIDER_TOKEN = ",";
115     protected static final boolean DEFAULT_CASE_SENSITIVE = false;
116 
117     /*--------------------------------------------
118     |    I N S T A N C E   V A R I A B L E S    |
119     ============================================*/
120     private List<Set<String>> parts;
121 
122     /*--------------------------------------------
123     |         C O N S T R U C T O R S           |
124     ============================================*/
125     /**
126      * Default no-arg constructor for subclasses only - end-user developers instantiating Permission instances must
127      * provide a wildcard string at a minimum, since Permission instances are immutable once instantiated.
128      * <p/>
129      * Note that the WildcardPermission class is very robust and typically subclasses are not necessary unless you
130      * wish to create type-safe Permission objects that would be used in your application, such as perhaps a
131      * {@code UserPermission}, {@code SystemPermission}, {@code PrinterPermission}, etc.  If you want such type-safe
132      * permission usage, consider subclassing the {@link DomainPermission DomainPermission} class for your needs.
133      */
134     protected WildcardPermission() {
135     }
136 
137     public WildcardPermission(String wildcardString) {
138         this(wildcardString, DEFAULT_CASE_SENSITIVE);
139     }
140 
141     public WildcardPermission(String wildcardString, boolean caseSensitive) {
142         setParts(wildcardString, caseSensitive);
143     }
144 
145     protected void setParts(String wildcardString) {
146         setParts(wildcardString, DEFAULT_CASE_SENSITIVE);
147     }
148 
149     protected void setParts(String wildcardString, boolean caseSensitive) {
150         if (wildcardString == null || wildcardString.trim().length() == 0) {
151             throw new IllegalArgumentException("Wildcard string cannot be null or empty. Make sure permission strings are properly formatted.");
152         }
153 
154         wildcardString = wildcardString.trim();
155 
156         List<String> parts = CollectionUtils.asList(wildcardString.split(PART_DIVIDER_TOKEN));
157 
158         this.parts = new ArrayList<Set<String>>();
159         for (String part : parts) {
160             Set<String> subparts = CollectionUtils.asSet(part.split(SUBPART_DIVIDER_TOKEN));
161             if (!caseSensitive) {
162                 subparts = lowercase(subparts);
163             }
164             if (subparts.isEmpty()) {
165                 throw new IllegalArgumentException("Wildcard string cannot contain parts with only dividers. Make sure permission strings are properly formatted.");
166             }
167             this.parts.add(subparts);
168         }
169 
170         if (this.parts.isEmpty()) {
171             throw new IllegalArgumentException("Wildcard string cannot contain only dividers. Make sure permission strings are properly formatted.");
172         }
173     }
174 
175     private Set<String> lowercase(Set<String> subparts) {
176         Set<String> lowerCasedSubparts = new LinkedHashSet<String>(subparts.size());
177         for (String subpart : subparts) {
178             lowerCasedSubparts.add(subpart.toLowerCase());
179         }
180         return lowerCasedSubparts;
181     }
182 
183     /*--------------------------------------------
184     |  A C C E S S O R S / M O D I F I E R S    |
185     ============================================*/
186     protected List<Set<String>> getParts() {
187         return this.parts;
188     }
189 
190     /*--------------------------------------------
191     |               M E T H O D S               |
192     ============================================*/
193 
194     public boolean implies(Permission p) {
195         // By default only supports comparisons with other WildcardPermissions
196         if (!(p instanceof WildcardPermission)) {
197             return false;
198         }
199 
200         WildcardPermission wp = (WildcardPermission) p;
201 
202         List<Set<String>> otherParts = wp.getParts();
203 
204         int i = 0;
205         for (Set<String> otherPart : otherParts) {
206             // If this permission has less parts than the other permission, everything after the number of parts contained
207             // in this permission is automatically implied, so return true
208             if (getParts().size() - 1 < i) {
209                 return true;
210             } else {
211                 Set<String> part = getParts().get(i);
212                 if (!part.contains(WILDCARD_TOKEN) && !part.containsAll(otherPart)) {
213                     return false;
214                 }
215                 i++;
216             }
217         }
218 
219         // If this permission has more parts than the other parts, only imply it if all of the other parts are wildcards
220         for (; i < getParts().size(); i++) {
221             Set<String> part = getParts().get(i);
222             if (!part.contains(WILDCARD_TOKEN)) {
223                 return false;
224             }
225         }
226 
227         return true;
228     }
229 
230     public String toString() {
231         StringBuilder buffer = new StringBuilder();
232         for (Set<String> part : parts) {
233             if (buffer.length() > 0) {
234                 buffer.append(":");
235             }
236             buffer.append(part);
237         }
238         return buffer.toString();
239     }
240 
241     public boolean equals(Object o) {
242         if (o instanceof WildcardPermission) {
243             WildcardPermission wp = (WildcardPermission) o;
244             return parts.equals(wp.parts);
245         }
246         return false;
247     }
248 
249     public int hashCode() {
250         return parts.hashCode();
251     }
252 
253 }