Problem/Motivation

Steps to reproduce:

  1. setup a view with a path like node/%node/foo
  2. use a conditional argument
  3. add validation on node type to the conditional argument and configure it
  4. add a local task entry for the view via the views UI
  5. visit a node of which the bundle will fail argument validation

Scenario one: Access denied

If the argument validation was configured to show an access denied upon failure, the expected result is that the tab does not show, yet it does. Menu links can also be added for these type of views and the expectation is that they only show when you have access.

Scenario two: Not found

If the argument validation was configured to show a not found upon failure, the expected result is that the tab does not show, yet it does. Menu links could theoretically be added for these type of views, but practically no-one would do so for an argument they know will 404.

Proposed resolution

Translate the argument validation to access checking, making sure it runs after the access plugin. Due to recent core changes in #3626740: AccessManager should (once again) bail out early to save resources and avoid adding cacheable metadata for no reason, we know the access plugin will bail out early if it denies access, assuring we only load the view to check for arguments if regular access was allowed.

Validators report what their result depends on through a new optional $cacheability argument of validateArgument(), so the access result can be cached.

Validators only check the current user. When access is checked for another account, validation is skipped and the result is not cached.

The 404 case is left to a follow-up: core can cache access results for links, but not a response code.

Remaining tasks

User interface changes

API changes

ArgumentValidatorPluginBase::validateArgument() gets an optional $cacheability argument, commented out in the signature until Drupal 13. See the change record.

Data model changes

Issue fork drupal-2778345

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

catch created an issue. See original summary.

dawehner’s picture

Yeah I think argument validators should be able to allow something similar to what \Drupal\views\Plugin\views\access\AccessPluginBase is doing.

larowlan’s picture

Yeah, I just debugged a similar issue on a project, we ended up going with a route subscriber to add additional access checks. This would be a great addition.

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

sukanya.ramakrishnan’s picture

This would be a very important addition for us too. Looking fwd to this !

tetranz’s picture

Assigned: Unassigned » tetranz

I'm taking a stab at this.

tetranz’s picture

Status: Active » Needs review
StatusFileSize
new5.49 KB

I think this is close to what we need. Unless I'm missing something, a generic solution fell into place quite nicely once I figured out how.

A few notes and things that might require some discussion or confirmation.
I made it only apply when the fail validation behavior is set to "page not found" or "access denied". If someone really wants to display one of the others, i.e., all results a "no results" message or a summary then the menu should probably still appear.

This applies to page and feed displays because Drupal\views\Plugin\views\display\PathPluginBase::getRoute was a good place to put this. If feeds is considered inappropriate then I can move some code to Drupal\views\Plugin\views\display\Page although I'd have to refactor a little to make $argument_map available.

I'm still a little uncertain about what AccessResult is the correct one in the various situations although I think I have it correct mostly by studying what happens on a view with an access restriction. AccessResult::neutral() makes the menu link disappear.

I think AccessResult::allowed() is the appropriate result when we're trying to access the view itself although intuitively AccessResult::neutral() would seem more likely. AccessResult::allowed() appears to work correctly. If the view has a failed access restriction and a validation, it still fails with access denied as intended despite my code returning a AccessResult::allowed();

I will look into writing some tests. I think I need to import a new view configuration to test this or at least add a display to one of the existing test views.

Status: Needs review » Needs work

The last submitted patch, 8: views-args-access-2778345-8.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

tetranz’s picture

StatusFileSize
new5.53 KB
new876 bytes
tetranz’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 10: views-args-access-2778345-10.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

tetranz’s picture

Status: Needs work » Needs review
StatusFileSize
new5.68 KB
new1.07 KB
tetranz’s picture

StatusFileSize
new13.47 KB
new7.79 KB

Added a test.

tetranz’s picture

Assigned: tetranz » Unassigned

I was feeling my way a little with the test. I'm not sure if it's in the most appropriate place or should / could do something different.

pritishkumar’s picture

StatusFileSize
new13.44 KB

Fixed Some Coding Standards which was in the previous patch.

Interdiff was not created due to an error.

tetranz’s picture

StatusFileSize
new1.13 KB

Thanks. Here's an interdiff.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

tetranz’s picture

StatusFileSize
new7.79 KB

Trying to bring this back to life.

Patch #16 fails to apply to 8.7.x.

I'm starting again with the patches since I didn't do it in the right order a year ago.

This one is the test only which should fail.

tetranz’s picture

StatusFileSize
new7.81 KB
new669 bytes

Submitting this again with the updated traits.

The last submitted patch, 21: views-args-access-2778345-21.patch, failed testing. View results

Status: Needs review » Needs work

The last submitted patch, 22: views-args-access-2778345-22.patch, failed testing. View results

tetranz’s picture

Status: Needs work » Needs review
StatusFileSize
new13.51 KB
new5.7 KB

This should pass.

catch’s picture

This looks in the right direction, couple of nits, one thing looks a bit odd, notes below:

  1. +++ b/core/modules/views/src/Access/ArgumentValidatorAccessCheck.php
    @@ -0,0 +1,83 @@
    +/**
    + * Access check views with page or feed display and argument validation.
    + * This is primarily used to avoid displaying menu links for views that will
    + * fail validation.
    + */
    

    This could do with a new line.

  2. +++ b/core/modules/views/src/Access/ArgumentValidatorAccessCheck.php
    @@ -0,0 +1,83 @@
    +  private $views_plugin_manager;
    

    We have a general guideline against using private properties (i.e. allows people to subclass if they really want to) so both of these should be protected. Should also be camelCase.

  3. +++ b/core/modules/views/src/Access/ArgumentValidatorAccessCheck.php
    @@ -0,0 +1,83 @@
    +      $parameter_value = $route_match->getRawParameter($argument['parameter_name']);
    +      $allowed = $allowed && $plugin->validateArgument($parameter_value);
    +      if (!$allowed) {
    +        break;
    +      }
    

    Since we never get to the next step of the foreach, couldn't this be
    <?php
    if (!$plugin->validateArgument($parameter_value)) {
    return AccessResult::neutral();
    }

    Then just return AccessResult::allowed() at the end of the method.

  4. +++ b/core/modules/views/src/Plugin/views/display/PathPluginBase.php
    @@ -198,6 +197,39 @@ protected function getRoute($view_id, $display_id) {
    +      $route->addRequirements([
    +        '_argument_validator_access' => serialize([
    +          'arguments' => $validate_arguments,
    +        ]),
    

    Couldn't this just be an array without the manual serialize/unserialize?

tetranz’s picture

StatusFileSize
new13.41 KB
new3.85 KB

Thanks @catch. I've addressed all those except the last one.

The route requirement can only be a string so we need the serialization. It looks like Symfony really intends it to be a regex (See Symfony\Component\Routing\Route::sanitizeRequirement) so I am kind of hijacking it for a different reason. But there are other places where it's pipe delimited "serialized" such as in Drupal\rest\Plugin\views\display\collectRoutes::RestExport. I'm not sure if there is an alternative. This is deeper than one dimension so a pipe delimited won't work.

I have changed to using ->setRequirement rather than ->addRequirements which eliminates one array.

tetranz’s picture

StatusFileSize
new13.41 KB
new619 bytes

Removed an unnecessary comma.

twod’s picture

Priority: Normal » Major
Issue tags: +Barcelona 2015, +Triaged core major
jeffam’s picture

Status: Needs review » Needs work

I just tested this today and it worked well. However, I can consistently get a PHP notice under certain circumstances, and I'm pretty sure it's related to the patch in #28.

I wish I had more time to dig a little deeper, but here's what I have so far.

I'm using two views with argument validation criteria. Both are listing custom entities.

The first one has a path of `/node/%node/slots`, uses a menu tab, and uses the 'Content' validator with a single content type selected. With the patch, everything works as expected. The tab appears on the nodes of the content type chosen in the validator and not on other node types.

The other view has a path of `/user/%user/reservations`, also uses a menu tab, and uses the 'User ID' validator. With the patch, the tab still appears on user pages (e.g. `/user/2`), but on every visit to the account page (`/user/%user`) after a cache rebuild, I see the following PHP notice:

Notice: Undefined index: bundles in Drupal\views\Plugin\views\argument_validator\Entity->validateEntity() (line 202 of core/modules/views/src/Plugin/views/argument_validator/Entity.php).
Drupal\views\Plugin\views\argument_validator\Entity->validateEntity(Object) (Line: 96)
Drupal\user\Plugin\views\argument_validator\User->validateEntity(Object) (Line: 180)
Drupal\views\Plugin\views\argument_validator\Entity->validateArgument('1') (Line: 73)
Drupal\views\Access\ArgumentValidatorAccessCheck->access(Object, Object)
call_user_func_array(Array, Array) (Line: 159)
Drupal\Core\Access\AccessManager->performCheck('access_check.views.argument_validator', Object) (Line: 135)
Drupal\Core\Access\AccessManager->check(Object, Object, NULL, 1) (Line: 92)
Drupal\Core\Access\AccessManager->checkNamedRoute('view.reservations_for_user.page_1', Array, Object, 1) (Line: 327)
Drupal\Core\Menu\LocalTaskManager->getTasksBuild('entity.user.canonical', Object) (Line: 358)
Drupal\Core\Menu\LocalTaskManager->getLocalTasks('entity.user.canonical', 0) (Line: 94)
Drupal\Core\Menu\Plugin\Block\LocalTasksBlock->build() (Line: 203)
Drupal\block\BlockViewBuilder::preRender(Array)
call_user_func('Drupal\block\BlockViewBuilder::preRender', Array) (Line: 378)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 83)
__TwigTemplate_491d354868c23a7cdc36790829dd9700797f10bbfee01afc733f74972d1a5ac2->doDisplay(Array, Array) (Line: 432)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template->display(Array) (Line: 411)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/modules/system/templates/page.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 84)
__TwigTemplate_4a0387b265d067bab2d2de06a8ead777749d03cb5cf7ba23df40bc8d00a80437->doDisplay(Array, Array) (Line: 432)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template->display(Array) (Line: 411)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/modules/system/templates/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 666)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

I don't see the error when I revert the patch, which is why I'm guessing it's related. It's interesting that the error is about an undefined index `bundles` and that user entities don't have bundles.

I'll dig around some more, but I'm hoping that this info will help.

tetranz’s picture

Thanks for testing. I've tried to reproduce the error but have not been able to.

Can you describe your second view in detail please.

tetranz’s picture

@jeffam I took another look trying to reproduce your error but was unsuccessful.

I created a custom entity with Drupal Console I think similar to your Reservation. It just has a name and a user reference. I created a view at /user/%user/foo to show the reservations for that user. Then I used the contextual filter validator to validate by role. "Restrict user based on role" is the only validator available when you validate by User ID. The tab appears as expected at /user/2 but not at /user/1.

It that similar to what you were doing?

It seems like somewhere in your view you're validating something by bundle, but what? Does Reservation have bundles? Mine doesn't. It would be nice to see the yml for the view or just a description of it.

I'm at a dead end with this now without more details on how to reproduce the error.

jeffam’s picture

StatusFileSize
new13.37 KB

@tetranz - Thanks for looking at this, and sorry for my delayed response. Attached is the view I'm using, although it has some extra stuff that probably isn't relevant. You'll be able to see the `reservee_uid` argument and its validation settings, though.

tetranz’s picture

Thanks @jeffam, I can reproduce the error. I should have a fix in few days.

tetranz’s picture

Status: Needs work » Needs review
StatusFileSize
new14 KB
new2.29 KB

Unfortunately, this is not quite as simple as I thought it was.

This patch fixes the problem but it is probably not the final solution.

The problem was caused by me not initializing the plugin properly. I was just setting the options which means that it wasn't getting the defaults which include that 'bundles' value.

The proper way to initialize the plugin is to call its ->init() method. That works fine except that it needs the view executable and the display handler. We really don't want to load the view as @catch said in the proposed solution.

I'm not sure what to do. I think we really only need the default options for the plugin but any way of getting at them directly is protected.

Anyway, I'm going to flip this to needs review. Perhaps someone will have a suggestion.

mirom’s picture

Status: Needs review » Needs work

This patch prevents showing taxonomy terms in menu. Steps to reproduce:
1. apply patch
2. create taxonomy term
3. add link to taxonomy term to menu
4. see nothing.

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

dflitner’s picture

RE: #36. Because this patch triggers on views with 404 or 403 results, a workaround is to change the contextual filter on your taxonomy term view to display contents of "no results found" or any other setting besides "page not found" or "access denied".

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

lunk rat’s picture

Views menu tabs are a key strategy in producing usable UI/UX workflows for complex Drupal architectures with lots of entities referencing each other. This regression from D7 is detrimental to that strategy because the views tabs appear on content types where they should not appear.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

kerasai’s picture

StatusFileSize
new0 bytes

The patch in #35 stops applying w/9.3.

Attached is a re-roll that applies for 9.4.x and 9.3.x.

Note: No changes to functionality or a review, just a re-roll.

kerasai’s picture

StatusFileSize
new14.05 KB

Somehow uploaded an empty patch in #45.

Here's the proper version.

jonathanshaw’s picture

Great work @tetranz.

The problem described in #35 is tricky. Here's a possible solution:

1. Create an ArgumentValidatorPluginInterface that extends ViewsPluginInterface and contains a method initOptions($options = NULL).
2. Have ArgumentValidatorPluginBase implement that interface, with initOptions simply being a version of init that sets up the options without needing the view and display.
3. When checking access ignore validator plugins that do not implement ArgumentValidatorPluginInterface
4. In ArgumentValidatorPluginBase::construct trigger a deprecation warning if the plugin does not implement ArgumentValidatorPluginInterface

jonathanshaw’s picture

This is a tricky architectural issue that may have relevance beyond this issue; maintainer guidance would be helpful.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

jonasanne’s picture

Status: Needs work » Needs review
StatusFileSize
new14.05 KB

Reroll patch #46 for 10.2.x

smustgrave’s picture

Status: Needs review » Needs work

Also recommend converting to MRs as easier reviews.

Still needs sub-maintainer review but NW for the CC failures.

dww made their first commit to this issue’s fork.

dww’s picture

Status: Needs work » Needs review
Issue tags: +Bug Smash Initiative

I just ran into this bug on a new project. I was amazed this was broken. I dug deep into the views code, only to find:

// @todo How do we apply argument validation?

buried in core/modules/views/src/Plugin/views/display/PathPluginBase.php.

Searched the d.o queue and landed here. Thankfully, patch #52 applies cleanly both to 11.x HEAD and my 10.2.5 site. Converted to an MR. Fixed the phpcs and phpstan errors. I haven't addressed #35 / #47, but wanted to get this back into a reviewable state.

Let's smash this bug!

Thanks,
-Derek

dww’s picture

Hiding all attached files and starting to save credits.

dww’s picture

Status: Needs review » Needs work

Well, drat. There are legit test failures in both of these:

core/modules/system/tests/src/Functional/Menu/BreadcrumbTest.php
core/modules/taxonomy/tests/src/Functional/TermTest.php

I'm out of time for today, but I hope to get back to this soon. 😅 If anyone else wants to run with it in the meanwhile, please do. 🙏

Thanks,
-Derek

jonathanshaw’s picture

@dww you may be encountering #35 / #47

rachel_norfolk’s picture

Issue tags: -Barcelona 2015 +Barcelona2015

Just tidying tags

mikell’s picture

StatusFileSize
new3.23 KB

Reroll patch #52 for 11.2.2
Edit: My bad, uploaded wrong file. See comment below.

mikell’s picture

StatusFileSize
new14.07 KB

Something went wrong with previous comment.
This is the correct reroll patch #52 for 11.2.2

fskreuz made their first commit to this issue’s fork.

fskreuz’s picture

Status: Needs work » Needs review
jonathanshaw’s picture

Status: Needs review » Needs work

#63 seems to be rerolling #58, which is NR not NR.

cslevy’s picture

StatusFileSize
new14.01 KB

The MR doesn't apply anymore on D10.6. I created a patch which will apply on D10.6

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

mortona2k made their first commit to this issue’s fork.

graber made their first commit to this issue’s fork.

graber’s picture

Status: Needs work » Needs review

kristiaanvandeneynde made their first commit to this issue’s fork.

kristiaanvandeneynde’s picture

Title: Views argument validators aren't taken into account on access checks - local task point to 404 » [PP-1] Views argument validators aren't taken into account on access checks - local task point to 404
Status: Needs review » Needs work

I'm going to add the code from #3626740: AccessManager should (once again) bail out early to save resources and avoid adding cacheable metadata for no reason because this relies on the access plugin checks (such as permission) to run before our more expensive one. So adding [PP-1] tag.

kristiaanvandeneynde’s picture

Status: Needs work » Needs review

All green, I might expand the tests but it's definitely ready for review.

kristiaanvandeneynde’s picture

My latest commit suggests browser tests, but those will just 404 or 403 without telling us where it came from, so ignore that message. Might still refactor the test to match the refactored code more closely, though.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new97 bytes

The Needs Review Queue Bot tested this issue. The merge request has merge conflicts and cannot be merged. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

kristiaanvandeneynde’s picture

Title: [PP-1] Views argument validators aren't taken into account on access checks - local task point to 404 » Views argument validators aren't taken into account on access checks - local task point to 404
Status: Needs work » Needs review

Parent issue went in so removing PP-1 tag. Also rebased on main.

jonathanshaw’s picture

There have been persistent performance concerns about loading the view in the access check.

Does anyone have perspectives about why we should or should not be concerned about this? Or ideas about how we could measure the performance impact?

graber’s picture

Status: Needs review » Needs work

Found a few issues, one major but I think it'll be easy to fix (added a test that must pass and proposed a resolution). Details in the MR.

kristiaanvandeneynde’s picture

Re #78 the change we just landed in core means we only run the argument check after the "regular" access check succeeded (i.e. permission check). This severely limits the impact of loading the view, as we will only do so for people who actually have access to it to begin with. Then the outcome of said access check is cached.

This is not much different from any route with an _entity_access check, where we too have to load an entity. Also keep in mind we do not execute the view at all, which is usually the most expensive part.

kristiaanvandeneynde’s picture

Okay so @graber and I discussed this and we agree we should for now only support the 403 case.

Access checks should not throw 404 exceptions, as demonstrated by the current MR. If we have the access check return a 403 in both scenarios, then we won't be able to reach the view controller and thus get a 403 where the user configured a 404, which is no good. The only way we can enforce a 404 on a route that I can currently think of, is via ParamNotConvertedException, which kills caching.

Then let's be pragmatic: Who is going to add a menu link to a Views page that will 404 (which happens for everyone) vs to a page that might 403 depending on your access? I think the latter is very common and the former is highly unlikely.

So with that said I'll adjust the MR to only support the 403 case and can create a follow-up for tackling the 404 case, if we ever even want that behavior to begin with.

graber’s picture

Yes, 404s are mainly result of removed content in general, I think we want such links to stay on pages instead of being quietly hidden resulting in mess in config or other content that contained references. Let's not create that follow-up IMO, I think that's expected behavior.

kristiaanvandeneynde’s picture

Title: Views argument validators aren't taken into account on access checks - local task point to 404 » Views argument validators aren't taken into account on access checks - menu links and local task point to 403 or 404
Issue summary: View changes
Status: Needs work » Needs review
kristiaanvandeneynde’s picture

Adjusted the IS, the only place where I think we'd want to fix the 404 scenario is local tasks. But as mentioned in my latest comment, that is far more difficult than fixing a 403, which access checks can take care of. So I am still a fan of fixing the 403 first and then figuring out how we can make a route 404 from running custom code that can provide cacheable metadata.

kristiaanvandeneynde’s picture

For the 404, I asked an LLM and got the following suggestion to use a route enhancer:

  1. Implement EnhancerInterface, tag it route_enhancer, and give it a priority below 5000 so the parameters are already upcast. Personal note: validators receive the raw arguments, so we could actually opt to run before upcasting.
  2. Return early in enhance() for routes that aren't yours, e.g. check a custom route option in $defaults[RouteObjectInterface::ROUTE_OBJECT].Personal note: We could check for our access check.
  3. When the resource doesn't exist, throw new CacheableNotFoundHttpException($cacheability).
  4. The HTML 404 keeps your metadata: DefaultExceptionHtmlSubscriber adds the exception as a cacheable dependency (line 181). JSON responses do the same in ExceptionJsonSubscriber.
  5. Menu link access never sees the exception.

I still think we should land the 403 first to have a starting point that is simple and follows existing solutions (route access checks), but then create a follow-up to investigate the above for the 404 scenario.

kristiaanvandeneynde’s picture

Issue summary: View changes

Added a change record and pointed the comment to it. This seems about ready now.

kristiaanvandeneynde’s picture

Pushed a commit with 404 support after all, but might revert if it breaks too much. Curious what tests have to say.

The beauty is this:

  1. If the view is not configured to 404, the validation does not run as the enhancer does not trigger (i.e. load the view).
  2. Same for 403 and the access check
  3. Bonus for 403, cheaper access checks still run first and can shut down the more expensive one introduced here
kristiaanvandeneynde’s picture

Issue summary: View changes

TaxonomyTermViewTest was an interesting case for the 404 handling.

Given how the route enhancers always run first, if a view has a simple and cheap permission check, any view configured to 404 on invalid arguments will still try to 404 first before it tries to check route access. So the performance gain of running permissions checks first only works for views where argument validation is configured to 403 upon failure. That is why the test used to find a 403, but now gets a 404.

So long story short:

  1. Any view configured to 403 on invalid arguments has no performance loss and no more buggy menu links or local tasks
  2. Any view configured to 404 on invalid arguments has a potential performance loss and no more buggy menu links or local tasks. The potential performance loss being it will load the view to validate arguments, even if an access plugin (e.g.: permission check) check would deny access. When the access check would succeed, there is no performance loss.

But on both cases the bug from the IS is fixed.

graber’s picture

Status: Needs review » Reviewed & tested by the community

I think this looks great, passing to the big guys!

catch’s picture

Status: Reviewed & tested by the community » Needs review

I'm a bit confused why we went from:

Access checks should not throw 404 exceptions, as demonstrated by the current MR. If we have the access check return a 403 in both scenarios, then we won't be able to reach the view controller and thus get a 403 where the user configured a 404, which is no good. The only way we can enforce a 404 on a route that I can currently think of, is via ParamNotConvertedException, which kills caching.

Then let's be pragmatic: Who is going to add a menu link to a Views page that will 404 (which happens for everyone) vs to a page that might 403 depending on your access? I think the latter is very common and the former is highly unlikely.

to supporting 404s after all, given the performance penalty looks quite a bit higher and the use-case is extremely marginal, why not look at that in a follow-up?

kristiaanvandeneynde’s picture

Because I found that an EnhancerInterface can throw a 404 without killing caching.

From AccessManager:

    catch (ParamNotConvertedException) {
      // Uncacheable because conversion of the parameter may not have been
      // possible due to dynamic circumstances.
      $result = AccessResult::forbidden()->setCacheMaxAge(0);
      return $return_as_object ? $result : $result->isAllowed();
    }

But a route enhancer other than a param converter can throw a CacheableNotFoundHttpException, which does not trigger that code.

So then I had two choices:

  1. Defer to a follow-up and race before the next release to refactor the 403-only code so we can share code with the 404 path
  2. Try to get 404 working anyway and therefore be able to use a neatly organized base class

I tried the second and it seems to be working fine, with the one caveat explained in #88.


If a view has an access check that will deny access and an argument setup that would 404, the view used to 403 because the route check came first and then on the actual request the 404 check would run. Now, the potentially more expensive 404 runs first and access is never checked.

Arguably this fixes a bug, because as far as HTTP codes go I'd say a 404 always beats a 403 when both apply. You can't have access or not to something that can't be found.

But "can't be found" is admittedly a grey area here as argument validation can fail based on access checks and still be configured to 404 in such a case. But then we're really talking about a misconfiguration as you should have configured your validation to fail with a 403 instead, which will also fix the performance issue because no 404 is checked earlier anymore and the cheap route access checks will run first now.

So you could say that the taxonomy term view is misconfigured. But we can't fix that here as that would involve more work where we refactor the whole Views access layer to favor contextual stuff more and we'd need to allow one argument to have separate set-ups for both a possible 404 and 403 result. Now you have to pick between one of them.

kristiaanvandeneynde’s picture

Status: Needs review » Needs work

Just tried a few set-ups and the local tasks aren't consistently hidden because they do not seem to trigger the route enhancer. Will dig a little deeper.

kristiaanvandeneynde’s picture

Okay I found a solution that takes away all performance concerns, but leaves the current behavior that a view might 403 before it could 404.

The code that is screwing us over is AccessManager::checkNamedRoute(). It only runs param converters and an access check, not every route enhancer (which is fine for performance reasons). But it can only handle RouteNotFoundException and ParamNotConvertedException and in the latter case adds a mage axe of 0. What if we change that to also catch a CacheableNotFoundHttpException?

Then we can deny access from an access check as both 403 and 404, but we should document that you're now allowed to throw a CacheableNotFoundHttpException from an access checker.

Solves every other problem we solved up until now, but also for 404:

  1. Cheap access checks such as permission run first
  2. We only load the view when the user has access to the route, but arguments need validating
  3. Menu links, contextual links, etc are all hidden for both 403 and 404

I'll revert to the state where we handled both 403 and 404 from the access checker and add support for CacheableNotFoundHttpException in access checks.

kristiaanvandeneynde’s picture

Status: Needs work » Needs review

Might need a spinoff now for the AccessManager change, but this works for both 403 and 404, local tasks and menu links, and solves the performance concerns.

Performance metrics prove that we're now checking for views arguments on cold caches whenever there's a link on a page to a view that might 403 or 404, whereas hot caches remain unchanged. So cacheable metadata from the checks bubbles up properly.

kristiaanvandeneynde’s picture

Issue summary: View changes
kristiaanvandeneynde’s picture

Title: Views argument validators aren't taken into account on access checks - menu links and local task point to 403 or 404 » [PP-1] Views argument validators aren't taken into account on access checks - menu links and local task point to 403 or 404
Related issues: +#3633769: Support 404 in AccessManager::checkNamedRoute() without killing caching

Thinking of making ParamNotConvertedException carry cacheability and then change this MR one last time. See #3633769: Support 404 in AccessManager::checkNamedRoute() without killing caching

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new90 bytes

The Needs Review Queue Bot tested this issue. It no longer applies to Drupal core. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

graber’s picture

Merged main, resolved conflicts and left some comments on the MR. Still needs work. Will probably need an issue summary update (404 handling) but I'd wait with it until we'll have a good solution.

Any chance we can get back to the 404 handling as a follow-up plan?

graber’s picture

Title: [PP-1] Views argument validators aren't taken into account on access checks - menu links and local task point to 403 or 404 » [PP-1] Views argument validators aren't taken into account on access checks - menu links and local task point to 403
Issue summary: View changes
graber’s picture

Issue summary: View changes
Status: Needs work » Needs review
kristiaanvandeneynde’s picture

Any chance we can get back to the 404 handling as a follow-up plan?

YES!

As shown by the spin-off and now @graber's proposal for a fix (see #3637647: Let route access results carry a response code such as 404, we have to much too worry about with the 404 approach. So let's just stick to handling 403 right now until we figure out how to properly allow code to return a 404 early, with cacheable metadata and without cooking up a Drupalism that does not respect how Symfony works.