diff --git a/docs/Server/Access-Control.md b/docs/Server/Access-Control.md index 8e51c5ee..4e672267 100644 --- a/docs/Server/Access-Control.md +++ b/docs/Server/Access-Control.md @@ -457,6 +457,8 @@ A denied assertion is folded away before the query runs, so the attribute behave (|(cn=bob)(telephoneNumber=555-0100)) -> the cn=bob match, the other branch drops ``` +The search itself still runs as usual. Its base must exist and its controls still apply. + This is what stops a value being recovered a guess at a time. Reads are unaffected: denying the filter does not strip the value, and denying the read does not stop the filter. Pair the two to get both. A value-level modify on a filter-denied attribute is gated the same way; see [Value-Level Modify](#value-level-modify). diff --git a/docs/Server/Schema.md b/docs/Server/Schema.md index 04e51a41..c17db724 100644 --- a/docs/Server/Schema.md +++ b/docs/Server/Schema.md @@ -376,6 +376,9 @@ Raise or remove the bound with `maxLinkedValues` on the search limits, including rule. A client can read a large attribute either one slice at a time with the range option, covered in [Range Retrieval](../Client/Range-Retrieval.md), or as entries through a paged search on the back-link. +The Pre-Read and Post-Read controls return a linked attribute such as `member` in full. They bound a back-link by the +server's `maxLinkedValues` alone, never by a per-identity rule. + The in-memory backend keeps linked values on the entry as written. It does not refuse a name that resolves to nothing, does not follow a rename, does not remove a reference when its target is deleted, and does not bound how many values a read returns. diff --git a/src/FreeDSx/Ldap/Container/Provider/ConnectionGraphContainerProvider.php b/src/FreeDSx/Ldap/Container/Provider/ConnectionGraphContainerProvider.php index 437d4b41..93803798 100644 --- a/src/FreeDSx/Ldap/Container/Provider/ConnectionGraphContainerProvider.php +++ b/src/FreeDSx/Ldap/Container/Provider/ConnectionGraphContainerProvider.php @@ -198,7 +198,10 @@ private function makeWithheldAttributeMiddleware(Container $container): Withheld private function makeAssertionMiddleware(Container $container): AssertionMiddleware { - return new AssertionMiddleware($container->get(AssertionEvaluator::class)); + return new AssertionMiddleware( + $container->get(AssertionEvaluator::class), + $container->get(ServerProtocolHandlerFactory::class), + ); } private function makeResourceLimitMiddleware(Container $container): ResourceLimitMiddleware diff --git a/src/FreeDSx/Ldap/Container/Provider/DecoderContainerProvider.php b/src/FreeDSx/Ldap/Container/Provider/DecoderContainerProvider.php index 01161225..3b1bbf9e 100644 --- a/src/FreeDSx/Ldap/Container/Provider/DecoderContainerProvider.php +++ b/src/FreeDSx/Ldap/Container/Provider/DecoderContainerProvider.php @@ -35,6 +35,7 @@ use FreeDSx\Ldap\Protocol\Decoder\Control\PwdPolicyResponseControlDecoder; use FreeDSx\Ldap\Protocol\Decoder\Control\ReadEntryControlDecoder; use FreeDSx\Ldap\Protocol\Decoder\Control\ReadEntryResponseControlDecoder; +use FreeDSx\Ldap\Protocol\Decoder\Control\RequestControlDecoders; use FreeDSx\Ldap\Protocol\Decoder\Control\SortingControlDecoder; use FreeDSx\Ldap\Protocol\Decoder\Control\SortingResponseControlDecoder; use FreeDSx\Ldap\Protocol\Decoder\Control\SubentriesControlDecoder; @@ -82,6 +83,7 @@ use FreeDSx\Ldap\Search\Filter\GreaterThanOrEqualFilter; use FreeDSx\Ldap\Search\Filter\LessThanOrEqualFilter; use FreeDSx\Ldap\Search\Filter\OrFilter; +use FreeDSx\Ldap\Server\Middleware\ServerControlRegistry; /** * Registers the decoders that turn received messages into requests and responses. @@ -265,26 +267,29 @@ private function makeResponseMessageDecoder(Container $container): ResponseMessa } /** - * Types only the controls a client sends, holding any other OID to RFC 4511 4.1.11 criticality. + * Types only the controls a request's operation takes, holding any other to RFC 4511 4.1.11 criticality. */ - private function makeRequestControlDecoder(Container $container): ControlDecoder + private function makeRequestControlDecoder(Container $container): RequestControlDecoders { - return new ControlDecoder([ - Control::OID_PAGING => $container->get(PagingControlDecoder::class), - Control::OID_SORTING => $container->get(SortingControlDecoder::class), - Control::OID_SYNC_REQUEST => $container->get(SyncRequestControlDecoder::class), - Control::OID_PROXY_AUTHORIZATION => $container->get(ProxyAuthorizationControlDecoder::class), - Control::OID_ASSERTION => $container->get(AssertionControlDecoder::class), - Control::OID_PRE_READ => new ReadEntryControlDecoder( - PreReadControl::class, - $container->get(AttributeSelectionDecoder::class), - ), - Control::OID_POST_READ => new ReadEntryControlDecoder( - PostReadControl::class, - $container->get(AttributeSelectionDecoder::class), - ), - Control::OID_SUBENTRIES => $container->get(SubentriesControlDecoder::class), - ]); + return new RequestControlDecoders( + [ + Control::OID_PAGING => $container->get(PagingControlDecoder::class), + Control::OID_SORTING => $container->get(SortingControlDecoder::class), + Control::OID_SYNC_REQUEST => $container->get(SyncRequestControlDecoder::class), + Control::OID_PROXY_AUTHORIZATION => $container->get(ProxyAuthorizationControlDecoder::class), + Control::OID_ASSERTION => $container->get(AssertionControlDecoder::class), + Control::OID_PRE_READ => new ReadEntryControlDecoder( + PreReadControl::class, + $container->get(AttributeSelectionDecoder::class), + ), + Control::OID_POST_READ => new ReadEntryControlDecoder( + PostReadControl::class, + $container->get(AttributeSelectionDecoder::class), + ), + Control::OID_SUBENTRIES => $container->get(SubentriesControlDecoder::class), + ], + new ServerControlRegistry(), + ); } /** diff --git a/src/FreeDSx/Ldap/Container/Provider/DirectoryServerContainerProvider.php b/src/FreeDSx/Ldap/Container/Provider/DirectoryServerContainerProvider.php index 1bb944b8..c0ec02f5 100644 --- a/src/FreeDSx/Ldap/Container/Provider/DirectoryServerContainerProvider.php +++ b/src/FreeDSx/Ldap/Container/Provider/DirectoryServerContainerProvider.php @@ -61,6 +61,7 @@ use FreeDSx\Ldap\Server\Backend\Storage\Contract\WriteEntryInterface; use FreeDSx\Ldap\Server\Backend\Storage\Directory\AliasResolver; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Backend\Storage\Export\DirectoryDumper; use FreeDSx\Ldap\Server\Backend\Write\Replay\WriteRequestReplayer; use FreeDSx\Ldap\Server\Backend\Storage\Filter\FilterEvaluator; @@ -103,6 +104,7 @@ use FreeDSx\Ldap\Server\Backend\Storage\Adapter\Operation\RdnAttributeValues; use FreeDSx\Ldap\Server\Backend\Storage\Adapter\Operation\WriteEntryOperationHandler; use FreeDSx\Ldap\Server\Backend\Write\OperationalAttributeGenerator; +use FreeDSx\Ldap\Server\Backend\Storage\Search\EntryProjection; use FreeDSx\Ldap\Server\Backend\Storage\Search\SearchStreamBuilder; use FreeDSx\Ldap\Server\Backend\Storage\Search\StorageListOptionsFactory; use FreeDSx\Ldap\Server\Backend\ReadBackendInterface; @@ -191,6 +193,7 @@ public function factories(): array PasswordAuthenticatableInterface::class => $this->makePasswordAuthenticator(...), FilterEvaluatorInterface::class => $this->makeFilterEvaluator(...), DerivedResolver::class => $this->makeDerivedResolver(...), + BacklinkReader::class => $this->makeBacklinkReader(...), SchemaValidator::class => $this->buildSchemaValidator(...), EqualityComparatorResolver::class => $this->makeEqualityComparatorResolver(...), DirectoryDumper::class => $this->makeDirectoryDumper(...), @@ -339,6 +342,18 @@ private function makeDerivedResolver(Container $container): DerivedResolver return new DerivedResolver($container->get(ReadEntryInterface::class)); } + /** + * Back-links are read under the server's default link cap, as a search reads them. + */ + private function makeBacklinkReader(Container $container): BacklinkReader + { + return new BacklinkReader( + $container->get(ReadEntryInterface::class), + $container->get(LinkedAttributes::class)->backlinks(), + EntryProjection::linkCapFor($container->get(ServerOptions::class)->makeSearchLimits()->maxLinkedValues()), + ); + } + /** * Replay runs the pipeline stages that need no connection, so it cannot drift from the wire path. */ diff --git a/src/FreeDSx/Ldap/Container/Provider/HandlerContainerProvider.php b/src/FreeDSx/Ldap/Container/Provider/HandlerContainerProvider.php index b639a9af..847d4806 100644 --- a/src/FreeDSx/Ldap/Container/Provider/HandlerContainerProvider.php +++ b/src/FreeDSx/Ldap/Container/Provider/HandlerContainerProvider.php @@ -44,6 +44,7 @@ use FreeDSx\Ldap\Server\Backend\Auth\PasswordHashService; use FreeDSx\Ldap\Server\Backend\Storage\Contract\ReadEntryInterface; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Backend\Storage\Filter\FilterEvaluatorInterface; use FreeDSx\Ldap\Server\Backend\Storage\Filter\LinkedLeafWitness; use FreeDSx\Ldap\Server\Backend\Storage\Filter\StrippedEntryMatcher; @@ -251,6 +252,7 @@ private function makeDispatchHandler( ), assertions: $container->get(AssertionEvaluator::class), derived: $container->get(DerivedResolver::class), + backlinks: $container->get(BacklinkReader::class), readEntryControlHandler: new ReadEntryControlHandler( $container->get(ServerOptions::class)->getSchema(), $container->get(AccessControlInterface::class), diff --git a/src/FreeDSx/Ldap/Protocol/Bind/Sasl/SaslExchange.php b/src/FreeDSx/Ldap/Protocol/Bind/Sasl/SaslExchange.php index df3fb5a7..859de3ae 100644 --- a/src/FreeDSx/Ldap/Protocol/Bind/Sasl/SaslExchange.php +++ b/src/FreeDSx/Ldap/Protocol/Bind/Sasl/SaslExchange.php @@ -30,6 +30,7 @@ use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Protocol\Bind\Sasl\OptionsBuilder\MechanismOptionsBuilderFactory; use FreeDSx\Ldap\Protocol\Bind\Sasl\UsernameExtractor\SaslUsernameExtractorFactory; +use FreeDSx\Ldap\Protocol\DecodeFailureOutcome; use FreeDSx\Ldap\Protocol\DecodeFailureResponder; use FreeDSx\Ldap\Protocol\Factory\ResponseFactory; use FreeDSx\Ldap\Protocol\LdapMessageRequest; @@ -297,33 +298,35 @@ private function nextMessage(): LdapMessageRequest $message = $this->readMessage(); // Continuations skip the validation middleware, and the challenge echoes back whatever ID arrives. - if ($message->getMessageId() === 0) { + if ($message?->getMessageId() === 0) { throw new RequestValidationException('The message ID 0 cannot be used in a client request.'); } - } while ($message->getRequest() instanceof AbandonRequest); + } while ($message === null || $message->getRequest() instanceof AbandonRequest); return $message; } /** + * Reads a message, or null when a refused request that takes no response was dropped. + * * @throws ResponseAlreadySentException when a message that fails to decode is answered on its own ID. * @throws MessageDecodeException when a message that fails to decode cannot be answered. */ - private function readMessage(): LdapMessageRequest + private function readMessage(): ?LdapMessageRequest { try { return $this->queue->getMessage(); } catch (MessageDecodeException $e) { - if (!$this->decodeFailures->answer($e)) { - throw $e; - } - - // The bind ends with the message that broke it, which is already answered. - throw new ResponseAlreadySentException( - $e->getMessage(), - $e->getResultCode(), - $e, - ); + return match ($this->decodeFailures->answer($e)) { + DecodeFailureOutcome::Dropped => null, + // The bind ends with the message that broke it, which is already answered. + DecodeFailureOutcome::Answered => throw new ResponseAlreadySentException( + $e->getMessage(), + $e->getResultCode(), + $e, + ), + DecodeFailureOutcome::Unanswerable => throw $e, + }; } } diff --git a/src/FreeDSx/Ldap/Protocol/DecodeFailureOutcome.php b/src/FreeDSx/Ldap/Protocol/DecodeFailureOutcome.php new file mode 100644 index 00000000..b828019e --- /dev/null +++ b/src/FreeDSx/Ldap/Protocol/DecodeFailureOutcome.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace FreeDSx\Ldap\Protocol; + +/** + * What became of a message that failed to decode. + * + * @internal + * @author Chad Sikorra + */ +enum DecodeFailureOutcome +{ + /** + * A response was sent on the message's ID. + */ + case Answered; + + /** + * A refused request that takes no response was recorded and dropped. + */ + case Dropped; + + /** + * It cannot be answered and ends the session. + */ + case Unanswerable; +} diff --git a/src/FreeDSx/Ldap/Protocol/DecodeFailureResponder.php b/src/FreeDSx/Ldap/Protocol/DecodeFailureResponder.php index 6bff19ce..8d7bc33a 100644 --- a/src/FreeDSx/Ldap/Protocol/DecodeFailureResponder.php +++ b/src/FreeDSx/Ldap/Protocol/DecodeFailureResponder.php @@ -42,11 +42,11 @@ public function __construct( /** * @throws EncoderException */ - public function answer(MessageDecodeException $e): bool + public function answer(MessageDecodeException $e): DecodeFailureOutcome { // A response on the reserved message ID 0 would read as an unsolicited notification. if ($e->getMessageId() === 0) { - return false; + return DecodeFailureOutcome::Unanswerable; } $response = $this->responseFactory->getDecodeFailureResponse( @@ -69,20 +69,20 @@ public function answer(MessageDecodeException $e): bool $this->record($e); $this->queue->sendMessage($response); - return true; + return DecodeFailureOutcome::Answered; } /** * A request refused for room that takes no response is recorded and dropped instead of ending the session. */ - private function dropRefused(MessageDecodeException $e): bool + private function dropRefused(MessageDecodeException $e): DecodeFailureOutcome { if (!$e instanceof RequestRefusedException) { - return false; + return DecodeFailureOutcome::Unanswerable; } $this->record($e); - return true; + return DecodeFailureOutcome::Dropped; } private function record(MessageDecodeException $e): void diff --git a/src/FreeDSx/Ldap/Protocol/Decoder/Control/RequestControlDecoders.php b/src/FreeDSx/Ldap/Protocol/Decoder/Control/RequestControlDecoders.php new file mode 100644 index 00000000..05d20e43 --- /dev/null +++ b/src/FreeDSx/Ldap/Protocol/Decoder/Control/RequestControlDecoders.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace FreeDSx\Ldap\Protocol\Decoder\Control; + +use FreeDSx\Ldap\Operation\Request\RequestInterface; +use FreeDSx\Ldap\Server\Middleware\ServerControlRegistry; + +use function array_flip; +use function array_intersect_key; + +/** + * Decodes a request's controls, typing only the ones its operation takes and leaving the rest generic. + * + * @internal + * @author Chad Sikorra + */ +class RequestControlDecoders +{ + /** + * @var array, ControlDecoder> + */ + private array $byOperation = []; + + /** + * @param array $typed the decoder of each typed control, keyed by its OID. + */ + public function __construct( + private readonly array $typed, + private readonly ServerControlRegistry $registry, + ) {} + + public function for(RequestInterface $request): ControlDecoder + { + // Keyed by class, as the operation alone decides which controls it takes. + return $this->byOperation[$request::class] ??= new ControlDecoder(array_intersect_key( + $this->typed, + array_flip($this->registry->controlsTakenBy($request)), + )); + } +} diff --git a/src/FreeDSx/Ldap/Protocol/Decoder/MessageDecoder.php b/src/FreeDSx/Ldap/Protocol/Decoder/MessageDecoder.php index 305cab36..b6e5c2fa 100644 --- a/src/FreeDSx/Ldap/Protocol/Decoder/MessageDecoder.php +++ b/src/FreeDSx/Ldap/Protocol/Decoder/MessageDecoder.php @@ -37,7 +37,6 @@ public function __construct( private MessageEnvelopeReader $envelopes, private array $operations, - private ControlDecoderInterface $controls, ) {} /** @@ -58,18 +57,22 @@ public function decode( [$operation, $controls] = $this->envelopes->answerable( $envelope, - fn(): array => [ - $decoder->decode( + function () use ($decoder, $envelope, $context): array { + $operation = $decoder->decode( $envelope->operation, $context, - ), - $this->envelopes->controlsOf( - $envelope, - $context, - $this->controls, - $this->maxControls(), - ), - ], + ); + + return [ + $operation, + $this->envelopes->controlsOf( + $envelope, + $context, + $this->controlsFor($operation), + $this->maxControls(), + ), + ]; + }, ); return $this->message( @@ -87,6 +90,13 @@ protected function maxControls(): ?int return null; } + /** + * The decoder for the controls of a decoded operation. + * + * @param TOperation $operation + */ + abstract protected function controlsFor(ProtocolElementInterface $operation): ControlDecoderInterface; + /** * Wraps the decoded operation and its controls in the message this side receives. * diff --git a/src/FreeDSx/Ldap/Protocol/Decoder/RequestMessageDecoder.php b/src/FreeDSx/Ldap/Protocol/Decoder/RequestMessageDecoder.php index 0cfcc63b..eeaabd5b 100644 --- a/src/FreeDSx/Ldap/Protocol/Decoder/RequestMessageDecoder.php +++ b/src/FreeDSx/Ldap/Protocol/Decoder/RequestMessageDecoder.php @@ -15,6 +15,8 @@ use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Operation\Request\RequestInterface; +use FreeDSx\Ldap\Protocol\Decoder\Control\ControlDecoderInterface; +use FreeDSx\Ldap\Protocol\Decoder\Control\RequestControlDecoders; use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\ProtocolElementInterface; @@ -32,6 +34,25 @@ */ public const MAX_CONTROLS = 100; + /** + * @param array> $operations keyed by protocolOp tag. + */ + public function __construct( + MessageEnvelopeReader $envelopes, + array $operations, + private RequestControlDecoders $controls, + ) { + parent::__construct( + $envelopes, + $operations, + ); + } + + protected function controlsFor(ProtocolElementInterface $operation): ControlDecoderInterface + { + return $this->controls->for($operation); + } + protected function maxControls(): int { return self::MAX_CONTROLS; diff --git a/src/FreeDSx/Ldap/Protocol/Decoder/ResponseMessageDecoder.php b/src/FreeDSx/Ldap/Protocol/Decoder/ResponseMessageDecoder.php index c7ae5f8c..8582eed3 100644 --- a/src/FreeDSx/Ldap/Protocol/Decoder/ResponseMessageDecoder.php +++ b/src/FreeDSx/Ldap/Protocol/Decoder/ResponseMessageDecoder.php @@ -15,6 +15,7 @@ use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Operation\Response\ResponseInterface; +use FreeDSx\Ldap\Protocol\Decoder\Control\ControlDecoderInterface; use FreeDSx\Ldap\Protocol\LdapMessageResponse; use FreeDSx\Ldap\Protocol\ProtocolElementInterface; @@ -27,6 +28,25 @@ */ readonly class ResponseMessageDecoder extends MessageDecoder { + /** + * @param array> $operations keyed by protocolOp tag. + */ + public function __construct( + MessageEnvelopeReader $envelopes, + array $operations, + private ControlDecoderInterface $controls, + ) { + parent::__construct( + $envelopes, + $operations, + ); + } + + protected function controlsFor(ProtocolElementInterface $operation): ControlDecoderInterface + { + return $this->controls; + } + protected function message( int $messageId, ProtocolElementInterface $operation, diff --git a/src/FreeDSx/Ldap/Protocol/Queue/ReadAheadBuffer.php b/src/FreeDSx/Ldap/Protocol/Queue/ReadAheadBuffer.php index a76198df..64a5b340 100644 --- a/src/FreeDSx/Ldap/Protocol/Queue/ReadAheadBuffer.php +++ b/src/FreeDSx/Ldap/Protocol/Queue/ReadAheadBuffer.php @@ -84,6 +84,20 @@ public function take(): ?LdapMessageRequest return $message; } + /** + * Drops every message held, along with the bytes counted for them. + */ + public function clear(): void + { + $this->messages = []; + $this->bytes = 0; + } + + public function isEmpty(): bool + { + return $this->messages === []; + } + /** * Whether the buffer holds as many messages, or as many bytes of them, as read-ahead may. */ diff --git a/src/FreeDSx/Ldap/Protocol/Queue/Response/ResponseWriter.php b/src/FreeDSx/Ldap/Protocol/Queue/Response/ResponseWriter.php index 8057cb1e..3a1f6066 100644 --- a/src/FreeDSx/Ldap/Protocol/Queue/Response/ResponseWriter.php +++ b/src/FreeDSx/Ldap/Protocol/Queue/Response/ResponseWriter.php @@ -14,6 +14,7 @@ namespace FreeDSx\Ldap\Protocol\Queue\Response; use FreeDSx\Ldap\Exception\MessageDecodeException; +use FreeDSx\Ldap\Protocol\DecodeFailureOutcome; use FreeDSx\Ldap\Protocol\DecodeFailureResponder; use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\Queue\ServerQueue; @@ -151,7 +152,7 @@ private function pollForSignal( ? $this->outOfSequence->signalOrRefuse($messageId) : $this->queue->peekForCancelSignal($messageId); } catch (MessageDecodeException $e) { - if ($this->decodeFailures->answer($e)) { + if ($this->decodeFailures->answer($e) !== DecodeFailureOutcome::Unanswerable) { return null; } diff --git a/src/FreeDSx/Ldap/Protocol/Queue/ServerQueue.php b/src/FreeDSx/Ldap/Protocol/Queue/ServerQueue.php index 7946a2b0..4eec0d4a 100644 --- a/src/FreeDSx/Ldap/Protocol/Queue/ServerQueue.php +++ b/src/FreeDSx/Ldap/Protocol/Queue/ServerQueue.php @@ -236,16 +236,23 @@ public function sendMessage(LdapMessageResponse ...$response): self } /** - * Releases what a request the upgrade discards reserved while arriving. + * Discards the requests read ahead of the upgrade and releases what they reserved. */ public function encrypt(): static { $this->arrival->arrived(); + $this->readAhead->clear(); parent::encrypt(); return $this; } + public function hasBufferedInput(): bool + { + return parent::hasBufferedInput() + || !$this->readAhead->isEmpty(); + } + /** * A close that would truncate a response still going out waits until it has been written. */ diff --git a/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler.php b/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler.php index 91192369..2608c04c 100644 --- a/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler.php +++ b/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler.php @@ -147,7 +147,7 @@ private function nextMessage(): ?LdapMessageRequest return $this->queue->getMessage(); } catch (MessageDecodeException $e) { # A message whose envelope parsed is answered by its ID, and the stream is already past it. - if ($this->decodeFailures->answer($e)) { + if ($this->decodeFailures->answer($e) !== DecodeFailureOutcome::Unanswerable) { return null; } diff --git a/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler/ServerDispatchHandler.php b/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler/ServerDispatchHandler.php index 9803dcbf..432537e9 100644 --- a/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler/ServerDispatchHandler.php +++ b/src/FreeDSx/Ldap/Protocol/ServerProtocolHandler/ServerDispatchHandler.php @@ -22,6 +22,7 @@ use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\Queue\Response\ResponseStream; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Backend\Write\Schema\SchemaViolations; use FreeDSx\Ldap\Server\Backend\Write\WriteContext; use FreeDSx\Ldap\Server\Backend\Write\WriteControlEvaluator; @@ -40,6 +41,7 @@ public function __construct( private WriteRequestRouter $router, private AssertionEvaluator $assertions, private DerivedResolver $derived, + private BacklinkReader $backlinks, private ReadEntryControlHandler $readEntryControlHandler, private ResponseFactory $responseFactory = new ResponseFactory(), ) {} @@ -62,6 +64,7 @@ public function handleRequest( $token, $controls, $this->derived, + $this->backlinks, ); $this->router->route( diff --git a/src/FreeDSx/Ldap/Search/Filters.php b/src/FreeDSx/Ldap/Search/Filters.php index d8c5708c..00e94969 100644 --- a/src/FreeDSx/Ldap/Search/Filters.php +++ b/src/FreeDSx/Ldap/Search/Filters.php @@ -51,6 +51,15 @@ public static function or(FilterInterface ...$filters): OrFilter return new OrFilter(...$filters); } + /** + * Whether the filter is the RFC 4526 absolute false, an 'or' with nothing in it, which no entry satisfies. + */ + public static function isAbsoluteFalse(FilterInterface $filter): bool + { + return $filter instanceof OrFilter + && $filter->get() === []; + } + /** * Create a simple equality value check filter. */ diff --git a/src/FreeDSx/Ldap/Server/AccessControl/WithheldFilterRewriter.php b/src/FreeDSx/Ldap/Server/AccessControl/WithheldFilterRewriter.php index fdc1edfa..808384f6 100644 --- a/src/FreeDSx/Ldap/Server/AccessControl/WithheldFilterRewriter.php +++ b/src/FreeDSx/Ldap/Server/AccessControl/WithheldFilterRewriter.php @@ -21,6 +21,7 @@ use FreeDSx\Ldap\Search\Filter\FilterInterface; use FreeDSx\Ldap\Search\Filter\NotFilter; use FreeDSx\Ldap\Search\Filter\OrFilter; +use FreeDSx\Ldap\Search\Filters; use FreeDSx\Ldap\Server\Token\TokenInterface; use function count; @@ -53,15 +54,6 @@ public function rewrite( : $filter; } - /** - * Whether rewriting collapsed the filter to the RFC 4526 absolute false, which no entry satisfies. - */ - public function isAbsoluteFalse(FilterInterface $filter): bool - { - return $filter instanceof OrFilter - && $filter->get() === []; - } - /** * An indeterminate set names an assertion reaching every attribute, which nothing here can fold against one. * @@ -115,7 +107,7 @@ private function foldAnd( foreach ($filter->get() as $child) { $folded = $this->fold($child, $token); - if ($this->isAbsoluteFalse($folded)) { + if (Filters::isAbsoluteFalse($folded)) { return self::never(); } @@ -137,7 +129,7 @@ private function foldOr( foreach ($filter->get() as $child) { $folded = $this->fold($child, $token); - if (!$this->isAbsoluteFalse($folded)) { + if (!Filters::isAbsoluteFalse($folded)) { $kept[] = $folded; } } @@ -159,7 +151,7 @@ private function foldNot( ): FilterInterface { $folded = $this->fold($filter->get(), $token); - return $this->isAbsoluteFalse($folded) + return Filters::isAbsoluteFalse($folded) ? new AndFilter() : new NotFilter($folded); } diff --git a/src/FreeDSx/Ldap/Server/Backend/Storage/Adapter/SqlFilter/SqlFilterTranslatorTrait.php b/src/FreeDSx/Ldap/Server/Backend/Storage/Adapter/SqlFilter/SqlFilterTranslatorTrait.php index fd5b5acf..0b5a80af 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Storage/Adapter/SqlFilter/SqlFilterTranslatorTrait.php +++ b/src/FreeDSx/Ldap/Server/Backend/Storage/Adapter/SqlFilter/SqlFilterTranslatorTrait.php @@ -30,6 +30,7 @@ use FreeDSx\Ldap\Search\Filter\OrFilter; use FreeDSx\Ldap\Search\Filter\PresentFilter; use FreeDSx\Ldap\Search\Filter\SubstringFilter; +use FreeDSx\Ldap\Search\Filters; use FreeDSx\Ldap\Server\Backend\Storage\Adapter\SubstringIndex\SubstringIndexInterface; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedAttributeTrait; use FreeDSx\Ldap\Server\Backend\Storage\Filter\AttributeFilterSupport; @@ -830,6 +831,14 @@ private function drivableLeavesOf(SqlFilterResult $result): array */ private function translateOr(OrFilter $filter): ?SqlFilterResult { + // RFC 4526 absolute false, which is False rather than Undefined. + if (Filters::isAbsoluteFalse($filter)) { + return new SqlFilterResult( + '1 = 0', + [], + isExact: true, + ); + } $children = []; $values = []; $isExact = []; diff --git a/src/FreeDSx/Ldap/Server/Backend/Storage/Link/BacklinkReader.php b/src/FreeDSx/Ldap/Server/Backend/Storage/Link/BacklinkReader.php new file mode 100644 index 00000000..a60853bc --- /dev/null +++ b/src/FreeDSx/Ldap/Server/Backend/Storage/Link/BacklinkReader.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace FreeDSx\Ldap\Server\Backend\Storage\Link; + +use FreeDSx\Ldap\Entry\Attribute; +use FreeDSx\Ldap\Entry\Entry; +use FreeDSx\Ldap\Server\Backend\Storage\Contract\ReadEntryInterface; +use FreeDSx\Ldap\Server\Backend\Storage\Schema\Backlinks; +use FreeDSx\Ldap\Server\Backend\Storage\Search\EntryProjection; + +use function in_array; + +/** + * Reads the back-links a selection asks for onto an entry. + * + * @internal + * + * @author Chad Sikorra + */ +readonly class BacklinkReader +{ + /** + * @param ?int $linkCap Values read per back-link: null for every value. + */ + public function __construct( + private ReadEntryInterface $storage, + private Backlinks $backlinks, + private ?int $linkCap = EntryProjection::DEFAULT_LINK_CAP, + ) {} + + /** + * The entry with the back-links the selection names, by name or through every operational attribute. + * + * @param array $selection + */ + public function withSelected( + Entry $entry, + array $selection, + ): Entry { + $names = $this->backlinks->selectedBy($selection); + if ($names === []) { + return $entry; + } + $stored = $this->storage->find( + $entry->getDn(), + new EntryProjection( + attributes: $names, + linkCap: $this->linkCap, + backlinks: $names, + ), + ); + + foreach ($stored?->getAttributes() ?? [] as $attribute) { + if (in_array(Attribute::normalizeName($attribute->getName()), $names, true)) { + $entry->set($attribute); + } + } + + return $entry; + } +} diff --git a/src/FreeDSx/Ldap/Server/Backend/Storage/Search/EntryProjection.php b/src/FreeDSx/Ldap/Server/Backend/Storage/Search/EntryProjection.php index fe6be1f7..efb8e6a8 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Storage/Search/EntryProjection.php +++ b/src/FreeDSx/Ldap/Server/Backend/Storage/Search/EntryProjection.php @@ -44,6 +44,18 @@ public function __construct( public array $backlinks = [], ) {} + /** + * The link cap a configured maximum stands for: the default when unset, and every value at zero. + */ + public static function linkCapFor(?int $maxLinkedValues): ?int + { + return match ($maxLinkedValues) { + null => self::DEFAULT_LINK_CAP, + 0 => null, + default => $maxLinkedValues, + }; + } + /** * Every value of every linked attribute, for callers that write back what they read or hand it to a replica. * @@ -57,6 +69,16 @@ public static function unbounded(?array $attributes = null): self ); } + /** + * What a removal loads of its target: every linked value when a control reads the entry, otherwise none. + */ + public static function forRemoval(bool $entryRead): self + { + return $entryRead + ? self::unbounded() + : new self(linkCap: 0); + } + /** * The same projection also materializing the given base attribute. */ diff --git a/src/FreeDSx/Ldap/Server/Backend/Storage/Search/StorageListOptionsFactory.php b/src/FreeDSx/Ldap/Server/Backend/Storage/Search/StorageListOptionsFactory.php index 283c5d05..9d33c2ed 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Storage/Search/StorageListOptionsFactory.php +++ b/src/FreeDSx/Ldap/Server/Backend/Storage/Search/StorageListOptionsFactory.php @@ -107,15 +107,9 @@ public function projectionFor( SearchRequest $request, ?SearchLimits $effectiveLimits = null, ): EntryProjection { - $linkCap = ($effectiveLimits ?? $this->limits)->maxLinkedValues(); - return new EntryProjection( attributes: $this->materializedAttributes($request), - linkCap: match ($linkCap) { - null => EntryProjection::DEFAULT_LINK_CAP, - 0 => null, - default => $linkCap, - }, + linkCap: EntryProjection::linkCapFor(($effectiveLimits ?? $this->limits)->maxLinkedValues()), withHasSubordinates: $this->wantsHasSubordinates($request), windows: $this->linkWindows($request), backlinks: $this->linked diff --git a/src/FreeDSx/Ldap/Server/Backend/StorageReadBackend.php b/src/FreeDSx/Ldap/Server/Backend/StorageReadBackend.php index c51eb661..64d874c8 100644 --- a/src/FreeDSx/Ldap/Server/Backend/StorageReadBackend.php +++ b/src/FreeDSx/Ldap/Server/Backend/StorageReadBackend.php @@ -21,6 +21,7 @@ use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Schema\Definition\AttributeTypeOid; use FreeDSx\Ldap\Search\Filter\EqualityFilter; +use FreeDSx\Ldap\Search\Filters; use FreeDSx\Ldap\Server\Backend\Storage\Directory\EntryLocator; use FreeDSx\Ldap\Server\Backend\Storage\Contract\ListEntryInterface; use FreeDSx\Ldap\Server\Backend\Storage\Contract\ReadEntryInterface; @@ -124,7 +125,7 @@ public function search( $normBase, $baseDn, ); - + // Built first, so the absolute false still refuses an attribute selection any other filter would. $options = $this->listOptions->make( $request, $normBase, @@ -133,6 +134,9 @@ public function search( $effectiveLimits, $slice, ); + if (Filters::isAbsoluteFalse($request->getFilter())) { + return self::emptyStream(); + } return $this->searchStream->buildForList( $this->lister->list($options), diff --git a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/AppliesEntryUpdate.php b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/AppliesEntryUpdate.php index b056a359..dd901f65 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/AppliesEntryUpdate.php +++ b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/AppliesEntryUpdate.php @@ -56,7 +56,6 @@ private function updated( $updated, $command->systemChanges, ); - $context->controlEvaluator()?->captureResult($updated); return $updated; } diff --git a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/SubtreeDelete/SubtreeChunkRemover.php b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/SubtreeDelete/SubtreeChunkRemover.php index f3e6a420..b884aa9d 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/SubtreeDelete/SubtreeChunkRemover.php +++ b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/SubtreeDelete/SubtreeChunkRemover.php @@ -80,8 +80,7 @@ public function removeChunk( ), $context, ), - // Removing an entry takes its links with it. - new EntryProjection(linkCap: 0), + EntryProjection::forRemoval($context->controlEvaluator()?->inspectsEntry() === true), array_map( Dn::fromCanonical(...), $chunk, diff --git a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/TransactionalEntryWrite.php b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/TransactionalEntryWrite.php index 13dde840..d3c50b20 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Write/Operation/TransactionalEntryWrite.php +++ b/src/FreeDSx/Ldap/Server/Backend/Write/Operation/TransactionalEntryWrite.php @@ -56,6 +56,7 @@ public function add( $this->writes->insert($entry); $this->resolved($entry, $context); + $context->controlEvaluator()?->captureResult($entry); // Journaled within the same transaction, so a record can never outlive the write it describes. $this->changeRecorder->recordAdd( @@ -147,8 +148,7 @@ function (Entry $current) use ($dn, $context, $check): void { $context, ); }, - // Removing an entry takes its links with it, so journaling them would only record what is already gone. - new EntryProjection(linkCap: 0), + EntryProjection::forRemoval($context->controlEvaluator()?->inspectsEntry() === true), ); } @@ -172,6 +172,7 @@ private function stored( $entry, $context, ); + $context->controlEvaluator()?->captureResult($entry); $this->changeRecorder->recordModify( $entry, diff --git a/src/FreeDSx/Ldap/Server/Backend/Write/WriteControlEvaluator.php b/src/FreeDSx/Ldap/Server/Backend/Write/WriteControlEvaluator.php index 7a53bc76..cd21e0c1 100644 --- a/src/FreeDSx/Ldap/Server/Backend/Write/WriteControlEvaluator.php +++ b/src/FreeDSx/Ldap/Server/Backend/Write/WriteControlEvaluator.php @@ -21,6 +21,7 @@ use FreeDSx\Ldap\Exception\OperationException; use FreeDSx\Ldap\Protocol\ServerProtocolHandler\AssertionEvaluator; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Token\TokenInterface; /** @@ -32,29 +33,20 @@ */ class WriteControlEvaluator { - /** - * The controls that read the entry a write targets. - * - * @var list - */ - private const ENTRY_READING_OIDS = [ - Control::OID_ASSERTION, - Control::OID_PRE_READ, - Control::OID_POST_READ, - ]; - private ?Entry $preReadEntry = null; private ?Entry $postReadEntry = null; /** * @param ?DerivedResolver $derived Adds the derived attributes a read-entry control asks for; none when null. + * @param ?BacklinkReader $backlinks Adds the back-links a read-entry control asks for; none when null. */ public function __construct( private readonly AssertionEvaluator $assertions, private readonly TokenInterface $token, private readonly ControlBag $controls, private readonly ?DerivedResolver $derived = null, + private readonly ?BacklinkReader $backlinks = null, ) {} /** @@ -76,7 +68,7 @@ public function evaluateTarget(Entry $current): void } /** - * Holds the entry being added to the assertion, as it is the Add's target (RFC 4528 §3), then keeps it for a Post-Read. + * Holds the entry being added to the assertion, as it is the Add's target (RFC 4528 §3). * * @throws OperationException */ @@ -87,11 +79,10 @@ public function evaluateAddition(Entry $entry): void $this->controls, $this->token, ); - $this->captureResult($entry); } /** - * Keeps the entry as the write stores it, for a Post-Read (RFC 4527 §3.2). + * Keeps the entry once the write has stored it, for a Post-Read (RFC 4527 §3.2). */ public function captureResult(Entry $result): void { @@ -106,13 +97,10 @@ public function captureResult(Entry $result): void */ public function inspectsEntry(): bool { - foreach (self::ENTRY_READING_OIDS as $oid) { - if ($this->controls->has($oid)) { - return true; - } - } - - return false; + // A read-entry control left generic is one the operation does not take, which is ignored. + return $this->controls->has(Control::OID_ASSERTION) + || $this->controls->get(Control::OID_PRE_READ) instanceof ReadEntryControl + || $this->controls->get(Control::OID_POST_READ) instanceof ReadEntryControl; } /** @@ -144,7 +132,15 @@ private function keptFor( if (!$control instanceof ReadEntryControl) { return null; } + $selection = array_map( + static fn(string $name): Attribute => new Attribute($name), + $control->getAttributes(), + ); $kept = $entry->makeCopy(); + $kept = $this->backlinks?->withSelected( + $kept, + $selection, + ) ?? $kept; if ($this->derived === null) { return $kept; @@ -152,10 +148,7 @@ private function keptFor( return $this->derived->inject( $kept, - $this->derived->requested(array_map( - static fn(string $name): Attribute => new Attribute($name), - $control->getAttributes(), - )), + $this->derived->requested($selection), ); } } diff --git a/src/FreeDSx/Ldap/Server/Middleware/AssertionMiddleware.php b/src/FreeDSx/Ldap/Server/Middleware/AssertionMiddleware.php index fe7e8130..ef2f3ccc 100644 --- a/src/FreeDSx/Ldap/Server/Middleware/AssertionMiddleware.php +++ b/src/FreeDSx/Ldap/Server/Middleware/AssertionMiddleware.php @@ -17,6 +17,9 @@ use FreeDSx\Ldap\Control\PagingControl; use FreeDSx\Ldap\Exception\OperationException; use FreeDSx\Ldap\Operation\Request\SearchRequest; +use FreeDSx\Ldap\Protocol\Factory\HandlerId; +use FreeDSx\Ldap\Protocol\Factory\HandlerRouteResolverInterface; +use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\Queue\Response\ResponseStream; use FreeDSx\Ldap\Protocol\ServerProtocolHandler\AssertionEvaluator; use FreeDSx\Ldap\Server\Middleware\Pipeline\MiddlewareHandlerInterface; @@ -33,7 +36,10 @@ */ final readonly class AssertionMiddleware implements MiddlewareInterface { - public function __construct(private AssertionEvaluator $evaluator) {} + public function __construct( + private AssertionEvaluator $evaluator, + private HandlerRouteResolverInterface $routes, + ) {} /** * @throws OperationException @@ -47,8 +53,7 @@ public function process( # Paged search runs once at the start; continuation pages resume the same operation, so the assertion # (a precondition of that single execution) is only evaluated on the first page. - $paging = $message->controls()->get(Control::OID_PAGING); - if ($paging instanceof PagingControl && $paging->getCookie() !== '') { + if ($this->isPagingContinuation($message)) { return $next->handle($context); } @@ -66,4 +71,19 @@ public function process( return $next->handle($context); } + + /** + * Whether the request is a later page of a paged search. + */ + private function isPagingContinuation(LdapMessageRequest $message): bool + { + $paging = $message->controls()->get(Control::OID_PAGING); + + return $paging instanceof PagingControl + && $paging->getCookie() !== '' + && $this->routes->routeIdFor( + $message->getRequest(), + $message->controls(), + ) === HandlerId::Paging; + } } diff --git a/src/FreeDSx/Ldap/Server/Middleware/ServerControlRegistry.php b/src/FreeDSx/Ldap/Server/Middleware/ServerControlRegistry.php index 470ead56..897314b6 100644 --- a/src/FreeDSx/Ldap/Server/Middleware/ServerControlRegistry.php +++ b/src/FreeDSx/Ldap/Server/Middleware/ServerControlRegistry.php @@ -14,13 +14,20 @@ namespace FreeDSx\Ldap\Server\Middleware; use FreeDSx\Ldap\Control\Control; +use FreeDSx\Ldap\Operation\Request\AbandonRequest; use FreeDSx\Ldap\Operation\Request\AddRequest; +use FreeDSx\Ldap\Operation\Request\BindRequest; +use FreeDSx\Ldap\Operation\Request\CompareRequest; use FreeDSx\Ldap\Operation\Request\DeleteRequest; use FreeDSx\Ldap\Operation\Request\ModifyDnRequest; use FreeDSx\Ldap\Operation\Request\ModifyRequest; use FreeDSx\Ldap\Operation\Request\RequestInterface; +use FreeDSx\Ldap\Operation\Request\SearchRequest; +use FreeDSx\Ldap\Operation\Request\UnbindRequest; use FreeDSx\Ldap\Protocol\Factory\HandlerId; +use function array_unique; +use function array_values; use function in_array; /** @@ -71,6 +78,7 @@ final class ServerControlRegistry private const SYNC_CONTROLS = [ Control::OID_SYNC_REQUEST, + Control::OID_ASSERTION, ]; /** @@ -155,6 +163,33 @@ public function supportedControlsFor( ]; } + /** + * The controls a request's operation takes on any of its routes. + * + * @return list + */ + public function controlsTakenBy(RequestInterface $request): array + { + return match (true) { + $request instanceof BindRequest => self::BIND_CONTROLS, + $request instanceof AbandonRequest, $request instanceof UnbindRequest => [], + $request instanceof SearchRequest => array_values(array_unique([ + ...self::GLOBAL_CONTROLS, + ...self::SEARCH_CONTROLS, + ...self::PAGING_CONTROLS, + ...self::SYNC_CONTROLS, + ])), + $request instanceof CompareRequest => [ + ...self::GLOBAL_CONTROLS, + ...self::COMPARE_CONTROLS, + ], + default => [ + ...self::GLOBAL_CONTROLS, + ...$this->dispatchControlsFor($request), + ], + }; + } + /** * @return list */ diff --git a/src/FreeDSx/Ldap/Server/Middleware/WithheldAttributeMiddleware.php b/src/FreeDSx/Ldap/Server/Middleware/WithheldAttributeMiddleware.php index 5babaaa8..2661598b 100644 --- a/src/FreeDSx/Ldap/Server/Middleware/WithheldAttributeMiddleware.php +++ b/src/FreeDSx/Ldap/Server/Middleware/WithheldAttributeMiddleware.php @@ -17,7 +17,6 @@ use FreeDSx\Ldap\Control\Sorting\SortingControl; use FreeDSx\Ldap\Operation\Request\ModifyRequest; use FreeDSx\Ldap\Operation\Request\SearchRequest; -use FreeDSx\Ldap\Protocol\Factory\ResponseFactory; use FreeDSx\Ldap\Protocol\Queue\Response\ResponseStream; use FreeDSx\Ldap\Server\AccessControl\WithheldFilterRewriter; use FreeDSx\Ldap\Server\AccessControl\WithheldSortKeyFilter; @@ -25,7 +24,6 @@ use FreeDSx\Ldap\Server\Middleware\Pipeline\MiddlewareHandlerInterface; use FreeDSx\Ldap\Server\Middleware\Pipeline\MiddlewareInterface; use FreeDSx\Ldap\Server\Middleware\Pipeline\ServerRequestContext; -use FreeDSx\Ldap\Server\Operation\OperationOutcomeResult; /** * Withholds attributes from search assertions, sort keys, and value-level modifies, before storage. @@ -40,7 +38,6 @@ public function __construct( private WithheldFilterRewriter $rewriter, private WithheldSortKeyFilter $sortKeys, private WithheldValueModifyGuard $valueModify, - private ResponseFactory $responseFactory = new ResponseFactory(), ) {} public function process( @@ -76,19 +73,10 @@ private function processSearch( $token, ); } - $rewritten = $this->rewriter->rewrite( + $request->setFilter($this->rewriter->rewrite( $request->getFilter(), $token, - ); - - if ($this->rewriter->isAbsoluteFalse($rewritten)) { - return ResponseStream::of( - [$this->responseFactory->getStandardResponse($context->message)], - OperationOutcomeResult::succeeded(), - ); - } - - $request->setFilter($rewritten); + )); return $next->handle($context); } diff --git a/tests/integration/Runner/Concern/TlsTestsTrait.php b/tests/integration/Runner/Concern/TlsTestsTrait.php index f496dced..83625d6e 100644 --- a/tests/integration/Runner/Concern/TlsTestsTrait.php +++ b/tests/integration/Runner/Concern/TlsTestsTrait.php @@ -19,6 +19,7 @@ use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Operations; use FreeDSx\Ldap\Protocol\LdapMessageRequest; +use FreeDSx\Ldap\Search\Filters; use FreeDSx\Socket\Exception\ConnectionException; use FreeDSx\Socket\Exception\IdleTimeoutException; use Tests\Support\FreeDSx\Ldap\RawClientQueueTrait; @@ -77,6 +78,63 @@ public function testItDiscardsPlaintextPipelinedBehindStartTls(): void ); } + public function testItDiscardsRequestsReadAheadOfStartTlsDuringAStreamingSearch(): void + { + $this->stopServer(); + $this->createServerProcess( + 'tcp', + ['--entries=300'], + ); + $queue = $this->rawQueue( + timeoutRead: 2, + validateSslCert: false, + ); + $queue->sendMessage(new LdapMessageRequest( + 1, + Operations::bind( + 'cn=user,dc=foo,dc=bar', + '12345', + ), + )); + $queue->getMessage(1); + + $queue->sendMessage( + new LdapMessageRequest( + 2, + Operations::search(Filters::present('objectClass')) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + ), + new LdapMessageRequest( + 3, + Operations::extended(ExtendedRequest::OID_START_TLS), + ), + new LdapMessageRequest( + 4, + Operations::whoami(), + ), + ); + + $this->assertSame( + [2 => ResultCode::SUCCESS, 3 => ResultCode::SUCCESS], + $this->resultCodesFor( + $queue, + 2, + 3, + ), + ); + + $queue->encrypt(); + + $this->expectException(IdleTimeoutException::class); + + try { + $queue->getMessage(); + } finally { + $queue->close(); + } + } + public function testASilentStartTlsClientIsDisconnectedWithoutStallingOtherClients(): void { $this->stopServer(); diff --git a/tests/integration/Security/AclIntegrationTest.php b/tests/integration/Security/AclIntegrationTest.php index c7f14d72..72b39b6a 100644 --- a/tests/integration/Security/AclIntegrationTest.php +++ b/tests/integration/Security/AclIntegrationTest.php @@ -1063,12 +1063,7 @@ public function testFilteringOnAPasswordMatchesForAGrantedSubject(): void ); } - /** - * It's very unclear from the RFC whether a re-bind should be allowed to even resume a paged search. Other - * implementations allow it, and our ACL / filtering applies correctly. So keeping it as is and making sure - * an integration test is in place so it doesn't regress. - */ - public function testPagingAfterARebindAppliesTheNewIdentity(): void + public function testPagingAfterARebindThatChangesWhatTheFilterCanMatchIsRefused(): void { $search = Operations::search(Filters::present('userPassword')) ->base('dc=foo,dc=bar') @@ -1090,16 +1085,10 @@ public function testPagingAfterARebindAppliesTheNewIdentity(): void $this->ldapClient()->bind('cn=user,dc=foo,dc=bar', '12345'); - $delivered = 0; - while ($paging->hasEntries()) { - $delivered += count($paging->getEntries()); - } + $this->expectException(OperationException::class); + $this->expectExceptionCode(ResultCode::OPERATIONS_ERROR); - self::assertSame( - 0, - $delivered, - 'Entries the re-bound identity could not have selected must not continue to arrive.', - ); + $paging->getEntries(); } public function testADisjunctionKeepsTheBranchThatIsNotWithheld(): void diff --git a/tests/integration/Security/PasswordPolicyPlainModifyEnforcementTest.php b/tests/integration/Security/PasswordPolicyPlainModifyEnforcementTest.php index f94bc884..b74b41b0 100644 --- a/tests/integration/Security/PasswordPolicyPlainModifyEnforcementTest.php +++ b/tests/integration/Security/PasswordPolicyPlainModifyEnforcementTest.php @@ -32,6 +32,7 @@ use FreeDSx\Ldap\Server\Backend\Auth\PasswordHashService; use FreeDSx\Ldap\Server\Clock\ClockInterface; use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Backend\Storage\Schema\LinkedAttributes; use FreeDSx\Ldap\Server\Backend\StorageReadBackend; use FreeDSx\Ldap\Server\Backend\Write\PasswordPolicyWriteHandler; @@ -429,6 +430,7 @@ private function dispatchHandler( router: new WriteRequestRouter($policyWriteHandler), assertions: $container->get(AssertionEvaluator::class), derived: $container->get(DerivedResolver::class), + backlinks: $container->get(BacklinkReader::class), readEntryControlHandler: new ReadEntryControlHandler( new Schema(), $this->createMock(AccessControlInterface::class), diff --git a/tests/integration/Security/SaslIntegrationTest.php b/tests/integration/Security/SaslIntegrationTest.php index 29f42ca0..2b86e8b5 100644 --- a/tests/integration/Security/SaslIntegrationTest.php +++ b/tests/integration/Security/SaslIntegrationTest.php @@ -13,10 +13,12 @@ namespace Tests\Integration\FreeDSx\Ldap\Security; +use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Exception\BindException; use FreeDSx\Ldap\Exception\UnsolicitedNotificationException; use FreeDSx\Ldap\Operation\Request\AbandonRequest; use FreeDSx\Ldap\Operation\Request\ExtendedRequest; +use FreeDSx\Ldap\Operation\Request\RequestInterface; use FreeDSx\Ldap\Operation\Request\SaslBindRequest; use FreeDSx\Ldap\Operation\Request\UnbindRequest; use FreeDSx\Ldap\Operation\Response\BindResponse; @@ -446,6 +448,73 @@ public function testAnAbandonMidNegotiationIsIgnored(): void } } + /** + * @return iterable + */ + public static function noResponseRequestProvider(): iterable + { + yield 'abandon' => [new AbandonRequest(1)]; + yield 'unbind' => [new UnbindRequest()]; + } + + #[DataProvider('noResponseRequestProvider')] + public function testARequestWithNoResponseRefusedForRoomMidNegotiationIsPassedOver(RequestInterface $request): void + { + $this->stopServer(); + $this->createServerProcess( + 'tcp', + [ + '--sasl', + '--max-held-request-size=5000', + ], + ); + $queue = $this->rawQueue(); + + try { + $queue->sendMessage(new LdapMessageRequest( + 1, + new SaslBindRequest('CRAM-MD5'), + )); + $challenge = $queue->getMessage(1)->getResponse(); + self::assertInstanceOf( + BindResponse::class, + $challenge, + ); + + $queue->sendMessage( + new LdapMessageRequest( + 2, + $request, + ...array_map( + static fn(int $i): Control => new Control('1.3.6.1.4.1.99999.' . $i), + range( + 1, + 60, + ), + ), + ), + new LdapMessageRequest( + 3, + new SaslBindRequest( + 'CRAM-MD5', + 'user ' . hash_hmac( + 'md5', + (string) $challenge->getSaslCredentials(), + '12345', + ), + ), + ), + ); + + self::assertSame( + ResultCode::SUCCESS, + $this->resultCodeOf($queue->getMessage(3)), + ); + } finally { + $queue->close(); + } + } + public function testAFailedReplacementBindIsAnsweredOnce(): void { $queue = $this->rawQueue(); diff --git a/tests/integration/Storage/Concern/ControlValidationTestsTrait.php b/tests/integration/Storage/Concern/ControlValidationTestsTrait.php index 462f550d..415a8dad 100644 --- a/tests/integration/Storage/Concern/ControlValidationTestsTrait.php +++ b/tests/integration/Storage/Concern/ControlValidationTestsTrait.php @@ -20,7 +20,9 @@ use FreeDSx\Ldap\Controls; use FreeDSx\Ldap\Entry\Change; use FreeDSx\Ldap\Entry\Entry; +use FreeDSx\Ldap\Exception\BindException; use FreeDSx\Ldap\Exception\OperationException; +use FreeDSx\Ldap\Operation\LdapResult; use FreeDSx\Ldap\Operation\Request\RequestInterface; use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Operations; @@ -244,4 +246,127 @@ public static function controlsOnlyAServerSends(): iterable str_repeat("\x11", 16), )]; } + + /** + * @return iterable + */ + public static function malformedControlTheOperationDoesNotTake(): iterable + { + $bind = Operations::bind( + 'cn=user,dc=foo,dc=bar', + '12345', + ); + $compare = Operations::compare( + 'cn=user,dc=foo,dc=bar', + 'cn', + 'user', + ); + + yield 'non-critical paging on a bind' => [ + $bind, + self::malformed( + Control::OID_PAGING, + false, + ), + ResultCode::SUCCESS, + 'dn:cn=user,dc=foo,dc=bar', + ]; + yield 'critical paging on a bind' => [ + $bind, + self::malformed( + Control::OID_PAGING, + true, + ), + ResultCode::UNAVAILABLE_CRITICAL_EXTENSION, + '', + ]; + yield 'non-critical pre-read on a bind' => [ + $bind, + self::malformed( + Control::OID_PRE_READ, + false, + ), + ResultCode::SUCCESS, + 'dn:cn=user,dc=foo,dc=bar', + ]; + yield 'non-critical paging on a compare' => [ + $compare, + self::malformed( + Control::OID_PAGING, + false, + ), + ResultCode::COMPARE_TRUE, + 'dn:cn=user,dc=foo,dc=bar', + ]; + yield 'critical paging on a compare' => [ + $compare, + self::malformed( + Control::OID_PAGING, + true, + ), + ResultCode::UNAVAILABLE_CRITICAL_EXTENSION, + 'dn:cn=user,dc=foo,dc=bar', + ]; + yield 'non-critical pre-read on a compare' => [ + $compare, + self::malformed( + Control::OID_PRE_READ, + false, + ), + ResultCode::COMPARE_TRUE, + 'dn:cn=user,dc=foo,dc=bar', + ]; + } + + #[DataProvider('malformedControlTheOperationDoesNotTake')] + public function testAMalformedControlTheOperationDoesNotTakeIsJudgedByItsCriticality( + RequestInterface $request, + Control $control, + int $resultCode, + string $identity, + ): void { + $this->authenticateUser(); + + self::assertSame( + [$resultCode, $identity], + [ + $this->resultCodeOf( + $request, + $control, + ), + $this->ldapClient()->whoami(), + ], + ); + } + + private static function malformed( + string $oid, + bool $criticality, + ): Control { + return new Control( + $oid, + $criticality, + "\x01\x02\x03", + ); + } + + private function resultCodeOf( + RequestInterface $request, + Control $control, + ): int { + try { + $response = $this->ldapClient() + ->sendAndReceive( + $request, + $control, + ) + ->getResponse(); + } catch (OperationException|BindException $e) { + return $e->getCode(); + } + + return $response instanceof LdapResult + ? $response->getResultCode() + : -1; + } } diff --git a/tests/integration/Storage/Concern/DefaultAclTestsTrait.php b/tests/integration/Storage/Concern/DefaultAclTestsTrait.php index 76b4dae1..c633ea08 100644 --- a/tests/integration/Storage/Concern/DefaultAclTestsTrait.php +++ b/tests/integration/Storage/Concern/DefaultAclTestsTrait.php @@ -13,6 +13,9 @@ namespace Tests\Integration\FreeDSx\Ldap\Storage\Concern; +use FreeDSx\Ldap\Control\Control; +use FreeDSx\Ldap\Control\PagingControl; +use FreeDSx\Ldap\Controls; use FreeDSx\Ldap\Entry\Change; use FreeDSx\Ldap\Entry\Entry; use FreeDSx\Ldap\Exception\OperationException; @@ -20,6 +23,7 @@ use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Operations; use FreeDSx\Ldap\Schema\Definition\PasswordPolicyOid; +use FreeDSx\Ldap\Search\Filter\FilterInterface; use FreeDSx\Ldap\Search\Filters; use FreeDSx\Ldap\Server\AccessControl\AclRules; use PHPUnit\Framework\Attributes\DataProvider; @@ -383,6 +387,102 @@ public function testPagingOnAWithheldFilterReturnsNothing(): void ); } + /** + * @return iterable + */ + public static function filterMatchingNothingProvider(): iterable + { + yield 'a filter no entry matches' => [Filters::equal( + 'cn', + 'no-entry-has-this', + )]; + yield 'the absolute false' => [Filters::or()]; + yield 'a filter on a withheld attribute' => [Filters::present('userPassword')]; + } + + #[DataProvider('filterMatchingNothingProvider')] + public function testAFilterMatchingNothingStillAppliesTheBaseAndEveryControl(FilterInterface $filter): void + { + $this->authenticateUser(); + + self::assertSame( + [ + 'missing base' => ResultCode::NO_SUCH_OBJECT, + 'false assertion' => ResultCode::ASSERTION_FAILED, + 'invented paging cookie' => ResultCode::UNWILLING_TO_PERFORM, + 'critical sort it cannot do' => ResultCode::UNAVAILABLE_CRITICAL_EXTENSION, + ], + [ + 'missing base' => $this->searchResultCode( + $filter, + 'ou=nope,dc=foo,dc=bar', + ), + 'false assertion' => $this->searchResultCode( + $filter, + 'dc=foo,dc=bar', + Controls::assertion(Filters::equal( + 'dc', + 'no-entry-has-this', + )), + ), + 'invented paging cookie' => $this->searchResultCode( + $filter, + 'dc=foo,dc=bar', + Controls::paging( + 5, + 'invented', + ), + ), + 'critical sort it cannot do' => $this->searchResultCode( + $filter, + 'dc=foo,dc=bar', + Controls::sort('description')->setCriticality(true), + ), + ], + ); + } + + #[DataProvider('filterMatchingNothingProvider')] + public function testAFilterMatchingNothingStillRefusesARangeItCannotServe(FilterInterface $filter): void + { + $this->authenticateUser(); + + $this->expectException(OperationException::class); + $this->expectExceptionCode(ResultCode::UNWILLING_TO_PERFORM); + + $this->ldapClient()->search( + Operations::search( + $filter, + 'cn;range=0-5', + ) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + ); + } + + #[DataProvider('filterMatchingNothingProvider')] + public function testAPagedFilterMatchingNothingEndsWithAnEmptyPagingCookie(FilterInterface $filter): void + { + $this->authenticateUser(); + + $response = $this->ldapClient()->sendAndReceive( + Operations::search($filter) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + Controls::paging(5), + ); + $paging = $response->controls()->get(Control::OID_PAGING); + + self::assertInstanceOf( + PagingControl::class, + $paging, + ); + self::assertSame( + '', + $paging->getCookie(), + ); + } + public function testAValueLevelModifyOfAWithheldAttributeOnAnotherEntryIsRefused(): void { $this->authenticateAdmin(); @@ -455,4 +555,23 @@ public function testSelfMayMakeAValueLevelModifyOfItsOwnWithheldAttribute(): voi $code, ); } + + private function searchResultCode( + FilterInterface $filter, + string $base, + Control ...$controls, + ): int { + try { + $this->ldapClient()->search( + Operations::search($filter) + ->base($base) + ->useSubtreeScope(), + ...$controls, + ); + } catch (OperationException $e) { + return $e->getCode(); + } + + return ResultCode::SUCCESS; + } } diff --git a/tests/integration/Storage/Concern/LinkedReferenceTestsTrait.php b/tests/integration/Storage/Concern/LinkedReferenceTestsTrait.php index 90766866..1f4615f3 100644 --- a/tests/integration/Storage/Concern/LinkedReferenceTestsTrait.php +++ b/tests/integration/Storage/Concern/LinkedReferenceTestsTrait.php @@ -207,6 +207,28 @@ public function testARenamesPostReadShowsItsLinksIntoItsOwnSubtreeAtTheirNewDns( ); } + public function testARenamedMembersPostReadCarriesItsBackLinks(): void + { + $member = $this->seedReferencedMember('link-post-member'); + $group = $this->seedGroup( + 'link-post-group', + $member, + ); + + $response = $this->asAdmin(fn(LdapClient $admin): LdapMessageResponse => $admin->sendAndReceive( + Operations::rename( + $member, + 'cn=link-post-member-renamed', + ), + Controls::postRead('memberOf'), + )); + + self::assertSame( + [$group], + $this->postReadOf($response)?->get('memberOf')?->getValues(), + ); + } + private function seedLinkedToItselfAndRenamed( string $cn, string $newRdn, diff --git a/tests/integration/Storage/Concern/Query/SearchLimitTestsTrait.php b/tests/integration/Storage/Concern/Query/SearchLimitTestsTrait.php index 477e1658..4a1ca700 100644 --- a/tests/integration/Storage/Concern/Query/SearchLimitTestsTrait.php +++ b/tests/integration/Storage/Concern/Query/SearchLimitTestsTrait.php @@ -51,6 +51,29 @@ public function testAFilterEvaluatedInPhpTripsTheLookthroughLimit(): void ); } + public function testTheAbsoluteFalseLooksThroughNoEntries(): void + { + $this->stopServer(); + $this->createServerProcess( + 'tcp', + [ + ...static::storageExtraArgs(), + '--seed-entries=10', + '--max-search-lookthrough=3', + ], + ); + $this->authenticateUser(); + + self::assertCount( + 0, + $this->ldapClient()->search( + Operations::search(Filters::or()) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + ), + ); + } + public function testAnIndexAnsweredFilterAlsoTripsTheLookthroughLimit(): void { $this->stopServer(); diff --git a/tests/integration/Storage/Concern/Write/ReadEntryControlTestsTrait.php b/tests/integration/Storage/Concern/Write/ReadEntryControlTestsTrait.php index a6e402b6..fd05f2c9 100644 --- a/tests/integration/Storage/Concern/Write/ReadEntryControlTestsTrait.php +++ b/tests/integration/Storage/Concern/Write/ReadEntryControlTestsTrait.php @@ -16,12 +16,16 @@ use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Control\ReadEntry\PostReadResponseControl; use FreeDSx\Ldap\Control\ReadEntry\PreReadResponseControl; +use FreeDSx\Ldap\Control\ReadEntry\ReadEntryResponseControl; use FreeDSx\Ldap\Controls; use FreeDSx\Ldap\Entry\Change; use FreeDSx\Ldap\Entry\Entry; use FreeDSx\Ldap\Operations; +use FreeDSx\Ldap\Protocol\LdapMessageResponse; use PHPUnit\Framework\Attributes\DataProvider; +use function array_values; + /** * The pre-read and post-read controls (RFC 4527): the entry as a write found it and as it left it. */ @@ -238,4 +242,194 @@ public function testThePreReadOfASubtreeDeleteIsTheBaseWithItsSubordinates(): vo $this->authenticateUser(); self::assertNull($this->ldapClient()->read('cn=child,ou=pre-read-tree,dc=foo,dc=bar')); } + + /** + * @return iterable}> + */ + public static function backlinkSelections(): iterable + { + yield 'named' => [['memberOf']]; + yield 'operational wildcard' => [['+']]; + } + + /** + * @param list $attributes + */ + #[DataProvider('backlinkSelections')] + public function testThePreReadAndPostReadCarryTheBackLinksTheySelect(array $attributes): void + { + $this->authenticateAdmin(); + $member = 'cn=read-member,dc=foo,dc=bar'; + $group = 'cn=read-group,dc=foo,dc=bar'; + $this->ldapClient()->create(Entry::fromArray( + $member, + [ + 'objectClass' => ['inetOrgPerson'], + 'cn' => ['read-member'], + 'sn' => ['Member'], + ], + )); + $this->ldapClient()->create(Entry::fromArray( + $group, + [ + 'objectClass' => ['groupOfNames'], + 'cn' => ['read-group'], + 'member' => [$member, 'cn=user,dc=foo,dc=bar'], + ], + )); + + $modify = $this->ldapClient()->sendAndReceive( + Operations::modify( + $member, + Change::replace( + 'sn', + 'Changed', + ), + ), + Controls::preRead(...$attributes), + Controls::postRead(...$attributes), + ); + $delete = $this->ldapClient()->sendAndReceive( + Operations::delete($member), + Controls::preRead(...$attributes), + ); + $this->ldapClient()->delete($group); + + self::assertSame( + [[$group], [$group], [$group]], + [ + $this->readEntryValues( + $modify, + Control::OID_PRE_READ, + 'memberOf', + ), + $this->readEntryValues( + $modify, + Control::OID_POST_READ, + 'memberOf', + ), + $this->readEntryValues( + $delete, + Control::OID_PRE_READ, + 'memberOf', + ), + ], + ); + } + + public function testAPostReadCarriesTheBackLinkAWriteGivesItsOwnEntry(): void + { + $this->authenticateAdmin(); + $group = 'cn=read-self,dc=foo,dc=bar'; + + $add = $this->ldapClient()->sendAndReceive( + Operations::add(Entry::fromArray( + $group, + [ + 'objectClass' => ['groupOfNames'], + 'cn' => ['read-self'], + 'member' => [$group, 'cn=user,dc=foo,dc=bar'], + ], + )), + Controls::postRead('memberOf'), + ); + $modify = $this->ldapClient()->sendAndReceive( + Operations::modify( + $group, + Change::delete( + 'member', + $group, + ), + ), + Controls::preRead('memberOf'), + Controls::postRead('memberOf'), + ); + $this->ldapClient()->delete($group); + + self::assertSame( + [[$group], [$group], null], + [ + $this->readEntryValues( + $add, + Control::OID_POST_READ, + 'memberOf', + ), + $this->readEntryValues( + $modify, + Control::OID_PRE_READ, + 'memberOf', + ), + $this->readEntryValues( + $modify, + Control::OID_POST_READ, + 'memberOf', + ), + ], + ); + } + + /** + * @return iterable}> + */ + public static function groupRemovals(): iterable + { + yield 'delete' => [[]]; + yield 'subtree delete' => [[Controls::subtreeDelete()]]; + } + + /** + * @param list $controls + */ + #[DataProvider('groupRemovals')] + public function testThePreReadOfARemovedGroupCarriesItsMembers(array $controls): void + { + $this->authenticateAdmin(); + $group = 'cn=read-removed,dc=foo,dc=bar'; + $members = [ + 'cn=user,dc=foo,dc=bar', + 'cn=admin,dc=foo,dc=bar', + ]; + $this->ldapClient()->create(Entry::fromArray( + $group, + [ + 'objectClass' => ['groupOfNames'], + 'cn' => ['read-removed'], + 'member' => $members, + ], + )); + + $response = $this->ldapClient()->sendAndReceive( + Operations::delete($group), + Controls::preRead('member'), + ...$controls, + ); + + self::assertEqualsCanonicalizing( + $members, + $this->readEntryValues( + $response, + Control::OID_PRE_READ, + 'member', + ), + ); + } + + /** + * @return list|null + */ + private function readEntryValues( + LdapMessageResponse $response, + string $oid, + string $attribute, + ): ?array { + $control = $response->controls()->get($oid); + + $values = $control instanceof ReadEntryResponseControl + ? $control->getEntry()->get($attribute)?->getValues() + : null; + + return $values === null + ? null + : array_values($values); + } } diff --git a/tests/integration/Sync/SyncReplNativeTest.php b/tests/integration/Sync/SyncReplNativeTest.php index 7c981e32..70596724 100644 --- a/tests/integration/Sync/SyncReplNativeTest.php +++ b/tests/integration/Sync/SyncReplNativeTest.php @@ -15,6 +15,7 @@ use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Control\Sync\SyncRequestControl; +use FreeDSx\Ldap\Controls; use FreeDSx\Ldap\Entry\Attribute; use FreeDSx\Ldap\Entry\Change; use FreeDSx\Ldap\Entry\Entry; @@ -28,6 +29,7 @@ use FreeDSx\Ldap\Search\Filters; use FreeDSx\Ldap\Sync\Result\SyncEntryResult; use FreeDSx\Ldap\Sync\SyncRepl; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\Integration\FreeDSx\Ldap\ServerTestCase; use Tests\Support\FreeDSx\Ldap\RawClientQueueTrait; @@ -131,6 +133,98 @@ public function testTheSyncDoneControlIsSentAsNonCritical(): void } } + /** + * @return iterable + */ + public static function filterMatchingNothingProvider(): iterable + { + yield 'the absolute false' => [Filters::or()]; + yield 'a filter on a withheld attribute' => [Filters::present('userPassword')]; + } + + #[DataProvider('filterMatchingNothingProvider')] + public function testARefreshMatchingNothingStillEndsWithTheSyncDoneControl(FilterInterface $filter): void + { + $queue = $this->boundRawQueue(); + + try { + $queue->sendMessage(new LdapMessageRequest( + 2, + Operations::search($filter) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + new SyncRequestControl(), + )); + do { + $message = $queue->getMessage(2); + } while (!$message->getResponse() instanceof SearchResultDone); + + self::assertNotNull($message->controls()->get(Control::OID_SYNC_DONE)); + } finally { + $queue->close(); + } + } + + /** + * @return iterable + */ + public static function assertionProvider(): iterable + { + yield 'a critical assertion that fails' => [ + Controls::assertion(Filters::equal( + 'dc', + 'nope', + )), + ResultCode::ASSERTION_FAILED, + ]; + yield 'a critical assertion that holds' => [ + Controls::assertion(Filters::equal( + 'dc', + 'foo', + )), + ResultCode::SUCCESS, + ]; + yield 'a non-critical assertion that fails' => [ + Controls::assertion( + Filters::equal( + 'dc', + 'nope', + ), + false, + ), + ResultCode::ASSERTION_FAILED, + ]; + } + + #[DataProvider('assertionProvider')] + public function testASyncSearchHonorsTheAssertionControl( + Control $assertion, + int $resultCode, + ): void { + $queue = $this->boundRawQueue(); + + try { + $queue->sendMessage(new LdapMessageRequest( + 2, + Operations::search(Filters::present('objectClass')) + ->base('dc=foo,dc=bar') + ->useSubtreeScope(), + new SyncRequestControl(), + $assertion, + )); + do { + $message = $queue->getMessage(2); + } while (!$message->getResponse() instanceof SearchResultDone); + + self::assertSame( + $resultCode, + $message->getResponse()->getResultCode(), + ); + } finally { + $queue->close(); + } + } + public function testAPollWithAFilterOnlyStreamsMatchingEntries(): void { $this->authenticateUser(); diff --git a/tests/unit/Protocol/Bind/Sasl/SaslExchangeTest.php b/tests/unit/Protocol/Bind/Sasl/SaslExchangeTest.php index ccad0b0f..a6ee8bdd 100644 --- a/tests/unit/Protocol/Bind/Sasl/SaslExchangeTest.php +++ b/tests/unit/Protocol/Bind/Sasl/SaslExchangeTest.php @@ -15,6 +15,7 @@ use FreeDSx\Ldap\Entry\Dn; use FreeDSx\Ldap\Exception\MessageDecodeException; +use FreeDSx\Ldap\Exception\RequestRefusedException; use FreeDSx\Ldap\Exception\OperationException; use FreeDSx\Ldap\Exception\ProtocolException; use FreeDSx\Ldap\Exception\SaslNegotiationAbortedException; @@ -630,6 +631,66 @@ public function test_an_abandon_mid_exchange_is_ignored(): void ); } + /** + * @return iterable + */ + public static function noResponseOperationTags(): iterable + { + yield 'an abandon' => [16]; + yield 'an unbind' => [2]; + } + + #[DataProvider('noResponseOperationTags')] + public function test_a_request_with_no_response_refused_for_room_mid_exchange_is_passed_over( + int $operationTag, + ): void { + $this->mockChallenge + ->method('challenge') + ->willReturnOnConsecutiveCalls( + $this->makeContext( + isComplete: false, + response: 'server-challenge', + ), + $this->makeContext( + isComplete: true, + response: 'server-final', + ), + ); + + $this->mockQueue + ->expects(self::once()) + ->method('sendMessage'); + + $reads = 0; + $this->mockQueue + ->method('getMessage') + ->willReturnCallback(static function () use (&$reads, $operationTag): LdapMessageRequest { + if ($reads++ === 0) { + throw new RequestRefusedException( + 2, + $operationTag, + 'The request is larger than the server will hold.', + resultCode: ResultCode::ADMIN_LIMIT_EXCEEDED, + ); + } + + return new LdapMessageRequest( + 3, + new SaslBindRequest( + self::MECH, + 'creds', + ), + ); + }); + + $result = $this->subject->run($this->makeInput()); + + self::assertSame( + 3, + $result->getLastMessage()->getMessageId(), + ); + } + public function test_it_rejects_an_abandon_carrying_a_zero_message_id(): void { $this->mockChallenge diff --git a/tests/unit/Protocol/DecodeFailureResponderTest.php b/tests/unit/Protocol/DecodeFailureResponderTest.php index 05fadba1..f5198162 100644 --- a/tests/unit/Protocol/DecodeFailureResponderTest.php +++ b/tests/unit/Protocol/DecodeFailureResponderTest.php @@ -17,6 +17,7 @@ use FreeDSx\Ldap\Exception\RequestRefusedException; use FreeDSx\Ldap\Operation\Response\SearchResultDone; use FreeDSx\Ldap\Operation\ResultCode; +use FreeDSx\Ldap\Protocol\DecodeFailureOutcome; use FreeDSx\Ldap\Protocol\DecodeFailureResponder; use FreeDSx\Ldap\Protocol\LdapMessageResponse; use FreeDSx\Ldap\Protocol\Queue\ServerQueue; @@ -71,12 +72,15 @@ public function test_a_request_refused_for_room_is_answered_with_its_result_code ), ))); - self::assertTrue($this->subject->answer(new RequestRefusedException( - 3, - 3, - 'The server is too busy to hold the request.', - resultCode: ResultCode::BUSY, - ))); + self::assertSame( + DecodeFailureOutcome::Answered, + $this->subject->answer(new RequestRefusedException( + 3, + 3, + 'The server is too busy to hold the request.', + resultCode: ResultCode::BUSY, + )), + ); } public function test_a_request_refused_for_room_is_recorded_as_a_refused_operation(): void @@ -114,7 +118,7 @@ public function test_a_request_with_no_response_refused_for_room_is_recorded_and ->method('sendMessage'); self::assertSame( - [true, [ServerEvent::OperationRefused->value]], + [DecodeFailureOutcome::Dropped, [ServerEvent::OperationRefused->value]], [ $this->subject->answer(new RequestRefusedException( 3, @@ -134,11 +138,14 @@ public function test_a_malformed_request_with_no_response_is_not_answered(int $o ->expects(self::never()) ->method('sendMessage'); - self::assertFalse($this->subject->answer(new MessageDecodeException( - 3, - $operationTag, - 'The request is malformed.', - ))); + self::assertSame( + DecodeFailureOutcome::Unanswerable, + $this->subject->answer(new MessageDecodeException( + 3, + $operationTag, + 'The request is malformed.', + )), + ); } public function test_a_malformed_request_is_recorded_as_a_decode_failure(): void @@ -168,11 +175,14 @@ public function test_a_malformed_request_is_answered_on_its_message_id(): void ), ))); - self::assertTrue($this->subject->answer(new MessageDecodeException( - 3, - 3, - 'The search request is malformed.', - ))); + self::assertSame( + DecodeFailureOutcome::Answered, + $this->subject->answer(new MessageDecodeException( + 3, + 3, + 'The search request is malformed.', + )), + ); } public function test_a_malformed_request_carrying_message_id_zero_is_not_answered(): void @@ -181,11 +191,14 @@ public function test_a_malformed_request_carrying_message_id_zero_is_not_answere ->expects(self::never()) ->method('sendMessage'); - self::assertFalse($this->subject->answer(new MessageDecodeException( - 0, - 3, - 'The search request is malformed.', - ))); + self::assertSame( + DecodeFailureOutcome::Unanswerable, + $this->subject->answer(new MessageDecodeException( + 0, + 3, + 'The search request is malformed.', + )), + ); } public function test_a_bind_that_fails_to_decode_leaves_the_session_anonymous(): void diff --git a/tests/unit/Protocol/Decoder/RequestMessageDecoderTest.php b/tests/unit/Protocol/Decoder/RequestMessageDecoderTest.php index 899a8d28..6f9e8a92 100644 --- a/tests/unit/Protocol/Decoder/RequestMessageDecoderTest.php +++ b/tests/unit/Protocol/Decoder/RequestMessageDecoderTest.php @@ -28,6 +28,8 @@ use FreeDSx\Ldap\Exception\MessageDecodeException; use FreeDSx\Ldap\Exception\ProtocolException; use FreeDSx\Ldap\Operation\Request\DeleteRequest; +use FreeDSx\Ldap\Operation\Request\RequestInterface; +use FreeDSx\Ldap\Operation\Request\SearchRequest; use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Operations; use FreeDSx\Ldap\Protocol\Decoder\DecodeContext; @@ -56,7 +58,7 @@ public function testItDecodesTheRequestAndItsControls(): void { $message = $this->subject->decode(self::received(new LdapMessageRequest( 2, - new DeleteRequest('dc=foo,dc=bar'), + Operations::search(Filters::present('objectClass'))->base('dc=foo,dc=bar'), new PagingControl( 10, 'cookie', @@ -69,13 +71,83 @@ public function testItDecodesTheRequestAndItsControls(): void [2, 'dc=foo,dc=bar', 10, 'cookie'], [ $message->getMessageId(), - $message->getRequest() instanceof DeleteRequest ? $message->getRequest()->getDn()->toString() : null, + $message->getRequest() instanceof SearchRequest ? (string) $message->getRequest()->getBaseDn() : null, $paging?->getSize(), $paging?->getCookie(), ], ); } + #[DataProvider('controlsTheOperationDoesNotTake')] + public function testAMalformedControlTheOperationDoesNotTakeIsLeftGeneric( + RequestInterface $request, + string $oid, + ): void { + $message = $this->subject->decode(self::received(new LdapMessageRequest( + 2, + $request, + new Control( + $oid, + true, + "\x01\x02\x03", + ), + ))); + + self::assertSame( + Control::class, + get_debug_type($message->controls()->get($oid)), + ); + } + + /** + * @return iterable + */ + public static function controlsTheOperationDoesNotTake(): iterable + { + yield 'paging on a compare' => [ + Operations::compare( + 'dc=foo,dc=bar', + 'dc', + 'foo', + ), + Control::OID_PAGING, + ]; + yield 'paging on a delete' => [ + new DeleteRequest('dc=foo,dc=bar'), + Control::OID_PAGING, + ]; + yield 'pre-read on a bind' => [ + Operations::bind( + 'cn=user,dc=foo,dc=bar', + '12345', + ), + Control::OID_PRE_READ, + ]; + yield 'proxied authorization on a bind' => [ + Operations::bind( + 'cn=user,dc=foo,dc=bar', + '12345', + ), + Control::OID_PROXY_AUTHORIZATION, + ]; + yield 'post-read on a delete' => [ + new DeleteRequest('dc=foo,dc=bar'), + Control::OID_POST_READ, + ]; + yield 'paging on an abandon' => [ + Operations::abandon(1), + Control::OID_PAGING, + ]; + yield 'paging on an unbind' => [ + Operations::unbind(), + Control::OID_PAGING, + ]; + yield 'paging on an extended operation' => [ + Operations::whoami(), + Control::OID_PAGING, + ]; + } + public function testItLeavesThePasswordPolicyControlGenericOnARequest(): void { $message = $this->subject->decode(self::received(new LdapMessageRequest( @@ -214,7 +286,7 @@ public function testAFailureInsideAControlNamesTheMessageItBelongsTo(): void { $e = $this->decodeFailureOf(self::received(new LdapMessageRequest( 7, - new DeleteRequest('dc=foo,dc=bar'), + Operations::search(Filters::present('objectClass'))->base('dc=foo,dc=bar'), new Control( Control::OID_PAGING, false, @@ -223,7 +295,7 @@ public function testAFailureInsideAControlNamesTheMessageItBelongsTo(): void ))); self::assertSame( - [7, 10, ResultCode::PROTOCOL_ERROR], + [7, 3, ResultCode::PROTOCOL_ERROR], [$e->getMessageId(), $e->getProtocolOpTag(), $e->getResultCode()], ); } diff --git a/tests/unit/Protocol/Queue/ReadAheadBufferTest.php b/tests/unit/Protocol/Queue/ReadAheadBufferTest.php index 513078ec..6f26c6a1 100644 --- a/tests/unit/Protocol/Queue/ReadAheadBufferTest.php +++ b/tests/unit/Protocol/Queue/ReadAheadBufferTest.php @@ -100,6 +100,31 @@ public function test_its_bytes_are_forgotten_only_once_it_empties(): void self::assertFalse($this->subject->isFull()); } + public function test_it_is_empty_until_a_message_is_held(): void + { + self::assertTrue($this->subject->isEmpty()); + + $this->subject->append(self::message(1)); + + self::assertFalse($this->subject->isEmpty()); + } + + public function test_clearing_it_drops_every_message_and_the_bytes_counted_for_them(): void + { + $this->subject->append( + self::message(1), + 65_536, + ); + $this->subject->prepend(self::message(2)); + + $this->subject->clear(); + + self::assertSame( + [true, false, null], + [$this->subject->isEmpty(), $this->subject->isFull(), $this->subject->take()], + ); + } + private static function message(int $messageId): LdapMessageRequest { return new LdapMessageRequest( diff --git a/tests/unit/Protocol/Queue/ServerQueueTest.php b/tests/unit/Protocol/Queue/ServerQueueTest.php index 20ee4e88..9292e143 100644 --- a/tests/unit/Protocol/Queue/ServerQueueTest.php +++ b/tests/unit/Protocol/Queue/ServerQueueTest.php @@ -533,7 +533,7 @@ public function test_a_decoded_request_counts_the_elements_of_its_nested_parts() self::assertSame( HeldRequests::estimate( strlen($request), - 10, + 18, ), $this->budget->held(), ); @@ -1068,6 +1068,39 @@ public function test_encrypt_discards_plaintext_pipelined_behind_the_upgrade(): $queue->getMessage(); } + public function test_encrypt_discards_requests_read_ahead_behind_the_upgrade(): void + { + $queue = $this->queueReading([self::encodedDelete(5)]); + $queue->peekForCancelSignal(2); + + self::assertTrue($queue->hasBufferedInput()); + + $queue->encrypt(); + + self::assertFalse($queue->hasBufferedInput()); + + $this->expectException(ConnectionException::class); + + $queue->getMessage(); + } + + public function test_a_request_read_ahead_and_discarded_by_the_upgrade_releases_what_it_held(): void + { + $queue = $this->queueReading( + [self::encodedDelete(5)], + heldSize: 100_000, + ); + $queue->peekForCancelSignal(2); + $held = $this->budget->held(); + + $queue->encrypt(); + + self::assertSame( + [true, 0], + [$held > 0, $this->budget->held()], + ); + } + public function test_it_writes_a_message_larger_than_the_send_buffer_without_an_oversized_write(): void { $encoder = new LdapEncoder(); @@ -1289,7 +1322,7 @@ public function test_it_should_answer_a_request_whose_nested_parts_run_past_what [self::encodedSortRequest()], new RequestLimits( authorization: $this->authorization, - maxElements: 9, + maxElements: 17, ), ); @@ -1310,7 +1343,7 @@ public function test_it_should_decode_a_request_whose_nested_parts_fit_what_the_ [self::encodedSortRequest()], new RequestLimits( authorization: $this->authorization, - maxElements: 10, + maxElements: 18, ), ); @@ -1827,7 +1860,7 @@ private static function encodedSortRequest(): string { return (new LdapEncoder())->encode((new LdapMessageRequest( 5, - new DeleteRequest('dc=foo,dc=bar'), + Operations::search(Filters::present('cn'))->base('dc=foo,dc=bar'), new SortingControl( new SortKey('cn'), new SortKey('sn'), diff --git a/tests/unit/Protocol/ServerProtocolHandler/ServerDispatchHandlerTest.php b/tests/unit/Protocol/ServerProtocolHandler/ServerDispatchHandlerTest.php index c538300f..f96e3331 100644 --- a/tests/unit/Protocol/ServerProtocolHandler/ServerDispatchHandlerTest.php +++ b/tests/unit/Protocol/ServerProtocolHandler/ServerDispatchHandlerTest.php @@ -25,6 +25,7 @@ use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; use FreeDSx\Ldap\Server\Backend\Storage\Filter\FilterEvaluatorInterface; use FreeDSx\Ldap\Server\Backend\Storage\Filter\LinkedLeafWitness; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; use FreeDSx\Ldap\Server\Backend\Storage\Schema\LinkedAttributes; use FreeDSx\Ldap\Server\Backend\Write\WriteContext; use FreeDSx\Ldap\Entry\Entry; @@ -88,6 +89,10 @@ protected function setUp(): void $this->fromContainer(AssertionControlDecoder::class), ), derived: new DerivedResolver($this->createMock(ReadEntryInterface::class)), + backlinks: new BacklinkReader( + $this->createMock(ReadEntryInterface::class), + (new LinkedAttributes(new Schema()))->backlinks(), + ), readEntryControlHandler: new ReadEntryControlHandler( new Schema(), $this->mockAccessControl, diff --git a/tests/unit/Search/FiltersTest.php b/tests/unit/Search/FiltersTest.php index 1650f944..c3008f57 100644 --- a/tests/unit/Search/FiltersTest.php +++ b/tests/unit/Search/FiltersTest.php @@ -163,4 +163,17 @@ public function test_it_should_create_a_filter_from_a_raw_string_filter(): void Filters::raw('(foo=*)'), ); } + + public function test_only_an_empty_or_is_the_absolute_false(): void + { + self::assertSame( + [true, false, false, false], + [ + Filters::isAbsoluteFalse(Filters::or()), + Filters::isAbsoluteFalse(Filters::or(Filters::present('cn'))), + Filters::isAbsoluteFalse(Filters::and()), + Filters::isAbsoluteFalse(Filters::not(Filters::or())), + ], + ); + } } diff --git a/tests/unit/Server/AccessControl/WithheldFilterRewriterTest.php b/tests/unit/Server/AccessControl/WithheldFilterRewriterTest.php index 75848ded..ecb54c42 100644 --- a/tests/unit/Server/AccessControl/WithheldFilterRewriterTest.php +++ b/tests/unit/Server/AccessControl/WithheldFilterRewriterTest.php @@ -50,21 +50,21 @@ public function test_an_assertion_on_a_withheld_attribute_collapses_to_absolute_ { $rewritten = $this->rewrite(Filters::equal('userPassword', 'secret')); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_a_substring_assertion_on_a_withheld_attribute_collapses_to_absolute_false(): void { $rewritten = $this->rewrite(Filters::startsWith('userPassword', '{SHA}a')); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_a_presence_assertion_on_a_withheld_attribute_collapses_to_absolute_false(): void { $rewritten = $this->rewrite(Filters::present('userPassword')); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_a_conjunction_containing_a_withheld_assertion_collapses_to_absolute_false(): void @@ -74,7 +74,7 @@ public function test_a_conjunction_containing_a_withheld_assertion_collapses_to_ Filters::equal('userPassword', 'secret'), )); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_a_disjunction_drops_the_withheld_assertion_and_keeps_the_rest(): void @@ -112,7 +112,7 @@ public function test_a_disjunction_of_only_withheld_assertions_collapses_to_abso Filters::present('userPassword'), )); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_negating_a_withheld_assertion_matches_every_entry(): void @@ -134,7 +134,7 @@ public function test_an_attribute_option_does_not_evade_the_rewrite(): void { $rewritten = $this->rewrite(Filters::equal('userPassword;binary', 'secret')); - self::assertTrue($this->subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_an_assertion_on_a_filter_denied_attribute_collapses_to_absolute_false(): void @@ -146,7 +146,7 @@ public function test_an_assertion_on_a_filter_denied_attribute_collapses_to_abso $this->token, ); - self::assertTrue($subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } /** @@ -176,7 +176,7 @@ public function test_a_filter_deny_covers_a_derived_attribute(): void $this->token, ); - self::assertTrue($subject->isAbsoluteFalse($rewritten)); + self::assertTrue(Filters::isAbsoluteFalse($rewritten)); } public function test_a_filter_deny_leaves_every_other_attribute_alone(): void diff --git a/tests/unit/Server/Backend/Storage/Adapter/SqliteFilterTranslatorTest.php b/tests/unit/Server/Backend/Storage/Adapter/SqliteFilterTranslatorTest.php index a51a86de..79ce9967 100644 --- a/tests/unit/Server/Backend/Storage/Adapter/SqliteFilterTranslatorTest.php +++ b/tests/unit/Server/Backend/Storage/Adapter/SqliteFilterTranslatorTest.php @@ -180,6 +180,26 @@ public function test_or_composes_correlated_exists_with_or(): void ); } + public function test_an_empty_or_is_the_absolute_false_and_exact(): void + { + $result = $this->subject->translate(new OrFilter()); + + self::assertSame( + ['1 = 0', true], + [$result?->sql, $result?->isExact], + ); + } + + public function test_negating_an_empty_or_selects_every_row_exactly(): void + { + $result = $this->subject->translate(new NotFilter(new OrFilter())); + + self::assertSame( + ['NOT (1 = 0)', true], + [$result?->sql, $result?->isExact], + ); + } + public function test_not_value_correlated_sql_negates_the_value_exists(): void { $result = $this->subject->translate(new NotFilter( diff --git a/tests/unit/Server/Backend/Storage/Link/BacklinkReaderTest.php b/tests/unit/Server/Backend/Storage/Link/BacklinkReaderTest.php new file mode 100644 index 00000000..53b859b4 --- /dev/null +++ b/tests/unit/Server/Backend/Storage/Link/BacklinkReaderTest.php @@ -0,0 +1,167 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Tests\Unit\FreeDSx\Ldap\Server\Backend\Storage\Link; + +use FreeDSx\Ldap\Entry\Attribute; +use FreeDSx\Ldap\Entry\Dn; +use FreeDSx\Ldap\Entry\Entry; +use FreeDSx\Ldap\Server\Backend\Storage\Contract\ReadEntryInterface; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; +use FreeDSx\Ldap\Server\Backend\Storage\Schema\LinkedAttributes; +use FreeDSx\Ldap\Server\Backend\Storage\Search\EntryProjection; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Tests\Support\FreeDSx\Ldap\ServerContainerTrait; + +final class BacklinkReaderTest extends TestCase +{ + use ServerContainerTrait; + + private const ALICE = 'cn=Alice,dc=foo,dc=bar'; + + private const ADMINS = 'cn=Admins,dc=foo,dc=bar'; + + private ReadEntryInterface&MockObject $storage; + + private BacklinkReader $subject; + + private Entry $entry; + + protected function setUp(): void + { + $this->storage = $this->createMock(ReadEntryInterface::class); + $this->subject = new BacklinkReader( + $this->storage, + $this->fromContainer(LinkedAttributes::class)->backlinks(), + 25, + ); + $this->entry = Entry::fromArray( + self::ALICE, + ['cn' => ['Alice']], + ); + } + + public function test_it_reads_the_back_links_a_selection_names_under_the_link_cap(): void + { + $this->storage + ->expects(self::once()) + ->method('find') + ->with( + self::callback(static fn(Dn $dn): bool => $dn->toString() === self::ALICE), + self::callback(static fn(EntryProjection $projection): bool => $projection->backlinks === ['memberof'] + && $projection->linkCap === 25), + ) + ->willReturn(Entry::fromArray( + self::ALICE, + [ + 'cn' => ['Stored'], + 'memberOf' => [self::ADMINS], + ], + )); + + $entry = $this->subject->withSelected( + $this->entry, + [new Attribute('memberOf')], + ); + + self::assertSame( + [['Alice'], [self::ADMINS]], + [ + $entry->get('cn')?->getValues(), + $entry->get('memberOf')?->getValues(), + ], + ); + } + + public function test_it_reads_every_back_link_under_the_operational_wildcard(): void + { + $this->storage + ->expects(self::once()) + ->method('find') + ->with( + self::anything(), + self::callback(static fn(EntryProjection $projection): bool => $projection->backlinks === ['memberof']), + ) + ->willReturn(Entry::fromArray( + self::ALICE, + ['memberOf' => [self::ADMINS]], + )); + + self::assertSame( + [self::ADMINS], + $this->subject + ->withSelected( + $this->entry, + [new Attribute('+')], + ) + ->get('memberOf') + ?->getValues(), + ); + } + + public function test_it_keeps_a_back_link_cut_to_the_cap_under_its_range(): void + { + $this->storage + ->method('find') + ->willReturn(Entry::fromArray( + self::ALICE, + ['memberOf;range=0-24' => [self::ADMINS]], + )); + + self::assertSame( + [self::ADMINS], + $this->subject + ->withSelected( + $this->entry, + [new Attribute('memberOf')], + ) + ->get( + 'memberOf;range=0-24', + true, + ) + ?->getValues(), + ); + } + + public function test_it_reads_nothing_for_a_selection_naming_no_back_link(): void + { + $this->storage + ->expects(self::never()) + ->method('find'); + + self::assertNull($this->subject + ->withSelected( + $this->entry, + [ + new Attribute('cn'), + new Attribute('*'), + ], + ) + ->get('memberOf')); + } + + public function test_an_entry_no_longer_stored_gains_no_back_link(): void + { + $this->storage + ->method('find') + ->willReturn(null); + + self::assertNull($this->subject + ->withSelected( + $this->entry, + [new Attribute('memberOf')], + ) + ->get('memberOf')); + } +} diff --git a/tests/unit/Server/Backend/StorageReadBackendTest.php b/tests/unit/Server/Backend/StorageReadBackendTest.php index 13120f9e..a33c6e21 100644 --- a/tests/unit/Server/Backend/StorageReadBackendTest.php +++ b/tests/unit/Server/Backend/StorageReadBackendTest.php @@ -20,6 +20,7 @@ use FreeDSx\Ldap\Operation\Request\SearchRequest; use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Search\Filter\EqualityFilter; +use FreeDSx\Ldap\Search\Filter\OrFilter; use FreeDSx\Ldap\Search\Filter\PresentFilter; use FreeDSx\Ldap\Server\Backend\Storage\Adapter\InMemoryStorage; use FreeDSx\Ldap\Server\Backend\Storage\Contract\ListEntryInterface; @@ -252,6 +253,57 @@ public function test_search_subtree_throws_no_such_object_when_base_does_not_exi $this->subject->search($request, SubentryVisibility::All); } + public function test_an_absolute_false_search_returns_nothing_without_listing_storage(): void + { + $lister = $this->createMock(ListEntryInterface::class); + $lister->expects(self::never()) + ->method('list'); + $request = (new SearchRequest(new OrFilter())) + ->base('dc=example,dc=com') + ->useSubtreeScope(); + + $stream = $this->backendOver($lister)->search( + $request, + SubentryVisibility::All, + ); + + self::assertSame( + [], + iterator_to_array($stream->entries()), + ); + } + + public function test_an_absolute_false_search_still_needs_its_base_to_exist(): void + { + self::expectException(OperationException::class); + self::expectExceptionCode(ResultCode::NO_SUCH_OBJECT); + + $request = (new SearchRequest(new OrFilter())) + ->base('cn=Missing,dc=example,dc=com') + ->useSubtreeScope(); + $this->subject->search( + $request, + SubentryVisibility::All, + ); + } + + public function test_an_absolute_false_search_still_refuses_a_range_it_cannot_serve(): void + { + self::expectException(OperationException::class); + self::expectExceptionCode(ResultCode::UNWILLING_TO_PERFORM); + + $request = (new SearchRequest( + new OrFilter(), + 'cn;range=0-5', + )) + ->base('dc=example,dc=com') + ->useSubtreeScope(); + $this->subject->search( + $request, + SubentryVisibility::All, + ); + } + public function test_search_converts_time_limit_exception_to_operation_exception(): void { $lister = $this->createMock(ListEntryInterface::class); diff --git a/tests/unit/Server/Backend/Write/Operation/TransactionalEntryWriteTest.php b/tests/unit/Server/Backend/Write/Operation/TransactionalEntryWriteTest.php new file mode 100644 index 00000000..ef809f81 --- /dev/null +++ b/tests/unit/Server/Backend/Write/Operation/TransactionalEntryWriteTest.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Tests\Unit\FreeDSx\Ldap\Server\Backend\Write\Operation; + +use FreeDSx\Ldap\Control\ControlBag; +use FreeDSx\Ldap\Control\ReadEntry\PreReadControl; +use FreeDSx\Ldap\Entry\Dn; +use FreeDSx\Ldap\Entry\Entry; +use FreeDSx\Ldap\Protocol\ServerProtocolHandler\AssertionEvaluator; +use FreeDSx\Ldap\Server\Backend\Storage\Contract\ReadEntryInterface; +use FreeDSx\Ldap\Server\Backend\Storage\Search\EntryProjection; +use FreeDSx\Ldap\Server\Backend\Write\Operation\TransactionalEntryWrite; +use FreeDSx\Ldap\Server\Backend\Write\WriteContext; +use FreeDSx\Ldap\Server\Backend\Write\WriteControlEvaluator; +use FreeDSx\Ldap\Server\Token\AnonToken; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Tests\Support\FreeDSx\Ldap\ServerContainerTrait; + +final class TransactionalEntryWriteTest extends TestCase +{ + use ServerContainerTrait; + + private const GROUP = 'cn=Admins,dc=example,dc=com'; + + private ReadEntryInterface&MockObject $reader; + + private AssertionEvaluator $assertions; + + private TransactionalEntryWrite $subject; + + protected function setUp(): void + { + $this->reader = $this->createMock(ReadEntryInterface::class); + $this->assertions = $this->fromContainer(AssertionEvaluator::class); + $this->subject = $this->fromContainer( + TransactionalEntryWrite::class, + [ReadEntryInterface::class => $this->reader], + ); + } + + public function test_a_delete_a_control_reads_loads_every_link_of_its_target(): void + { + $this->expectTargetReadWithLinkCap(null); + $controls = new ControlBag(new PreReadControl('member')); + + $this->subject->delete( + new Dn(self::GROUP), + new WriteContext( + new AnonToken(), + $controls, + controlEvaluator: new WriteControlEvaluator( + $this->assertions, + new AnonToken(), + $controls, + ), + ), + static function (): void {}, + ); + } + + public function test_a_delete_no_control_reads_leaves_the_links_of_its_target_unread(): void + { + $this->expectTargetReadWithLinkCap(0); + + $this->subject->delete( + new Dn(self::GROUP), + new WriteContext( + new AnonToken(), + new ControlBag(), + ), + static function (): void {}, + ); + } + + private function expectTargetReadWithLinkCap(?int $linkCap): void + { + $this->reader + ->expects(self::once()) + ->method('find') + ->with( + self::anything(), + self::callback(static fn(EntryProjection $projection): bool => $projection->linkCap === $linkCap), + ) + ->willReturn(Entry::fromArray( + self::GROUP, + ['cn' => ['Admins']], + )); + } +} diff --git a/tests/unit/Server/Backend/Write/WriteControlEvaluatorTest.php b/tests/unit/Server/Backend/Write/WriteControlEvaluatorTest.php index 002d9f72..70fac14e 100644 --- a/tests/unit/Server/Backend/Write/WriteControlEvaluatorTest.php +++ b/tests/unit/Server/Backend/Write/WriteControlEvaluatorTest.php @@ -32,8 +32,11 @@ use FreeDSx\Ldap\Server\Backend\Storage\Derived\DerivedResolver; use FreeDSx\Ldap\Server\Backend\Storage\Filter\FilterEvaluatorInterface; use FreeDSx\Ldap\Server\Backend\Storage\Filter\LinkedLeafWitness; +use FreeDSx\Ldap\Server\Backend\Storage\Link\BacklinkReader; +use FreeDSx\Ldap\Server\Backend\Storage\Schema\LinkedAttributes; use FreeDSx\Ldap\Server\Backend\Write\WriteControlEvaluator; use FreeDSx\Ldap\Server\Token\BindToken; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Tests\Support\FreeDSx\Ldap\ServerContainerTrait; @@ -108,6 +111,51 @@ public function test_a_post_read_keeps_a_copy_of_the_result(): void ); } + /** + * @param list $controls + */ + #[DataProvider('entryInspections')] + public function test_only_a_control_it_acts_on_inspects_the_entry( + array $controls, + bool $inspects, + ): void { + self::assertSame( + $inspects, + $this->evaluatorFor(...$controls)->inspectsEntry(), + ); + } + + /** + * @return iterable, bool}> + */ + public static function entryInspections(): iterable + { + yield 'an assertion' => [ + [Controls::assertion(Filters::present('cn'))], + true, + ]; + yield 'a pre-read' => [ + [new PreReadControl('cn')], + true, + ]; + yield 'a post-read' => [ + [new PostReadControl('cn')], + true, + ]; + yield 'a post-read the operation does not take' => [ + [new Control( + Control::OID_POST_READ, + false, + "\x01\x02\x03", + )], + false, + ]; + yield 'no control' => [ + [], + false, + ]; + } + public function test_a_post_read_reads_the_result(): void { self::assertTrue($this->evaluatorFor(new PostReadControl('sn'))->readsResult()); @@ -127,7 +175,7 @@ public function test_an_addition_failing_the_assertion_answers_assertion_failed( ->evaluateAddition($this->entry); } - public function test_an_addition_satisfying_the_assertion_is_kept_for_a_post_read(): void + public function test_an_addition_keeps_nothing_for_a_post_read_until_it_is_stored(): void { $subject = $this->evaluatorFor( Controls::assertion(Filters::equal('sn', 'Smith')), @@ -136,9 +184,36 @@ public function test_an_addition_satisfying_the_assertion_is_kept_for_a_post_rea $subject->evaluateAddition($this->entry); + self::assertNull($subject->postReadEntry()); + } + + public function test_a_pre_read_carries_the_back_links_it_names(): void + { + $this->storage + ->method('find') + ->willReturn($this->memberOfAdmins()); + $subject = $this->evaluatorFor(new PreReadControl('memberOf')); + + $subject->evaluateTarget($this->entry); + self::assertSame( - ['Smith'], - $subject->postReadEntry()?->get('sn')?->getValues(), + ['cn=admins,dc=ex,dc=com'], + $subject->preReadEntry()?->get('memberOf')?->getValues(), + ); + } + + public function test_a_post_read_carries_the_back_links_it_names(): void + { + $this->storage + ->method('find') + ->willReturn($this->memberOfAdmins()); + $subject = $this->evaluatorFor(new PostReadControl('memberOf')); + + $subject->captureResult($this->entry); + + self::assertSame( + ['cn=admins,dc=ex,dc=com'], + $subject->postReadEntry()?->get('memberOf')?->getValues(), ); } @@ -239,6 +314,18 @@ private function evaluatorFor(Control ...$controls): WriteControlEvaluator BindToken::fromDn('cn=foo,dc=ex,dc=com'), new ControlBag(...$controls), new DerivedResolver($this->storage), + new BacklinkReader( + $this->storage, + $this->fromContainer(LinkedAttributes::class)->backlinks(), + ), + ); + } + + private function memberOfAdmins(): Entry + { + return Entry::fromArray( + 'cn=foo,dc=ex,dc=com', + ['memberOf' => ['cn=admins,dc=ex,dc=com']], ); } } diff --git a/tests/unit/Server/Middleware/AssertionMiddlewareTest.php b/tests/unit/Server/Middleware/AssertionMiddlewareTest.php index b86d3383..9c8c66ff 100644 --- a/tests/unit/Server/Middleware/AssertionMiddlewareTest.php +++ b/tests/unit/Server/Middleware/AssertionMiddlewareTest.php @@ -15,6 +15,7 @@ use FreeDSx\Ldap\Control\Control; use FreeDSx\Ldap\Control\PagingControl; +use FreeDSx\Ldap\Control\Sync\SyncRequestControl; use FreeDSx\Ldap\Controls; use FreeDSx\Ldap\Entry\Entry; use FreeDSx\Ldap\Exception\OperationException; @@ -24,6 +25,7 @@ use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Protocol\Decoder\Control\AssertionControlDecoder; use FreeDSx\Ldap\Operations; +use FreeDSx\Ldap\Protocol\Factory\ServerProtocolHandlerFactory; use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\ServerProtocolHandler\AssertionEvaluator; use FreeDSx\Ldap\Search\Filters; @@ -61,13 +63,16 @@ protected function setUp(): void ['cn' => ['foo']], )); - $this->subject = new AssertionMiddleware(new AssertionEvaluator( - $this->fromContainer(FilterEvaluatorInterface::class), - $this->backend, - new RuleBasedAccessControl(AclRules::fromEmpty()), - $this->fromContainer(LinkedLeafWitness::class), - $this->fromContainer(AssertionControlDecoder::class), - )); + $this->subject = new AssertionMiddleware( + new AssertionEvaluator( + $this->fromContainer(FilterEvaluatorInterface::class), + $this->backend, + new RuleBasedAccessControl(AclRules::fromEmpty()), + $this->fromContainer(LinkedLeafWitness::class), + $this->fromContainer(AssertionControlDecoder::class), + ), + $this->fromContainer(ServerProtocolHandlerFactory::class), + ); $this->next = new RecordingMiddlewareHandler(new CallLog()); } @@ -135,6 +140,28 @@ public function test_it_skips_assertion_on_a_paging_continuation(): void ); } + public function test_a_sync_search_carrying_a_paging_cookie_still_has_its_assertion_enforced(): void + { + $this->expectException(OperationException::class); + $this->expectExceptionCode(ResultCode::ASSERTION_FAILED); + + $this->subject->process( + $this->contextFor( + $this->search(), + Controls::assertion(Filters::equal( + 'cn', + 'nope', + )), + new PagingControl( + 10, + 'continuation-cookie', + ), + new SyncRequestControl(), + ), + $this->next, + ); + } + public function test_a_compare_is_passed_on_to_be_evaluated_against_the_entry_it_reads(): void { $this->subject->process( diff --git a/tests/unit/Server/Middleware/ServerControlRegistryTest.php b/tests/unit/Server/Middleware/ServerControlRegistryTest.php index 086bc503..b573e45d 100644 --- a/tests/unit/Server/Middleware/ServerControlRegistryTest.php +++ b/tests/unit/Server/Middleware/ServerControlRegistryTest.php @@ -51,6 +51,23 @@ public function test_search_supports_expected_controls(): void ); } + public function test_sync_supports_the_assertion_alongside_its_own_control(): void + { + self::assertSame( + [ + Control::OID_PROXY_AUTHORIZATION, + Control::OID_MANAGE_DSA_IT, + Control::OID_PWD_POLICY, + Control::OID_SYNC_REQUEST, + Control::OID_ASSERTION, + ], + $this->subject->supportedControlsFor( + HandlerId::Sync, + self::searchRequest(), + ), + ); + } + public function test_paging_supports_expected_controls(): void { self::assertSame( @@ -230,6 +247,87 @@ public static function checkedHandlers(): iterable yield 'unsupported extended' => [HandlerId::UnsupportedExtended]; } + /** + * @param list $controls + */ + #[DataProvider('controlsTakenByEachOperation')] + public function test_each_operation_takes_the_controls_of_every_route_it_may_take( + RequestInterface $request, + array $controls, + ): void { + self::assertSame( + $controls, + $this->subject->controlsTakenBy($request), + ); + } + + /** + * @return iterable}> + */ + public static function controlsTakenByEachOperation(): iterable + { + $global = [ + Control::OID_PROXY_AUTHORIZATION, + Control::OID_MANAGE_DSA_IT, + Control::OID_PWD_POLICY, + ]; + + yield 'a search, across the search, paging and sync routes' => [ + self::searchRequest(), + [ + ...$global, + Control::OID_SORTING, + Control::OID_ASSERTION, + Control::OID_SUBENTRIES, + Control::OID_PAGING, + Control::OID_SYNC_REQUEST, + ], + ]; + yield 'a compare' => [ + Operations::compare( + 'cn=foo,dc=bar', + 'cn', + 'foo', + ), + [ + ...$global, + Control::OID_ASSERTION, + ], + ]; + yield 'a delete' => [ + Operations::delete('cn=foo,dc=bar'), + [ + ...$global, + Control::OID_RELAX_RULES, + Control::OID_ASSERTION, + Control::OID_PRE_READ, + Control::OID_SUBTREE_DELETE, + ], + ]; + yield 'an extended operation' => [ + Operations::whoami(), + $global, + ]; + yield 'a bind' => [ + Operations::bind( + 'cn=foo,dc=bar', + 'secret', + ), + [ + Control::OID_MANAGE_DSA_IT, + Control::OID_PWD_POLICY, + ], + ]; + yield 'an abandon' => [ + Operations::abandon(1), + [], + ]; + yield 'an unbind' => [ + Operations::unbind(), + [], + ]; + } + /** * A stand-in for the cases that assert on the global set alone, which no request type varies. */ diff --git a/tests/unit/Server/Middleware/WithheldAttributeMiddlewareTest.php b/tests/unit/Server/Middleware/WithheldAttributeMiddlewareTest.php index 8b5d630f..108f6e69 100644 --- a/tests/unit/Server/Middleware/WithheldAttributeMiddlewareTest.php +++ b/tests/unit/Server/Middleware/WithheldAttributeMiddlewareTest.php @@ -17,7 +17,6 @@ use FreeDSx\Ldap\Control\Sorting\SortingControl; use FreeDSx\Ldap\Control\Sorting\SortKey; use FreeDSx\Ldap\Operation\Request\RequestInterface; -use FreeDSx\Ldap\Operation\ResultCode; use FreeDSx\Ldap\Operations; use FreeDSx\Ldap\Protocol\LdapMessageRequest; use FreeDSx\Ldap\Protocol\Queue\Response\ResponseStream; @@ -32,7 +31,6 @@ use FreeDSx\Ldap\Server\Middleware\WithheldAttributeMiddleware; use FreeDSx\Ldap\Server\Middleware\Pipeline\MiddlewareHandlerInterface; use FreeDSx\Ldap\Server\Middleware\Pipeline\ServerRequestContext; -use FreeDSx\Ldap\Server\Operation\OperationOutcome; use FreeDSx\Ldap\Server\Operation\OperationOutcomeResult; use FreeDSx\Ldap\Server\Token\BindToken; use FreeDSx\Ldap\Server\Token\TokenInterface; @@ -62,32 +60,28 @@ protected function setUp(): void ); } - public function test_a_search_on_a_withheld_attribute_succeeds_with_no_entries(): void + public function test_a_search_on_a_withheld_attribute_is_passed_on_as_the_absolute_false(): void { + $request = Operations::search(Filters::equal( + 'userPassword', + 'secret', + )) + ->base('dc=foo,dc=bar'); + $this->next - ->expects(self::never()) - ->method('handle'); + ->expects(self::once()) + ->method('handle') + ->willReturn(ResponseStream::of( + [], + OperationOutcomeResult::succeeded(), + )); - $stream = $this->subject->process( - $this->context( - Operations::search(Filters::equal('userPassword', 'secret')) - ->base('dc=foo,dc=bar'), - ), + $this->subject->process( + $this->context($request), $this->next, ); - self::assertSame( - OperationOutcome::Succeeded, - $stream->outcome()->outcome(), - ); - self::assertSame( - ResultCode::SUCCESS, - $stream->outcome()->resultCode(), - ); - self::assertCount( - 1, - [...$stream->messages], - ); + self::assertTrue(Filters::isAbsoluteFalse($request->getFilter())); } public function test_a_search_keeping_a_branch_is_rewritten_and_passed_on(): void