authentik.enterprise.requests.tests.test_grant_requests_agents

  1from datetime import timedelta
  2
  3from django.urls import reverse
  4from django.utils.timezone import now
  5from rest_framework.test import APIClient, APITestCase
  6
  7from authentik.core.models import (
  8    ActorPolicyInheritance,
  9    Application,
 10    ApplicationEntitlement,
 11    Token,
 12    TokenIntents,
 13    User,
 14    UserTypes,
 15    default_token_duration,
 16)
 17from authentik.core.tests.utils import create_test_user
 18from authentik.enterprise.agents.models import Agent
 19from authentik.enterprise.requests.models import (
 20    GrantRequest,
 21    RequestRule,
 22    RequestRuleBinding,
 23    RequestStatus,
 24)
 25from authentik.enterprise.tests import enterprise_test
 26from authentik.lib.generators import generate_id
 27from authentik.lib.utils.time import timedelta_from_string
 28from authentik.policies.engine import PolicyEngine
 29from authentik.policies.models import PolicyBinding, PolicyBindingModel
 30
 31
 32@enterprise_test()
 33class AgentGrantRequestTests(APITestCase):
 34    """An agent inherits no access, so it earns it by asking its owner to delegate some. It may
 35    only ask for what the owner already holds -- no flow runs on this path, so there is no
 36    justification to hand a reviewer -- and the owner's approval is the whole decision."""
 37
 38    def _app(self) -> Application:
 39        return Application.objects.create(name=generate_id(), slug=generate_id())
 40
 41    def _entitlement(self, app: Application) -> ApplicationEntitlement:
 42        return ApplicationEntitlement.objects.create(app=app, name=generate_id())
 43
 44    def _agent_for(self, owner: User) -> tuple[Agent, APIClient]:
 45        """A self-service-shaped agent (no inherited access) plus a client authenticating
 46        as it, exactly as a harness holding the agent's API token would."""
 47        agent = Agent.create_for_user(
 48            owner,
 49            expiring=True,
 50            expires=default_token_duration(),
 51            policy_behavior=ActorPolicyInheritance.NONE,
 52        )
 53        token = Token.objects.create(
 54            identifier=agent.username,
 55            intent=TokenIntents.INTENT_API,
 56            user=agent,
 57            expiring=True,
 58            expires=default_token_duration(),
 59        )
 60        client = APIClient()
 61        client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.key}")
 62        return agent, client
 63
 64    def _request_access(self, client: APIClient, *pbms):
 65        return client.post(
 66            reverse("authentik_api:grantrequest-agent"),
 67            data={"pbms": [str(pbm.pk) for pbm in pbms]},
 68            format="json",
 69        )
 70
 71    def _fulfill(self, user: User, req: GrantRequest, status: str = "approved"):
 72        self.client.force_login(user)
 73        return self.client.patch(
 74            reverse("authentik_api:grantrequest-fulfill", kwargs={"pk": req.pk}),
 75            data={"status": status, "data": {}},
 76        )
 77
 78    def _requestable_by(
 79        self, target: PolicyBindingModel, requester: User, reviewer: User
 80    ) -> RequestRule:
 81        """Wire `target` up so `requester` may request it and `reviewer` may approve."""
 82        rule = RequestRule.objects.create(name=generate_id())
 83        rule_binding = RequestRuleBinding.objects.create(rule=rule, target=target)
 84        PolicyBinding.objects.create(target=rule_binding, user=requester, order=0)
 85        PolicyBinding.objects.create(target=rule, user=reviewer, order=0)
 86        return rule
 87
 88    def test_owner_already_has_access_owner_approval_suffices(self):
 89        """The owner can already reach the target, so there is nothing for reviewers to
 90        decide -- the owner's own approval grants the agent access."""
 91        owner = create_test_user()
 92        app = self._app()
 93        PolicyBinding.objects.create(target=app, user=owner, order=0)
 94        agent, agent_client = self._agent_for(owner)
 95
 96        # The agent starts with nothing, even though its owner passes.
 97        self.assertTrue(PolicyEngine(app, owner).build().passing)
 98        self.assertFalse(PolicyEngine(app, agent).build().passing)
 99
100        res = self._request_access(agent_client, app)
101        self.assertEqual(res.status_code, 201, res.content)
102        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
103        self.assertEqual(req.created_by_id, agent.pk)
104        self.assertEqual(req.agent_owner_id, owner.pk)
105
106        res = self._fulfill(owner, req)
107        self.assertEqual(res.status_code, 204, res.content)
108        req.refresh_from_db()
109        self.assertEqual(req.status, RequestStatus.APPROVED)
110        # The grant lands on the agent, not on the owner who approved it.
111        self.assertTrue(PolicyBinding.objects.filter(user=agent, target=app).exists())
112        self.assertTrue(PolicyEngine(app, agent).build().passing)
113
114    def test_response_carries_fulfill_url_for_the_owner(self):
115        """An agent has no browser, so it gets back the URL its owner opens to act on the
116        request -- the same deep link the created event points at."""
117        owner = create_test_user()
118        app = self._app()
119        PolicyBinding.objects.create(target=app, user=owner, order=0)
120        _, agent_client = self._agent_for(owner)
121
122        body = self._request_access(agent_client, app).json()
123        req = GrantRequest.objects.get(pk=body["grant_request"]["uuid"])
124        # Absolute, so it is usable verbatim by whatever the agent hands it to.
125        self.assertTrue(body["fulfill_url"].startswith("http"))
126        self.assertTrue(
127            body["fulfill_url"].endswith(f"#/requests/access-request/{req.uuid}/fulfill"),
128            body["fulfill_url"],
129        )
130
131    def test_target_owner_may_only_request_is_rejected(self):
132        """A target the owner could request but does not yet hold is refused: approving it
133        would mean asking a reviewer to judge a request with no justification, since no flow
134        runs on this path."""
135        owner = create_test_user()
136        reviewer = create_test_user()
137        app = self._app()
138        # Bound to somebody else, so the owner does not currently pass.
139        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
140        self._requestable_by(app, owner, reviewer)
141        _, agent_client = self._agent_for(owner)
142
143        res = self._request_access(agent_client, app)
144        self.assertEqual(res.status_code, 400, res.content)
145        self.assertFalse(GrantRequest.objects.exists())
146
147    def test_rule_reviewer_cannot_act_on_agent_request(self):
148        """A held target can still carry a RequestRule, but its reviewers have no say in an
149        agent's request -- they must not be able to deny it (a denial finalizes immediately)
150        or revoke the grant, and it must not show up in their queue."""
151        owner = create_test_user()
152        reviewer = create_test_user()
153        app = self._app()
154        PolicyBinding.objects.create(target=app, user=owner, order=0)
155        self._requestable_by(app, owner, reviewer)
156        agent, agent_client = self._agent_for(owner)
157
158        res = self._request_access(agent_client, app)
159        self.assertEqual(res.status_code, 201, res.content)
160        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
161
162        # Not in the reviewer's queue...
163        self.client.force_login(reviewer)
164        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
165        self.assertEqual(res.json()["results"], [])
166        # ...and they cannot deny it.
167        self.assertEqual(self._fulfill(reviewer, req, status="denied").status_code, 403)
168        req.refresh_from_db()
169        self.assertEqual(req.status, RequestStatus.CREATED)
170
171        # The owner approves; the reviewer still cannot revoke the resulting grant.
172        self.assertEqual(self._fulfill(owner, req).status_code, 204)
173        req.refresh_from_db()
174        self.assertEqual(req.status, RequestStatus.APPROVED)
175        self.client.force_login(reviewer)
176        res = self.client.delete(
177            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
178        )
179        self.assertEqual(res.status_code, 403, res.content)
180        req.refresh_from_db()
181        self.assertEqual(req.status, RequestStatus.APPROVED)
182        self.assertTrue(PolicyEngine(app, agent).build().passing)
183
184    def test_non_expiring_agent_cannot_request(self):
185        """Delegated access is bounded by the agent's own lifetime, so a standing agent has
186        nothing to bound the grant with and may not request at all."""
187        owner = create_test_user()
188        app = self._app()
189        PolicyBinding.objects.create(target=app, user=owner, order=0)
190        agent, agent_client = self._agent_for(owner)
191        agent.expiring = False
192        agent.expires = None
193        agent.save()
194
195        res = self._request_access(agent_client, app)
196        self.assertEqual(res.status_code, 403, res.content)
197        self.assertFalse(GrantRequest.objects.exists())
198
199    def test_owner_denial_finalizes_immediately(self):
200        owner = create_test_user()
201        app = self._app()
202        PolicyBinding.objects.create(target=app, user=owner, order=0)
203        agent, agent_client = self._agent_for(owner)
204
205        req = GrantRequest.objects.get(
206            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
207        )
208        res = self._fulfill(owner, req, status="denied")
209        self.assertEqual(res.status_code, 204, res.content)
210        req.refresh_from_db()
211        self.assertEqual(req.status, RequestStatus.DENIED)
212        self.assertFalse(PolicyBinding.objects.filter(user=agent, target=app).exists())
213
214    def test_target_owner_cannot_reach_is_rejected(self):
215        """An agent can never reach past its owner: a target the owner neither has access to
216        nor may request is refused outright."""
217        owner = create_test_user()
218        app = self._app()
219        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
220        _, agent_client = self._agent_for(owner)
221
222        res = self._request_access(agent_client, app)
223        self.assertEqual(res.status_code, 400, res.content)
224        self.assertFalse(GrantRequest.objects.exists())
225
226    def test_one_unheld_target_rejects_the_batch(self):
227        """A batch is all-or-nothing: one target the owner does not hold refuses the whole
228        request, so a held target cannot smuggle an unheld one through with it."""
229        owner = create_test_user()
230        reviewer = create_test_user()
231        held, requestable = self._app(), self._app()
232        PolicyBinding.objects.create(target=held, user=owner, order=0)
233        PolicyBinding.objects.create(target=requestable, user=create_test_user(), order=0)
234        self._requestable_by(requestable, owner, reviewer)
235        _, agent_client = self._agent_for(owner)
236
237        res = self._request_access(agent_client, held, requestable)
238        self.assertEqual(res.status_code, 400, res.content)
239        self.assertFalse(GrantRequest.objects.exists())
240
241    def test_entitlement_owner_holds_owner_approval_suffices(self):
242        """An entitlement the owner is actually bound to is genuinely held, so the owner's
243        approval alone grants it -- the application case, for a child target."""
244        owner = create_test_user()
245        app = self._app()
246        ent = self._entitlement(app)
247        PolicyBinding.objects.create(target=ent, user=owner, order=0)
248        agent, agent_client = self._agent_for(owner)
249
250        self.assertIn(ent, owner.app_entitlements(app))
251        self.assertNotIn(ent, agent.app_entitlements(app))
252
253        res = self._request_access(agent_client, ent)
254        self.assertEqual(res.status_code, 201, res.content)
255        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
256
257        self.assertEqual(self._fulfill(owner, req).status_code, 204)
258        req.refresh_from_db()
259        self.assertEqual(req.status, RequestStatus.APPROVED)
260        # Checked through authentik's own definition of holding an entitlement, not just the
261        # presence of a PolicyBinding row.
262        self.assertIn(ent, agent.app_entitlements(app))
263
264    def test_unbound_entitlement_rejected(self):
265        """An entitlement with no bindings is held by NOBODY -- unlike an application, where no
266        bindings means everyone -- so the owner does not hold it and the agent cannot ask for
267        it. True whether or not a RequestRule happens to cover it."""
268        owner = create_test_user()
269        reviewer = create_test_user()
270        app = self._app()
271        ruleless = self._entitlement(app)
272        covered = self._entitlement(app)
273        self._requestable_by(covered, owner, reviewer)
274        _, agent_client = self._agent_for(owner)
275
276        self.assertNotIn(ruleless, owner.app_entitlements(app))
277        self.assertNotIn(covered, owner.app_entitlements(app))
278
279        for ent in (ruleless, covered):
280            res = self._request_access(agent_client, ent)
281            self.assertEqual(res.status_code, 400, res.content)
282        self.assertFalse(GrantRequest.objects.exists())
283
284    def test_held_app_and_entitlement_batch(self):
285        """A held application and a held entitlement in one call: the two `_owner_holds`
286        engine passes combine, and both targets land on the request."""
287        owner = create_test_user()
288        app = self._app()
289        PolicyBinding.objects.create(target=app, user=owner, order=0)
290        ent = self._entitlement(self._app())
291        PolicyBinding.objects.create(target=ent, user=owner, order=0)
292        _, agent_client = self._agent_for(owner)
293
294        res = self._request_access(agent_client, app, ent)
295        self.assertEqual(res.status_code, 201, res.content)
296        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
297        self.assertEqual(req.targets.count(), 2)
298
299    def test_non_agent_callers_rejected(self):
300        """Only an agent may use this endpoint."""
301        user = create_test_user()
302        app = self._app()
303        PolicyBinding.objects.create(target=app, user=user, order=0)
304
305        self.client.force_login(user)
306        res = self.client.post(
307            reverse("authentik_api:grantrequest-agent"),
308            data={"pbms": [str(app.pk)]},
309            format="json",
310        )
311        self.assertEqual(res.status_code, 403, res.content)
312
313        # A plain service account is not an agent either.
314        service_account = User.objects.create(
315            username=generate_id(), type=UserTypes.SERVICE_ACCOUNT
316        )
317        token = Token.objects.create(
318            identifier=generate_id(),
319            intent=TokenIntents.INTENT_API,
320            user=service_account,
321            expiring=False,
322        )
323        client = APIClient()
324        client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.key}")
325        res = self._request_access(client, app)
326        self.assertEqual(res.status_code, 403, res.content)
327
328    def test_orphaned_agent_rejected(self):
329        """Deleting the owner orphans the agent (Actor.parent is SET_DEFAULT); with nobody
330        left to approve, it cannot request anything."""
331        owner = create_test_user()
332        app = self._app()
333        PolicyBinding.objects.create(target=app, user=owner, order=0)
334        agent, agent_client = self._agent_for(owner)
335
336        owner.delete()
337        agent.refresh_from_db()
338        self.assertIsNone(agent.parent)
339
340        res = self._request_access(agent_client, app)
341        self.assertEqual(res.status_code, 403, res.content)
342
343    def test_agent_cannot_fulfill_its_own_request(self):
344        owner = create_test_user()
345        app = self._app()
346        PolicyBinding.objects.create(target=app, user=owner, order=0)
347        _, agent_client = self._agent_for(owner)
348
349        req = GrantRequest.objects.get(
350            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
351        )
352        res = agent_client.patch(
353            reverse("authentik_api:grantrequest-fulfill", kwargs={"pk": req.pk}),
354            data={"status": "approved", "data": {}},
355            format="json",
356        )
357        self.assertEqual(res.status_code, 403, res.content)
358        req.refresh_from_db()
359        self.assertEqual(req.status, RequestStatus.CREATED)
360
361    def test_owner_can_revoke_without_being_a_reviewer(self):
362        """The owner can end their agent's grant on their own -- reviewer eligibility never
363        enters into it."""
364        owner = create_test_user()
365        app = self._app()
366        PolicyBinding.objects.create(target=app, user=owner, order=0)
367        agent, agent_client = self._agent_for(owner)
368
369        req = GrantRequest.objects.get(
370            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
371        )
372        self._fulfill(owner, req)
373        self.assertTrue(PolicyEngine(app, agent).build().passing)
374
375        self.client.force_login(owner)
376        res = self.client.delete(
377            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
378        )
379        self.assertEqual(res.status_code, 204, res.content)
380        req.refresh_from_db()
381        self.assertEqual(req.status, RequestStatus.REVOKED)
382        self.assertFalse(PolicyEngine(app, agent).build().passing)
383
384    def test_grant_never_outlives_the_agent(self):
385        """The granted duration is capped by the agent's own expiry, so a grant can't hand
386        out access that survives the identity holding it."""
387        owner = create_test_user()
388        app = self._app()
389        PolicyBinding.objects.create(target=app, user=owner, order=0)
390        agent, agent_client = self._agent_for(owner)
391        # Well inside the "hours=1" default the request would otherwise pick up.
392        agent.expires = now() + timedelta(minutes=5)
393        agent.save()
394
395        req = GrantRequest.objects.get(
396            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
397        )
398        self.assertLessEqual(timedelta_from_string(req.requested_expiry), timedelta(minutes=5))
399        self.assertGreater(timedelta_from_string(req.requested_expiry), timedelta(minutes=4))
400
401    def test_pending_review_surfaces_agent_request_to_owner(self):
402        """An agent request reaches its owner through ownership rather than through reviewer
403        eligibility, and reaches nobody else."""
404        owner = create_test_user()
405        outsider = create_test_user()
406        app = self._app()
407        PolicyBinding.objects.create(target=app, user=owner, order=0)
408        _, agent_client = self._agent_for(owner)
409
410        req = GrantRequest.objects.get(
411            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
412        )
413
414        self.client.force_login(owner)
415        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
416        self.assertEqual(res.status_code, 200, res.content)
417        self.assertEqual({r["uuid"] for r in res.json()["results"]}, {str(req.pk)})
418
419        self.client.force_login(outsider)
420        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
421        self.assertEqual(res.status_code, 200, res.content)
422        self.assertEqual(res.json()["results"], [])
@enterprise_test()
class AgentGrantRequestTests(rest_framework.test.APITestCase):
 33@enterprise_test()
 34class AgentGrantRequestTests(APITestCase):
 35    """An agent inherits no access, so it earns it by asking its owner to delegate some. It may
 36    only ask for what the owner already holds -- no flow runs on this path, so there is no
 37    justification to hand a reviewer -- and the owner's approval is the whole decision."""
 38
 39    def _app(self) -> Application:
 40        return Application.objects.create(name=generate_id(), slug=generate_id())
 41
 42    def _entitlement(self, app: Application) -> ApplicationEntitlement:
 43        return ApplicationEntitlement.objects.create(app=app, name=generate_id())
 44
 45    def _agent_for(self, owner: User) -> tuple[Agent, APIClient]:
 46        """A self-service-shaped agent (no inherited access) plus a client authenticating
 47        as it, exactly as a harness holding the agent's API token would."""
 48        agent = Agent.create_for_user(
 49            owner,
 50            expiring=True,
 51            expires=default_token_duration(),
 52            policy_behavior=ActorPolicyInheritance.NONE,
 53        )
 54        token = Token.objects.create(
 55            identifier=agent.username,
 56            intent=TokenIntents.INTENT_API,
 57            user=agent,
 58            expiring=True,
 59            expires=default_token_duration(),
 60        )
 61        client = APIClient()
 62        client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.key}")
 63        return agent, client
 64
 65    def _request_access(self, client: APIClient, *pbms):
 66        return client.post(
 67            reverse("authentik_api:grantrequest-agent"),
 68            data={"pbms": [str(pbm.pk) for pbm in pbms]},
 69            format="json",
 70        )
 71
 72    def _fulfill(self, user: User, req: GrantRequest, status: str = "approved"):
 73        self.client.force_login(user)
 74        return self.client.patch(
 75            reverse("authentik_api:grantrequest-fulfill", kwargs={"pk": req.pk}),
 76            data={"status": status, "data": {}},
 77        )
 78
 79    def _requestable_by(
 80        self, target: PolicyBindingModel, requester: User, reviewer: User
 81    ) -> RequestRule:
 82        """Wire `target` up so `requester` may request it and `reviewer` may approve."""
 83        rule = RequestRule.objects.create(name=generate_id())
 84        rule_binding = RequestRuleBinding.objects.create(rule=rule, target=target)
 85        PolicyBinding.objects.create(target=rule_binding, user=requester, order=0)
 86        PolicyBinding.objects.create(target=rule, user=reviewer, order=0)
 87        return rule
 88
 89    def test_owner_already_has_access_owner_approval_suffices(self):
 90        """The owner can already reach the target, so there is nothing for reviewers to
 91        decide -- the owner's own approval grants the agent access."""
 92        owner = create_test_user()
 93        app = self._app()
 94        PolicyBinding.objects.create(target=app, user=owner, order=0)
 95        agent, agent_client = self._agent_for(owner)
 96
 97        # The agent starts with nothing, even though its owner passes.
 98        self.assertTrue(PolicyEngine(app, owner).build().passing)
 99        self.assertFalse(PolicyEngine(app, agent).build().passing)
100
101        res = self._request_access(agent_client, app)
102        self.assertEqual(res.status_code, 201, res.content)
103        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
104        self.assertEqual(req.created_by_id, agent.pk)
105        self.assertEqual(req.agent_owner_id, owner.pk)
106
107        res = self._fulfill(owner, req)
108        self.assertEqual(res.status_code, 204, res.content)
109        req.refresh_from_db()
110        self.assertEqual(req.status, RequestStatus.APPROVED)
111        # The grant lands on the agent, not on the owner who approved it.
112        self.assertTrue(PolicyBinding.objects.filter(user=agent, target=app).exists())
113        self.assertTrue(PolicyEngine(app, agent).build().passing)
114
115    def test_response_carries_fulfill_url_for_the_owner(self):
116        """An agent has no browser, so it gets back the URL its owner opens to act on the
117        request -- the same deep link the created event points at."""
118        owner = create_test_user()
119        app = self._app()
120        PolicyBinding.objects.create(target=app, user=owner, order=0)
121        _, agent_client = self._agent_for(owner)
122
123        body = self._request_access(agent_client, app).json()
124        req = GrantRequest.objects.get(pk=body["grant_request"]["uuid"])
125        # Absolute, so it is usable verbatim by whatever the agent hands it to.
126        self.assertTrue(body["fulfill_url"].startswith("http"))
127        self.assertTrue(
128            body["fulfill_url"].endswith(f"#/requests/access-request/{req.uuid}/fulfill"),
129            body["fulfill_url"],
130        )
131
132    def test_target_owner_may_only_request_is_rejected(self):
133        """A target the owner could request but does not yet hold is refused: approving it
134        would mean asking a reviewer to judge a request with no justification, since no flow
135        runs on this path."""
136        owner = create_test_user()
137        reviewer = create_test_user()
138        app = self._app()
139        # Bound to somebody else, so the owner does not currently pass.
140        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
141        self._requestable_by(app, owner, reviewer)
142        _, agent_client = self._agent_for(owner)
143
144        res = self._request_access(agent_client, app)
145        self.assertEqual(res.status_code, 400, res.content)
146        self.assertFalse(GrantRequest.objects.exists())
147
148    def test_rule_reviewer_cannot_act_on_agent_request(self):
149        """A held target can still carry a RequestRule, but its reviewers have no say in an
150        agent's request -- they must not be able to deny it (a denial finalizes immediately)
151        or revoke the grant, and it must not show up in their queue."""
152        owner = create_test_user()
153        reviewer = create_test_user()
154        app = self._app()
155        PolicyBinding.objects.create(target=app, user=owner, order=0)
156        self._requestable_by(app, owner, reviewer)
157        agent, agent_client = self._agent_for(owner)
158
159        res = self._request_access(agent_client, app)
160        self.assertEqual(res.status_code, 201, res.content)
161        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
162
163        # Not in the reviewer's queue...
164        self.client.force_login(reviewer)
165        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
166        self.assertEqual(res.json()["results"], [])
167        # ...and they cannot deny it.
168        self.assertEqual(self._fulfill(reviewer, req, status="denied").status_code, 403)
169        req.refresh_from_db()
170        self.assertEqual(req.status, RequestStatus.CREATED)
171
172        # The owner approves; the reviewer still cannot revoke the resulting grant.
173        self.assertEqual(self._fulfill(owner, req).status_code, 204)
174        req.refresh_from_db()
175        self.assertEqual(req.status, RequestStatus.APPROVED)
176        self.client.force_login(reviewer)
177        res = self.client.delete(
178            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
179        )
180        self.assertEqual(res.status_code, 403, res.content)
181        req.refresh_from_db()
182        self.assertEqual(req.status, RequestStatus.APPROVED)
183        self.assertTrue(PolicyEngine(app, agent).build().passing)
184
185    def test_non_expiring_agent_cannot_request(self):
186        """Delegated access is bounded by the agent's own lifetime, so a standing agent has
187        nothing to bound the grant with and may not request at all."""
188        owner = create_test_user()
189        app = self._app()
190        PolicyBinding.objects.create(target=app, user=owner, order=0)
191        agent, agent_client = self._agent_for(owner)
192        agent.expiring = False
193        agent.expires = None
194        agent.save()
195
196        res = self._request_access(agent_client, app)
197        self.assertEqual(res.status_code, 403, res.content)
198        self.assertFalse(GrantRequest.objects.exists())
199
200    def test_owner_denial_finalizes_immediately(self):
201        owner = create_test_user()
202        app = self._app()
203        PolicyBinding.objects.create(target=app, user=owner, order=0)
204        agent, agent_client = self._agent_for(owner)
205
206        req = GrantRequest.objects.get(
207            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
208        )
209        res = self._fulfill(owner, req, status="denied")
210        self.assertEqual(res.status_code, 204, res.content)
211        req.refresh_from_db()
212        self.assertEqual(req.status, RequestStatus.DENIED)
213        self.assertFalse(PolicyBinding.objects.filter(user=agent, target=app).exists())
214
215    def test_target_owner_cannot_reach_is_rejected(self):
216        """An agent can never reach past its owner: a target the owner neither has access to
217        nor may request is refused outright."""
218        owner = create_test_user()
219        app = self._app()
220        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
221        _, agent_client = self._agent_for(owner)
222
223        res = self._request_access(agent_client, app)
224        self.assertEqual(res.status_code, 400, res.content)
225        self.assertFalse(GrantRequest.objects.exists())
226
227    def test_one_unheld_target_rejects_the_batch(self):
228        """A batch is all-or-nothing: one target the owner does not hold refuses the whole
229        request, so a held target cannot smuggle an unheld one through with it."""
230        owner = create_test_user()
231        reviewer = create_test_user()
232        held, requestable = self._app(), self._app()
233        PolicyBinding.objects.create(target=held, user=owner, order=0)
234        PolicyBinding.objects.create(target=requestable, user=create_test_user(), order=0)
235        self._requestable_by(requestable, owner, reviewer)
236        _, agent_client = self._agent_for(owner)
237
238        res = self._request_access(agent_client, held, requestable)
239        self.assertEqual(res.status_code, 400, res.content)
240        self.assertFalse(GrantRequest.objects.exists())
241
242    def test_entitlement_owner_holds_owner_approval_suffices(self):
243        """An entitlement the owner is actually bound to is genuinely held, so the owner's
244        approval alone grants it -- the application case, for a child target."""
245        owner = create_test_user()
246        app = self._app()
247        ent = self._entitlement(app)
248        PolicyBinding.objects.create(target=ent, user=owner, order=0)
249        agent, agent_client = self._agent_for(owner)
250
251        self.assertIn(ent, owner.app_entitlements(app))
252        self.assertNotIn(ent, agent.app_entitlements(app))
253
254        res = self._request_access(agent_client, ent)
255        self.assertEqual(res.status_code, 201, res.content)
256        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
257
258        self.assertEqual(self._fulfill(owner, req).status_code, 204)
259        req.refresh_from_db()
260        self.assertEqual(req.status, RequestStatus.APPROVED)
261        # Checked through authentik's own definition of holding an entitlement, not just the
262        # presence of a PolicyBinding row.
263        self.assertIn(ent, agent.app_entitlements(app))
264
265    def test_unbound_entitlement_rejected(self):
266        """An entitlement with no bindings is held by NOBODY -- unlike an application, where no
267        bindings means everyone -- so the owner does not hold it and the agent cannot ask for
268        it. True whether or not a RequestRule happens to cover it."""
269        owner = create_test_user()
270        reviewer = create_test_user()
271        app = self._app()
272        ruleless = self._entitlement(app)
273        covered = self._entitlement(app)
274        self._requestable_by(covered, owner, reviewer)
275        _, agent_client = self._agent_for(owner)
276
277        self.assertNotIn(ruleless, owner.app_entitlements(app))
278        self.assertNotIn(covered, owner.app_entitlements(app))
279
280        for ent in (ruleless, covered):
281            res = self._request_access(agent_client, ent)
282            self.assertEqual(res.status_code, 400, res.content)
283        self.assertFalse(GrantRequest.objects.exists())
284
285    def test_held_app_and_entitlement_batch(self):
286        """A held application and a held entitlement in one call: the two `_owner_holds`
287        engine passes combine, and both targets land on the request."""
288        owner = create_test_user()
289        app = self._app()
290        PolicyBinding.objects.create(target=app, user=owner, order=0)
291        ent = self._entitlement(self._app())
292        PolicyBinding.objects.create(target=ent, user=owner, order=0)
293        _, agent_client = self._agent_for(owner)
294
295        res = self._request_access(agent_client, app, ent)
296        self.assertEqual(res.status_code, 201, res.content)
297        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
298        self.assertEqual(req.targets.count(), 2)
299
300    def test_non_agent_callers_rejected(self):
301        """Only an agent may use this endpoint."""
302        user = create_test_user()
303        app = self._app()
304        PolicyBinding.objects.create(target=app, user=user, order=0)
305
306        self.client.force_login(user)
307        res = self.client.post(
308            reverse("authentik_api:grantrequest-agent"),
309            data={"pbms": [str(app.pk)]},
310            format="json",
311        )
312        self.assertEqual(res.status_code, 403, res.content)
313
314        # A plain service account is not an agent either.
315        service_account = User.objects.create(
316            username=generate_id(), type=UserTypes.SERVICE_ACCOUNT
317        )
318        token = Token.objects.create(
319            identifier=generate_id(),
320            intent=TokenIntents.INTENT_API,
321            user=service_account,
322            expiring=False,
323        )
324        client = APIClient()
325        client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.key}")
326        res = self._request_access(client, app)
327        self.assertEqual(res.status_code, 403, res.content)
328
329    def test_orphaned_agent_rejected(self):
330        """Deleting the owner orphans the agent (Actor.parent is SET_DEFAULT); with nobody
331        left to approve, it cannot request anything."""
332        owner = create_test_user()
333        app = self._app()
334        PolicyBinding.objects.create(target=app, user=owner, order=0)
335        agent, agent_client = self._agent_for(owner)
336
337        owner.delete()
338        agent.refresh_from_db()
339        self.assertIsNone(agent.parent)
340
341        res = self._request_access(agent_client, app)
342        self.assertEqual(res.status_code, 403, res.content)
343
344    def test_agent_cannot_fulfill_its_own_request(self):
345        owner = create_test_user()
346        app = self._app()
347        PolicyBinding.objects.create(target=app, user=owner, order=0)
348        _, agent_client = self._agent_for(owner)
349
350        req = GrantRequest.objects.get(
351            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
352        )
353        res = agent_client.patch(
354            reverse("authentik_api:grantrequest-fulfill", kwargs={"pk": req.pk}),
355            data={"status": "approved", "data": {}},
356            format="json",
357        )
358        self.assertEqual(res.status_code, 403, res.content)
359        req.refresh_from_db()
360        self.assertEqual(req.status, RequestStatus.CREATED)
361
362    def test_owner_can_revoke_without_being_a_reviewer(self):
363        """The owner can end their agent's grant on their own -- reviewer eligibility never
364        enters into it."""
365        owner = create_test_user()
366        app = self._app()
367        PolicyBinding.objects.create(target=app, user=owner, order=0)
368        agent, agent_client = self._agent_for(owner)
369
370        req = GrantRequest.objects.get(
371            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
372        )
373        self._fulfill(owner, req)
374        self.assertTrue(PolicyEngine(app, agent).build().passing)
375
376        self.client.force_login(owner)
377        res = self.client.delete(
378            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
379        )
380        self.assertEqual(res.status_code, 204, res.content)
381        req.refresh_from_db()
382        self.assertEqual(req.status, RequestStatus.REVOKED)
383        self.assertFalse(PolicyEngine(app, agent).build().passing)
384
385    def test_grant_never_outlives_the_agent(self):
386        """The granted duration is capped by the agent's own expiry, so a grant can't hand
387        out access that survives the identity holding it."""
388        owner = create_test_user()
389        app = self._app()
390        PolicyBinding.objects.create(target=app, user=owner, order=0)
391        agent, agent_client = self._agent_for(owner)
392        # Well inside the "hours=1" default the request would otherwise pick up.
393        agent.expires = now() + timedelta(minutes=5)
394        agent.save()
395
396        req = GrantRequest.objects.get(
397            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
398        )
399        self.assertLessEqual(timedelta_from_string(req.requested_expiry), timedelta(minutes=5))
400        self.assertGreater(timedelta_from_string(req.requested_expiry), timedelta(minutes=4))
401
402    def test_pending_review_surfaces_agent_request_to_owner(self):
403        """An agent request reaches its owner through ownership rather than through reviewer
404        eligibility, and reaches nobody else."""
405        owner = create_test_user()
406        outsider = create_test_user()
407        app = self._app()
408        PolicyBinding.objects.create(target=app, user=owner, order=0)
409        _, agent_client = self._agent_for(owner)
410
411        req = GrantRequest.objects.get(
412            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
413        )
414
415        self.client.force_login(owner)
416        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
417        self.assertEqual(res.status_code, 200, res.content)
418        self.assertEqual({r["uuid"] for r in res.json()["results"]}, {str(req.pk)})
419
420        self.client.force_login(outsider)
421        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
422        self.assertEqual(res.status_code, 200, res.content)
423        self.assertEqual(res.json()["results"], [])

An agent inherits no access, so it earns it by asking its owner to delegate some. It may only ask for what the owner already holds -- no flow runs on this path, so there is no justification to hand a reviewer -- and the owner's approval is the whole decision.

def test_owner_already_has_access_owner_approval_suffices(self):
 89    def test_owner_already_has_access_owner_approval_suffices(self):
 90        """The owner can already reach the target, so there is nothing for reviewers to
 91        decide -- the owner's own approval grants the agent access."""
 92        owner = create_test_user()
 93        app = self._app()
 94        PolicyBinding.objects.create(target=app, user=owner, order=0)
 95        agent, agent_client = self._agent_for(owner)
 96
 97        # The agent starts with nothing, even though its owner passes.
 98        self.assertTrue(PolicyEngine(app, owner).build().passing)
 99        self.assertFalse(PolicyEngine(app, agent).build().passing)
100
101        res = self._request_access(agent_client, app)
102        self.assertEqual(res.status_code, 201, res.content)
103        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
104        self.assertEqual(req.created_by_id, agent.pk)
105        self.assertEqual(req.agent_owner_id, owner.pk)
106
107        res = self._fulfill(owner, req)
108        self.assertEqual(res.status_code, 204, res.content)
109        req.refresh_from_db()
110        self.assertEqual(req.status, RequestStatus.APPROVED)
111        # The grant lands on the agent, not on the owner who approved it.
112        self.assertTrue(PolicyBinding.objects.filter(user=agent, target=app).exists())
113        self.assertTrue(PolicyEngine(app, agent).build().passing)

The owner can already reach the target, so there is nothing for reviewers to decide -- the owner's own approval grants the agent access.

def test_response_carries_fulfill_url_for_the_owner(self):
115    def test_response_carries_fulfill_url_for_the_owner(self):
116        """An agent has no browser, so it gets back the URL its owner opens to act on the
117        request -- the same deep link the created event points at."""
118        owner = create_test_user()
119        app = self._app()
120        PolicyBinding.objects.create(target=app, user=owner, order=0)
121        _, agent_client = self._agent_for(owner)
122
123        body = self._request_access(agent_client, app).json()
124        req = GrantRequest.objects.get(pk=body["grant_request"]["uuid"])
125        # Absolute, so it is usable verbatim by whatever the agent hands it to.
126        self.assertTrue(body["fulfill_url"].startswith("http"))
127        self.assertTrue(
128            body["fulfill_url"].endswith(f"#/requests/access-request/{req.uuid}/fulfill"),
129            body["fulfill_url"],
130        )

An agent has no browser, so it gets back the URL its owner opens to act on the request -- the same deep link the created event points at.

def test_target_owner_may_only_request_is_rejected(self):
132    def test_target_owner_may_only_request_is_rejected(self):
133        """A target the owner could request but does not yet hold is refused: approving it
134        would mean asking a reviewer to judge a request with no justification, since no flow
135        runs on this path."""
136        owner = create_test_user()
137        reviewer = create_test_user()
138        app = self._app()
139        # Bound to somebody else, so the owner does not currently pass.
140        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
141        self._requestable_by(app, owner, reviewer)
142        _, agent_client = self._agent_for(owner)
143
144        res = self._request_access(agent_client, app)
145        self.assertEqual(res.status_code, 400, res.content)
146        self.assertFalse(GrantRequest.objects.exists())

A target the owner could request but does not yet hold is refused: approving it would mean asking a reviewer to judge a request with no justification, since no flow runs on this path.

def test_rule_reviewer_cannot_act_on_agent_request(self):
148    def test_rule_reviewer_cannot_act_on_agent_request(self):
149        """A held target can still carry a RequestRule, but its reviewers have no say in an
150        agent's request -- they must not be able to deny it (a denial finalizes immediately)
151        or revoke the grant, and it must not show up in their queue."""
152        owner = create_test_user()
153        reviewer = create_test_user()
154        app = self._app()
155        PolicyBinding.objects.create(target=app, user=owner, order=0)
156        self._requestable_by(app, owner, reviewer)
157        agent, agent_client = self._agent_for(owner)
158
159        res = self._request_access(agent_client, app)
160        self.assertEqual(res.status_code, 201, res.content)
161        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
162
163        # Not in the reviewer's queue...
164        self.client.force_login(reviewer)
165        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
166        self.assertEqual(res.json()["results"], [])
167        # ...and they cannot deny it.
168        self.assertEqual(self._fulfill(reviewer, req, status="denied").status_code, 403)
169        req.refresh_from_db()
170        self.assertEqual(req.status, RequestStatus.CREATED)
171
172        # The owner approves; the reviewer still cannot revoke the resulting grant.
173        self.assertEqual(self._fulfill(owner, req).status_code, 204)
174        req.refresh_from_db()
175        self.assertEqual(req.status, RequestStatus.APPROVED)
176        self.client.force_login(reviewer)
177        res = self.client.delete(
178            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
179        )
180        self.assertEqual(res.status_code, 403, res.content)
181        req.refresh_from_db()
182        self.assertEqual(req.status, RequestStatus.APPROVED)
183        self.assertTrue(PolicyEngine(app, agent).build().passing)

A held target can still carry a RequestRule, but its reviewers have no say in an agent's request -- they must not be able to deny it (a denial finalizes immediately) or revoke the grant, and it must not show up in their queue.

def test_non_expiring_agent_cannot_request(self):
185    def test_non_expiring_agent_cannot_request(self):
186        """Delegated access is bounded by the agent's own lifetime, so a standing agent has
187        nothing to bound the grant with and may not request at all."""
188        owner = create_test_user()
189        app = self._app()
190        PolicyBinding.objects.create(target=app, user=owner, order=0)
191        agent, agent_client = self._agent_for(owner)
192        agent.expiring = False
193        agent.expires = None
194        agent.save()
195
196        res = self._request_access(agent_client, app)
197        self.assertEqual(res.status_code, 403, res.content)
198        self.assertFalse(GrantRequest.objects.exists())

Delegated access is bounded by the agent's own lifetime, so a standing agent has nothing to bound the grant with and may not request at all.

def test_owner_denial_finalizes_immediately(self):
200    def test_owner_denial_finalizes_immediately(self):
201        owner = create_test_user()
202        app = self._app()
203        PolicyBinding.objects.create(target=app, user=owner, order=0)
204        agent, agent_client = self._agent_for(owner)
205
206        req = GrantRequest.objects.get(
207            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
208        )
209        res = self._fulfill(owner, req, status="denied")
210        self.assertEqual(res.status_code, 204, res.content)
211        req.refresh_from_db()
212        self.assertEqual(req.status, RequestStatus.DENIED)
213        self.assertFalse(PolicyBinding.objects.filter(user=agent, target=app).exists())
def test_target_owner_cannot_reach_is_rejected(self):
215    def test_target_owner_cannot_reach_is_rejected(self):
216        """An agent can never reach past its owner: a target the owner neither has access to
217        nor may request is refused outright."""
218        owner = create_test_user()
219        app = self._app()
220        PolicyBinding.objects.create(target=app, user=create_test_user(), order=0)
221        _, agent_client = self._agent_for(owner)
222
223        res = self._request_access(agent_client, app)
224        self.assertEqual(res.status_code, 400, res.content)
225        self.assertFalse(GrantRequest.objects.exists())

An agent can never reach past its owner: a target the owner neither has access to nor may request is refused outright.

def test_one_unheld_target_rejects_the_batch(self):
227    def test_one_unheld_target_rejects_the_batch(self):
228        """A batch is all-or-nothing: one target the owner does not hold refuses the whole
229        request, so a held target cannot smuggle an unheld one through with it."""
230        owner = create_test_user()
231        reviewer = create_test_user()
232        held, requestable = self._app(), self._app()
233        PolicyBinding.objects.create(target=held, user=owner, order=0)
234        PolicyBinding.objects.create(target=requestable, user=create_test_user(), order=0)
235        self._requestable_by(requestable, owner, reviewer)
236        _, agent_client = self._agent_for(owner)
237
238        res = self._request_access(agent_client, held, requestable)
239        self.assertEqual(res.status_code, 400, res.content)
240        self.assertFalse(GrantRequest.objects.exists())

A batch is all-or-nothing: one target the owner does not hold refuses the whole request, so a held target cannot smuggle an unheld one through with it.

def test_entitlement_owner_holds_owner_approval_suffices(self):
242    def test_entitlement_owner_holds_owner_approval_suffices(self):
243        """An entitlement the owner is actually bound to is genuinely held, so the owner's
244        approval alone grants it -- the application case, for a child target."""
245        owner = create_test_user()
246        app = self._app()
247        ent = self._entitlement(app)
248        PolicyBinding.objects.create(target=ent, user=owner, order=0)
249        agent, agent_client = self._agent_for(owner)
250
251        self.assertIn(ent, owner.app_entitlements(app))
252        self.assertNotIn(ent, agent.app_entitlements(app))
253
254        res = self._request_access(agent_client, ent)
255        self.assertEqual(res.status_code, 201, res.content)
256        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
257
258        self.assertEqual(self._fulfill(owner, req).status_code, 204)
259        req.refresh_from_db()
260        self.assertEqual(req.status, RequestStatus.APPROVED)
261        # Checked through authentik's own definition of holding an entitlement, not just the
262        # presence of a PolicyBinding row.
263        self.assertIn(ent, agent.app_entitlements(app))

An entitlement the owner is actually bound to is genuinely held, so the owner's approval alone grants it -- the application case, for a child target.

def test_unbound_entitlement_rejected(self):
265    def test_unbound_entitlement_rejected(self):
266        """An entitlement with no bindings is held by NOBODY -- unlike an application, where no
267        bindings means everyone -- so the owner does not hold it and the agent cannot ask for
268        it. True whether or not a RequestRule happens to cover it."""
269        owner = create_test_user()
270        reviewer = create_test_user()
271        app = self._app()
272        ruleless = self._entitlement(app)
273        covered = self._entitlement(app)
274        self._requestable_by(covered, owner, reviewer)
275        _, agent_client = self._agent_for(owner)
276
277        self.assertNotIn(ruleless, owner.app_entitlements(app))
278        self.assertNotIn(covered, owner.app_entitlements(app))
279
280        for ent in (ruleless, covered):
281            res = self._request_access(agent_client, ent)
282            self.assertEqual(res.status_code, 400, res.content)
283        self.assertFalse(GrantRequest.objects.exists())

An entitlement with no bindings is held by NOBODY -- unlike an application, where no bindings means everyone -- so the owner does not hold it and the agent cannot ask for it. True whether or not a RequestRule happens to cover it.

def test_held_app_and_entitlement_batch(self):
285    def test_held_app_and_entitlement_batch(self):
286        """A held application and a held entitlement in one call: the two `_owner_holds`
287        engine passes combine, and both targets land on the request."""
288        owner = create_test_user()
289        app = self._app()
290        PolicyBinding.objects.create(target=app, user=owner, order=0)
291        ent = self._entitlement(self._app())
292        PolicyBinding.objects.create(target=ent, user=owner, order=0)
293        _, agent_client = self._agent_for(owner)
294
295        res = self._request_access(agent_client, app, ent)
296        self.assertEqual(res.status_code, 201, res.content)
297        req = GrantRequest.objects.get(pk=res.json()["grant_request"]["uuid"])
298        self.assertEqual(req.targets.count(), 2)

A held application and a held entitlement in one call: the two _owner_holds engine passes combine, and both targets land on the request.

def test_non_agent_callers_rejected(self):
300    def test_non_agent_callers_rejected(self):
301        """Only an agent may use this endpoint."""
302        user = create_test_user()
303        app = self._app()
304        PolicyBinding.objects.create(target=app, user=user, order=0)
305
306        self.client.force_login(user)
307        res = self.client.post(
308            reverse("authentik_api:grantrequest-agent"),
309            data={"pbms": [str(app.pk)]},
310            format="json",
311        )
312        self.assertEqual(res.status_code, 403, res.content)
313
314        # A plain service account is not an agent either.
315        service_account = User.objects.create(
316            username=generate_id(), type=UserTypes.SERVICE_ACCOUNT
317        )
318        token = Token.objects.create(
319            identifier=generate_id(),
320            intent=TokenIntents.INTENT_API,
321            user=service_account,
322            expiring=False,
323        )
324        client = APIClient()
325        client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.key}")
326        res = self._request_access(client, app)
327        self.assertEqual(res.status_code, 403, res.content)

Only an agent may use this endpoint.

def test_orphaned_agent_rejected(self):
329    def test_orphaned_agent_rejected(self):
330        """Deleting the owner orphans the agent (Actor.parent is SET_DEFAULT); with nobody
331        left to approve, it cannot request anything."""
332        owner = create_test_user()
333        app = self._app()
334        PolicyBinding.objects.create(target=app, user=owner, order=0)
335        agent, agent_client = self._agent_for(owner)
336
337        owner.delete()
338        agent.refresh_from_db()
339        self.assertIsNone(agent.parent)
340
341        res = self._request_access(agent_client, app)
342        self.assertEqual(res.status_code, 403, res.content)

Deleting the owner orphans the agent (Actor.parent is SET_DEFAULT); with nobody left to approve, it cannot request anything.

def test_agent_cannot_fulfill_its_own_request(self):
344    def test_agent_cannot_fulfill_its_own_request(self):
345        owner = create_test_user()
346        app = self._app()
347        PolicyBinding.objects.create(target=app, user=owner, order=0)
348        _, agent_client = self._agent_for(owner)
349
350        req = GrantRequest.objects.get(
351            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
352        )
353        res = agent_client.patch(
354            reverse("authentik_api:grantrequest-fulfill", kwargs={"pk": req.pk}),
355            data={"status": "approved", "data": {}},
356            format="json",
357        )
358        self.assertEqual(res.status_code, 403, res.content)
359        req.refresh_from_db()
360        self.assertEqual(req.status, RequestStatus.CREATED)
def test_owner_can_revoke_without_being_a_reviewer(self):
362    def test_owner_can_revoke_without_being_a_reviewer(self):
363        """The owner can end their agent's grant on their own -- reviewer eligibility never
364        enters into it."""
365        owner = create_test_user()
366        app = self._app()
367        PolicyBinding.objects.create(target=app, user=owner, order=0)
368        agent, agent_client = self._agent_for(owner)
369
370        req = GrantRequest.objects.get(
371            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
372        )
373        self._fulfill(owner, req)
374        self.assertTrue(PolicyEngine(app, agent).build().passing)
375
376        self.client.force_login(owner)
377        res = self.client.delete(
378            reverse("authentik_api:grantrequest-revoke", kwargs={"pk": req.pk})
379        )
380        self.assertEqual(res.status_code, 204, res.content)
381        req.refresh_from_db()
382        self.assertEqual(req.status, RequestStatus.REVOKED)
383        self.assertFalse(PolicyEngine(app, agent).build().passing)

The owner can end their agent's grant on their own -- reviewer eligibility never enters into it.

def test_grant_never_outlives_the_agent(self):
385    def test_grant_never_outlives_the_agent(self):
386        """The granted duration is capped by the agent's own expiry, so a grant can't hand
387        out access that survives the identity holding it."""
388        owner = create_test_user()
389        app = self._app()
390        PolicyBinding.objects.create(target=app, user=owner, order=0)
391        agent, agent_client = self._agent_for(owner)
392        # Well inside the "hours=1" default the request would otherwise pick up.
393        agent.expires = now() + timedelta(minutes=5)
394        agent.save()
395
396        req = GrantRequest.objects.get(
397            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
398        )
399        self.assertLessEqual(timedelta_from_string(req.requested_expiry), timedelta(minutes=5))
400        self.assertGreater(timedelta_from_string(req.requested_expiry), timedelta(minutes=4))

The granted duration is capped by the agent's own expiry, so a grant can't hand out access that survives the identity holding it.

def test_pending_review_surfaces_agent_request_to_owner(self):
402    def test_pending_review_surfaces_agent_request_to_owner(self):
403        """An agent request reaches its owner through ownership rather than through reviewer
404        eligibility, and reaches nobody else."""
405        owner = create_test_user()
406        outsider = create_test_user()
407        app = self._app()
408        PolicyBinding.objects.create(target=app, user=owner, order=0)
409        _, agent_client = self._agent_for(owner)
410
411        req = GrantRequest.objects.get(
412            pk=self._request_access(agent_client, app).json()["grant_request"]["uuid"]
413        )
414
415        self.client.force_login(owner)
416        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
417        self.assertEqual(res.status_code, 200, res.content)
418        self.assertEqual({r["uuid"] for r in res.json()["results"]}, {str(req.pk)})
419
420        self.client.force_login(outsider)
421        res = self.client.get(reverse("authentik_api:grantrequest-pending-review"))
422        self.assertEqual(res.status_code, 200, res.content)
423        self.assertEqual(res.json()["results"], [])

An agent request reaches its owner through ownership rather than through reviewer eligibility, and reaches nobody else.