When we announced Zend Framework 3 last year, one of the changes was setting the minimum supported PHP version to 5.6. Our initial plan was to support 5.6 until it reaches end-of-life, which occurs 31 December 2018.

PHP 5.6, however, stopped receiving active support almost five months ago, on 19 Jan 2017. This means that it is no longer receiving bugfixes, only critical security fixes. As such, a number of contributors have been pushing for us to up our minimum supported version to support only actively supported PHP versions, which would mean only PHP 7 versions.

In addition to active support, there are other benefits to jumping to PHP 7, including:

  • Scalar type hints
  • Return type hints
  • Null coalescing operator
  • Spaceship operator
  • Anonymous classes
  • Potential for enabling strict type checking

Of course, PHP 7.0 ends active support at the end of this year, on 3 December 2017; moving to 7.0 means that we could anticipate further version bumps in a very short time frame.

PHP 7.1 adds more features and benefits over those in 7.0:

  • Void return types
  • Nullable types
  • "iterable" pseudo-type
  • Non-public class constants
  • Multi-catch exception handling
  • Support for keys in list()
  • Built-in asynchronous signal handling

Further, 7.1 has active support until 1 Dec 2018, giving us a reasonable time frame for supporting the version.

Our view is that the new features in PHP 7 will allow us to simplify our code dramatically, reduce bugs (primarily by increasing type safety), make our code more easily maintainable (less code required to check types; less repetitive code), provide stronger and more predictable interfaces to our users, and simultaneously provide users access to more and better language features.

HHVM

In addition to evaluating PHP 5.6 support, we have also been evaluating our support of HipHop Virtual Machine (HHVM), the alternative PHP runtime maintained by Facebook.

We started running tests against HHVM around the time we released ZF 2, and, for quite some time, required tests to pass except in specific components that used extensions without equivalents in the HHVM ecosystem.

Since we started adopting PHP 5.6, and, in select cases, PHP 7, we've increasingly needed to mark HHVM test jobs as "allowing failure", due to usage of PHP language features that do not exist in HHVM, or incompatibilities in the HHVM runtime.

One initial "selling" feature of HHVM was its performance. However, at this time, PHP 7 competes favorably with HHVM, eliminating one large argument in favor of choosing it. PHP 7.1 also includes many features at the language level (e.g., scalar typehints, return type hints, nullable types, etc.) that many were choosing HHVM for.

Finally, we have found that HHVM usage is an incredibly small percentage of our user base. We have noted that other projects have found similarly, and feel now is the appropriate time to stop supporting HHVM.

Acknowledging the Problems

The biggest downside to adopting PHP 7 releases at this time is one of adoption. Many organizations lock projects to specific infrastructure, including PHP versions. Even with supported repositories such as the Remi RPM repository (for RHEL, CentOS, and Fedora) and Ondřej Debian repository (for Ubuntu and other Debian-based distributions), enterprises still want to pin to distribution-provided PHP versions, which are often literally years out-of-date.

Zend itself offers a supported PHP 7.1 stack via Zend Server, which can be a solution for many of these organizations.

Additionally, with the rise in usage of virtual machines and containers, many of these obstacles are gradually disappearing for organizations. When you can package the entire infrastructure stack, testing and deployment become more predictable, eliminating many of the issues traditionally associated with infrastructure changes. We feel this trend will only increase.

The Plan

As such, our plan is this:

  • We will start releasing new major versions of components that pin to PHP 7.1+, so we can take advantage of the latest language features.

  • We will no longer test against HHVM. Most of our components were failing against HHVM already, so this does not pose a BC break at this time.

  • We will continue providing security patches only to the last release branch supporting PHP 5.6 until PHP 5.6 reaches its end-of-life date. This allows us to minimize the amount of maintenance we need for supporting these versions, while still providing stable, secure releases for our PHP 5 users.

  • New components will pin to PHP 7.1+.

We announced most details of this previously on our newsletter, so some of this work has already begun; we welcome all assistance any of our readers and users can provide in this effort!

On a personal note, I still fondly remember the release of PHP 5; the organization I worked at adopted it fairly early, and I was very excited about the features then. PHP 7 has stoked similar enthusiasm for me, and I'm excited to see what we build for Zend Framework using it!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.

Source

With the release of Expressive 2, one of the key stories was the ability to require ZF components within Expressive, and have their dependencies auto-wired into your application courtesy of the component installer.

However, we recently had a user in our Slack channel (need an invite?) indicating they were having issues with usage of custom validators, filters, and input filters. After a more thorough writeup on our forums, I realized we'd missed something important when making these integrations, and set out to solve it.

The problem

In zend-mvc applications, zend-modulemanager aggregates Module classes registered with the application, and, in the process, does things like merge all configuration. One thing it also does is seed plugin managers. The process for this is rather convoluted, as it uses a combination of configuration keys as well as methods defined in Module classes in order to pull together all configuration for a given plugin manager prior to initializing it.

What this means is that, in most cases, components can have a specific configuration key they look under for service definitions specific to a given plugin manager. As an example, for zend-filter, you might do something like:

[
    'filters' => [
        'aliases' => [ /* ... */ ],
        'invokables' => [ /* ... */ ],
        'factories' => [ /* ... */ ],
        'delegators' => [ /* ... */ ],
    ],
]

All plugin manager configurations follow the same format, but use a different top-level key.

The problem we ran into in Expressive is that while we have encouraged users to do this, the plugin managers were never seeded with this configuration, as the logic for that was relegated to zend-modulemanager integrations!

The solution

Over the past few days, I identified seven affected components, and wrote patches for each that fix the problem. What they do is check to see if a zend-modulemanager-specific service is present, and, if not, they then check for and pull the relevant configuration, and use it to configure the plugin manager.

The following releases now have these fixes:

  • zend-log 2.9.2; enables the log_processors, log_writers, log_filters, and log_formatters keys for configuring the ProcessorPluginManager, WriterPluginManager, FilterPluginManager, and FormatterPluginManager, respectively.
  • zend-i18n 2.7.4; enables the translator_plugins key for configuring the Zend\I18n\Translator\LoaderPluginManager.
  • zend-hydrator 2.2.2; enables the hydrators key for configuring the HydratorPluginManager.
  • zend-filter 2.7.2; enables the filters key for configuring the FilterPluginManager.
  • zend-validator 2.9.1; enables the validators key for configuring the ValidatorPluginManager.
  • zend-inputfilter 2.7.4; enables the input_filters key for configuring the InputFilterPluginManager.
  • zend-form 2.10.2; enables the form_elements key for configuring the FormElementManager.

The end result is that each of these components will now work with Expressive out of the box just as they would in a zend-mvc application!

Wrapup

I feel this is a huge step forward in usability of Expressive; in fact, each of these components can now be more easily used in any application, which is a huge win. I'm hoping that with these releases, folks will start evaluating them more seriously for inclusion in other middleware architectures as well.

This problem would likely have not been identified as quickly without the new community process and tools we now have in place. A Slack thread helped identify a problem existed, and a forum post helped us get all the details necessary to reproduce the issue, and then coordinate the patches.

If you have not yet signed up for Slack, you can do so here. If you have not yet visited our forums, head over and start participating!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.

Source

Security of your website is not just about mitigating and preventing things like SQL injection; it's also about protecting your users as they browse the site from things like cross-site scripting (XSS) attacks, cross-site request forgery (CSRF), and more. In particular, you need to be very careful about how you generate HTML, CSS, and JavaScript to ensure that you do not create such vectors.

As the mantra goes, filter input, and escape output.

Believe it or not, escaping in PHP is not terribly easy to get right. For example, to properly escape HTML, you need to use htmlspecialchars(), with the flags ENT_QUOTES | ENT_SUBSTITUTE, and provide a character encoding. Who really wants to write

htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'utf-8')

every single time they need to escape a string for use in HTML?

Escaping HTML attributes, CSS, and JavaScript each require a regular expression to identify known problem strings, and a number of heuristics to replace unicode characters with hex entities, each with different rules. While much of this can be done with built-in PHP features, these features do not catch all potential attack vectors. A comprehensive solution is required.

Zend Framework provides the zend-escaper component to manage this complexity for you, exposing functionality for escaping HTML, HTML attributes, JavaScript, CSS, and URLs to ensure they are safe for the browser.

Installation

zend-escaper only requires PHP (of at least version 5.5 at the time of writing), and is installable via composer:

$ composer require zendframework/zend-escaper

Usage

While we considered making zend-escaper act as either functions or static methods, there was one thing in the way: proper escaping requires knowledge of the intended output character set. As such, Zend\Escaper\Escaper must first be instantiated; once it has, you call methods on it.

use Zend\Escaper\Escaper;

$escaper = new Escaper('iso-8859-1');

By default, if no character set is provided, it assumes utf-8; we recommend using UTF-8 unless there is a compelling reason not to. As such, in most cases, you can instantiate it with no arguments:

use Zend\Escaper\Escaper;

$escaper = new Escaper();

The class provides five methods:

  • escapeHtml(string $html) : string will escape the string so it may be safely used as HTML. In general, this means <, >, and & characters (as well as others) are escaped to prevent injection of unwanted tags and entities.
  • escapeHtmlAttr(string $value) : string escapes a string so it may safely be used within an HTML attribute value.
  • escapeJs(string $js) : string escapes a string so it may safely be used within a <script> tag. In particular, this ensures that the code injected cannot contain continuations and escape sequences that lead to XSS vectors.
  • escapeCss(string $css) : string escapes a string to use as CSS within <style> tags; similar to JS, it prevents continuations and escape sequences that can lead to XSS vectors.
  • escapeUrl(string $urlPart) : string escapes a string to use within a URL; it should not be used to escape the entire URL itself. It should be used to escape things such as the URL path, query string parameters, and fragment, however.

So, as examples:

echo $escaper->escapeHtml('<script>alert("zf")</script>');
// results in "&lt;script&gt;alert(&quot;zf&quot;)&lt;/script&gt;"

echo $escaper->escapeHtmlAttr("<script>alert('zf')</script>");
// results in "&lt;script&gt;alert&#x28;&#x27;zf&#x27;&#x29;&lt;&#x2F;script&gt;"

echo $escaper->escapeJs("bar&quot;; alert(&quot;zf&quot;); var xss=&quot;true");
// results in "bar\x26quot\x3B\x3B\x20alert\x28\x26quot\x3Bzf\x26quot\x3B\x29\x3B\x20var\x20xss\x3D\x26quot\x3Btrue"

echo $escaper->escapeCss("background-image: url('/zf.png?</style><script>alert(\'zf\')</script>');");
// results in "background\2D image\3A \20 url\28 \27 \2F zf\2E png\3F \3C \2F style\3E \3C script\3E alert\28 \5C \27 zf\5C \27 \29 \3C \2F script\3E \27 \29 \3B"

echo $escaper->escapeUrl('/foo " onmouseover="alert(\'zf\')');
// results in "%2Ffoo%20%22%20onmouseover%3D%22alert%28%27zf%27%29"

As you can see from these examples, the component aggresively filters each string to ensure it is escaped correctly for the context for which it is intended.

How and where might you use this?

  • Within templates, to ensure output is properly escaped. For example, zend-view includes helpers for it; it would be easy to add such functionality to Plates and other templating solutions.
  • In email templates.
  • In serializers for APIs, to ensure things like URLs or XML attribute data are properly escaped.
  • In error handlers, to ensure error messages are escaped and do not contain XSS vectors.

The main point is that escaping can be easy with zend-escaper; start securing your output today!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.

Source

The last couple posts have been around authorization, the act of determining if a given identity has access to a resource. We covered usage of role based access controls, as well as middleware that uses an RBAC.

In this post, we'll explore another option provided by Zend Framework, zend-permissions-acl, which implements Access Control Lists (ACL).

This post will follow the same basic format as the one covering zend-permissions-rbac, using the same basic examples.

Installing zend-permissions-acl

Just as you would any of our components, install zend-permissions-acl via Composer:

$ composer require zendframework/zend-permissions-acl

The component has no requirements at this time other than a PHP version of at least 5.5.

Vocabulary

In ACL systems, we have three concepts:

  • a resource is something to which we control access.
  • a role is something that will request access to a resource.
  • Each resource has privileges for which access will be requested to specific roles.

As an example, an author might request to create (privilege) a blog post (resource); later, an editor (role) might request to edit (privilege) a blog post (resource).

The chief difference to RBAC is that RBAC essentially combines the resource and privilege into a single item. By separating them, you can create a set of discrete permissions for your entire application, and then create roles with multiple-inheritance in order to implement fine-grained permissions.

ACLs

An ACL is created by instantiating the Acl class:

use Zend\Permissions\Acl\Acl;

$acl = new Acl();

Once that instance is available, we can start adding roles, resources, and privileges.

For this blog post, our ACL will be used for a content-based website.

Roles

Roles are added via the $acl->addRole() method. This method takes either a string role name, or a Zend\Permissions\Acl\Role\RoleInterface instance.

Let's start with a "guest" role, that only allows "read" permissions.

use Zend\Permissions\Acl\Role\GenericRole as Role;

// Create some roles
$guest = new Role('guest');
$acl->addRole($guest);

// OR
$acl->addRole('guest');

Referencing roles and resources

Roles are simply strings. We model them as objects in zend-permissions-acl in order to provide strong typing, but the only requirement is that they return a string role name. As such, when creating permissions, you can use either a role instance, or the equivalent name.

The same is true for resources, which we cover in a later section.

By default, zend-permissions-acl implements a whitelist approach. A whitelist denies access to everything unless it is explicitly whitelisted. (This is as opposed to a blacklist, where access is allowed to everything unless it is in the blacklist.) Unless you really know what you're doing we do not suggest toggling this; whitelists are widely regarded as a best practice for security.

What that means is that, out of the gate, while we can do some privilege assertions:

$acl->isAllowed('guest', 'blog', 'read');
$acl->isAllowed('guest', 'blog', 'write');

these will always return false, denying access. So, we need to start adding privileges.

Privileges

Privileges are assigned using $acl->allow().

For the guest role, we'll allow the read privilege on any resource:

$acl->allow('guest', null, 'read');

The second argument to allow() is the resource (or resources); specifying null indicates the privilege applies to all resources. If we re-run the above assertions, we get the following:

$acl->isAllowed('guest', 'blog', 'read');  // true
$acl->isAllowed('guest', 'blog', 'write'); // false

Unknown roles or resources

One thing to note: if either the role or resource used with isAllowed() does not exist, this method raises an exception, specifically a Zend\Permissions\Acl\Exception\InvalidArgumentException, indicating the role or resource could not be found.

In many situations, this may not be what you want; you may want to handle non-existent roles and/or resources gracefully. You could do this in a couple ways. First, you can test to see if the role or resource exists before you check the permissions, using hasRole() and/or hasResource():

if (! $acl->hasRole($foo)) {
    // failed, due to missing role
}
if (! $acl->hasResource($bar)) {
    // failed, due to missing resource
}
if (! $acl->isAllowed($foo, $bar, $privilege)) {
    // failed, due to invalid privilege
}

Alternately, wrap the isAllowed() call in a try/catch block:

try {
    if (! $acl->isAllowed($foo, $bar, $privilege)) {
        // failed, due to missing privileges
    }
} catch (AclInvalidArgumentException $e) {
      // failed, due to missing role or resource
}

Personally, I don't like to use exceptions for application flow, so I recommend the first solution. That said, in most cases, you will be working with a role instance that you've just added to the ACL, and should only perform assertions against known resources.

Resources

Now let's add some actual resources. These are almost exactly like roles in terms of usage: you create a ResourceInterface instance to pass to the ACL, or, more simply, a string; resources are added via the $acl->addResource() method.

use Zend\Permissions\Acl\Resource\GenericResource as Resource;

$resource = new Resource('blog');
$acl->addResource($resource);

// OR:
$acl->addResource('blog');

A resource is anything to which you want to apply permissions. In the remaining examples of this post, we'll use a "blog" as the resource, and provide a variety of permissions related to it.

Inheritance

Let's say we want to build on our previous examples, and create an "editor" role that also incorporates the permissions of the "guest" role, and adds a "write" permission to the "blog" resource.

Unlike RBAC, roles themselves contain no information about inheritance; instead, the ACL takes care of that when you add the role to the ACL:

$editor = new Role('editor');
$acl->addRole($editor, $guest); // OR:
$acl->addRole($editor, 'guest');

The above creates a new role, editor, which inherits the permissions of our guest role. Now, let's add a privilege allowing editors to write to our blog:

$acl->allow('editor', 'blog', 'write');

With this in place, let's do some assertions:

$acl->isAllowed('editor', 'blog', 'write'); // true
$acl->isAllowed('editor', 'blog', 'read');  // true
$acl->isAllowed('guest',  'blog', 'write'); // false

Another role might be a "reviewer" who can "moderate" content:

$acl->addRole('reviewer', 'guest');
$acl->allow('reviewer', 'blog', 'moderate');

$acl->isAllowed('reviewer', 'blog', 'moderate'); // true
$acl->isAllowed('reviewer', 'blog', 'write');    // false; editor only!
$acl->isAllowed('reviewer', 'blog', 'read');     // true
$acl->isAllowed('guest',    'blog', 'moderate'); // false

Let's create another, an "admin" who can do all of the above, but also has permissions for "settings":

$acl->addRole('admin', ['guest', 'editor', 'reviewer']);
$acl->allow('admin', 'blog', 'settings');

$acl->isAllowed('admin',    'blog', 'settings'); // true
$acl->isAllowed('admin',    'blog', 'write');    // true
$acl->isAllowed('admin',    'blog', 'moderate'); // true
$acl->isAllowed('admin',    'blog', 'read');     // true
$acl->isAllowed('editor',   'blog', 'settings'); // false
$acl->isAllowed('reviewer', 'blog', 'settings'); // false
$acl->isAllowed('guest',    'blog', 'write');    // false

Note that the addRole() call here provides an array of roles as the second value this time; when called this way, the new role will inherit the privileges of every role listed; this allows for multiple-inheritance at the role level.

Resource inheritance

Resource inheritance works exactly the same as Role inheritance! Add one or more parent resources when calling addResource() on the ACL, and any privileges assigned to that parent resource will also apply to the new resource.

As an example, I could have a "news" section in my website that has the same privilege and role schema as my blog:

$acl->addResource('news', 'blog');

Fun with privileges!

Privileges are assigned using allow(). Interestingly, like addRole() and addResource(), the role and resource arguments presented may be arrays of each; in fact, so can the privileges themselves!

As an example, we could do the following:

$acl->allow(
    ['reviewer', 'editor'],
    ['blog', 'homepage'],
    ['write', 'maintenance']
);

This would assign the "write" and "maintenance" privileges on each of the "blog" and "homepage" resources to the "reviewer" and "editor" roles! Due to inheritance, the "admin" role would also gain these privileges.

Creating your ACL

When should you create your ACL, exactly? And should it contain all roles and permissions?

Typically, you will create a finite number of application or domain permissions. In our above examples, we could omit the blog resource and apply the ACL only within the blog domain (for example, only within a module of a zend-mvc or Expressive application); alternately, it could be an application-wide ACL, with resources segregated by specific domain within the application.

In either case, you will generally:

  • Create a finite set of well-known roles, resources, and privileges as a global or per-domain ACL.
  • Create a custom role for the current user, typically inheriting from the set of well-known roles.
  • Validate the current user against the ACL.

Unlike RBAC, you typically will not add custom permissions for a user. The reason for this is due to the complexity of storing the combination of roles, resources, and privileges in a database. Storing roles is trivial:

user_id fullname roles
mario Mario editor,reviewer

You could then create the role by splitting the roles field and assigning each as parents:

$acl->addRole($user->getId(), explode(',', $user->getRoles());

However, for fine-grained permissions, you would essentially need an additional lookup table mapping the user to a resource and list of privileges:

user_id resource privileges
mario blog update,delete
mario news update

While it can be done, it's resource and code intensive.

Putting it all together, let's say the user "mario" has logged in, with the role "editor"; further, let's assume that the identity instance for our user implements RoleInterface. If our ACL is already populated per the above examples, I might do the following:

$acl->addRole($mario, $mario->getRoles());

$acl->isAllowed($mario, 'blog', 'settings'); // false; admin only!
$acl->isAllowed($mario, 'blog', 'write');    // true; all editors
$acl->isAllowed($mario, 'blog', 'read');     // true; all guests

Now, let's say we've gone to the work of creating the join table necessary for storing user ACL information; we might have something like the following to further populate the ACL:

foreach ($mario->getPrivileges() as $resource => $privileges) {
    $acl->allow($mario, $resource, explode(',', $privileges));
}

We could then do the following assertions:

$acl->isAllowed($mario,   'blog', 'update'); // true
$acl->isAllowed('editor', 'blog', 'update'); // false; mario only!
$acl->isAllowed($mario,   'blog', 'delete'); // true
$acl->isAllowed('editor', 'blog', 'delete'); // false; mario only!

Custom assertions

Fine-grained as the privilege system can be, sometimes it's not enough.

As an example, we may want to implement a rule that the creator of a content item in our website always has rights to edit the item. How would we implement that with the above system?

zend-permissions-acl allows you to do so via dynamic assertions. Such assertions are classes that implement Zend\Permissions\Acl\Assertion\AssertionInterface, which defines a single method:

namespace Zend\Permissions\Assertion;

use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Resource\ResourceInterface;
use Zend\Permissions\Acl\Role\RoleInterface;

interface AssertionInterface
{
    /**
     * @return bool
     */
    public function assert(
        Acl $acl,
        RoleInterface $role = null,
        ResourceInterface $resource = null,
        $privilege = null
    );
}

For the sake of this example, let's assume:

  • We cast our identity to a RoleInterface instance after retrieval.
  • The content item is represented as an object.
  • The object has a method getCreatorUsername() that will return the same username as we might have in our custom identity from the previous example.
  • If the username is the same as the custom identity, allow any privileges.

Because we have PHP 7 at our disposal, we'll create the assertion as an anonymous class:

use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Assertion\AssertionInterface;
use Zend\Permissions\Acl\Resource\ResourceInterface;
use Zend\Permissions\Acl\Role\RoleInterface;

$assertion = new class ($identity, $content) implements AssertionInterface {
    private $content;
    private $identity;

    public function __construct(RoleInterface $identity, $content)
    {
        $this->identity = $identity;
        $this->content = $content;
    }

    /**
     * @return bool
     */
    public function assert(
        Acl $acl,
        RoleInterface $role = null,
        ResourceInterface $resource = null,
        $privilege = null
    ) {
        if (null === $role || $role->getRoleId() !== $this->identity->getRoleId()) {
            return false;
        }

        if (null === $resource || 'blog' !== $resource->getResourceId()) {
            return false;
        }

        return $this->identity->getRoleId() === $this->content->getCreatorUsername();
    }
};

// Attach the assertion to all roles on the blog resource;
// custom assertions are provided as a fourth argument to allow().
$acl->allow(null, 'blog', null, $assertion);

$acl->isAllowed('mario', 'blog', 'edit'); // returns true if $mario created $content

The above creates a new assertion that will trigger for the "blog" resource when a privilege we do not already know about is queried. In that particular case, if the creator of our content is the same as the current user, it will return true, allowing access!

By creating such assertions in-place with data retrieved at runtime, you can achieve an incredible amount of flexibility for your ACLs.

Wrapping up

zend-permissions-acl provides a huge amount of power, and the ability to provide both role and resource inheritance can vastly simplify setup of complex ACLs. Additionally, the privilege system provides much-needed granularity.

If you wanted to use ACLs in middleware, the usage is quite similar to zend-permissions-rbac: inject your ACL instance in your middleware, retrieve your user identity (and thus role) from the request, and perform queries against the ACL using the current middleware or route as a resource, and either the HTTP method or the domain action you will perform as the privilege.

The main difficulty with zend-permissions-acl is that there is no 1:1 relationship between a role and a privilege, which makes storing ACL information in a database more complex. If you find yourself struggling with that fact, you may want to use RBAC instead.

Hopefully these last few posts provide you with the information you need to start adding authentication and authorization to any PHP application you're writing!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.

Source

In a previous post, we demonstrated how to authenticate a middleware application in PHP. In this post we will continue the discussion, showing how to manage authorizations.

We will start from an authenticated user and demonstrate how to allow or disable actions for specific users. We will collect users by groups and we will use a Role-Based Access Control (RBAC) system to manage the authorizations.

To implement RBAC, we will consume zendframework/zend-permissions-rbac.

If you are not familiar with RBAC and the usage of zend-permissions-rbac, you can read our previous blog post on the subject.

Getting started

This article assumes you have already created the Auth module, as described in our previous post on authentication. For the purposes of our application, we'll create a new module, Permission, in which we'll put our classes, middleware, and general configuration.

First, if you have not already, install the tooling support:

$ composer require --dev zendframework/zend-expressive-tooling

Next, we'll create the Permission module:

$ ./vendor/bin/expressive module:create Permission

With that out of the way, we can get started.

Authentication

As already mentioned, we will reuse the Auth module created in our previous post. We will reuse the Auth\Action\AuthAction::class to get the authenticated user's data.

Authorization

In order to manage authorization, we will use a RBAC system using the user's role. A user's role is a string that represents the permission level; as an example, the role administrator might provide access to all permissions.

In our scenario, we want to allow or disable access of specific routes to a role or set of roles. Each route represents a permission in RBAC terminology.

We can use zendframework/zend-permissions-rbac to manage the RBAC system using a PHP configuration file storing the list of roles and permissions. Using zend-permissions-rbac, we can also manage permissions inheritance.

For instance, imagine implementing a blog application; we might define the following roles:

  • administrator
  • editor
  • contributor

A contributor can create, edit, and delete only the posts created by theirself. The editor can create, edit, and delete all posts and publish posts (that means enabling public view of a post in the web site). The administrator can perform all actions, including changing the blog's configuration.

This is a perfect use case for using permission inheritance. In fact, the administrator role would inherit the permissions of the editor, and the editor role inherits the permissions of the contributor.

To manage the previous scenario, we can use the following configuration file:

// In src/Permission/config/rbac.php:

return [
    'roles' => [
        'administrator' => [],
        'editor'        => ['admin'],
        'contributor'   => ['editor'],
    ],
    'permissions' => [
        'contributor' => [
            'admin.dashboard',
            'admin.posts',
        ],
        'editor' => [
            'admin.publish',
        ],
        'administrator' => [
            'admin.settings',
        ],
    ],
];

In this file we have specified 3 roles, including the inheritance relationship using an array of role names. The parent of administator is an empty array, meaning no parents.

The permissions are configured using the permissions key. Each role has the list of permissions, specified with an array of route names.

All the roles can access the route admin.dashboard and admin.posts. The editor role can also access admin.publish. The administrator can access all the roles of contributor and editor. Moreover, only the administrator can access the admin.settings route.

We used the route names as RBAC permissions because in this way we can allow URL and HTTP methods using a single resource name. Moreover, in Expressive we have a config/routes.php file containing all the routes and we can easily use it to add authorization, as we did for authentication.

Authorization middleware

Now that we have the RBAC configuration in place, we can create a middleware that performs the user authorization verifications.

We can create an AuthorizationAction middleware in our Permission module as follows:

// in src/Permission/src/Action/AuthorizationAction.php:

namespace Permission\Action;

use Auth\Action\AuthAction;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as MiddlewareInterface;
use Permission\Entity\Post as PostEntity;
use Permission\Service\PostService;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Expressive\Router\RouteResult;
use Zend\Permissions\Rbac\AssertionInterface;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\RoleInterface;

class AuthorizationAction implements MiddlewareInterface
{
    private $rbac;
    private $postService;

    public function __construct(Rbac $rbac, PostService $postService)
    {
        $this->rbac        = $rbac;
        $this->postService = $postService;
    }

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $user = $request->getAttribute(AuthAction::class, false);
        if (false === $user) {
            return new EmptyResponse(401);
        }

        // if a post attribute is present and user is contributor
        $postUrl = $request->getAttribute('post', false);
        if (false !== $postUrl && $user['role'] === 'contributor') {
            $post = $this->postService->getPost($postUrl);
            $assert = new class ($user['username'], $post) implements AssertionInterface {
                private $post;
                private $username;

                public function __construct(string $username, PostEntity $post)
                {
                    $this->username = $username;
                    $this->post     = $post;
                }

                public function assert(Rbac $rbac)
                {
                    return $this->username === $this->post->getAuthor();
                }
            };
        }

        $route     = $request->getAttribute(RouteResult::class);
        $routeName = $route->getMatchedRoute()->getName();
        if (! $this->rbac->isGranted($user['role'], $routeName, $assert ?? null)) {
            return new EmptyResponse(403);
        }

        return $delegate->process($request);
    }
}

If the user is not present, the AuthAction::class attribute will be false. In this case we are returning a 401 error, indicating we have an unauthenticated user, and halting execution.

If a user is returned from AuthAction::class attribute, this means that we have an authenticated user.

The authentication is performed by the Auth\Action\AuthAction class that stores the AuthAction::class attribute in the request. See the previous post for more information.

This middleware performs the authorization check using isGranted($role, $permission) where $role is the user's role ($user['role']) and $permission is the route name, retrieved by the RouteResult::class attribute. If the role is granted, we continue the execution flow with the delegate middleware. Otherwise, we stop the execution with a 403 error, indicating lack of authorization.

We manage also the case when the user is a contributor and there is a post attribute in the request (e.g. /admin/posts/{post}). That means someone is performing some action on a specific post. To perform this action, we require that the owner of the post should be the same as the authenticated user.

This will prevent a contributor to change the content of a post if he/she is not the author. We managed this special case using a dynamic assertion, built using an anonymous class; it checks if the authenticated username is the same of the author's post. We used a general PostEntity class with a getAuthor() function.

In order to retrieve for the route name, we used the RouteResult::class attribute provided by Expressive. This attribute facilitates access to the matched route.

The AuthorizationAction middleware requires the Rbac and the PostService dependencies. The first is an instance of Zend\Permissions\Rbac\Rbac and the second is a general service to manage blog posts, i.e. a class that performs some lookup to retrieve the post data from a database.

To inject these dependencies, we use an AuthorizationFactory like the following:

namespace Permission\Action;

use Interop\Container\ContainerInterface;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\Role;
use Permission\Service\PostService;
use Exception;

class AuthorizationFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $config = $container->get('config');
        if (! isset($config['rbac']['roles'])) {
            throw new Exception('Rbac roles are not configured');
        }
        if (!isset($config['rbac']['permissions'])) {
            throw new Exception('Rbac permissions are not configured');
        }

        $rbac = new Rbac();
        $rbac->setCreateMissingRoles(true);

        // roles and parents
        foreach ($config['rbac']['roles'] as $role => $parents) {
            $rbac->addRole($role, $parents);
        }

        // permissions
        foreach ($config['rbac']['permissions'] as $role => $permissions) {
            foreach ($permissions as $perm) {
                $rbac->getRole($role)->addPermission($perm);
            }
        }
        $post = $container->get(PostService::class);

        return new AuthorizationAction($rbac, $post);
    }
}

This factory class builds the Rbac object using the configuration file stored in src/Permission/config/rbac.php. We read all the roles and the permissions following the order in the array. It is important to enable the creation of missing roles in the Rbac object using the function setCreateMissingRoles(true). This is required to be sure to create all the roles even if we add it out of order. For instance, without this setting, the following configuration will throw an exception:

return [
    'roles' => [
        'contributor'   => ['editor'],
        'editor'        => ['administrator'],
        'administrator' => []
    ]
]

because the editor and the administrator roles are specified as parents of other roles before they were created.

Finally, we can configure the Permission module adding the following dependencies:

// In src/Permission/src/ConfigProvider.php:

// Update the following methods:
public function __invoke()
{
    return [
        'dependencies' => $this->getDependencies(),
        'rbac'         => include __DIR__ . '/../config/rbac.php',
    ];
}

public function getDependencies()
{
    return [
        'factories' => [
            Service\PostService::class => Service\PostFactory::class,
            Action\AuthorizationAction::class => Action\AuthorizationFactory::class,
        ],
    ];
}

Configure the route for authorization

To enable authorization on a specific route, we need to add the Permission\Action\AuthorizationAction middleware in the route, as follows:

$app->get('/admin/dashboard', [
    Auth\Action\AuthAction::class,
    Permission\Action\AuthorizationAction::class,
    Admin\Action\DashboardAction::class
], 'admin.dashboard');

This is an example of the GET /admin/dashboard route with admin.dashboard as the name. We add AuthAction and AuthorizationAction before execution of the DashboardAction. The order of the middleware array is important; authentication must happen first, and authorization must happen before executing the dashboard middleware.

Add the AuthorizationAction middleware to all routes requiring authorization.

Conclusion

This article, together with the one related to the authentication middleware, demonstrates how to accomodate authentication and authorization within middleware in PHP.

We showed how to create two separate Expressive modules, Auth and Permission, to provide authentication and authorization using zend-authentication and zend-permissions-rbac.

We showed also the usage of a dynamic assertion for specific permissions based on the role and username of an authenticated user.

The blog use case proposed in this article is quite simple, but the architecture used can be applied also in complex scenario, to manage permissions based on different requirements.

In the future we will talk again about authentication and authorization, since this is a very important aspect of web applications.

Save the date!

Want to learn more about Expressive and Zend Framework? What better location than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas, Nevada, USA. Visit the ZendCon website for more information.

Source

ZF2016-04: Potential remote code execution in zend-mail via Sendmail adapter

When using the zend-mail component to send email via the Zend\Mail\Transport\Sendmail transport, a malicious user may be able to inject arbitrary parameters to the system sendmail program. The attack is performed by providing additional quote characters within an address; when unsanitized, they can be interpreted as additional command line arguments, leading to the vulnerability.

The following example demonstrates injecting additional parameters to the sendmail binary via the From address:

use Zend\Mail;

$mail = new Mail\Message();
$mail->setBody('This is the text of the email.');

// inject additional parameters to sendmail command line
$mail->setFrom('"AAA\" params injection"@domain', 'Sender\'s name');

$mail->addTo('hacker@localhost', 'Name of recipient');
$mail->setSubject('TestSubject');

$transport = new Mail\Transport\Sendmail();
$transport->send($mail);

The attack works because zend-mail filters the email addresses using the RFC 3696 specification, where the string "AAA\" params injection"@domain is considered a valid address. This validation is provided using the zend-validator component with the following parameters:

Zend\Validator\EmailAddress(
    Zend\Validator\Hostname::ALLOW_DNS | Zend\Validator\Hostname::ALLOW_LOCAL
)

The above accepts local domain with any string specified by double quotes as the local part. While this is valid per RFC 3696, due to the fact that sender email addresses are provided to the sendmail binary via the command line, they create the vulnerability described above.

Action Taken

To fix the issue, we added a transport-specific email filter for the From header in the Sendmail transport adapter. The filter checks for the sequence \" in the local part of the email From address.

$from = $headers->get('From');
if ($from) {
    foreach ($from->getAddressList() as $address) {
        if (preg_match('/\\\"/', $address->getEmail())) {
            throw new Exception\RuntimeException("Potential code injection in From header");
        }
    }
}

The patch resolving the vulnerability is available in:

  • zend-mail, starting in version 2.7.2
  • zend-mail, 2.4.11
  • Zend Framework, 2.4.11

Zend Framework 2.5 and 3.0 versions will receive the update automatically, as executing composer update in proejcts using these versions will update to zend-mail 2.7.2+.

Acknowledgments

The Zend Framework team thanks the following for identifying the issues and working with us to help protect its users:

  • The independent security researcher Dawid Golunski, who reported the vulnerability to Beyond Security’s SecuriTeam Secure Disclosure program;
  • Enrico Zimuel, who provided the patch.

Source

The Zend Framework community is pleased to announce the immediate availability of Zend Framework 1.12.20! Packages and installation instructions are available at:

Changelog

This release includes a single security patch, reported as ZF2016-03, for SQL injection vulnerabilities in the Zend_Db_Select::order() and Zend_Db_Select::group() methods. If you use these, we recommend updating immedaitely.

To see the complete set of issues resolved for 1.12.20, please visit the changelog:

End of Life

As announced previously, Zend Framework 1 will reach its end of life on 28 September 2016, and only receive security fixes between now and that date. Past that point, we will offer custom bug and security fixes for Zend Framework 1 on-demand only to Enterprise users of Zend Server.

Thank You!

Many thanks to Enrico Zimuel for his efforts in developing the security patch for this release!

Source

ZF2016-03: Potential SQL injection in ORDER and GROUP functions of ZF1

The implementation of ORDER BY and GROUP BY in Zend_Db_Select remained prone to SQL injection when a combination of SQL expressions and comments were used. This security patch provides a comprehensive solution that identifies and removes comments prior to checking validity of the statement to ensure no SQLi vectors occur.

The implementation of ORDER BY and GROUP BY in Zend_Db_Select of ZF1 is vulnerable by the following SQL injection:

$db = Zend_Db::factory(/* options here */);
$select = new Zend_Db_Select($db);
$select->from('p');
$select->order("MD5(\"a(\");DELETE FROM p2; #)"); // same with group()

The above $select will render the following SQL statement:

SELECT `p`.* FROM `p` ORDER BY MD5("a(");DELETE FROM p2; #) ASC

instead of the correct one:

SELECT "p".* FROM "p" ORDER BY "MD5(""a("");DELETE FROM p2; #)" ASC

This security fix can be considered an improvement of the previous ZF2016-02 and ZF2014-04 advisories.

As a final consideration, we recommend developers either never use user input for these operations, or filter user input thoroughly prior to invoking Zend_Db. You can use the Zend_Db_Select::quoteInto() method to filter the input data, as shown in this example:

$db    = Zend_Db::factory(...);
$input = "MD5(\"a(\");DELETE FROM p2; #)"; // user input can be an attack
$order = $db->quoteInto("SQL statement for ORDER", $input);

$select = new Zend_Db_Select($db);
$select->from('p');
$select->order($order); // same with group()

Action Taken

We fixed the reported SQL injection by removing comments from the SQL statement before passing it to either the order() or group() methods; this patch effectively solves any comment-based SQLi vectors.

We used the following regex to remove comments from a SQL statement:

const REGEX_SQL_COMMENTS = '@
    (([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
    |(                   # $3 : Match comments
        (?:\#|--).*?$    # - Single line comments
        |                # - Multi line (nested) comments
         /\*             #   . comment open marker
            (?: [^/*]    #   . non comment-marker characters
                |/(?!\*) #   . ! not a comment open
                |\*(?!/) #   . ! not a comment close
                |(?R)    #   . recursive case
            )*           #   . repeat eventually
        \*\/             #   . comment close marker
    )\s*                 # Trim after comments
    |(?<=;)\s+           # Trim after semi-colon
    @msx';

The patch is available starting in Zend Framework 1.12.20.

Other Information

This SQL injection attack does not affect Zend Framework 2 and 3 versions because the implementations of Zend\Db\Sql\Select::order() and Zend\Db\Sql\Select::group() do not manage parenthetical expressions.

Acknowledgments

The Zend Framework team thanks the following for identifying the issues and working with us to help protect its users:

  • Hiroshi Tokumaru (HASH Consulting Corp.), who discovered the issue;
  • Masanobu Katagi (Japan Computer Emergency Response Team Coordination Center), who reported the issue;
  • Enrico Zimuel, who provided the patch.

Source

Recently, we released zend-crypt 3.1.0, the cryptographic component from Zend Framework. This last version includes a hybrid cryptosystem, a feature that can be used to implement end-to-end encryption schema in PHP.

A hybrid cryptosystem is a cryptographic mechanism that uses symmetric encyption (e.g. AES) to encrypt a message, and public-key cryptography (e.g. RSA) to protect the encryption key. This methodology guarantee two advantages: the speed of a symmetric algorithm and the security of public-key cryptography.

Before we talk about the PHP implementation, let's explore the hybrid mechanism in more detail. Below is a diagram demonstrating a hybrid encryption schema:

Encryption schema

A user (the sender) wants to send a protected message to another user (the receiver). He/she generates a random session key (one-time pad) and uses this key with a symmetric algorithm to encrypt the message (in the figure, Block cipher represents an authenticated encryption algorithm). At the same time, the sender encrypts the session key using the public key of the receiver. This operation is done using a public-key algorithm, e.g., RSA. Once the encryption is done, the sender can send the encrypted session key along with the encrypted message to the receiver. The receiver can decrypt the session key using his/her private key, and consequently decrypt the message.

This idea of combining together symmetric and asymmetric (public-key) encryption can be used to implement end-to-end encryption (E2EE). An E2EE is a communication system that encrypts messages exchanged by two users with the property that only the two users can decrypt the message. End-to-end encryption has become quite popular in the last years with the usage in popular software, and particularly messaging systems, such as WhatsApp. More generally, when you have a software used by many users, end-to-end encryption can be used to protect information exchanged by users. Only the users can access (decrypt) exchanged information; even the administrator of the system is not able to access this data.

Build end-to-end encryption in PHP

We want to implement end-to-end encryption for a web application with user authentication. We will use zend-crypt 3.1.0 to implement our cryptographic schemas. This component of Zend Framework uses the OpenSSL extension for PHP for its cryptographic primitives.

The first step is to create public and private keys for each users. Typically, this step can be done when the user credentials are created. To generare the pairs of keys, we can use Zend\Crypt\PublicKey\RsaOptions. Below is an example demonstrating how to generate public and private keys to store in the filesystem:

use Zend\Crypt\PublicKey\RsaOptions;
use Zend\Crypt\BlockCipher;

$username = 'alice';
$password = 'test'; // user's password

// Generate public and private key
$rsaOptions = new RsaOptions();
$rsaOptions->generateKeys([
    'private_key_bits' => 2048
]);
$publicKey  = $rsaOptions->getPublicKey()->toString();
$privateKey = $rsaOptions->getPrivateKey()->toString();

// store the public key in a .pub file
file_put_contents($username . '.pub', $publicKey);

// encrypt and store the private key in a file
$blockCipher = BlockCipher::factory('openssl', array('algo' => 'aes'));
$blockCipher->setKey($password);
file_put_contents($username, $blockCipher->encrypt($privateKey));

In the above example, we generated a private key of 2048 bits. If you are wondering why not 4096 bits, this is questionable and depends on the real use case. For the majority of applications, 2048 is still a good key size, at least until 2030. If you want more security and you don't care about the additional CPU time, you can increase the key size to 4096. We suggest reading the following blog posts for more information on key key size:

We did not generate the private key using a passphrase; this is because the OpenSSL extension of PHP does not support AEAD (Authenticated Encrypt with Associated Data) mode yet; AEAD mode will be supported starting in PHP 7.1, which should release this autumn.

The default passphrase encryption algorithm for OpenSSL is des-ede3-cbc using PBKDF2 with 2048 iterations for generating the encryption key from the user's password. Even if this encryption algorithm is quite good, the number of iterations of PBKDF2 is not optimal; zend-crypt improves on this in a variety of ways, out-of-the-box. As demonstrated above, we use Zend\Crypt\BlockCipher to encrypt the private key; this class provides encrypt-then-authenticate using the AES-256 algorithm for encryption and HMAC-SHA-256 for authentication. Moreover, BlockCipher uses the PBKDF2 algorithm to derivate the encryption key from the user's key (password). The default number of iterations for PBKDF2 is 5000, and you can increase it using the BlockCipher::setKeyIteration() method.

In the example, we stored the public and private keys in two files named, respectively, $username.pub and $username. Because the private file is encrypted, using the user's password, it can be access only by the user. This is a very important aspect for the security of the entire system (we take for granted that the web application stores the hashes of the user's passwords using a secure algorithm such as bcrypt).

Once we have the public and private keys for the users, we can start using the hybrid cryptosystem provided by zend-crypt. For instance, imagine Alice wants to send an encrypted message to Bob:

use Zend\Crypt\Hybrid;
use Zend\Crypt\BlockCipher;

$sender   = 'alice';
$receiver = 'bob';
$password = 'test'; // bob's password

$msg = sprintf('A secret message from %s!', $sender);

// encrypt the message using the public key of the receiver
$publicKey  = file_get_contents($receiver . '.pub');
$hybrid     = new Hybrid();
$ciphertext = $hybrid->encrypt($msg, $publicKey);

// send the ciphertext to the receiver

// decrypt the private key of bob
$blockCipher = BlockCipher::factory('openssl', ['algo' => 'aes']);
$blockCipher->setKey($password);
$privateKey = $blockCipher->decrypt(file_get_contents($receiver));

$plaintext = $hybrid->decrypt($ciphertext, $privateKey);

printf("%s\n", $msg === $plaintext ? "The message is: $msg" : 'Error!');

The above example demonstrates encrypting information between two users. Of course, in this case, the sender (Alice) knows the message because she wrote it. More in general, if we need to store a secret between multiple users, we need to specify the public keys to be used for encryption.

The hybrid component of zend-crypt supports encrypting messages for multiple recipients. To do so, pass an array of public keys in the $publicKey parameter of Zend\Crypt\Hybrid::encrypt($data, $publicKey).

Below demonstrates encrypting a file for two users, Alice and Bob.

use Zend\Crypt\Hybrid;
use Zend\Crypt\BlockCipher;

$data    = file_get_contents('path/to/file/to/protect');
$pubKeys = [
  'alice' => file_get_contents('alice.pub'),
  'bob'   => file_get_contents('bob.pub')
];

$hybrid     = new Hybrid();

// Encrypt using the public keys of both alice and bob
$ciphertext = $hybrid->encrypt($data, $pubKeys);

file_put_contents('file.enc', $ciphertext);

$blockCipher = BlockCipher::factory('openssl', ['algo' => 'aes']);

$passwords = [
  'alice' => 'password of Alice',
  'bob'   => 'password of Bob'
];

// decrypt using the private keys of alice and bob, one at time
foreach ($passwords as $id => $pass) {
  $blockCipher->setKey($pass);
  $privateKey = $blockCipher->decrypt(file_get_contents($id));
  $plaintext  = $hybrid->decrypt($ciphertext, $privateKey, null, $id);
  printf("%s for %s\n", $data === $plaintext ? 'Decryption ok' : 'Error', $id);
}

For decryption, we used a hard coded password for the users. Usually, the user's password is provided during the login process of a web application and should not be stored as permanent data; for instance, the user's password can be saved in a PHP session variable for temporary usage. If you use sessions to save the user's password, ensure that data is protected; the PHP-Secure-Session library or the Suhosin PHP extension will help you do so.

To decrypt the file we used the Zend\Crypt\Hybrid::decrypt() function, where we specified the $privateKey, a null passphrase, and finally the $id of the privateKey. This parameters are necessary to find the correct key to use in the header of the encrypted message.

Source

We are pleased to announce the immediate availability of Apigility 1.4.0!

This is our first minor release in over a year, and our largest, feature-wise, to date!

Zend Framework 3 Support

Six weeks ago, we announce Zend Framework 3 availablility. Our efforts since then have been focused on making all Apigility modules forwards compatible with version 3 releases of Zend Framework components. This touched on every Apigility component, and required the addition of a couple new components as well to help with migration.

This update also means that Apigility has adopted the same minimum supported PHP version as Zend Framework itself: 5.6. If you are using an earlier version of PHP, we recommend updating as soon as possible, as earlier versions are no longer supported by the PHP project.

The main takeaway to know is: you can upgrade your existing Apigility applications now, and they will continue to work, albeit with a number of bugfixes and new features!

Upgrade script

Additionally, once you've verified your application is working, we have provided a script to update your application to take advantage of Zend Framework v3 components and reduce the overall dependency footprint of your application!

$ ./vendor/bin/apigility-upgrade-to-1.5

(The 1.5 here refers to the internal version of the zf-apigility-admin module, in which this script is defined.)

Once you've run that script, you will be pinned to version 3 Zend Framework component releases, and no longer have a dependency on the full ZF metapackage.

There are other things you can do as well to modernize your application, and we have created a comprehensive migration document for 1.4 detailing the changes.

New Apigility skeleton

We decided to mondernize the Apigility skeleton in the same way that we updated the Zend Framework skeleton application. In particular:

  • Adopting PSR-4 directory structure for the shipped Application module.
  • Providing unit tests for the shipped Application module.
  • Removal of i18n features.
  • Enabling PSR-4 Apigility module structure by default.
  • Enabling usage of short array syntax in Apigility-generated configuration files by default.
  • Enabling usage of ::class notation in Apigility-generated configuration files by default.
  • Usage of zfcampus/zf-asset-manager for asset management by default.
  • Addition of zfcampus/zf-composer-autoloading as a development requirement, to facilitate enabling Composer-based autoloading of your Apigility (or Zend Framework) modules.
  • Addition of zendframework/zend-component-installer, to automate registration of ZF components and modules with Apigility applications.
  • Addition of several Composer scripts for working with development mode, serving your application via the PHP built-in web server, and running QA tools.
  • New vagrant and docker-compose configuration based on Ubuntu 16.04 and PHP 7.

The new skeleton updates Apigility applications to use modern approaches to PHP application structure, and provides better tooling around usage of virtual machines and containers in the development workflow.

Improvements

This release wraps new releases of every Apigility module. Notable features of these modules include:

  • zf-apigility
    • Support in ZF\Apigility\Application for handling PHP 7 Throwables.
  • zf-apigility-admin
    • Extracts all factories defined in the Module class to their own classes.
    • Extracts all listeners defined in the Module class to their own classes.
    • Adds a patchList() stub to the REST resource class template, so that it is present by default.
    • Adds support for working with modules using PSR-4 directory format, and the ability to generate PSR-4-style modules.
    • Adds a vendor script, apigility-upgrade-to-1.5, for upgrading an existing Apigility application so that it may use Zend Framework component v3 releases.
    • Adds the ability to generate all configuration files using short array syntax and ::class notation.
    • Adds a new API endpoint for reporting the current Apigility skeleton version.
  • zf-apigility-admin-ui
    • Displays the current Apigility skeleton version as returned by the zf-apigility-admin API.
    • Uses full controller service names when interacting with the zf-apigility-admin API; this resolves some lingering UI issues due to version mismatch.
    • Adds a "field type" input to new field entries, allowing you to provide this information via the UI (previously the information could only be provided by manually updating configuration files). This allows communicating field type information to documentation systems such as Swagger.
    • Numerous UI fixes, particularly with regards to sidebar behavior.
  • zf-apigility-documentation
    • Adds support for displaying documentation of APIs in nested PHP namespaces.
    • Adds support for transforming Markdown documentation to HTML, and enables it by default.
    • Displays field types, if provided, by default.
  • zf-apigility-provider
    • Deprecates the Module class. You no longer need to list the ZF\Apigility\Provider module in your application module configuration.
  • zf-configuration
    • Adds a new configuration switch, zf-configuration.class_name_scalars, allowing you to configure whether or not generated configuration will use ::class notation.
  • zf-console
    • Adds the ability to substitute your own dispatcher via the ZF\Console\DispatcherInterface
    • Adds the ability to disable output of the application banner.
    • Adds the ability to compose a container-interop container with the dispatcher, which allows providing service names as console handlers.
    • The exception handler now catches PHP 7 Throwable instances as well.
  • zf-content-validation
    • Adds support for mapping input filters to GET requests. This feature is not yet supported in the admin UI, however.
  • zf-hal
    • Adds an interface, concrete classes, and configuration for allowing alternate "self" and generic link generation strategies. As such, usage of the server url and url helpers with the Hal plugin is now deprecated.
    • Adds service factories for the two link extraction services, allowing the ability to provide alternate facilities if needed.
    • Adds a new method to the Hal plugin, resetEntityHashStack(); this can be used when rendering multiple responses or payloads within the same request cycle to allow re-use of the same entity instances.
  • zf-http-cache
    • Adds ETag support, with configurable hashing.
    • Adds more capabilities aroudn matching routed controllers.
  • zf-oauth2
    • Adds support for the ext/mongodb extension.
    • Adds token revocation suport.

New modules

Two new modules were added to Apigility:

  • zfcampus/zf-asset-manager uses configuration from rwoverdijk/assetmanager to expose asset directories in the document root of your application. It acts as a Composer plugin, and copies configured asset directories under your public/ directory, adding an entry to that directory's .gitignore file to prevent checking those files into version control. Updates to modules are honored, and removal of a module will remove the files from your source tree.
  • zfcampus/zf-composer-autoloading will add an autoloading entry to your Composer configuration for the module you specify, and then update autoloading rules locally. This package can be used with any Zend Framework application!

Doctrine support

At this time, Doctrine support for Apigility has not yet been updated. Contributors and collaborators are working with the Doctrine team to ensure the various Zend Framework modules they maintain are updated to work with Zend Framework component v3 releases, while working in parallel on zf-apigility-doctrine and zf-doctrine-querybuilder. We hope to announce support for these in the next few weeks.

Upgrading to the latest versions of Apigility modules, however, should allow you to continue using Doctrine features; you will simply be constrained to Zend Framework component v2 releases.

Thank You!

We had a number of contributors to this release, but wish to call out two individuals in particular:

  • Adam Grabek provided the initial pull requests implementing Zend Framework v3 support for around a half-dozen or more modules, and maintained a checklist monitoring progress.
  • Michal (webimpress) Bundyra provided a number of compatibility patches, bugfixes, features, and, most notably, innumerable hours of testing and collaboration towards finalizing the skeleton changes.

To everyone who has contributed patches, features, feedback, and documentation: thank you!

Source