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.wiki.auth;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.auth.user.UserDatabase;
024import org.apache.wiki.auth.user.UserProfile;
025import org.apache.wiki.util.TextUtil;
026
027import java.io.Serializable;
028import java.security.Principal;
029import java.util.Date;
030import java.util.Properties;
031import java.util.concurrent.TimeUnit;
032import java.util.function.Supplier;
033
034
035/**
036 * What happens to a user account as the password of its owner gets older, on top of {@link PasswordExpiry}. Each stage is optional and
037 * is counted in days from the last time the password was changed ({@link UserProfile#getPasswordChanged()}):
038 * <ul>
039 * <li>{@value #PROP_WARN_DAYS}: the owner is told that the password is going to expire. Only if {@value PasswordExpiry#PROP_EXPIRY_DAYS}
040 * is set, and later than this.</li>
041 * <li>{@value #PROP_LOCK_DAYS}: the account is locked, and its owner told. It stays locked until an administrator unlocks it.</li>
042 * <li>{@value #PROP_DELETE_DAYS}: the account is deleted, and its owner told.</li>
043 * </ul>
044 * A stage has to come after the ones before it, in the order of the list and of the expiry of the password; if it does not, it is
045 * logged and the stage is off. {@link #apply(Date)} goes through all the accounts once. The password that has no date yet gets it, which
046 * is when its clock starts.
047 *
048 * @since 3.0.1
049 */
050public final class AccountLifecycle {
051
052    private static final Logger LOG = LogManager.getLogger( AccountLifecycle.class );
053
054    /** Property with the number of days after which the owner of an account is told that the password is going to expire. */
055    public static final String PROP_WARN_DAYS = "jspwiki.credentials.expiry.warnDays";
056
057    /** Property with the number of days after which an account is locked. */
058    public static final String PROP_LOCK_DAYS = "jspwiki.credentials.lock.days";
059
060    /** Property with the number of days after which an account is deleted. */
061    public static final String PROP_DELETE_DAYS = "jspwiki.credentials.delete.days";
062
063    /** Attribute of a profile with the time the owner was told that the password is going to expire. */
064    static final String ATTR_REMINDER_SENT = "jspwiki.credentials.reminderSent";
065
066    /** The end of the year 9999: far enough to be forever, and a date that every user database can keep. */
067    static final Date LOCKED_UNTIL = new Date( 253_402_300_799_000L );
068
069    /** Tells the owners of the accounts what happens to them. */
070    public interface Notifier {
071
072        /**
073         * Tells the owner that the password is going to expire. If this throws, the owner is told again at the next pass.
074         *
075         * @param profile the profile of the account
076         * @param expires the day the password expires
077         */
078        void passwordWillExpire( UserProfile profile, Date expires );
079
080        /**
081         * Tells the owner that the account has been locked.
082         *
083         * @param profile the profile of the account
084         * @param deleted the day the account is deleted, or {@code null} if it is not
085         */
086        void accountLocked( UserProfile profile, Date deleted );
087
088        /**
089         * Tells the owner that the account has been deleted.
090         *
091         * @param profile the profile of the account that has been deleted
092         */
093        void accountDeleted( UserProfile profile );
094
095    }
096
097    private final Supplier< UserDatabase > databases;
098    private final Notifier notifier;
099    private final int expiryDays;
100    private final int warnDays;
101    private final int lockDays;
102    private final int deleteDays;
103
104    /**
105     * Reads the stages from the properties.
106     *
107     * @param props the wiki properties
108     * @param databases gives the user database, which is not needed before a pass
109     * @param notifier tells the owners
110     */
111    public AccountLifecycle( final Properties props, final Supplier< UserDatabase > databases, final Notifier notifier ) {
112        this.databases = databases;
113        this.notifier = notifier;
114
115        expiryDays = new PasswordExpiry( props ).getDays();
116        final int warn = days( props, PROP_WARN_DAYS );
117        if( warn > 0 && expiryDays == 0 ) {
118            LOG.error( "{} needs {} to be set; the stage is off", PROP_WARN_DAYS, PasswordExpiry.PROP_EXPIRY_DAYS );
119            warnDays = 0;
120        } else {
121            warnDays = inOrder( PROP_WARN_DAYS, warn, 0, expiryDays );
122        }
123        lockDays = inOrder( PROP_LOCK_DAYS, days( props, PROP_LOCK_DAYS ), expiryDays, Integer.MAX_VALUE );
124        deleteDays = inOrder( PROP_DELETE_DAYS, days( props, PROP_DELETE_DAYS ), Math.max( expiryDays, lockDays ), Integer.MAX_VALUE );
125    }
126
127    /**
128     * Reads a number of days.
129     *
130     * @return the days, or 0 if the property is not set to a positive number
131     */
132    private static int days( final Properties props, final String key ) {
133        final String value = TextUtil.getStringProperty( props, key, "0" ).trim();
134        try {
135            final int days = Integer.parseInt( value );
136            if( days < 0 ) {
137                LOG.error( "{}={} is negative; the stage is off", key, value );
138                return 0;
139            }
140            return days;
141        } catch( final NumberFormatException e ) {
142            LOG.error( "{}={} is not a number; the stage is off", key, value );
143            return 0;
144        }
145    }
146
147    /**
148     * Checks that the days of a stage are after the stage before it and before the one after it.
149     *
150     * @return the days, or 0 if they are not in order or are not set
151     */
152    private static int inOrder( final String key, final int days, final int after, final int before ) {
153        if( days > after && days < before ) {
154            return days;
155        }
156        if( days > 0 ) {
157            LOG.error( "{}={} is not after {} days and before {} days; the stage is off", key, days, after, before );
158        }
159        return 0;
160    }
161
162    /**
163     * Tells if any stage is on.
164     *
165     * @return {@code true} if there is something to do for the accounts
166     */
167    public boolean isEnabled() {
168        return warnDays > 0 || lockDays > 0 || deleteDays > 0;
169    }
170
171    /**
172     * Returns the days after which the owner is told that the password is going to expire.
173     *
174     * @return the days, or 0 if the owner is not told
175     */
176    public int getWarnDays() {
177        return warnDays;
178    }
179
180    /**
181     * Returns the days after which an account is locked.
182     *
183     * @return the days, or 0 if accounts are not locked
184     */
185    public int getLockDays() {
186        return lockDays;
187    }
188
189    /**
190     * Returns the days after which an account is deleted.
191     *
192     * @return the days, or 0 if accounts are not deleted
193     */
194    public int getDeleteDays() {
195        return deleteDays;
196    }
197
198    /**
199     * Goes through all the accounts once and does what their age calls for. An account that cannot be dealt with is logged and left for
200     * the next pass.
201     *
202     * @param now the time to count the age from
203     */
204    public void apply( final Date now ) {
205        final UserDatabase db = databases.get();
206        final Principal[] wikiNames;
207        try {
208            wikiNames = db.getWikiNames();
209        } catch( final WikiSecurityException e ) {
210            LOG.error( "Could not list the user accounts: {}", e.getMessage(), e );
211            return;
212        }
213
214        for( final Principal wikiName : wikiNames ) {
215            try {
216                apply( db, db.findByWikiName( wikiName.getName() ), now );
217            } catch( final NoSuchPrincipalException e ) {
218                LOG.debug( "The account of {} is gone", wikiName.getName(), e );
219            } catch( final WikiSecurityException | RuntimeException e ) {
220                LOG.error( "Could not apply the account policy to {}: {}", wikiName.getName(), e.getMessage(), e );
221            }
222        }
223    }
224
225    private void apply( final UserDatabase db, final UserProfile profile, final Date now ) throws WikiSecurityException {
226        final Date changed = profile.getPasswordChanged();
227        if( changed == null ) {
228            // The clock of the password starts here
229            profile.setPasswordChanged( now );
230            db.save( profile );
231            return;
232        }
233
234        final long age = now.getTime() - changed.getTime();
235        if( deleteDays > 0 && age > TimeUnit.DAYS.toMillis( deleteDays ) ) {
236            delete( db, profile );
237        } else if( lockDays > 0 && age > TimeUnit.DAYS.toMillis( lockDays ) ) {
238            if( !profile.isLocked() ) {
239                lock( db, profile, changed );
240            }
241        } else if( warnDays > 0 && age > TimeUnit.DAYS.toMillis( warnDays ) && !profile.isLocked() && !reminderSent( profile, changed ) ) {
242            warn( db, profile, changed, now );
243        }
244    }
245
246    private boolean reminderSent( final UserProfile profile, final Date changed ) {
247        final Serializable sent = profile.getAttributes().get( ATTR_REMINDER_SENT );
248        return sent instanceof Date && !( ( Date )sent ).before( changed );
249    }
250
251    private void warn( final UserDatabase db, final UserProfile profile, final Date changed, final Date now ) throws WikiSecurityException {
252        final Date expires = new Date( changed.getTime() + TimeUnit.DAYS.toMillis( expiryDays ) );
253        notifier.passwordWillExpire( profile, expires );
254        profile.getAttributes().put( ATTR_REMINDER_SENT, now );
255        db.save( profile );
256    }
257
258    private void lock( final UserDatabase db, final UserProfile profile, final Date changed ) throws WikiSecurityException {
259        profile.setLockExpiry( LOCKED_UNTIL );
260        db.save( profile );
261        LOG.warn( "AUDIT - The account of {} is locked: its password is older than {} days", profile.getLoginName(), lockDays );
262        final Date deleted = deleteDays > 0 ? new Date( changed.getTime() + TimeUnit.DAYS.toMillis( deleteDays ) ) : null;
263        tell( () -> notifier.accountLocked( profile, deleted ), profile );
264    }
265
266    private void delete( final UserDatabase db, final UserProfile profile ) throws WikiSecurityException {
267        db.deleteByLoginName( profile.getLoginName() );
268        LOG.warn( "AUDIT - The account of {} is deleted: its password is older than {} days", profile.getLoginName(), deleteDays );
269        tell( () -> notifier.accountDeleted( profile ), profile );
270    }
271
272    /** What has been done to an account stays done if the owner cannot be told. */
273    private void tell( final Runnable notification, final UserProfile profile ) {
274        try {
275            notification.run();
276        } catch( final RuntimeException e ) {
277            LOG.warn( "Could not tell {} about the change of the account: {}", profile.getLoginName(), e.getMessage(), e );
278        }
279    }
280
281}