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     */
019    package org.apache.shiro.authz.permission;
020    
021    import org.apache.shiro.authz.Permission;
022    import org.apache.shiro.util.CollectionUtils;
023    
024    import java.io.Serializable;
025    import java.util.ArrayList;
026    import java.util.LinkedHashSet;
027    import java.util.List;
028    import java.util.Set;
029    
030    /**
031     * A <code>WildcardPermission</code> is a very flexible permission construct supporting multiple levels of
032     * permission matching. However, most people will probably follow some standard conventions as explained below.
033     * <p/>
034     * <h3>Simple Usage</h3>
035     * <p/>
036     * In the simplest form, <code>WildcardPermission</code> can be used as a simple permission string. You could grant a
037     * user an &quot;editNewsletter&quot; permission and then check to see if the user has the editNewsletter
038     * permission by calling
039     * <p/>
040     * <code>subject.isPermitted(&quot;editNewsletter&quot;)</code>
041     * <p/>
042     * This is (mostly) equivalent to
043     * <p/>
044     * <code>subject.isPermitted( new WildcardPermission(&quot;editNewsletter&quot;) )</code>
045     * <p/>
046     * but more on that later.
047     * <p/>
048     * The simple permission string may work for simple applications, but it requires you to have permissions like
049     * <code>&quot;viewNewsletter&quot;</code>, <code>&quot;deleteNewsletter&quot;</code>,
050     * <code>&quot;createNewsletter&quot;</code>, etc. You can also grant a user <code>&quot;*&quot;</code> permissions
051     * using the wildcard character (giving this class its name), which means they have <em>all</em> permissions. But
052     * using this approach there's no way to just say a user has &quot;all newsletter permissions&quot;.
053     * <p/>
054     * For this reason, <code>WildcardPermission</code> supports multiple <em>levels</em> of permissioning.
055     * <p/>
056     * <h3>Multiple Levels</h3>
057     * <p/>
058     * WildcardPermission</code> also supports the concept of multiple <em>levels</em>.  For example, you could
059     * restructure the previous simple example by granting a user the permission <code>&quot;newsletter:edit&quot;</code>.
060     * The colon in this example is a special character used by the <code>WildcardPermission</code> that delimits the
061     * next token in the permission.
062     * <p/>
063     * In this example, the first token is the <em>domain</em> that is being operated on
064     * and the second token is the <em>action</em> being performed. Each level can contain multiple values.  So you
065     * could simply grant a user the permission <code>&quot;newsletter:view,edit,create&quot;</code> which gives them
066     * access to perform <code>view</code>, <code>edit</code>, and <code>create</code> actions in the <code>newsletter</code>
067     * <em>domain</em>. Then you could check to see if the user has the <code>&quot;newsletter:create&quot;</code>
068     * permission by calling
069     * <p/>
070     * <code>subject.isPermitted(&quot;newsletter:create&quot;)</code>
071     * <p/>
072     * (which would return true).
073     * <p/>
074     * In addition to granting multiple permissions via a single string, you can grant all permission for a particular
075     * level. So if you wanted to grant a user all actions in the <code>newsletter</code> domain, you could simply give
076     * them <code>&quot;newsletter:*&quot;</code>. Now, any permission check for <code>&quot;newsletter:XXX&quot;</code>
077     * will return <code>true</code>. It is also possible to use the wildcard token at the domain level (or both): so you
078     * could grant a user the <code>&quot;view&quot;</code> action across all domains <code>&quot;*:view&quot;</code>.
079     * <p/>
080     * <h3>Instance-level Access Control</h3>
081     * <p/>
082     * Another common usage of the <code>WildcardPermission</code> is to model instance-level Access Control Lists.
083     * In this scenario you use three tokens - the first is the <em>domain</em>, the second is the <em>action</em>, and
084     * the third is the <em>instance</em> you are acting on.
085     * <p/>
086     * So for example you could grant a user <code>&quot;newsletter:edit:12,13,18&quot;</code>.  In this example, assume
087     * that the third token is the system's ID of the newsletter. That would allow the user to edit newsletters
088     * <code>12</code>, <code>13</code>, and <code>18</code>. This is an extremely powerful way to express permissions,
089     * since you can now say things like <code>&quot;newsletter:*:13&quot;</code> (grant a user all actions for newsletter
090     * <code>13</code>), <code>&quot;newsletter:view,create,edit:*&quot;</code> (allow the user to
091     * <code>view</code>, <code>create</code>, or <code>edit</code> <em>any</em> newsletter), or
092     * <code>&quot;newsletter:*:*</code> (allow the user to perform <em>any</em> action on <em>any</em> newsletter).
093     * <p/>
094     * To perform checks against these instance-level permissions, the application should include the instance ID in the
095     * permission check like so:
096     * <p/>
097     * <code>subject.isPermitted( &quot;newsletter:edit:13&quot; )</code>
098     * <p/>
099     * 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    }