Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
strategy:
fail-fast: false
matrix:
example: [ hello-world, params-validation, auth, cors, openapi-console, logging-errors, custom-authorization, json-body, file-upload, pagination, versions, rate-limit, testing, problem-details, di-extension, attributes ]
example: [ hello-world, params-validation, auth, cors, openapi-console, logging-errors, custom-authorization, json-body, file-upload, pagination, versions, rate-limit, testing, problem-details, di-extension, attributes, typed-input ]

name: Example ${{ matrix.example }}

Expand Down
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip
Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch.

### Added
* Custom error message for token authorization
* Custom error message for token authorization (#242)

### Changed (BC breaks)
* Renamed the unsafe CORS mode `'auto'` (any website can make credentialed requests) to `'reflect-unsafe'` (`CorsMode::ReflectUnsafe`) with the same behaviour plus `Vary: Origin, Referer`: `setCorsHeader('auto')` throws and `api: cors: mode: auto` fails the compilation, both with the allowlist to use instead and the new name (#186).
Expand All @@ -30,6 +30,8 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch.
* Classes not meant for extension are `final`: `Api`, `ApiHolder`, `EndpointIdentifier`, `NoAuthorization`, `NoRateLimit`, `RateLimitResponse`, `IpDetector`, `StaticIpDetector`, `StaticTokenRepository`, `ConsoleRequest`, `ConsoleResponse`, `OpenApiTransform`, `ParamsProcessor`, `InputValidator`, `JsonSchemaValidator`, `ValidationResult`, `DebuggerConfigurator`, `EnvConfigurator`, `QueryConfigurator`. See `UPGRADE-4.0.md`.
* `TextApiResponse` throws `InvalidArgumentException` for arrays and non-`Stringable` objects instead of outputting `Array` with a warning (arrays) or failing with an `Error` (objects); non-string values in validation messages, IP headers, console fields and OpenAPI examples are converted to strings instead of raising warnings or `TypeError`.
* `Error\ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has two new methods, `handleNotFound(EndpointInterface)` and `handleRateLimit(RateLimitResponse)`. Own implementations must add them (#196).
* `Error\ErrorHandlerInterface` has a new method `handleUnsupportedMediaType(string $detail)` for the `415` of typed handlers. Own implementations must add it (#197).
* `Params\ParamType` has new cases `Path`, `Header` and `Body`, so an exhaustive `match` without a `default` arm fails on them; `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`, which a subclass with the same method names must match (#197).
* `ApiPresenter` builds the `404` for an unknown endpoint and the `429` for a reached rate limit (without an own error response) through the error handler. `DefaultErrorHandler` sends the same bodies as before, except that a `429` without a known retry time says only `Too many requests.` instead of `Retry after seconds.` (#196).
* `Handlers\DefaultHandler` is `final`. `ApiPresenter` does not call its `handle()`, so a subclass could no longer change the `404`; do it in `ErrorHandlerInterface::handleNotFound()` (#196).
* Request logs are masked by default (#187): `ApiPresenter` replaces secret header values (`Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, names containing `token`, `secret` or `key`, `X-Auth-*`), secret query parameters in the logged URI (`api_key`, `token`, `access_token`, `password`, `signature`, `code`, ...) and the names used by the API key authentications with `***` before `ApiLoggerInterface::log()`. The DI extension's `logging: maskHeaders` defaults to `true`. Opt out with `setMaskedLogHeaders([])` / `setMaskedLogQueryParams([])` or `maskHeaders: false` / `maskQueryParams: false`. See `UPGRADE-4.0.md`.
Expand Down Expand Up @@ -59,10 +61,17 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch.
* Rate limiting (#195): `FixedWindowLimiter`, `SlidingWindowLimiter` and `TokenBucketLimiter` behind `RateLimit\RateLimiterInterface`, combined by `RateLimiterChain`; keys by IP, identity, endpoint or a combination (`Key\RateLimitKeyInterface`); storages in memory, in the Nette cache (atomic on one server through a file lock in `%tempDir%`, waiting at most 3 seconds) or in Redis with one atomic Lua script that keeps the whole state of a counter in one hash with one expiration (`Storage\RedisStorage` with ext-redis or Predis, keys `prefix{policy:key}` for Redis Cluster); own algorithms (`Algorithm\RateLimitAlgorithmInterface`, with `RedisScriptAlgorithmInterface` for Redis) and own storages (`Storage\RateLimitStorageInterface`, `KeyValueStorage`). `ApiPresenter` checks the limits before the authorization and, for identity keys, after it. A failing storage lets the request pass and logs a warning. Time comes from a `Psr\Clock\ClockInterface`. Intervals are from 1 second to 366 days. `IpKey` hashes values longer than an IP and other keys longer than 200 characters are hashed, the memory storage drops expired counters as it grows, and all algorithms keep the newest window or time of servers with skewed clocks. When the logger fails, the warning goes to `error_log`. Limits are at most 1 000 000 000, policy and `rateLimits` names are ASCII, the parts of a list key are escaped, and the presenter escapes policy names of own limiters in the headers. A list of policies stops at the first rejection, so rejected requests do not use up a shared quota. The `ip` key counts an IPv6 client per `/64`. `api: rateLimiting: logger` sets the logger of the warnings. `Authorization\AuthorizationIdentityInterface` gives a limit keyed by `identity` the caller; the token authorizations and `BasicAuthentication` implement it. An authorization that returns no identity after a successful `authorized()` is logged once per process and policy. `ApiDecider::addApi()` without the 4th argument throws a `LogicException` naming the services when the container has more autowired `RateLimitInterface` services, instead of using none. A failing API logger after the handler only goes to the Tracy log, the response of the handler is sent.
* DI extension: named policies in `api: rateLimits` (`{algorithm, limit, interval, key, name}`), `api: rateLimiting` (`storage`, `redis`, `prefix`, `clock`), lists of policies and inline limits on endpoints and in `api: defaults`, `rateLimit: false`; inline limits always keep counters per endpoint (also with `name`), two named policies with the same `name` and an inline `name` equal to a named policy fail the compilation; `#[RateLimit]` takes a list or `limit`, `interval`, `algorithm`, `key` and `name` (#195).
* `examples/rate-limit` uses the built-in policies; `examples/auth`, `examples/di-extension` and `examples/attributes` no longer ship an own `FileRateLimit` (#195).
* Typed input DTOs (#197, #240): `Handlers\TypedHandler` with `handleDto(SomeInput $input)` reads a readonly DTO whose properties carry `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` or `#[File]`. It is an equal second way to declare input next to `params()`, which is unchanged, and the same declaration drives validation, OpenAPI and the API console. `PathInputParam`, `HeaderInputParam` and `BodyInputParam` are usable from `params()` too. See [typed input](https://tomaj.github.io/nette-api/guide/typed-input) and `examples/typed-input`.
* Endpoint actions can have `{name}` segments, for example `#[Get(1, 'users', '{id}/detail')]`. `ApiDecider::getApi()` keeps its signature; the new `ApiDecider::matchPath()` finds the endpoint of a URL template. `ApiLink::link()` fills `{name}` from the parameter of the same name.
* Strict conversion of scalars, backed enums, `DateTimeImmutable` (RFC 3339) and `list<T>`; `#[Cast]` with `CasterInterface` (`DateFormat`, `UnixTimestamp` and `Split` built in); constraints `Range`, `Length`, `Pattern`, `Email` and own `ConstraintInterface`.
* Nested DTOs and lists for JSON, form and multipart bodies, with errors reported as `items[1].quantity` in the existing envelope and in Problem Details.
* `#[Consumes]` limits the body media types; any other one is a `415`.
* For typed handlers, strings must be valid UTF-8, a JSON body that names another charset is a `400`, and so are a multipart body sent with `PUT` or `PATCH` and a form with more fields than `max_input_vars` (a multipart form that reaches the limit, as PHP gives no way to count it again). `BodyInputParam` in `params()` reads the body the same way.

### Changed
* Dev tools: PHPUnit ^12 || ^13, PHPStan ^2.1 (level max, no baseline), Rector ^2.2, PHP_CodeSniffer ^4.0, Infection; `symfony/yaml` ^7.4.12 || ^8.0.12.
* `vendor/bin/phpunit` no longer requires `XDEBUG_MODE=coverage`; coverage reports are opt-in via `composer coverage`.
* `BearerTokenAuthorization` also reads the token from `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite (#240).

### Deprecated
* `RateLimit\RateLimitInterface` and its `check()`: it still works through `LegacyRateLimitAdapter` with an `E_USER_DEPRECATED` notice and is removed in 5.0. Implement `RateLimiterInterface` or use a built-in limiter (#195).
Expand Down
43 changes: 39 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,16 @@ services:

For new projects we recommend [RFC 9457 Problem Details](https://tomaj.github.io/nette-api/guide/problem-details) errors: register `Tomaj\NetteApi\Error\ProblemDetailsErrorHandler` as `apiErrorHandler`. `DefaultErrorHandler` stays the default, so existing clients that read `message` keep working.

Write the handler:
Write the handler. There are two equal ways to declare its input; pick the one that fits the endpoint, and mix them freely in one API.

With a list of params, the handler gets an array:

```php
use Tomaj\NetteApi\Handlers\BaseHandler;
use Tomaj\NetteApi\Params\GetInputParam;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

final class HelloHandler extends BaseHandler
{
public function params(): array
Expand All @@ -75,6 +82,34 @@ final class HelloHandler extends BaseHandler
}
```

With a typed DTO (since 4.0), the handler gets a validated object:

```php
use Tomaj\NetteApi\Handlers\TypedHandler;
use Tomaj\NetteApi\Input\Query;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

final readonly class HelloInput
{
public function __construct(
#[Query]
public string $name = 'world',
) {
}
}

final class HelloHandler extends TypedHandler
{
public function handleDto(HelloInput $input): ResponseInterface
{
return new JsonApiResponse(200, ['message' => 'Hello ' . $input->name . '!']);
}
}
```

Both go through the same validation pipeline, OpenAPI and web console; a typed DTO converts values more strictly than `params()`. See [Handlers](https://tomaj.github.io/nette-api/guide/handlers) and [Typed input (DTO)](https://tomaj.github.io/nette-api/guide/typed-input).

```bash
curl http://localhost:8000/api/v1/hello?name=Nette
# {"message":"Hello Nette!"}
Expand All @@ -101,7 +136,7 @@ Or put `#[Get(1, 'hello')]` on the handler class and let the extension find it w
| --- | --- |
| How a request is processed | [Architecture](https://tomaj.github.io/nette-api/guide/architecture) |
| What each layer does: ApiDecider, presenter, authorization, params, handler, outputs | [Layers](https://tomaj.github.io/nette-api/guide/layers), [ApiDecider](https://tomaj.github.io/nette-api/guide/api-decider), [ApiPresenter pipeline](https://tomaj.github.io/nette-api/guide/presenter) |
| Handlers, params and outputs | [Handlers](https://tomaj.github.io/nette-api/guide/handlers), [Params](https://tomaj.github.io/nette-api/guide/params), [Outputs](https://tomaj.github.io/nette-api/guide/outputs) |
| Handlers, params, typed input DTOs and outputs | [Handlers](https://tomaj.github.io/nette-api/guide/handlers), [Params](https://tomaj.github.io/nette-api/guide/params), [Typed input (DTO)](https://tomaj.github.io/nette-api/guide/typed-input), [Outputs](https://tomaj.github.io/nette-api/guide/outputs) |
| Bearer tokens, API keys, HTTP Basic, IP restrictions | [Authorization](https://tomaj.github.io/nette-api/guide/authorization) |
| Rate limits, CORS, logging, errors | [Rate limiting](https://tomaj.github.io/nette-api/guide/rate-limit), [CORS](https://tomaj.github.io/nette-api/guide/cors), [Logging](https://tomaj.github.io/nette-api/guide/logging), [Error handling](https://tomaj.github.io/nette-api/guide/errors) |
| OpenAPI, web console, `{apiLink}` | [OpenAPI](https://tomaj.github.io/nette-api/guide/openapi), [Web console](https://tomaj.github.io/nette-api/guide/console), [Links and versions](https://tomaj.github.io/nette-api/guide/links) |
Expand All @@ -117,8 +152,8 @@ Or put `#[Get(1, 'hello')]` on the handler class and let the extension find it w

## Examples

Sixteen runnable projects in [`examples/`](examples/), each with an `e2e.sh` test that CI runs against the current code:
[hello world](examples/hello-world), [params and validation](examples/params-validation), [authorization and rate limit](examples/auth), [CORS](examples/cors), [OpenAPI and console](examples/openapi-console), [logging and errors](examples/logging-errors), [Problem Details](examples/problem-details), [DI extension](examples/di-extension), [attribute endpoints](examples/attributes), [custom authorization](examples/custom-authorization), [JSON and raw body](examples/json-body), [file upload](examples/file-upload), [pagination](examples/pagination), [API versions](examples/versions), [rate limit](examples/rate-limit), [testing](examples/testing).
Seventeen runnable projects in [`examples/`](examples/), each with an `e2e.sh` test that CI runs against the current code:
[hello world](examples/hello-world), [params and validation](examples/params-validation), [authorization and rate limit](examples/auth), [CORS](examples/cors), [OpenAPI and console](examples/openapi-console), [logging and errors](examples/logging-errors), [Problem Details](examples/problem-details), [DI extension](examples/di-extension), [attribute endpoints](examples/attributes), [custom authorization](examples/custom-authorization), [JSON and raw body](examples/json-body), [file upload](examples/file-upload), [typed input DTOs](examples/typed-input), [pagination](examples/pagination), [API versions](examples/versions), [rate limit](examples/rate-limit), [testing](examples/testing).

## Upgrading

Expand Down
17 changes: 16 additions & 1 deletion UPGRADE-4.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ new BearerTokenAuthorization(new StaticBearerTokenRepository(['token' => '*']),
new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDetector);
```

## Typed input: enum cases and InputParam methods

`TypedHandler` is an additional way to declare input; handlers on `params()` keep their conversion, validation and OpenAPI output. What can affect existing code:

* `ParamType` has new cases `Path`, `Header` and `Body`. An exhaustive `match` on `ParamType` without a `default` arm throws `UnhandledMatchError` for them.
* `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`. A subclass with a method of the same name must match their signatures.
* An own `InputParam` subclass whose `$type` is `'PATH'`, `'HEADER'` or `'BODY'` is now treated as the new `PathInputParam`, `HeaderInputParam` or `BodyInputParam`: OpenAPI lists it `in: path`, `in: header` or in the request body, and the console sends it there. Rename such a type, for example to `'CUSTOM_HEADER'`, to keep the 3.x behaviour.

`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath($method, $version, $package, $apiAction, $params)` from the values of the route, where `$params` are the segments after the action. `ApiPresenter` calls it when `getApi()` returns no static endpoint, and first when the URL has segments after the action. An own presenter that should serve URL templates calls `matchPath()` the same way; `getApi()` returns a template only for its literal URL, such as `{id}/detail`, which the presenter must not treat as a match of a request.

## Stricter types

* Every file declares `strict_types=1`.
Expand Down Expand Up @@ -125,7 +135,7 @@ Overriding methods are marked with `#[\Override]`.

## Error handlers

`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has two new methods. An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`:
`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has three new methods compared with 3.x: `handleNotFound()` and `handleRateLimit()` (#196), and `handleUnsupportedMediaType(string $detail)` for the `415` that a typed handler sends when the body content type is missing or not accepted (#197; `params()` handlers are not affected). An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`:

```php
use Tomaj\NetteApi\EndpointInterface;
Expand All @@ -141,6 +151,11 @@ public function handleRateLimit(RateLimitResponse $rateLimit): ResponseInterface
{
return $this->inner->handleRateLimit($rateLimit);
}

public function handleUnsupportedMediaType(string $detail): ResponseInterface
{
return $this->inner->handleUnsupportedMediaType($detail);
}
```

Returning `JsonApiResponse` from the old methods still satisfies the interface. Code that calls an error handler and needs `JsonApiResponse` methods such as `getPayload()` must check the type.
Expand Down
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@
"autoload-dev": {
"psr-4": {
"Tomaj\\NetteApi\\Test\\": "tests"
}
},
"classmap": [
"tests/Input/Fixtures/Handlers.php",
"tests/Input/Fixtures/Shared.php"
]
},
"scripts": {
"test": "phpunit",
Expand Down
2 changes: 1 addition & 1 deletion docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default defineConfig({

lastUpdated: true,
markdown: {
languageAlias: { latte: 'html', neon: 'yaml' },
languageAlias: { latte: 'html', neon: 'yaml', openapi: 'yaml' },
},

sitemap: {
Expand Down
Loading
Loading