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