stave.dev

PHP Attributes

Declarative gates and input handling using PHP 8 attributes — run by the framework before your endpoint executes.

Overview

Zero uses PHP 8 attributes for the checks that would otherwise open every method: who is calling, what they may do, which HTTP method they used, which parameters they sent. You declare what the endpoint requires:

// Instead of this:
public function deleteUser($id) {
    if (!isset($_SESSION['user_id'])) { redirect('/login'); }
    if (!userCan('allow.user.delete')) { http_response_code(403); exit; }
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
    // ...finally, the actual logic
}

// Do this:
#[RequirePermission('allow.user.delete')]   // implies login
#[AllowedMethods('POST')]
public function deleteUser($id) {
    // All checks already passed — just write your logic
}

Each attribute is a class in core/attribute/ (namespace Zero\Core\Attribute) with a handler() method. Application::checkAttributes($class, $endpoint) in core/Application.php instantiates each one that applies and calls its handler(). A handler refuses the request by throwing HTTPError or by redirecting and exiting; its return value is not read.

Available Attributes

Listed in the order they are meant to be declared (see Order).

Attribute Constructor Purpose On refusal
RestrictIP string|array $allowed Allow only the listed client IPs / CIDR ranges 403
AllowWithToken none Establish a session from a Bearer API token 401 for a bad token; passes when there is no header
RequireLogin ?string $redirect = null Require a signed-in, verified user Redirect to login; 401 for a JSON caller
RequireAuthLevel $level = 9 Require a minimum auth.level. Shelved — use RequirePermission 401
RequirePermission string|array $permissions Require named capabilities (allow.*); implies login Redirect to the access-request page; 403 for a JSON caller
AuditLog string $eventType, bool $includeParams = false Record the request as an event entity Never refuses
AllowedMethods array|string $methods Restrict the HTTP method 405
RequiredParams array|string $params Require GET/POST parameters to be present 400
Sanitize array $params Clean GET/POST parameters in place Never refuses
Validate array $rules Check parameter format and values (partial — see below) 400
One attribute here is not Zero's

This site's core/attribute/ also contains #[PageMeta], which composes the <title> and meta tags of every page you are reading. It is stave.dev's own and is not part of rmvanda/zero.core — clone the framework and you will not find it.

use Zero\Core\Attribute\{
    RestrictIP,
    AllowWithToken,
    RequireLogin,
    RequirePermission,
    AuditLog,
    AllowedMethods,
    RequiredParams,
    Sanitize,
    Validate
};

How They Run

Class attributes
→
Method attributes
→
handler() on each, in that order
→
Endpoint
  1. Application::resolveAttributes() collects the class-level and method-level attributes for this (class, endpoint) pair and decides which apply.
  2. Anything outside the Zero\Core\Attribute\ namespace is dropped (Application::gates()).
  3. Each remaining attribute is instantiated and its handler() called: class-level first, then method-level, each in declaration order. Nothing is sorted at runtime.
  4. A handler that refuses throws HTTPError, which Application::run() catches and passes to the module's renderError() — see Error Handling. RequireLogin and RequirePermission redirect and exit instead when the caller is a browser.
  5. If none refuses, the endpoint runs.

Only Zero\Core\Attribute is run

The namespace is the only test. An attribute anywhere else — a PHP built-in such as #[\AllowDynamicProperties], or one of your own in another namespace — is ignored by the dispatcher and its handler() is never called.

Every dispatcher checks its own level

checkAttributes() is public and static because Application::run() is not the only place a method gets called. Each dispatcher calls it for its own (class, endpoint) pair:

Dispatcher Checks
Application::run() The module named by the URL
Module::__call() A submodule and its endpoint
Response::__call() The Index module, for a standalone page with an Index method behind it
AdminResponse::routeToModuleAdmin() A module's admin controller

Gates therefore add up down the chain. A request for /shop/orders/save, where Orders is a submodule of Shop, runs (Shop, 'orders') — Shop's class-level attributes, since it has no orders() method — and then (Shop\Orders, 'save'). The last three dispatchers check before constructing the class they dispatch to, so a refused request never runs that constructor.

Class-Level vs. Method-Level

A class-level attribute applies to every endpoint of the class. A method-level attribute applies to one.

Method level replaces class level of the same type

If a method declares any attribute of type X, the class-level attributes of type X are skipped for that endpoint. Class-level attributes of other types still apply.

#[RequireLogin]
#[AllowedMethods('GET')]
class Notes extends \Zero\Core\Module {

    public function list() {}      // login required, GET only — both from the class

    #[AllowedMethods('POST')]
    public function create() {}    // login required, POST only: the class-level GET is replaced

    #[RequireLogin('/notes/welcome')]
    public function index() {}     // GET only; anonymous visitors go to /notes/welcome
}

Replace is the rule because these attributes name a destination or a constraint, and two of those contradict each other.

The one exception: RequirePermission adds

Application::isAdditive() names RequirePermission as the only type whose method-level declaration does not replace the class-level one. Both run, so the requirement is the union.

#[RequirePermission('allow.receipt.view')]
class Receipts extends \Zero\Core\Module {

    public function index() {}     // needs allow.receipt.view

    #[RequirePermission('allow.receipt.edit')]
    public function update() {}    // needs allow.receipt.view AND allow.receipt.edit
}
A class-level gate cannot be dropped for one endpoint

A method can replace a class-level attribute with another of the same type, never remove it, and a class-level RequirePermission cannot even be narrowed. A class with any deliberately public endpoint must gate per method instead.

Virtual endpoints: attributes on __call()

When the endpoint named by the URL is not a method of the class but the class has __call(), resolveAttributes() uses the attributes on __call() as the method-level attributes, under the same replace and additive rules. That is how a class gates everything it dispatches dynamically.

class Paste extends \Zero\Core\Module {

    // /paste/{slug} — the slug is data, not a method
    #[AllowedMethods('GET')]
    public function __call($slug, $args) { /* ... */ }

    #[RequireLogin]
    #[AllowedMethods('POST')]
    public function create() { /* ... */ }
}

Two consequences. A class-level gate still applies to a virtual endpoint when __call() declares nothing of that type, so a class whose __call() serves anonymous traffic must not carry a class-level gate. And __call()'s attributes also run when the URL segment names a submodule, because the parent has no method of that name either; the submodule's own check then runs on top.

Inheritance

Class-level attributes are not inherited by a subclass — reflection does not walk to the parent. Method-level attributes are, because an inherited method keeps the attributes of its declaration. A submodule extends Module, not its parent module; the parent's gates reach it through the dispatch chain above, not through inheritance.

Order

Declaration order is execution order, class level before method level. Declare attributes in this sequence:

#[RestrictIP(['10.0.0.0/8'])]       //  1. Network deny; needs nothing from the session
#[AllowWithToken]                   //  2. ESTABLISHES a session from a Bearer token
#[RequireLogin]                     //  3. Who are you
#[RequireAuthLevel(1)]              //  4. Shelved; listed because it still has a slot
#[RequirePermission('allow.api')]   //  5. What may you do
#[AuditLog('action_type')]          //  6. Reads the session's user id
#[AllowedMethods('POST')]           //  7. Request shape, after auth
#[RequiredParams(['data'])]         //  8. Required parameters
#[Sanitize(['data'])]               //  9. After the params are known to be present
#[Validate(['data' => 'required'])] // 10. Last, so it judges the sanitized value
public function secureEndpoint() {}

You would not declare all ten on one endpoint: RequirePermission already implies RequireLogin, and RequireAuthLevel should not sit beside RequirePermission.

The invariant: AllowWithToken before RequireLogin

AllowWithToken is the one attribute that creates a session; the gates after it check one. Put a gate first and the Bearer caller is refused before the attribute that would have authenticated it runs. The order spans both levels: a class-level #[RequireLogin] with a method-level #[AllowWithToken] reads correctly at each site and is wrong combined, because class-level attributes run first.

core/tests/module/AttributeOrderTest.php enforces the sequence. Its ORDER constant is the authority; the test calls Application::resolveAttributes() for every endpoint of every module, plus a virtual endpoint to exercise the __call() fallback, so it checks the sequence that actually runs. It also fails when an attribute in core/attribute/ is missing from ORDER. It is a test, not a runtime sort: it catches a bad order only where the suite is run.

The other reasons for the order: AuditLog records Session::userId(), so above AllowWithToken it would log token requests with no user; and auth precedes request shape so an anonymous caller gets a 401 rather than a 405 or 400 that confirms what the endpoint accepts.

RestrictIP

Restricts an endpoint or a class to a list of addresses and CIDR ranges, IPv4 and IPv6. Accepts one entry or an array. Any other client gets 403.

#[RestrictIP('203.0.113.5')]
public function oneAddress() { /* ... */ }

#[RestrictIP(['10.0.0.0/8', '2001:db8::/32'])]
public function internalOnly() { /* ... */ }

The client address comes from Request::clientIp(), which believes a forwarding header only when the peer is a Cloudflare edge and otherwise uses REMOTE_ADDR. The attribute fails closed: if Request::clientIpIsVerified() is false it refuses with 403 before matching anything. A method-level list replaces the class-level list; the two are not merged.

AllowWithToken

Takes no parameters. With no Authorization header it passes, leaving normal session auth to the gates after it. With one, the header must be Bearer zk_...; the token's SHA-256 hash is looked up in the api_tokens table.

#[AllowWithToken]
#[RequireLogin]
public function apiEndpoint() {
    // Reached by a browser session OR a Bearer token
}

Tokens themselves are covered in Sessions & Permissions.

RequireLogin

The authentication gate. It passes when Session::isLoggedIn() is true, which means a signed-in and verified user.

#[RequireLogin]                     // anonymous visitors go to /user/login?r=y
public function profile() {
    $userId = \Zero\Core\Session::userId();
}

#[RequireLogin('/notes/welcome')]   // ...or to a page of the module's choosing
public function index() { /* ... */ }

RequireAuthLevel — shelved

Do not add new ones

#[RequireAuthLevel] still exists and still works, but core/docs/attributes/RequireAuthLevel.md marks it shelved. Use #[RequirePermission] instead, and never pair the two on the same endpoint.

It requires Session::user()?->authLevel() — the auth.level key in user_settings — to be at least $level, which defaults to 9. What makes it the odd gate out:

RequirePermission

The authorization gate. Requires one capability key or an array of them — the user must hold all. A capability key is allow. followed by lowercase words joined by dots.

// One key
#[RequirePermission('allow.receipt.view')]
public function index() { /* ... */ }

// Several (ALL required)
#[RequirePermission(['allow.admin', 'allow.receipt.edit'])]
public function purge() { /* ... */ }

What a capability is, and how one is granted, is on Sessions & Permissions.

AuditLog

Creates a Zero\Entity\Event with the given event type and a detail string: module and endpoint, the session's user id and username when there are any, the request method and the first 100 characters of the user agent. It always returns true — if the write fails, the error is logged and the endpoint still runs.

#[AuditLog('admin_action')]
public function updatePermission() { /* ... */ }

// Include request parameters in the log
#[AuditLog('data_export', includeParams: true)]
public function exportData() { /* ... */ }

With includeParams: true, $_GET and $_POST are merged into the detail. These keys are replaced with [REDACTED]: password, passwd, pwd, pass, secret, token, api_key, apikey, auth, authorization, csrf, csrf_token. String values over 200 characters are truncated.

AllowedMethods

Accepts one method or an array; names are upper-cased before comparing. Any other method gets 405 with a message listing the allowed ones.

#[AllowedMethods('POST')]
public function submit() { /* ... */ }

#[AllowedMethods(['PUT', 'PATCH'])]
public function update($id) { /* ... */ }

RequiredParams

Requires each named parameter to be non-empty in $_POST or $_GET. Every missing one is reported together.

#[RequiredParams('username')]
public function lookup() { /* ... */ }

#[RequiredParams(['email', 'password'])]
public function register() { /* ... */ }

Returns 400 with Missing required parameter(s): email, password.

The test is empty()

A parameter counts as missing when PHP's empty() says so in both arrays — so an empty string, 0 and '0' are all missing. An endpoint that legitimately accepts 0 should check for the parameter itself.

Sanitize

Rewrites the named values in $_POST and $_GET before the endpoint runs. It never refuses a request and skips parameters that are not set. Array values are sanitized element by element.

// Default: strip unusual characters, collapse whitespace, trim
#[Sanitize(['title', 'content'])]

// A name ending in "id" with no rule given is cast to an integer
#[Sanitize(['user_id', 'post_id'])]

// Built-in preset
#[Sanitize(['upload_name' => 'filename'])]

// A filter_var() sanitize filter
#[Sanitize(['email' => FILTER_SANITIZE_EMAIL])]

// A regex: every match is REMOVED
#[Sanitize(['code' => '/[^a-zA-Z0-9]/'])]

Presets: filename, slug, alphanumeric, alpha, numeric. A regex names the characters to delete, so write it as a negated character class. A rule the attribute does not recognise falls back to the default and logs a warning.

Validate

Partial

core/attribute/Validate.php describes itself as a stub, not yet ready for production use. The rules below are the ones its code implements today.

Takes [param => rule] or [param => [rule, rule]]. The value is read from $_POST, then $_GET. All failures are collected and returned as one 400: Validation failed: ....

Rule Passes when
required The value is not null or an empty string
email, url, int, float, bool The matching FILTER_VALIDATE_* filter accepts it
in:a,b,c The value is one of the listed values
length:min,max String length is in range; omit max for no upper limit
range:min,max Numeric value is in range; either bound may be omitted
/regex/ The value matches the pattern

Every rule except required passes an absent or empty value, so pair it with required when the parameter is mandatory. An unknown rule name logs a warning and passes.

#[Validate([
    'email'  => ['required', 'email'],
    'status' => 'in:active,pending,closed',
    'title'  => 'length:1,255',
])]
public function save() { /* ... */ }

A Typical Endpoint

<?php
namespace Zero\Module;

use Zero\Core\Attribute\{
    RequirePermission,
    AuditLog,
    AllowedMethods,
    RequiredParams,
    Sanitize
};

#[RequirePermission('allow.receipt.view')]
class Receipts extends \Zero\Core\Module {

    #[RequirePermission('allow.receipt.edit')]
    #[AuditLog('receipt_update', includeParams: true)]
    #[AllowedMethods('POST')]
    #[RequiredParams(['receipt_id', 'amount'])]
    #[Sanitize(['receipt_id', 'amount' => 'numeric'])]
    public function update() {
        // By the time we reach this line:
        // ✓ User is logged in and verified
        // ✓ User holds allow.receipt.view AND allow.receipt.edit
        // ✓ Access has been logged with parameters
        // ✓ Request is POST
        // ✓ receipt_id and amount both exist
        // ✓ Both inputs are sanitized

        $receiptId = $_POST['receipt_id'];
        $amount    = $_POST['amount'];

        // Just write your business logic
    }
}

Gating is the attribute's job: an endpoint does not re-implement a login or permission check in its body. What stays in the body is anything that depends on the record being acted on — ownership, and per-item sharing, which Sessions & Permissions covers.

Creating Custom Attributes

An attribute is a class with a public handler() method. Constructor arguments are whatever the declaration passes. Throw HTTPError to refuse:

<?php
namespace Zero\Core\Attribute;

use \Attribute;
use \Zero\Core\Exception\HTTPError;

#[Attribute]
class RateLimit {

    public function __construct(
        private int $maxRequests = 60,
        private int $windowSeconds = 60
    ) {}

    public function handler() {
        $key = \Zero\Core\Request::clientIp() . ':' . \Zero\Core\Request::$module;

        if ($this->isRateLimited($key)) {
            throw new HTTPError(429, 'Too many requests');
        }

        return true;
    }

    private function isRateLimited(string $key): bool {
        // Your rate-limiting logic here
        return false;
    }
}
Custom Attribute Requirements

The namespace must be Zero\Core\Attribute — an attribute in any other namespace is never run — and the autoloader maps that namespace to core/attribute/, so the file goes there. The class needs PHP's #[Attribute] declaration and a public handler(). Give it a place in AttributeOrderTest::ORDER, or that test fails.