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  import org.apache.shiro.util.StringUtils;
24  
25  import java.io.Serializable;
26  import java.util.ArrayList;
27  import java.util.Iterator;
28  import java.util.LinkedHashSet;
29  import java.util.List;
30  import java.util.Set;
31  
32  /**
33   * A <code>WildcardPermission</code> is a very flexible permission construct supporting multiple levels of
34   * permission matching. However, most people will probably follow some standard conventions as explained below.
35   * <p/>
36   * <h3>Simple Usage</h3>
37   * <p/>
38   * In the simplest form, <code>WildcardPermission</code> can be used as a simple permission string. You could grant a
39   * user an &quot;editNewsletter&quot; permission and then check to see if the user has the editNewsletter
40   * permission by calling
41   * <p/>
42   * <code>subject.isPermitted(&quot;editNewsletter&quot;)</code>
43   * <p/>
44   * This is (mostly) equivalent to
45   * <p/>
46   * <code>subject.isPermitted( new WildcardPermission(&quot;editNewsletter&quot;) )</code>
47   * <p/>
48   * but more on that later.
49   * <p/>
50   * The simple permission string may work for simple applications, but it requires you to have permissions like
51   * <code>&quot;viewNewsletter&quot;</code>, <code>&quot;deleteNewsletter&quot;</code>,
52   * <code>&quot;createNewsletter&quot;</code>, etc. You can also grant a user <code>&quot;*&quot;</code> permissions
53   * using the wildcard character (giving this class its name), which means they have <em>all</em> permissions. But
54   * using this approach there's no way to just say a user has &quot;all newsletter permissions&quot;.
55   * <p/>
56   * For this reason, <code>WildcardPermission</code> supports multiple <em>levels</em> of permissioning.
57   * <p/>
58   * <h3>Multiple Levels</h3>
59   * <p/>
60   * WildcardPermission</code> also supports the concept of multiple <em>levels</em>.  For example, you could
61   * restructure the previous simple example by granting a user the permission <code>&quot;newsletter:edit&quot;</code>.
62   * The colon in this example is a special character used by the <code>WildcardPermission</code> that delimits the
63   * next token in the permission.
64   * <p/>
65   * In this example, the first token is the <em>domain</em> that is being operated on
66   * and the second token is the <em>action</em> being performed. Each level can contain multiple values.  So you
67   * could simply grant a user the permission <code>&quot;newsletter:view,edit,create&quot;</code> which gives them
68   * access to perform <code>view</code>, <code>edit</code>, and <code>create</code> actions in the <code>newsletter</code>
69   * <em>domain</em>. Then you could check to see if the user has the <code>&quot;newsletter:create&quot;</code>
70   * permission by calling
71   * <p/>
72   * <code>subject.isPermitted(&quot;newsletter:create&quot;)</code>
73   * <p/>
74   * (which would return true).
75   * <p/>
76   * In addition to granting multiple permissions via a single string, you can grant all permission for a particular
77   * level. So if you wanted to grant a user all actions in the <code>newsletter</code> domain, you could simply give
78   * them <code>&quot;newsletter:*&quot;</code>. Now, any permission check for <code>&quot;newsletter:XXX&quot;</code>
79   * will return <code>true</code>. It is also possible to use the wildcard token at the domain level (or both): so you
80   * could grant a user the <code>&quot;view&quot;</code> action across all domains <code>&quot;*:view&quot;</code>.
81   * <p/>
82   * <h3>Instance-level Access Control</h3>
83   * <p/>
84   * Another common usage of the <code>WildcardPermission</code> is to model instance-level Access Control Lists.
85   * In this scenario you use three tokens - the first is the <em>domain</em>, the second is the <em>action</em>, and
86   * the third is the <em>instance</em> you are acting on.
87   * <p/>
88   * So for example you could grant a user <code>&quot;newsletter:edit:12,13,18&quot;</code>.  In this example, assume
89   * that the third token is the system's ID of the newsletter. That would allow the user to edit newsletters
90   * <code>12</code>, <code>13</code>, and <code>18</code>. This is an extremely powerful way to express permissions,
91   * since you can now say things like <code>&quot;newsletter:*:13&quot;</code> (grant a user all actions for newsletter
92   * <code>13</code>), <code>&quot;newsletter:view,create,edit:*&quot;</code> (allow the user to
93   * <code>view</code>, <code>create</code>, or <code>edit</code> <em>any</em> newsletter), or
94   * <code>&quot;newsletter:*:*</code> (allow the user to perform <em>any</em> action on <em>any</em> newsletter).
95   * <p/>
96   * To perform checks against these instance-level permissions, the application should include the instance ID in the
97   * permission check like so:
98   * <p/>
99   * <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  */
107 public 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 }