# BitFlagsResource.java

    /*
    ** Module   : BitFlagsResource.java
    ** Abstract : security mgr plugin for the "bitflags" resource.
    **
    ** Copyright (c) 2005-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ------------------------------Description------------------------------------
    ** 001 GES 20200115 First version based on the NetResource implementation.
    **     GES 20200206 Moved code to StringHelper.
    ** 002 HC  20230427 Implemented management for file-system resource. This includes Admin and
    **                  server directory changes.
    ** 003 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.security;

    import com.goldencode.p2j.directory.*;

    import com.goldencode.p2j.util.logging.*;
    import java.util.*;
    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.logging.*;

    /**
     * Implements the "bitFlags" resource. This can be used to protect any resource whose
     * rights can be represented by a small set of flags:
     * <ul>
     *   <li> create - a runtime instance of the resource can be created
     *   <li> delete - an existing runtime instance can be destroyed
     *   <li> read - the state or data associated with an existing runtime instance can be accessed
     *   <li> write - the state or data associated with an existing runtime instance can be modified
     *   <li> denied - no access is allowed (overrides any other access flags)
     * </ul>
     * <p>
     * Rights objects for this resource are made of one bitfield with 8 bits.  The first four bits
     * correspond to the create, delete, read and write respectively.  There are 3 reserved bits.
     * The last bit is for explicit denial of access. When printed, they are shown as
     * {@code CDRW...N}.
     * <p>
     * Resource names will be namespaced using the subclass' resource type name.  The naming approach
     * is {@code /resource_type_name/instance_name}.  Each different instance of a particular
     * resource type will share the same type name but must have a unique, non-empty instance name.
     */
    public abstract class BitFlagsResource
    extends AbstractResource
    implements BitFlagsConstants
    {
       /** Extended bits, if any */
       private String[] extBits;

       /** Logger. */
       private static final CentralLogger LOG = CentralLogger.get(BitFlagsResource.class);

       /**
        * Constructor.
        */
       public BitFlagsResource()
       {
          extBits = getExtendedBits();
       }

       /**
        * Returns the plugin's resource type name as a string.
        *
        * @return   The plugin's resource type name.
        */
       public abstract String getTypeName();

       /**
        * Override the method to provide extended bit names to augment the default set of bits.
        * The method must return either {@code null} for no extended bits or an array of length 1, 2, 3.
        * An array of length 1 will carry name of bit 4, length 2 bits 4 and 5, and length 3 bits 4, 5 and 6.
        *
        * @return  See above.
        */
       public String[] getExtendedBits()
       {
          return null;
       }

       /**
        * Returns an array of descriptions, one object per the plugin's access rights item.
        * <p>
        * This plugin uses one field of type BitField with three bits: read, write
        * end execute.
        *
        * @return   The descriptions, one per access rights item.
        */
       public final Description[] describeRights()
       {
          List<String> bitNames = new LinkedList<>();
          Collections.addAll(bitNames, "create", "delete", "read", "write", "denied");
          if (extBits != null)
          {
             for (String bitName : extBits)
             {
                // insert the additional bits just before "denied"
                bitNames.add(bitNames.size() - 1, bitName);
             }
          }

          Description[] items = new Description[1];

          items[0] = new Description(AttributeType.ATTR_BITFIELD,  // string
                                     true,                         // mandatory?
                                     false,                        // variable size?
                                     BITSET_SIZE,                  // size
                                     "permissions",                // text label
                                     "bit set to ON enables access",
                                     bitNames.toArray(new String[bitNames.size()]),
                                     new BitSet(BITSET_SIZE));     // 3 unused bits

          return items;
       }

       /**
        * Converts from the persistent form of the plugin's rights to the specific in-memory
        * type.
        *
        * @param    rights
        *           An array of objects of proper types representing items in a set
        *           of access rights.
        *
        * @return   The reference to the interface.
        */
       public Rights getRightsInstance(Object[] rights)
       {
          return new BitFlagsRights(BitSetHelper.fromBitField((BitField)rights[0]));
       }

       /**
        * Checks whether a given array of objects representing a set of access
        * rights fields is acceptable.
        * <p>This method returns <code>true</code> only if:
        * <ul>
        *   <li>DENIED bit is not set, or
        *   <li>DENIED bit is set and no other bit is set.
        * </ul>
        *
        * @param    rights
        *           An array of objects of proper types representing items in a set of access rights.
        *
        * @return   <code>true</code> if the array is acceptable for an instance of access rights.
        */
       public boolean isRightsSetValid(Object[] rights)
       {
          if (rights.length != 1)
             return false;

          if (!rights[0].getClass().isInstance(new BitField(1)))
             return false;

          BitSet bs = BitSetHelper.fromBitField((BitField)rights[0]);
          BitFlagsRights r = new BitFlagsRights(bs);

          boolean denied = r.get(BIT_DENIED_ACCESS);

          if (!denied)
             return true;

          boolean set = r.get(BIT_CREATE_ACCESS)  ||
                     r.get(BIT_DELETE_ACCESS)  ||
                     r.get(BIT_READ_ACCESS)    ||
                     r.get(BIT_WRITE_ACCESS);

          // check extended bits if any
          if (!set && extBits != null)
          {
             for (int i = 0; i < Math.min(3, extBits.length); i++)
             {
                set = r.get(i + 4);
                if (set)
                {
                   break;
                }
             }
          }

          if (set)
             return false;

          return true;
       }

       /**
        * Reports if CREATE is allowed for the given resource name.
        *
        * @param    name
        *           Resource instance name.
        *
        * @return   <code>true</code> if access is allowed.
        */
       public boolean canCreate(String name)
       {
          return accessWorker(name, BIT_CREATE_ACCESS);
       }

       /**
        * Reports if DELETE is allowed for the given resource name.
        *
        * @param    name
        *           Resource instance name.
        *
        * @return   <code>true</code> if access is allowed.
        */
       public boolean canDelete(String name)
       {
          return accessWorker(name, BIT_DELETE_ACCESS);
       }

       /**
        * Reports if READ is allowed for the given resource name.
        *
        * @param    name
        *           Resource instance name.
        *
        * @return   <code>true</code> if access is allowed.
        */
       public boolean canRead(String name)
       {
          return accessWorker(name, BIT_READ_ACCESS);
       }

       /**
        * Reports if WRITE is allowed for the given resource name.
        *
        * @param    name
        *           Resource instance name.
        *
        * @return   <code>true</code> if access is allowed.
        */
       public boolean canWrite(String name)
       {
          return accessWorker(name, BIT_WRITE_ACCESS);
       }

       /**
        * Implements generalized access rights check worker.
        *
        * @param    name
        *           Resource instance name.
        * @param    bit
        *           The bit to check.
        *
        * @return   <code>true</code> if access is allowed.
        */
       public boolean accessWorker(String name, int bit)
       {
          // check to see if there is a cached decision
          Boolean cached = sm.getCachedDecision(resourceIndex, name, bit);

          if (cached != null)
          {
             return cached.booleanValue();
          }

          // initiate the ACL search
          int handle = sm.openRightsSearch(resourceIndex, name, bit);

          boolean isFinerLoggable = LOG.isLoggable(Level.FINER);
          if (isFinerLoggable)
          {
             LOG.finer("Search open: resId " + resourceIndex + ", instance " +
                          name + ", bit " + bit + ", handle " + handle);
          }

          boolean decision = false;

          BitFlagsRights rights = (BitFlagsRights) sm.getNextRights(handle);

          if (rights == null)
          {
             // no rights defined for the name
             if (isFinerLoggable)
             {
                LOG.finer("Search done: handle " + handle + ", no rights found for " +
                             name + ", cache false");
             }
          }
          else
          {
             loop:
             while (rights != null)
             {
                if (isFinerLoggable)
                {
                   LOG.finer("Search next: handle " + handle + ", rights " + rights);
                }

                if (rights.get(BIT_DENIED_ACCESS))
                {
                   // no access ends the search
                   break loop;
                }
                else if (rights.get(bit))
                {
                   decision = true;

                   // allowed access, ends the search
                   break loop;
                }

                // try the next rights instance
                rights = (BitFlagsRights) sm.getNextRights(handle);
             }

             if (isFinerLoggable)
             {
                LOG.finer("Search done: handle " + handle + ", decision " +
                             decision + ", cache true");
             }
          }

          sm.closeRightsSearch(handle, decision, true);

          return decision;
       }
    }