nautobot / cookiecutter-nautobot-app

Cookiecutter template for creating new Nautobot Apps.
https://docs.nautobot.com/projects/cookiecutter-nautobot-app/en/latest/
Apache License 2.0
16 stars 5 forks source link

Add test case checking/enforcing authentication on URL endpoints #102

Open glennmatthews opened 7 months ago

glennmatthews commented 7 months ago

Environment

Proposed Functionality

To protect against inadvertently implementing views (UI, API, or other) that can expose sensitive information to unauthenticated users, the app cookiecutter should provide a default generic test case that iterates over all URL patterns published by the app and attempts to access them as an anonymous/unauthenticated user.

A similar pattern was implemented in Nautobot itself in nautobot/nautobot#5464; if the app requires Nautobot 2.1.9 or 1.6.16 or later, the test can use the nautobot.apps.utils.get_url_patterns and nautobot.apps.utils.get_url_for_url_pattern APIs introduced in those versions, something along the lines of:

import my_app.api.urls as api_urls
import my_app.urls as ui_urls

for urlconf in (api_urls, ui_urls):
    url_patterns = get_url_patterns(urlconf)
    for url_pattern in url_patterns:
        url = get_url_for_url_pattern(url_pattern)
        response = self.client.get(url, follow=True)
        if response.status_code == 405:  # Method not allowed
            response = self.client.post(url, follow=True)
        if response.status_code == 200:
            # UI views generally should redirect unauthenticated users to the appropriate login page
            redirect_url = f"/login/?next={url}"
            self.assertRedirects(response, redirect_url)
        else:
            self.assertEqual(response.status_code, 403)

Use Case

Proactively protect against a common implementation error that has security implications.