Draft

Exception Control Draft

Agreed API

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface BeforeHandles
{
    /**
     * Precedence relative to callbacks for the same type
     */
    int ordinal() default 0;
}

b

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface Handles
{
    /**
     * Precedence relative to handlers for the same type
     */
    int ordinal() default 0; //TODO discuss Precedence
}

/**
 * Marker for types containing Exception Handler methods.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ExceptionHandler
{
}

b

/**
 * Payload for an exception to be handled.  Implementations of this interface should not expose internals and remain
 * immutable for this contract.
 *
 * @param <T> Exception type this event represents
 */
public interface ExceptionEvent<T extends Throwable>
{
    /**
     * The exception causing this event.
     */
    T getException();

    /**
     * Instructs the dispatcher to abort further processing of handlers.
     */
    void abort();

    /**
     * Instructs the dispatcher to throw the original exception after handler processing.
     */
    void throwOriginal();

    /**
     * Instructs the dispatcher to terminate additional handler processing and mark the event as handled.
     */
    void handled();

    /**
     * Default instruction to dispatcher, continues handler processing.
     */
    void handledAndContinue();

    /**
     * Similar to {@link ExceptionEvent#handledAndContinue()},
     * but instructs the dispatcher to markHandled to the next element
     * in the cause chain without processing additional handlers for this cause chain element.
     */
    void skipCause();

    /**
     * Instructs the dispatcher to allow this handler to be invoked again.
     */
    void unmute();

    /**
     * Rethrow the exception, but use the given exception instead of the original.
     *
     * @param t Exception to be thrown in place of the original.
     */
    void rethrow(Throwable t);

    /**
     * Check to see if this exception has been handled.
     */
    boolean isMarkedHandled();
}

b

//TODO discuss the introduction of an interface
/**
 * Information about the current exception and exception cause container.  This object is not immutable.
 */
@Typed()
public class ExceptionStackEvent implements Serializable
{
    private static final long serialVersionUID = -6069790756478700680L;

    /**
     * Builds the stack from the given exception.
     *
     * @param exception Caught exception
     */
    public ExceptionStackEvent(final Throwable exception)
    {
        //...
    }

    public Collection<Throwable> getCauseElements()
    {
        //...
    }

    /**
     * Test if iteration is finished
     *
     * @return finished with iteration
     */
    public boolean isLast()
    {
        //...
    }

    public Throwable getNext()
    {
        //...
    }

    public Collection<Throwable> getRemaining()
    {
        //...
    }

    /**
     * Tests if the current exception is the root exception
     *
     * @return Returns true if iteration is at the root exception (top of the inverted stack)
     */
    public boolean isRoot()
    {
        //...
    }

    /**
     * Current exception in the iteration
     *
     * @return current exception
     */
    public Throwable getCurrent()
    {
        //...
    }

    /**
     * Internal only.
     *
     * @param elements new stack.
     */
    public void setCauseElements(Collection<Throwable> elements)
    {
        //...
    }
}

b

/**
 * Entry point event into the Catch system.  This object is nearly immutable, the only mutable portion
 * is the handled flag.
 */
@Typed()
public class ExceptionToCatchEvent implements Serializable
{
    /**
     * Constructor that adds qualifiers for the handler(s) to run.
     * Typically only integrators will be using this constructor.
     *
     * @param exception  Exception to handle
     * @param qualifiers qualifiers to use to narrow the handlers called
     */
    public ExceptionToCatchEvent(Throwable exception, Annotation... qualifiers)
    {
        //...
    }

    /**
     * Basic constructor without any qualifiers defined.
     *
     * @param exception Exception to handle.
     */
    public ExceptionToCatchEvent(Throwable exception)
    {
        //...
    }

    public Throwable getException()
    {
        //...
    }

    /**
     * Internal only.
     *
     * @param handled new value
     */
    public void setHandled(boolean handled)
    {
        //...
    }

    /**
     * Test to see if the exception has been handled via Solder Catch.
     *
     * @return test if the exception has been through Solder Catch handling.
     */
    public boolean isHandled()
    {
        //...
    }

    /**
     * Qualifiers with which the instance was created.
     *
     * @return Qualifiers with which the instance was created.
     */
    public Set<Annotation> getQualifiers()
    {
        //...
    }
}

b

/**
 * Flow control enum.  Used in the dispatcher to determine how to markHandled.
 */
public enum ExceptionHandlingFlow
{
    HANDLED,
    HANDLED_AND_CONTINUE,
    SKIP_CAUSE,
    ABORT,
    THROW_ORIGINAL,
    THROW
}

b

/**
 * Container for the exception and it's stack trace.
 */
@Typed()
public final class ExceptionStackItem implements Serializable
{
    public ExceptionStackItem(final Throwable cause)
    {
        //...
    }

    public ExceptionStackItem(Throwable throwable, StackTraceElement[] stackTraceElements)
    {
        //...
    }

    public StackTraceElement[] getStackTraceElements()
    {
        //...
    }

    public Throwable getThrowable()
    {
        //...
    }
}

b

/**
 * Meta data interface about an exception handler. It is the responsibility of the
 * implementation to support {@link javax.enterprise.inject.spi.InjectionPoint}s and to
 * validate those {@link javax.enterprise.inject.spi.InjectionPoint}s.
 *
 * @param <T> Exception for which this handler is responsible
 */
public interface HandlerMethod<T extends Throwable>
{
    /**
     * Obtains the set of handled event qualifiers.
     */
    Set<Annotation> getQualifiers();

    /**
     * Obtains the handled event type.
     */
    Type getExceptionType();

    /**
     * Flag indicating this handler should be invoked during the before traversal.
     */
    boolean isBeforeHandler();

    /**
     * Calls the handler method, passing the given event object.
     *
     * @param event event to pass to the handler.
     */
    void notify(ExceptionEvent<T> event);

    /**
     * Obtains the precedence of the handler.
     */
    int getOrdinal();

    /**
     * Basic {@link Object#equals(Object)} but must use all of the get methods from this interface to
     * maintain compatibility.
     *
     * @param o Object being compared to this.
     * @return true or false based on standard equality.
     */
    @Override
    boolean equals(Object o);

    @Override
    int hashCode();
}

Under discussion

  • Exception Handlers
  • Entry into the Exception Handling system

API/SPI

Use-cases

Fire and observe exceptions

An exception happens either in some business logic or from the container (maybe a session timed out or something like that). Developers need a simple, easy to use way to handle exceptions in a uniform way. They also need to be able to tell, after exception handling, if the exception was actually handled (a handler was found for the particular exception type or super type) or if it needs to be bubbled up to a higher level.

Scenario

Business method using try / catch
public void myBusinessMethod(...) {
    try {
        ...
    } catch (Exception e) {
        // entry into exception handling system
}

b

JSF integration
public void handle() throws FacesException {
    // iterate over exceptions
    // entry into exception handling system
    // exception handling inspection
}

b

JAX-RS integration
public class MyExceptionMapper implements ExceptionMapper<Throwable> {
    public Response toResponse(E exception) {
        // entry into exception handling system
        // exception handling inspection
    }
}

Message module draft

Features to merge

original list: https://issues.apache.org/jira/browse/DELTASPIKE-119

Part 1

|| Feature || Comments || Objections || Discussion finished | Basic API | | | (+) | | Serializable messages | | not compatible with type-safe messages | | | Transferable messages (resolve the final text for a different context (locale,…)) and context-config | | | (+) | | custom message types | | | | | creating messages via builder pattern | | | (+) | | numbered message arguments | | | (+) | | eval existing converter approach for numbered message arguments | | | | | message resolver to support different message-sources | | | (+) | | message interpolator | | | (+) | | locale resolver | | | (+) due to type-safe messages it changed a bit - we have to re-visit it | | type safe messages | | | (+) |

Part 2

This part depends on decissions of part 1.

|| Feature || Comments || Objections || Discussion finished | el support (= el interpolation) | | | | | named message arguments | | | | | message payload -> allows to control processing of the message (via custom impl. of different SPIs) – similar to payload in bean-validation | | | | | message context (config) is immutable to avoid side-effects | | | | | clone a message context to use the same config but it’s possible to change it before the new context gets created (and is immutable) | | | | | formatter to allow to format argument-values for the final message text (similar to a converter -> we can think about merging the concepts) | | | | | tooling for devs to generate their own type-safe messages | | | | | messages within a database, or any other possible back end | | | | | inline translated type safe messages | | | | | pluralizer system for message i18n | | | | | static helpers for simple messages | | | |

Part 3

This part depends on the planned integration with other technologies like JSF, BV,...

|| Feature || Comments || Objections || Discussion finished | add message to the "current" context | | | | | factories to customize the default behaviour | | | | | allows multi-tenant support | | | | | message targets (ie. a message for a specific component) | | | | | application and client locale | | | | | application and client timezone | | | | | support jsr310 dates | | | | | transaction phase for message, ie. only produce a message when a transaction is committed (usually used in conjunction with observers) | | | | | integrate type safe messages with bean validation | | | | | ability to hook Bean Validation messages into same infrastructure | needs clarification - reason: ConstraintViolation#getMessage returns a string | | | | ability to hook JSF validation messages into same infrastructure | see "current" context | | | | messages surviving multiple http redirects | | | |

Part 4

This part contains features for integrating 3rd party libraries.

Feature Comments

Agreed API

Basic API

/**
 * Basic interface for all message-types
 */
public interface Message extends Localizable, Serializable
{
    /**
     * @return the message key (or inline-text) of the current message
     */
    String getDescriptor();

    /**
     * @return all named and numbered arguments
     */
    Serializable[] getArguments();

    /**
     * @param arguments 1-n new arguments for the current message
     * @return the current instance
     */
    Message addArgument(Serializable... arguments);

    /*
     * TBD
     */
    String toText();
}

b

@MessageBundle
public interface CustomMessageBundle
{
    @Message("Hello %s")
    Message sayHello(String cause);
}

//...

@Inject
private CustomMessageBundle messages;

//...

String messageText;
messageText = messages.sayHello("DeltaSpike").toText();
//or
messageText = messages.sayHello("DeltaSpike").toString();
//or
Message message = messages.sayHello("DeltaSpike");

API under discussion - Part 1

Message Interface

/**
 * Basic interface for all message-types
 */
public interface Message extends Localizable, Serializable
{
    /**
     * @return the message key (or inline-text) of the current message
     */
    String getDescriptor();

    /**
     * @return all named and numbered arguments
     */
    Serializable[] getArguments();

    /**
     * @param arguments 1-n new arguments for the current message
     * @return the current instance
     */
    Message addArgument(Serializable... arguments);

    //TODO check compatibility with type-safe messages
    //payload postponed (addPayload, getPayload)
}

Localizable

/**
 * Classes which implement it can provide the message-text based on the given {@link MessageContext}
 */
public interface Localizable
{
    /**
     * @param messageContext the current context
     * @return the text which represents the current instance for the given message context
     */
    String toString(MessageContext messageContext);
}

MessageInterpolator

/**
 * Implementations are responsible to replace placeholders in a message with the final value
 */
public interface MessageInterpolator extends Serializable
{
    /**
     * replaces the arguments of the given message with the given arguments
     *
     * @param messageContext the current {@link org.apache.myfaces.extensions.cdi.message.api.MessageContext}
     * instead of a MessageContextAware interface. we need it to avoid expensive operations like locking or deep cloning
     * @param messageText the message text which has to be interpolated
     * @param arguments a list of numbered and/or named arguments for the current message
     * @return the final (interpolated) message text
     *         if it was possible to replace the parameters with the given arguments
     *         the unmodified messageText otherwise
     */
    String interpolate(MessageContext messageContext, String messageText, Serializable... arguments);
}

MessageResolver

/**
 * Implementations have to resolve the text stored for a given key in the message-source they are aware of
 */
public interface MessageResolver extends Serializable
{
    String MISSING_RESOURCE_MARKER = "???";

    /**
     * @param messageContext the current {@link org.apache.myfaces.extensions.cdi.message.api.MessageContext}
     * @param messageDescriptor the message key (or in-lined text) of the current message
     * @param payload //TBD the payload of the message e.g. to use different message sources
     * @return the final but not interpolated message text
     */
    String getMessage(MessageContext messageContext,
                      String messageDescriptor,
                      /*TBD*/ Map<Class, MessagePayload> payload);
}

LocaleResolver

/**
 * Implementations have to provide the current locale
 */
public interface LocaleResolver extends Serializable
{
    /**
     * @return the current locale
     */
    Locale getLocale();
}

MessageContext

/**
 * Central context for handling messages
 */
public interface MessageContext extends LocaleResolver, MessageHandler, Serializable
{
    /**
     * @return message builder to add and/or create a new message based on the current context via a fluent api
     */
    MessageBuilder message();

    /**
     * @return the current config to change it or create a new one base on the current config
     */
    MessageContextConfig config();



    /*
     * TBD:
     */


    /**
     * @param contextType the type of the custom implementation
     * @return the instance of the current message context to use the api of the concrete implementation
     */
    <T extends MessageContext> T typed(Class<T> contextType);

    /*
     * convenient methods
     */

    /**
     * @return creates a new context based on the current one
     */
    MessageContext cloneContext();

    //the rest will be discussed later
}

MessageContextConfig

/**
 * Config for customizing a {@link MessageContext}
 */
public interface MessageContextConfig extends Serializable
{
    /**
     * create a new context based on the default context - the default context won't get modified
     *
     * @return a message context builder based on the current config
     */
    MessageContextBuilder use();

    /**
     * change the default context
     *
     * @return a message context builder to change the current config
     */
    MessageContextBuilder change();

    /**
     * @return the current message interpolator
     */
    MessageInterpolator getMessageInterpolator();

    /**
     * @return the current message resolver
     */
    MessageResolver getMessageResolver();

    /**
     * @return the current locale resolver
     */
    LocaleResolver getLocaleResolver();

    //the rest will be discussed later

    interface MessageContextBuilder
    {
        /**
         * @param messageInterpolator a new message interpolator
         * @return the instance of the current message context builder
         */
        MessageContextBuilder messageInterpolator(MessageInterpolator messageInterpolator);

        /**
         * @param messageResolver a new message resolver
         * @return the instance of the current message context builder
         */
        MessageContextBuilder messageResolver(MessageResolver messageResolver);

        /**
         * @param localeResolver a new locale resolver
         * @return the instance of the current message context builder
         */
        MessageContextBuilder localeResolver(LocaleResolver localeResolver);

        /**
         * @return a new message context based on the current config
         */
        MessageContext create();

        //the rest will be discussed later
    }
}

# Security Module draft

Agreed API

  • @Secured
  • @SecurityBindingType
  • AccessDecisionVoter
  • SecurityStrategy

Agreed API and SPI of Part 1

commit: 1a2c7ffd0d0a1ad3dea34515a54958f0a6ce2932

API

Identity

Session scoped result of the authentication process.

public interface Identity extends Serializable
{
    public enum AuthenticationResult
    {
        SUCCESS, FAILED
    }

    AuthenticationResult login();

    void logout();

    boolean isLoggedIn();

    User getUser();
}

User

Depending on further use-cases it can be refactored to an interface

The id is an unique identifier for an user. It isn't defined if it is an internal identifier or an identifier known by the user (like the user-name). If users login e.g. via their e-mail address, it's possible to lookup an internal id in a custom implementation of {{LoginCredential}} or a bean which is in between (and {{LoginCredential}} doesn't get called directly in the 2nd case).

@Typed()
public class User implements Serializable
{
    private static final long serialVersionUID = -2234530384311026364L;

    private final String id;

    public User(String id)
    {
        this.id = id;
    }

    public String getId()
    {
        return id;
    }
}

Credential

Credential is a holder for the "secret key" like a password.

public interface Credential<T>
{
    T getValue();
}

LoginCredential (former Credentials)

Request scoped holder for the authentication process.

[TODO] we need a better name for it

  • LoginCredentialState
  • LoginCredentialHolder
  • LoginCredentialProvider

    public interface LoginCredential { String getUserId();

    void setUserId(String userId);
    
    Credential getCredential();
    
    void setCredential(Credential credential);
    
    void invalidate();
    

    }

Events

  • LoggedInEvent
  • LoginFailedEvent
  • AlreadyLoggedInEvent
  • PreLoggedOutEvent
  • PostLoggedOutEvent
  • PreAuthenticateEvent
  • PostAuthenticateEvent

SPI

AuthenticatorSelector

Request scoped bean used to find the current {{Authenticator}} for the authentication process - e.g. to provide different login-types used by the same client (e.g. a component in an UI).

[TODO] discuss default (internal) Authenticator if there is no custom implementation.

public interface AuthenticatorSelector
{
    Class<? extends Authenticator> getAuthenticatorClass();

    void setAuthenticatorClass(Class<? extends Authenticator> authenticatorClass);

    String getAuthenticatorName();

    void setAuthenticatorName(String authenticatorName);

    Authenticator getSelectedAuthenticator();
}

Authenticator

Called by {{Identity}} and performs the final authentication based on the information in {{LoginCredential}} .

public interface Authenticator
{
    public enum AuthenticationStatus
    {
        SUCCESS, FAILURE, DEFERRED
    }

    void authenticate();

    void postAuthenticate();

    AuthenticationStatus getStatus();

    User getUser();
}

b

public abstract class BaseAuthenticator implements Authenticator
{
    private AuthenticationStatus status;

    public AuthenticationStatus getStatus()
    {
        return status;
    }

    protected void setStatus(AuthenticationStatus status)
    {
        this.status = status;
    }

    public void postAuthenticate()
    {
        // No-op, override if any post-authentication processing is required.
    }
}

Usage

Simple Login/Logout by Example (Java-SE)

@ApplicationScoped
public class LoginBean
{
    @Inject
    private LoginCredential loginCredential;

    @Inject
    private Identity identity;

    public boolean login(String userName, final String password)
    {
        this.loginCredential.setUserId(userName);
        this.loginCredential.setCredential(new Credential<String>() {
            @Override
            public String getValue()
            {
                return password;
            }
        });

        this.identity.login();
        return this.identity.isLoggedIn();
    }

    public boolean logout()
    {
        this.identity.logout();
        return !this.identity.isLoggedIn();
    }
}

b

public class CustomBean
{
    @Inject
    private Identity identity;

    @Inject
    private LoginBean loginBean;

    public void execute()
    {
        if(this.loginBean.login("spike", "apache"))
        {
            User user = this.identity.getUser();
            //...
        }
        else
        {
            //...
        }
    }
}

Under discussion

API/SPI

Packages

  • */authentication
  • */authentication/events
  • */authorization
  • */authorization/annotation
  • */credential or */authentication/credential

Part 1

|| Feature || Comments || Objections || Discussion finished || | Login via Username/Password | | | (+) | | Logout | | | (+) | | Authentication API and SPI | Credentials vs Credential (one of it needs a better name) | | (+) | | Basic User/Identity API | | | (+) | | Duration of a valid authentication | ExpirationEvaluator SPI | | |

Part 2

|| Feature || Comments || Objections || Discussion finished || | Object level permission | | | | | Grant or revoke permissions | | | | | Basic Roles and groups API | optional type-safe (-> static) groups (and roles) | | | | @SecurityMethodBinding | | | | | Super-users | | | | | User/Identity management | | | | | Password-Hash-Service | | | | | Group management | optional support for typ-safe groups/group-types | | |

Part 3

|| Feature || Comments || Objections || Discussion finished || | Support for deputies (see Impersonalization) | | | | | Privileges concept | | | | | UI SPI (Component based authorization) | add optional type-safe authorization; integration with JSF | | | | Permissions of resources | Merge with CODI view-configs,... | | | | Persistence SPI | integration with JPA | | | | Identity Store SPI | | | | | Query API | | | | | Application roles | | | |

Part 4

|| Feature || Comments || Objections || Discussion finished || | Support of alternative authentication concepts | Extend the Authentication SPI | | | | Integration with authentication concepts of (application-) servers | Extend the Authentication SPI | | | | Personalization | | | | | Alternatives for roles/groups | | | | | Permission for external applications | | | |

Use-cases

Authentication

Scenario

The user must be able to log in by supplying a username and password

Example JSF code:

Username: <h:inputText value="#{credentials.username}"/>
Password: <h:inputSecret id="password" value="#{credentials.password}"/>
<h:commandButton value="LOGIN" action="#{identity.login}"/>

Scenario

The user must be able to log out

Example JSF codee

<h:commandButton value="LOGOUT" action="#{identity.logout}"/>

Scenario

The developer must be able to easily implement their own custom authentication logic using a provided SPI

Example

public class SimpleAuthenticator extends BaseAuthenticator implements Authenticator {
    @Inject Credentials credentials;

    @Override
    public void authenticate() {
        if ("demo".equals(credentials.getUsername()) &&
                credentials.getCredential() instanceof PasswordCredential &&
                "demo".equals(((PasswordCredential) credentials.getCredential()).getValue())) {
            setStatus(AuthenticationStatus.SUCCESS);
            setUser(new SimpleUser("demo"));
        } else {
            setStatus(AuthenticationStatus.FAILURE);
        }
    }
}

{code}

Scenario

It should be possible to provide an optional password service to create a password-hash based on the given password which will be stored instead of the real password. Maybe there should be different default implementations (provided via qualifiers).

Scenario

The developer needs to authenticate application users stored inside corporate LDAP server.

Scenario

The developer must be able to easily support alternative authentication providers, such as those supporting services such as OpenID or token based authentication. Those can be more complex then just “username/password” scenario and require redirects to or communication with specific external ISP (Identity Service Provider)

Examples:

  • Web SSO, Desktop SSO (SPNEGO), SAML...
  • Open ID
  • OAuth
  • REST
  • Token based
  • Service authenticating to application

Requirements:

Well thought API and SPI that doesn’t limit integration with those. For some of those technologies where authentication is token based identity model needs to be capable of persisting needed information - token and reference to specific identity provider. Ability to implement own authenticator that have access to IDM and Securtiy/Permissions API in it. Provide automatic mapping between attributes returned by the Identity provider, and attributes stored in the local Identity store. Allow authentication from alternative view technologies, (i.e. AJAX)

Scenario

The user must be able to authenticate automatically using a “Remember Me” feature, based on a unique cookie value stored by the user’s browser. For authentication performed in this manner, it must be also possible for the developer to configure a validation policy, which determines whether the user is required to provide their actual credentials for critical application operations such as changing passwords or e-mail address, placing orders, etc.

The validation policy should also determine how long the validation window lasts, with some possible options being:

  • Validated for this request only
  • Validated for X minutes
  • Validated until end of session

Scenario

The developer must be able to easily integrate with AS security layer (JAAS/JAAC). Ideally by plugging DeltaSpike security into LoginModule stack.

Impersonalization

Scenario

Administrator needs to verify assigned access, applied changes or exposed resources for specific user. He authenticates “as a user” or access application imitating his identity - without knowing his password.

Examples:

  • Facebook, see your profile as user 'bob'
  • Mary is away from the office and someone needs to execute something on her behalf

Authorization

Scenario

The developer must be able to control which elements of the user interface are displayed to the user based on the user's privilege level

Example JSF code:

<div class="menu">
  <h:commandLink value="Admin functions" rendered="#{identity.hasRole('admin', 'APPLICATION')}" action="..."/>
</div>

Scenario

The developer must be able to control which elements of the user interface are displayed to the user based on their assigned permissions

Example JSF code:

<table class="customers">
  <ui:repeat value="#{customerSearch.customers}" var="#{customer}">
    <tr>
      <td>#{customer.firstName}</td>
      <td>#{customer.lastName}</td>
      <td><h:commandButton value="Edit" rendered="#{identity.hasPermission(customer, 'EDIT')}" action="..."/>
    </tr>
  </ui:repeat>
</table>

Scenario

Sometimes developer may not have available instance of resource, which he wants to protect. It may be useful to ask for permission without need to obtain object from DB. It might be useful to have method: identity.hasPermission(String resourceType, String resourceId, String permission) in addition to current identity.hasPermission(Object resource, String permission)

Example JSF code:

 <h:commandButton value="Edit page" rendered="#{identity.hasPermission('PAGE', 'AcmePage', 'EDIT')}" action="..."/>

Scenario

The developer must be able to restrict method access based on the user's privilege level. Example:

(Already addressed with typesafe security annotations, e.g. @SecurityBindingType)

Scenario

The framework must provide a system for resolving object permissions, and the developer must have access to an SPI for easily providing their own custom permission resolver logic.

Scenario

The user (with the necessary privileges) must be able assign permissions to individual objects within the application’s business domain (i.e. ACL style permissions) and have these permissions persisted. These permissions should:

  • Be assignable to either the individual user, a group, or a role
  • Be stored using an identifier that is unique for the object that the permission is being granted for
  • Have configurable identifier policies, i.e. Entity beans will use an identifier based on the primary key value
  • Have a configurable permission store, i.e. it must be possible to store permissions in a database using JPA, etc.

Scenario

Further to the previous requirement, there must be an API for managing persistent permissions. Operations performed by the user on this API (such as granting or revoking permissions to/from other users) may be subjected to an additional security check.

Scenario

The developer needs to perform authorization checks based on information stored in corporate LDAP server or dedicated database. This external store contains information about all company employees and maps hierarchy including groups present in the organization with information about their members.

Company has a Windows domain and whole security model build around structure of group of users stored in Microsoft Active Directory. Application developer needs to integrate security with this information. Examples:

  • Restrict access to employees: identityManager.getUser(userName).hasRole(“member”, “/organization/employees”);
  • Restrict access to publishing content only to marketing
  • identityManager.hasRole(“member”,“john”,”/organization/departments/marketing”);
  • Restrict adding new members to a group only for its administrator
  • identityManager.hasRole(“administrator”, “john”, “/some/specific/group”);

Scenario

The developer needs to control access to application resources based on structure of groups and user roles

Scenario

Web application has a number of resources that needs to be secured with more fine grained security model. Invoking operations on a given resource needs to be restricted with a given permission. User can inherit set of permissions to the given resource from group to which he belongs or from role he posses.

Examples:

  • Application has a structure of pages and needs to restrict access to specific ones
  • Application wants to only allow specific operations on given resource
  • User can add new customers only if it has CREATE permission on Customer resource.
  • User can review and approve new content pending to be published if he has VALIDATE permission assigned for Announcements resource. User inherits this permission because it is member of group “/organization/senior_managers” *User belongs to group “/operators/content_creator”. Therefore he inherits a set of permissions (CREATE, EDIT, REMOVE) to add new content on specified page in the application.

Requirements:

Permissions model

Scenario

Application has a structure of resources. Permissions assigned to user for a given resource in the tree are inherited by other resources. User is able to edit all sub resources based on permissions assigned to parent resource.

Example:

  • Application has structure of pages.
  • User assigned to manage specific page should also be able to manage all sub pages.
  • Permissions are inherited.

Scenario

Application persists a structure of groups and users that have roles in those groups. Application developer needs to have some permissions related to one group be inherited by their sub groups.

Example:

  • Group “/organization” has assigned READ permission associated with “Corporate news” page
  • Group “/organization/it_dept” has assigned READ and CREATE permission associated with “IT Security Event Logs” page in the application.
  • All users with role in “/organizaiton/it_dept” will be able to read “Corporate news” page because READ permission will be inherited from “/organization” group.

Scenario

The developer needs to define several types of contexts in which user is connected with a given group to enable flexible authorization of different types of performed operations

Example:

John is an “administrator” of “/communities/base_jumping” group and can perform administrative tasks on resources connected with this group John is a “member” of “/communities/base_jumping” group and he can access and read resources connected with this group John is a “content validator” of “/communities/base_jumping” group and he will be asked to authorize any new content on pages related to this group before it gets published.

In all examples described above single group can have several users with same role.

This specifically can be addressed with the Domain ACL type approach, as prototyped in Seam Security:

One of the biggest problems of Java web app security to date, and what will also be a problem in our framework, is that Java EE, Seam Security have not been able to satisfy a very common type of Authentication, domain authentication, and have focused solely on global role-based security authorisation:

E.g: Global authentication is "Is the user an Admin of the application," as opposed to domain authentication, which asks, "Is the user an Admin of this Domain Object,"

Developers typically have to implement their own security system (via direct method calls, or etc...) for this type of business logic.

REST endpoint or RPC: (Lincoln's prototyped API - functional in Seam Security)

@SecurityBinding
public @interface ProjectAdmin
{
    // empty
}

@SecurityMethodBinding
public @interface ProjectBinding
{
    // empty
}

@ProjectAdmin
public void updateName(@ProjectBinding Project p, String name)
{
   // save project name
}

@Secures
@ProjectAdmin
public boolean isProjectAdmin(@ProjectBinding Project p, Identity identity)
{
   if(identity.hasRole("project" + p.getId() + "_admin")
   {
       ...
   }
}

Note that the @Project annotation is not a CDI bean Qualifier / Stereotype annotation, it is a method parameter security binding annotation that tells Seam Security to use the value of the Project passed to the method call in the security binding check itself.

Scenario

The developer needs to define single user or group that will serve as super users (aka root users. Those will have any available permissions.

Example:

  • identity.isRootUser()
  • identityManager.getRootUsers();

Scenario

Application needs to authorize access based on inherited group membership.

Example:

Access to information about new trips is restricted to members of “/communities/hiking” group Users being members of “/communities/hiking/instructors”, “/communities/hiking/juniors” and /communities/hiking/seniors” will inherit membership in group “/communities/hiking” and gain access to information about new trips. On the other hand, access to information about climbing trips should not be available to juniors. So in this case, we want to have it available only for “/communities/hiking” but not for “/communities/hiking/juniors”. So it might be useful if group inheritance is configurable for individual resources.

Example: You can configure that info about classic trips is available for “/communities/hiking*” which would mean /communities/hiking and all it’s subgroups. On the other hand info about climbing trips is available only for individual groups “/communities/hiking” and “/communities/hiking/seniors” as we don’t want to have group inheritance here. For this climbing usecase, it may be useful to DENY permission available from parent groups.

Example: You can configure that info about climbing trips will be available for “/communities/hiking*” but permission is denied for members for “/communites/hiking/juniors”. In this case, groups “/commuinites/hiking”, “/communities/hiking/instructors”, “/communities/hiking/seniors” will have permission. Members of group “/communities/hiking/juniors” won’t hav permission.

Scenario

The developer may want to have permissions based on other criterias than only roles/groups. Some of these requirements can be handled by XACML integration mentioned below.

  • I want page "hobby" to be accessible for employees only after 6pm, to enforce that my employees won't go to hobby page during their working time.
  • I want forum portlet with "Retiree forum" to be accessible only for users older than 60 years. Only exceptions can be "/platform/administrators" group, whose members can access page everytime regardless of their age.

Scenario

The developer needs to integrate application with more advanced security resolution mechanisms.

Examples:

  • Rules based engine to resolve permissions
  • Integration with external services - XACML architecture with separate Policy Enforcement Point, Policy Decision Point and Policy Store.
  • Simplified model where permissions are hardcoded and resolved based on information about group membership.

Requirements:

Well thought API/SPI that doesn’t limit such integration.

Scenario

The developer needs to expose part of application features to be accessible by external services and authorize their access.

Delegated Administration

Scenario

Web application has a number of user groups or resources that needs to be managed. It is desired that management permission to only part of those are delegated to specific user

Examples:

  • User gets administration privileges for specific group of users
  • User gets administration privileges for specific set of application resources (group of pages
  • User gets administration privileges to all sub groups of specific group - can include all users belonging there
  • User gets administration privileges to sub resources - all sub pages in navigation hierarchy

Requirements:

Advanced enough security and identity model to map required permissions

Identity Management (IDM)

All use cases with strong focus around concepts and operations on User, Group and Role

Scenario

Application needs to expose basic user management capabilities. To register new user, edit profile and remove old users. Basic provisioning and management API for user, group and role.

Examples:

User johnUser = identityManager.createUser(john);
johnUser.setEmail(john@acme.com);
johnUser.enable();
johnUser.addRole(member,/employees);
johnUser.setAttribute(manager,Max Kowalski);

Scenario

Application needs to enable groups management capabilities. Administrators must be able to map organization structure in the application to be able to set proper security restrictions

Examples:

Group parisOffice = identityManager.createGroup(paris,/global/offices/emea/);
parisOffice.addRole(manager,John Doe);
parisOffice.setAttribute(displayName,Paris Office);
parisOffice.setAttribute(address,......);

Scenario

Application needs to enable group based security that maps relationships from real organization structure. Therefore users need to be associated with specific groups in organization hierarchy and have defined roles in context of those groups

Examples:

Group itsec = identityManager.createGroup(itsec,/organization/engineering/security);
itsec.addRole(manager,johnDoe);
Group hr = identityManager.createGroup(hr,/organization);
hr.addRole(supervisor,aliceDoe);
hr.addRole(headhunter,chrisDoe);
aliceDoe.hasRole(headhunter);
List<User> headHunters = identityManager.createUserQuery().setRole(headhunter).sort(true).setRange(Range.of(0,50).execute();

Scenario

Application needs to expose capabilities to associate authenticated user with specific roles in application context.

Examples:

identity.addApplicationRole(SuperUser);
identity.addApplicationRole(Authenticated);

Scenario

The developer needs to query user, groups and roles in a way that will not affect performance. He needs to sync into database 500k user entries from corporate LDAP server and quite big group structure. Methods like identityManager.getAllUsers() will be performance bottlenecs. The developer needs to obtain pagainated and sorted results.

Examples:

identityManager.createGroupQuery().setRelatedUser(john).setParentGroup(/offices).sort(true).setRange(Range.of(0,10)).execute();

Scenario

The developer needs to query user by unique attribute (email) and group membership when “new user registration” form is submitted in the application.

Examples:

identityManager.createUserQuery().setRelatedGroup(/employees).setAttributeFilter(personal.email, values).setRange(Range.of(0.100));

Scenario

The developer needs to persist user, group and role information in database. JPA implementation is his dream.

Scenario

The developer want to give freedom to plug different type of identityStore into his application in the future. Not all identity store expose equal operations for pagination, sorting or querying by attributes. He needs to design his GUI so it can query underlying IdentityStore if specific operations are supported.

Examples:

identityManager.getSupportedFeatures().isUserSortSupported();
identityManager.getSupportedFeatures().isUserQueryPaginationSupported();

Events

Scenario

Application developer needs to add specific hooks for common IDM or Security operations

Examples:

Audit and logging for permission and IDM related changes or information resolution Assigning specific permissions for every user that was added to the given group Synchronization based integration with LDAP. All changes to users and groups are synced back to external store. On specific event LDAP is queried for a changelog and based on that changes from external store are synced to the internal store.

Requirements:

Event API.

Personalization

This is not fully related to security but it is tightly coupled with identity model that is already in place

Scenario

The developer needs to let application users set their own locale. He also needs to set default ones per group of users. For case that user is member of more groups, we need to specify which group will have priority for determining the defaultLocale (or other attribute) for user. Some groups can be ignored. Examples:

Group “/application_users” have attribute “defalutLocale”. All users with role “member” in this group inherit this attribute. Each user can override this value User is member of “/application_users” and “/partners” . Group “/application_users” has default locale “fr” and group “/partners” has default locale “en”. We assume that “/application_users” has bigger priority so defaultLocale of user will be “fr”.

Scenario

The developer needs to let application users set their own skin in their application. He also needs to set default skins per group of users. Examples:

Groups “/vendors”, “/partners” and “/employees” have different value of attribute “defaultSkin”. Their members inherit this attribute value.

LDAP or External Identity Store Integration

Integrating external identity store is a common scenario for application developers. Most common case is corporate LDAP or MSAD hosting users in Windows Domain. However other custom solutions like Web Service or REST based services for IDM are often spotted in organizations.

There are 3 ways such internal store can be integrated. At least “Direct Integration” and “Synchronization” scenarios need to be addressed

Scenario - Direct Integration

In such case application developer replaces default JPA based identity store implementation with custom one.

Few limitations apply in such case. Different identity storage services (even LDAP) have certain limitations in compare to full blown IDM framework API. For example LDAP cannot flexibly store any type of attribute unless LDAP schema is extended - which is often not possible in the organization and restricted by administrators. Other example is no direct or easy mapping of roles - just simple notion if user is member of a group or not. Some of strict LDAP schema implementations doesn’t allow group without any member.

Other limitation is typically less flexible query mechanism. For example in LDAP you cannot easily perform efficient query with multiple conditions that would be sorted and paginated. With flexible Query API and big number of identity entries in the store it is a rising issue. Implementing rich IDM API/SPI can easily create performance bottlenecks

Scenario - Identity Store Routing

In this scenario application developer implements routing to invoke methods on several identity stores and merge results. In simplest case part of user attributes (limited by LDAP schema) and information about user roles are kept in JPA implementation. Users and groups can be created in external store based on routing configuration.

Limitations described in previous scenario still apply in this scenario. Additionally it is easy to introduce serious performance bottlenecks. For example If developer allows situation of having some users stored in database and some in LDAP then queries become non trival. Any kind of more complex query may involve retrieving all results from both sources, merging and applying sort and pagination in the second step. With 500k entries in directory it is impossible to perform such queries efficiently.

Scenario - Synchronization

In this scenario all identities are always kept in default JPA based identity store. All queries are performed on it. External identity store content is synchronized based on scheduled plan or event system. Many modern LDAP stores expose feature called “changelog”. It is possible to obtain small delta of frequent changes to apply.

Still some operations like authentication are performed directly on external store. Reason is that modern authentication systems won’t expose password but just validatePassword type of operation.

Examples:

  • During user authentication LDAP is queried if user profile or group assignment was updated and this information is synced into default identity store.
  • During identity.setAttribute() operation external store is also updated.
  • During any “write” operation external store is updated with applied change.
  • Scheduler is triggering synchronizing operation.
  • There is manual synchronization hook that can be invoked to trigger synchronization when administrator update information in external store.