Преглед изворни кода

Closes #23736: Enable background jobs to assert access restrictions (#23760)

Jeremy Stretch пре 1 дан
родитељ
комит
b455ce849d

+ 3 - 0
docs/customization/custom-scripts.md

@@ -555,6 +555,9 @@ Optionally `schedule_at` can be passed in the form data with a datetime string t
 !!! note "Changed in NetBox v4.7.4"
     A script's `result` in the REST API reports only jobs the requesting user is permitted to view (`core.view_job`), and is `null` when there are none. The response to running a script always includes the job just created. To let users poll the results of their own script runs, grant them `core.view_job` with the constraint `{"user": "$user"}`.
 
+!!! note "Changed in NetBox v4.8"
+    A script's jobs are accessible only to users who are permitted to view the script (`extras.view_script`), in addition to `core.view_job`. Permission to run a script (`extras.run_script`) is not sufficient: a user who runs a script via the REST API must also be permitted to view it in order to poll the job for its results.
+
 ### Via the CLI
 
 Scripts can be run on the CLI by invoking the management command:

+ 10 - 0
docs/features/background-jobs.md

@@ -8,6 +8,16 @@ NetBox includes the ability to execute certain functions as background tasks. Th
 
 Additionally, NetBox plugins can enqueue their own background tasks. This is accomplished using the [Job model](../models/core/job.md). Background tasks are executed by the `rqworker` process(es).
 
+## Job Access
+
+Each job has an access class, which determines who may access it in addition to the permissions assigned for jobs:
+
+* **Requester** - Only the user who created the job. Jobs for background REST API bulk operations and background UI operations use this class.
+* **Object** - Only users permitted to view the job's assigned object. For example, the results of a custom script are visible only to users permitted to view the script, and those of a data source synchronization only to users permitted to view the data source.
+* **Shared** - Any user permitted to view jobs. Housekeeping and other system jobs use this class.
+
+Superusers can access all jobs regardless of access class. The access class applies to every action, so only superusers can view or delete another user's requester jobs, even if permitted to delete jobs. (Housekeeping still purges all jobs under [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention).)
+
 ## Scheduled Jobs
 
 Background jobs can be configured to run immediately, or at a set time in the future. Scheduled jobs can also be configured to repeat at a set interval.

+ 1 - 1
docs/integrations/rest-api.md

@@ -795,7 +795,7 @@ Poll the job's URL to track its progress. When the job reaches a terminal status
 
 A failed job records the equivalent error response, for instance `{"status_code": 400, "data": {"slug": ["This field may not be blank."]}}`, with a short summary also placed in the job's `error` field.
 
-A `202` response indicates that the request was accepted and queued, not that it succeeded: validation (including malformed or invalid payloads) and the database write all occur when the job runs. A rejected payload is therefore reported as a failed job rather than a synchronous error response. Always inspect the job's final status to confirm the outcome. Because the result is stored on the job, any user permitted to view jobs (`core.view_job`, subject to object permissions) can read the serialized objects it contains.
+A `202` response indicates that the request was accepted and queued, not that it succeeded: validation (including malformed or invalid payloads) and the database write all occur when the job runs. A rejected payload is therefore reported as a failed job rather than a synchronous error response. Always inspect the job's final status to confirm the outcome. The job is accessible only to the user who submitted the request (who must also be permitted to view jobs, `core.view_job`) and to superusers. Jobs created before NetBox v4.8 are not restricted in this way and remain accessible to any user permitted to view jobs until they are purged under [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention).
 
 Background processing applies only to bulk operations (a JSON list) on a model's list endpoint. For a single-object write the `background` parameter is ignored and the request is processed synchronously. It cannot be combined with an [`If-Match`](#if-match) precondition (which cannot be evaluated reliably once execution is deferred); such a request is rejected with an `HTTP 400` response. If no background worker is running to service the queue, the request is rejected with an `HTTP 503` response rather than enqueuing a job that would never run.
 

+ 10 - 0
docs/models/core/job.md

@@ -49,6 +49,16 @@ The job's current status. Potential values include:
 | Failed | The job did not complete successfully |
 | Errored | An unexpected error was encountered during execution |
 
+### Access
+
+The job's access class, which determines which users may access the job in addition to the permissions assigned for jobs. It is set by the job runner when the job is created. Superusers can access all jobs regardless of access class.
+
+| Value | Who can access the job |
+|-------|------------------------|
+| Requester | Only the user who created the job |
+| Object | Only users permitted to view the job's assigned object |
+| Shared | Any user permitted to view jobs |
+
 ### Data
 
 Any data associated with the execution of the job, such as log output.

+ 25 - 0
docs/plugins/development/background-jobs.md

@@ -39,6 +39,31 @@ You can schedule the background job from within your code (e.g. from a model's `
 
 This is the human-friendly names of your background job. If omitted, the class name will be used.
 
+#### `access`
+
+The default [access class](../../models/core/job.md#access) for jobs created by this runner, which determines which users may access them in addition to the permissions assigned for jobs. Choices are defined in `core.choices.JobAccessChoices`:
+
+| Access class | Who can access the job |
+|---|---|
+| `requester` | Only the user who created the job |
+| `object` | Only users permitted to view the job's assigned object |
+| `shared` | Any user permitted to view jobs (default) |
+
+A job with the `object` access class must be assigned to an object: calling `enqueue()` without an `instance` raises a `ValueError`. The default may be overridden for an individual job by passing `access` to `enqueue()`.
+
+!!! warning
+    A subclass of a job runner which declares its own `Meta` class does not inherit the parent's `access`, and falls back to `shared`. Either subclass the parent's `Meta` (e.g. `class Meta(ScriptJob.Meta)`) or declare `access` again.
+
+```python
+from core.choices import JobAccessChoices
+from netbox.jobs import JobRunner
+
+class MyTestJob(JobRunner):
+    class Meta:
+        name = "My Test Job"
+        access = JobAccessChoices.ACCESS_OBJECT
+```
+
 ### Logging
 
 A Python logger is instantiated by the runner for each job. It can be utilized within a job's `run()` method as needed:

+ 2 - 1
netbox/core/api/serializers_/jobs.py

@@ -25,12 +25,13 @@ class JobSerializer(BaseModelSerializer):
         allow_missing_serializer=True
     )
     notifications = ChoiceField(choices=JobNotificationChoices, read_only=True)
+    access = ChoiceField(choices=JobAccessChoices, read_only=True)
 
     class Meta:
         model = Job
         fields = [
             'id', 'url', 'display_url', 'display', 'object_type', 'object_id', 'object', 'name', 'status', 'created',
             'scheduled', 'interval', 'started', 'completed', 'execution_time', 'user', 'data', 'error', 'job_id',
-            'queue_name', 'notifications', 'log_entries',
+            'queue_name', 'notifications', 'access', 'log_entries',
         ]
         brief_fields = ('url', 'created', 'completed', 'user', 'status')

+ 12 - 0
netbox/core/choices.py

@@ -84,6 +84,18 @@ class JobNotificationChoices(ChoiceSet):
     )
 
 
+class JobAccessChoices(ChoiceSet):
+    ACCESS_REQUESTER = 'requester'
+    ACCESS_OBJECT = 'object'
+    ACCESS_SHARED = 'shared'
+
+    CHOICES = (
+        Choice(ACCESS_REQUESTER, _('Requester'), description=_('Only the user who created the job')),
+        Choice(ACCESS_OBJECT, _('Object'), description=_("Users permitted to view the job's assigned object")),
+        Choice(ACCESS_SHARED, _('Shared'), description=_('Any user permitted to view jobs')),
+    )
+
+
 class JobIntervalChoices(ChoiceSet):
     INTERVAL_MINUTELY = 1
     INTERVAL_HOURLY = 60

+ 5 - 0
netbox/core/filtersets.py

@@ -154,6 +154,11 @@ class JobFilterSet(BaseFilterSet):
         distinct=False,
         null_value=None
     )
+    access = django_filters.MultipleChoiceFilter(
+        choices=JobAccessChoices,
+        distinct=False,
+        null_value=None
+    )
     queue_name = django_filters.CharFilter()
     user_id = django_filters.ModelMultipleChoiceFilter(
         queryset=User.objects.all(),

+ 6 - 1
netbox/core/forms/filtersets.py

@@ -75,7 +75,7 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
     model = Job
     fieldsets = (
         FieldSet('q', 'filter_id'),
-        FieldSet('object_type_id', 'status', 'queue_name', 'user_id', name=_('Attributes')),
+        FieldSet('object_type_id', 'status', 'access', 'queue_name', 'user_id', name=_('Attributes')),
         FieldSet(
             'created__before', 'created__after', 'scheduled__before', 'scheduled__after', 'started__before',
             'started__after', 'completed__before', 'completed__after', name=_('Scheduling')
@@ -92,6 +92,11 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
         choices=JobStatusChoices,
         required=False
     )
+    access = forms.MultipleChoiceField(
+        label=_('Access'),
+        choices=JobAccessChoices,
+        required=False
+    )
     queue_name = forms.CharField(
         label=_('Queue'),
         required=False

+ 2 - 1
netbox/core/jobs.py

@@ -15,7 +15,7 @@ from netbox.jobs import JobRunner, system_job
 from netbox.search.backends import search_backend
 from utilities.proxy import resolve_proxies
 
-from .choices import DataSourceStatusChoices, JobIntervalChoices, ObjectChangeActionChoices
+from .choices import DataSourceStatusChoices, JobAccessChoices, JobIntervalChoices, ObjectChangeActionChoices
 from .models import DataSource
 
 
@@ -26,6 +26,7 @@ class SyncDataSourceJob(JobRunner):
 
     class Meta:
         name = 'Synchronization'
+        access = JobAccessChoices.ACCESS_OBJECT
 
     @classmethod
     def enqueue(cls, *args, **kwargs):

+ 16 - 0
netbox/core/migrations/0027_job_access.py

@@ -0,0 +1,16 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('core', '0026_populate_job_execution_time'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='job',
+            name='access',
+            field=models.CharField(default='shared', max_length=30),
+        ),
+    ]

+ 46 - 0
netbox/core/migrations/0028_populate_job_access.py

@@ -0,0 +1,46 @@
+from django.db import migrations
+from django.db.models import Q
+
+BATCH_SIZE = 5000
+
+
+def populate_job_access(apps, schema_editor):
+    """
+    Assign the "object" access class to existing script and data source jobs (see ScriptJob and SyncDataSourceJob).
+    Updates are performed in batches, as installations which retain job history indefinitely can accumulate a very
+    large number of rows.
+    """
+    ContentType = apps.get_model('contenttypes', 'ContentType')
+    Job = apps.get_model('core', 'Job')
+
+    object_types = ContentType.objects.filter(
+        Q(app_label='extras', model='script') | Q(app_label='core', model='datasource')
+    )
+    queryset = Job.objects.filter(object_type__in=object_types, object_id__isnull=False, access='shared')
+
+    last_pk = 0
+    while True:
+        pks = list(
+            queryset.filter(pk__gt=last_pk).order_by('pk').values_list('pk', flat=True)[:BATCH_SIZE]
+        )
+        if not pks:
+            break
+        Job.objects.filter(pk__in=pks).update(access='object')
+        last_pk = pks[-1]
+
+
+class Migration(migrations.Migration):
+    # Kept separate from the migration which adds the column and run without a wrapping transaction, so that each
+    # batch commits independently (see 0026_populate_job_execution_time)
+    atomic = False
+
+    dependencies = [
+        ('core', '0027_job_access'),
+    ]
+
+    operations = [
+        migrations.RunPython(
+            code=populate_job_access,
+            reverse_code=migrations.RunPython.noop,
+        ),
+    ]

+ 18 - 4
netbox/core/models/jobs.py

@@ -16,16 +16,16 @@ from django.utils import timezone
 from django.utils.translation import gettext as _
 from rq.exceptions import InvalidJobOperation
 
-from core.choices import JobNotificationChoices, JobStatusChoices
+from core.choices import JobAccessChoices, JobNotificationChoices, JobStatusChoices
 from core.dataclasses import JobLogEntry
 from core.events import JOB_COMPLETED, JOB_ERRORED, JOB_FAILED
 from core.models import ObjectType
+from core.querysets import JobQuerySet
 from core.signals import job_end, job_start
 from core.utils import get_job_result_url
 from extras.models import Notification
 from netbox.models.features import has_feature
 from utilities.json import JobLogDecoder
-from utilities.querysets import RestrictedQuerySet
 from utilities.rqworker import get_queue_for_model
 
 __all__ = (
@@ -131,6 +131,13 @@ class Job(models.Model):
         choices=JobNotificationChoices,
         default=JobNotificationChoices.NOTIFICATION_ALWAYS
     )
+    access = models.CharField(
+        verbose_name=_('access'),
+        max_length=30,
+        choices=JobAccessChoices,
+        default=JobAccessChoices.ACCESS_SHARED,
+        help_text=_('Determines which users may access the job, in addition to the permissions assigned for jobs')
+    )
     log_entries = ArrayField(
         verbose_name=_('log entries'),
         base_field=models.JSONField(
@@ -141,7 +148,7 @@ class Job(models.Model):
         default=list,
     )
 
-    objects = RestrictedQuerySet.as_manager()
+    objects = JobQuerySet.as_manager()
 
     class Meta:
         ordering = ['-created']
@@ -320,6 +327,7 @@ class Job(models.Model):
             immediate=False,
             queue_name=None,
             notifications=None,
+            access=None,
             **kwargs
     ):
         """
@@ -335,9 +343,14 @@ class Job(models.Model):
             immediate: Run the job immediately without scheduling it in the background. Should be used for interactive
                 management commands only.
             notifications: Notification behavior on job completion (always, on_failure, or never)
+            access: The job's access class (requester, object, or shared; defaults to shared)
         """
         if schedule_at and immediate:
             raise ValueError(_("enqueue() cannot be called with values for both schedule_at and immediate."))
+        if access is None:
+            access = JobAccessChoices.ACCESS_SHARED
+        if access == JobAccessChoices.ACCESS_OBJECT and instance is None:
+            raise ValueError(_("A job with object access must be assigned to an object."))
 
         if instance:
             object_type = ObjectType.objects.get_for_model(instance, for_concrete_model=False)
@@ -357,7 +370,8 @@ class Job(models.Model):
             user=user,
             job_id=uuid.uuid4(),
             queue_name=rq_queue_name,
-            notifications=notifications if notifications is not None else JobNotificationChoices.NOTIFICATION_ALWAYS
+            notifications=notifications if notifications is not None else JobNotificationChoices.NOTIFICATION_ALWAYS,
+            access=access,
         )
         job.full_clean()
         job.save()

+ 42 - 0
netbox/core/querysets.py

@@ -1,14 +1,56 @@
 from django.apps import apps
 from django.contrib.contenttypes.models import ContentType
+from django.db.models import Q
 from django.db.utils import ProgrammingError
 
+from netbox.registry import registry
 from utilities.querysets import RestrictedQuerySet
 
+from .choices import JobAccessChoices
+
 __all__ = (
+    'JobQuerySet',
     'ObjectChangeQuerySet',
 )
 
 
+class JobQuerySet(RestrictedQuerySet):
+
+    def restrict(self, user, action='view'):
+        """
+        Additionally limit the jobs returned to those permitted by each job's access class (see JobAccessChoices).
+        """
+        queryset = super().restrict(user, action)
+
+        # Superusers can access all jobs, and there's nothing left to filter if the user has no permission
+        if (user and user.is_active and user.is_superuser) or queryset.query.is_empty():
+            return queryset
+
+        access = Q(access=JobAccessChoices.ACCESS_SHARED)
+        if user is not None and user.is_authenticated:
+            access |= Q(access=JobAccessChoices.ACCESS_REQUESTER, user=user)
+
+        # Object jobs are limited to those whose assigned object the user can view. A job assigned to a model which
+        # is no longer installed (e.g. that of a removed plugin) can't be evaluated, and is excluded.
+        supports_jobs = registry['model_features']['jobs']
+        for model in apps.get_models():
+            if not supports_jobs(model):
+                continue
+            objects = model._default_manager.all()
+            if not hasattr(objects, 'restrict'):
+                continue
+            objects = objects.restrict(user, 'view')
+            if objects.query.is_empty():
+                continue
+            access |= Q(
+                access=JobAccessChoices.ACCESS_OBJECT,
+                object_type=ContentType.objects.get_for_model(model, for_concrete_model=False),
+                object_id__in=objects.values('pk'),
+            )
+
+        return queryset.filter(access)
+
+
 class ObjectChangeQuerySet(RestrictedQuerySet):
 
     def valid_models(self):

+ 4 - 1
netbox/core/tables/jobs.py

@@ -51,6 +51,9 @@ class JobTable(NetBoxTable):
     queue_name = tables.Column(
         verbose_name=_('Queue'),
     )
+    access = columns.ChoiceFieldColumn(
+        verbose_name=_('Access'),
+    )
     log_entries = tables.Column(
         verbose_name=_('Log Entries'),
     )
@@ -62,7 +65,7 @@ class JobTable(NetBoxTable):
         model = Job
         fields = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'scheduled', 'interval', 'started',
-            'completed', 'execution_time', 'user', 'queue_name', 'log_entries', 'error', 'job_id',
+            'completed', 'execution_time', 'user', 'queue_name', 'access', 'log_entries', 'error', 'job_id',
         )
         default_columns = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'started', 'completed', 'execution_time',

+ 29 - 1
netbox/core/tests/test_api.py

@@ -16,7 +16,7 @@ from core.api.serializers import DataSourceSerializer
 from dcim.choices import PortTypeChoices
 from dcim.models import FrontPort, PortMapping, RearPort, Site
 from users.constants import TOKEN_PREFIX
-from users.models import ObjectPermission, Token
+from users.models import ObjectPermission, Token, User
 from utilities.testing import APITestCase, APIViewTestCases, GraphQLQueryTest, TestCase, create_tags, create_test_device
 from utilities.testing.mixins import RQQueueTestMixin
 from utilities.testing.utils import disable_logging
@@ -327,6 +327,34 @@ class JobTestCase(
             ]
         )
 
+    def test_job_access(self):
+        """Jobs are limited to those permitted by their access class."""
+        other_user = User.objects.create_user(username='otheruser')
+        own_job, other_job, object_job = Job.objects.bulk_create([
+            Job(name='Own job', job_id=uuid.uuid4(), user=self.user, access='requester'),
+            Job(name='Other job', job_id=uuid.uuid4(), user=other_user, access='requester'),
+            Job(
+                name='Object job', job_id=uuid.uuid4(), access='object',
+                object_type=ContentType.objects.get_for_model(DataSource), object_id=DataSource.objects.first().pk,
+            ),
+        ])
+        self.add_permissions('core.view_job')
+        url = reverse('core-api:job-list')
+
+        # Another user's requester job isn't listed, and can't be retrieved
+        response = self.client.get(url, **self.header)
+        listed = {job['id'] for job in response.data['results']}
+        self.assertIn(own_job.pk, listed)
+        self.assertNotIn(other_job.pk, listed)
+        self.assertNotIn(object_job.pk, listed)
+        response = self.client.get(self._get_detail_url(other_job), **self.header)
+        self.assertHttpStatus(response, status.HTTP_404_NOT_FOUND)
+
+        # An object job requires permission to view its assigned object
+        self.add_permissions('core.view_datasource')
+        response = self.client.get(self._get_detail_url(object_job), **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+
     def test_list_objects_by_execution_time(self):
         """The Job list endpoint supports filtering and ordering by execution_time."""
         self.add_permissions('core.view_job')

+ 7 - 0
netbox/core/tests/test_filtersets.py

@@ -276,11 +276,13 @@ class JobTestCase(TestCase, BaseFilterSetTestMixin):
                 name='Job 1', job_id=uuid.uuid4(), user=users[0],
                 notifications=JobNotificationChoices.NOTIFICATION_ALWAYS,
                 execution_time=timedelta(seconds=30),
+                access=JobAccessChoices.ACCESS_REQUESTER,
             ),
             Job(
                 name='Job 2', job_id=uuid.uuid4(), user=users[0],
                 notifications=JobNotificationChoices.NOTIFICATION_ALWAYS,
                 execution_time=timedelta(seconds=60),
+                access=JobAccessChoices.ACCESS_OBJECT,
             ),
             Job(
                 name='Job 3', job_id=uuid.uuid4(), user=users[1],
@@ -309,6 +311,11 @@ class JobTestCase(TestCase, BaseFilterSetTestMixin):
         ]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
 
+    def test_access(self):
+        """Filter Jobs by access class."""
+        params = {'access': [JobAccessChoices.ACCESS_REQUESTER, JobAccessChoices.ACCESS_OBJECT]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_execution_time(self):
         """Filter Jobs by execution time (exact value and gte/lte range)."""
         params = {'execution_time': timedelta(seconds=60)}

+ 88 - 2
netbox/core/tests/test_models.py

@@ -6,6 +6,7 @@ from io import StringIO
 from pathlib import Path
 from unittest.mock import MagicMock, patch
 
+from django.contrib.auth.models import AnonymousUser
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ObjectDoesNotExist
 from django.core.management import call_command
@@ -15,7 +16,13 @@ from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
 from django.utils import timezone
 
-from core.choices import DataSourceStatusChoices, JobNotificationChoices, JobStatusChoices, ObjectChangeActionChoices
+from core.choices import (
+    DataSourceStatusChoices,
+    JobAccessChoices,
+    JobNotificationChoices,
+    JobStatusChoices,
+    ObjectChangeActionChoices,
+)
 from core.data_backends import LocalBackend
 from core.events import JOB_COMPLETED, JOB_FAILED
 from core.exceptions import SyncError
@@ -24,7 +31,7 @@ from core.signals import post_sync
 from dcim.models import Device, Location, Site
 from extras.models import ConfigTemplate, Notification, Script
 from netbox.constants import CENSOR_TOKEN, CENSOR_TOKEN_CHANGED
-from users.models import User
+from users.models import ObjectPermission, User
 from utilities.querysets import RestrictedQuerySet
 from utilities.testing import PinnedConnectionRouter
 
@@ -672,3 +679,82 @@ class JobTestCase(TestCase):
         # Jobs for custom scripts link to the script result view
         job = Job(pk=123, name='Test Job', object_type=ObjectType.objects.get_for_model(Script), object_id=1)
         self.assertEqual(job.get_absolute_url(), reverse('extras:script_result', kwargs={'job_pk': 123}))
+
+
+class JobAccessTestCase(TestCase):
+    """
+    Job.objects.restrict() must limit jobs to those permitted by their access class.
+    """
+    ALL_JOBS = {'shared', 'own', 'other', 'unowned', 'source1', 'source2', 'stale'}
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.user = User.objects.create_user(username='user1')
+        other_user = User.objects.create_user(username='user2')
+        datasources = [
+            DataSource.objects.create(name=f'Data Source {i}', type='local', source_url=f'file:///var/tmp/source{i}/')
+            for i in (1, 2)
+        ]
+        datasource_type = ContentType.objects.get_for_model(DataSource)
+        # An object type for a model which is no longer installed (e.g. that of a removed plugin)
+        stale_type = ContentType.objects.create(app_label='removed_plugin', model='widget')
+
+        Job.objects.bulk_create([
+            Job(name=name, job_id=uuid.uuid4(), access=access, **kwargs)
+            for name, access, kwargs in (
+                ('shared', JobAccessChoices.ACCESS_SHARED, {}),
+                ('own', JobAccessChoices.ACCESS_REQUESTER, {'user': cls.user}),
+                ('other', JobAccessChoices.ACCESS_REQUESTER, {'user': other_user}),
+                ('unowned', JobAccessChoices.ACCESS_REQUESTER, {}),
+                ('source1', JobAccessChoices.ACCESS_OBJECT, {
+                    'object_type': datasource_type, 'object_id': datasources[0].pk,
+                }),
+                ('source2', JobAccessChoices.ACCESS_OBJECT, {
+                    'object_type': datasource_type, 'object_id': datasources[1].pk,
+                }),
+                ('stale', JobAccessChoices.ACCESS_OBJECT, {'object_type': stale_type, 'object_id': 1}),
+            )
+        ])
+
+    def _grant(self, model, actions=('view',), constraints=None):
+        permission = ObjectPermission.objects.create(
+            name=f'{model._meta.model_name} {actions}', actions=list(actions), constraints=constraints
+        )
+        permission.users.add(self.user)
+        permission.object_types.add(ObjectType.objects.get_for_model(model))
+
+    def _visible_jobs(self, user=None, action='view'):
+        # Re-fetch the user so that its permissions cache reflects any permissions granted
+        user = user or User.objects.get(pk=self.user.pk)
+        return set(Job.objects.restrict(user, action).values_list('name', flat=True))
+
+    def test_superuser_can_access_all_jobs(self):
+        superuser = User.objects.create_user(username='superuser', is_superuser=True)
+        self.assertEqual(self._visible_jobs(superuser), self.ALL_JOBS)
+
+    def test_no_job_permission(self):
+        self._grant(DataSource)
+        self.assertEqual(self._visible_jobs(), set())
+
+    def test_requester_and_shared_jobs(self):
+        self._grant(Job)
+        self.assertEqual(self._visible_jobs(), {'shared', 'own'})
+
+    def test_object_jobs_require_permission_to_view_object(self):
+        self._grant(Job)
+        self._grant(DataSource, constraints={'name': 'Data Source 1'})
+        self.assertEqual(self._visible_jobs(), {'shared', 'own', 'source1'})
+
+    def test_job_permission_constraints_still_apply(self):
+        self._grant(Job, constraints={'name__in': ['shared', 'other', 'source1']})
+        self._grant(DataSource)
+        self.assertEqual(self._visible_jobs(), {'shared', 'source1'})
+
+    def test_access_applies_to_other_actions(self):
+        self._grant(Job, actions=('delete',))
+        self._grant(DataSource)
+        self.assertEqual(self._visible_jobs(action='delete'), {'shared', 'own', 'source1', 'source2'})
+
+    @override_settings(EXEMPT_VIEW_PERMISSIONS=['core.job', 'core.datasource'])
+    def test_exempt_view_permissions(self):
+        self.assertEqual(self._visible_jobs(AnonymousUser()), {'shared', 'source1', 'source2'})

+ 1 - 0
netbox/core/ui/panels.py

@@ -54,6 +54,7 @@ class JobPanel(panels.ObjectAttributesPanel):
     status = attrs.ChoiceAttr('status')
     error = attrs.TextAttr('error')
     user = attrs.TextAttr('user', label=_('Created by'))
+    access = attrs.ChoiceAttr('access')
 
 
 class JobSchedulingPanel(panels.ObjectAttributesPanel):

+ 2 - 0
netbox/extras/jobs.py

@@ -8,6 +8,7 @@ from django.urls import reverse
 from django.utils.translation import gettext as _
 from django_pg_utils import advisory_lock
 
+from core.choices import JobAccessChoices
 from core.signals import clear_events
 from core.utils import register_job_result_url
 from dcim.models import Device
@@ -277,6 +278,7 @@ class ScriptJob(JobRunner):
 
     class Meta:
         name = 'Run Script'
+        access = JobAccessChoices.ACCESS_OBJECT
 
     @classmethod
     def enqueue(cls, *args, **kwargs):

+ 10 - 5
netbox/netbox/jobs.py

@@ -21,7 +21,7 @@ from django_pg_utils import advisory_lock
 from rest_framework.exceptions import APIException
 from rq.timeouts import JobTimeoutException
 
-from core.choices import JobStatusChoices
+from core.choices import JobAccessChoices, JobStatusChoices
 from core.exceptions import JobFailed
 from core.models import Job, ObjectType
 from netbox.constants import ADVISORY_LOCK_KEYS
@@ -198,12 +198,14 @@ class JobRunner(ABC):
                 schedule_at=new_scheduled_time,
                 interval=job.interval,
                 notifications=job.notifications,
+                access=job.access,
                 **kwargs,
             )
-        except ValidationError as e:
-            # Keep the run's outcome when invalid configuration blocks the reschedule (see #22872)
+        except (ValidationError, ValueError) as e:
+            # Keep the run's outcome when invalid configuration blocks the reschedule (see #22872). A ValueError is
+            # raised for an object job whose assigned object no longer exists.
             message = _("Recurring job not rescheduled due to invalid configuration: {error}").format(
-                error='; '.join(e.messages)
+                error='; '.join(e.messages) if isinstance(e, ValidationError) else str(e)
             )
             logger.error(f"Job {job}: {message}")
             job.log(logging.makeLogRecord({
@@ -238,7 +240,8 @@ class JobRunner(ABC):
         parameters.
         """
         name = kwargs.pop('name', None) or cls.name
-        return Job.enqueue(cls.handle, name=name, *args, **kwargs)
+        access = kwargs.pop('access', None) or getattr(cls.Meta, 'access', JobAccessChoices.ACCESS_SHARED)
+        return Job.enqueue(cls.handle, name=name, access=access, *args, **kwargs)
 
     @classmethod
     @advisory_lock(ADVISORY_LOCK_KEYS['job-schedules'])
@@ -284,6 +287,7 @@ class AsyncViewJob(JobRunner):
     """
     class Meta:
         name = 'Async View'
+        access = JobAccessChoices.ACCESS_REQUESTER
 
     def run(self, view_cls, request, **kwargs):
         view = view_cls.as_view()
@@ -308,6 +312,7 @@ class AsyncAPIJob(JobRunner):
     """
     class Meta:
         name = 'Async API Request'
+        access = JobAccessChoices.ACCESS_REQUESTER
 
     @staticmethod
     def _build_request(request_copy, payload, scheme):

+ 66 - 1
netbox/netbox/tests/test_jobs.py

@@ -12,13 +12,15 @@ from django.utils import timezone
 from django_pg_utils import advisory_lock
 from django_rq import get_queue
 
-from core.choices import JobStatusChoices
+from core.choices import JobAccessChoices, JobStatusChoices
 from core.events import JOB_COMPLETED, JOB_FAILED
 from core.exceptions import JobFailed
+from core.jobs import SyncDataSourceJob, SystemHousekeepingJob
 from core.models import DataSource, Job
 from core.signals import job_end
 from dcim.models import Site
 from dcim.views import SiteBulkEditView
+from extras.jobs import ScriptJob
 from extras.models import Notification
 from users.models import User
 from utilities.request import copy_safe_request
@@ -276,6 +278,35 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
                 self.assertEqual(observed, [(status, [successor.pk])])
                 self.assertEqual((successor.status, successor.interval), (JobStatusChoices.STATUS_SCHEDULED, 60))
 
+    def test_handle_reschedule_keeps_access(self):
+        """A periodic job's successor has the same access class."""
+        instance = DataSource.objects.create(name='Data Source 1', type='local')
+        job = TestJobRunner.enqueue(
+            instance, interval=60, schedule_at=self.get_schedule_at(), access=JobAccessChoices.ACCESS_REQUESTER
+        )
+        TestJobRunner.handle(job)
+
+        successor = TestJobRunner.get_jobs(instance).exclude(pk=job.pk).get()
+        self.assertEqual(successor.access, JobAccessChoices.ACCESS_REQUESTER)
+
+    def test_handle_object_job_without_object_is_not_rescheduled(self):
+        """A periodic object job whose assigned object is gone completes without being rescheduled."""
+        instance = DataSource.objects.create(name='Data Source 1', type='local')
+        job = TestJobRunner.enqueue(
+            instance, interval=60, schedule_at=self.get_schedule_at(), access=JobAccessChoices.ACCESS_OBJECT
+        )
+        # Point the job at an object which doesn't exist
+        Job.objects.filter(pk=job.pk).update(object_id=instance.pk + 1000)
+        job = Job.objects.get(pk=job.pk)
+
+        with disable_logging():
+            TestJobRunner.handle(job)
+
+        job.refresh_from_db()
+        self.assertEqual(job.status, JobStatusChoices.STATUS_COMPLETED)
+        self.assertIn('not rescheduled', job.log_entries[-1]['message'])
+        self.assertEqual(Job.objects.count(), 1)
+
     def test_handle_keeps_run_outcome_when_reschedule_is_invalid(self):
         """A reschedule rejected as invalid keeps the run's outcome and ends the job once."""
         user = User.objects.create_user(username='job-owner')
@@ -388,6 +419,40 @@ class EnqueueTestCase(BaseJobRunnerTestCase):
             self.assertIsInstance(job, Job)
             self.assertEqual(TestJobRunner.get_jobs(instance).count(), i)
 
+    def test_enqueue_access(self):
+        class ObjectJobRunner(TestJobRunner):
+            class Meta:
+                access = JobAccessChoices.ACCESS_OBJECT
+
+        # The runner's default access class
+        job = TestJobRunner.enqueue(DataSource(), schedule_at=self.get_schedule_at())
+        self.assertEqual(job.access, JobAccessChoices.ACCESS_SHARED)
+        job = ObjectJobRunner.enqueue(DataSource(), schedule_at=self.get_schedule_at())
+        self.assertEqual(job.access, JobAccessChoices.ACCESS_OBJECT)
+
+        # Overridden for an individual job
+        job = ObjectJobRunner.enqueue(
+            DataSource(), schedule_at=self.get_schedule_at(), access=JobAccessChoices.ACCESS_REQUESTER
+        )
+        self.assertEqual(job.access, JobAccessChoices.ACCESS_REQUESTER)
+
+    def test_enqueue_object_access_requires_instance(self):
+        with self.assertRaises(ValueError):
+            TestJobRunner.enqueue(schedule_at=self.get_schedule_at(), access=JobAccessChoices.ACCESS_OBJECT)
+        self.assertFalse(Job.objects.exists())
+
+    def test_core_job_runner_access(self):
+        expected = {
+            AsyncAPIJob: JobAccessChoices.ACCESS_REQUESTER,
+            AsyncViewJob: JobAccessChoices.ACCESS_REQUESTER,
+            ScriptJob: JobAccessChoices.ACCESS_OBJECT,
+            SyncDataSourceJob: JobAccessChoices.ACCESS_OBJECT,
+            SystemHousekeepingJob: JobAccessChoices.ACCESS_SHARED,
+        }
+        for runner, access in expected.items():
+            with self.subTest(runner=runner.__name__):
+                self.assertEqual(getattr(runner.Meta, 'access', JobAccessChoices.ACCESS_SHARED), access)
+
     def test_enqueue_once(self):
         job = TestJobRunner.enqueue_once(instance=DataSource(), schedule_at=self.get_schedule_at())