Skip to content

Commit

Permalink
REST: Allow optional denial context for permission denied errors
Browse files Browse the repository at this point in the history
Bug: T330914
Change-Id: I5d135a407fea89647d368475d4f91a43b32c98a2
  • Loading branch information
jakobw committed Sep 19, 2024
1 parent d7cebe5 commit 1b37a7c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
10 changes: 8 additions & 2 deletions repo/rest-api/src/Application/UseCases/UseCaseError.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ class UseCaseError extends UseCaseException {
public const CONTEXT_PATH = 'path';
public const CONTEXT_PROPERTY_ID = 'property_id';
public const CONTEXT_DENIAL_REASON = 'denial_reason';
public const CONTEXT_DENIAL_CONTEXT = 'denial_context';
public const CONTEXT_REDIRECT_TARGET = 'redirect_target';
public const CONTEXT_RESOURCE_TYPE = 'resource_type';
public const CONTEXT_SITE_ID = 'site_id';
Expand Down Expand Up @@ -212,8 +213,13 @@ public static function newPatchResultModifiedReadOnlyValue( string $path ): self
);
}

public static function newPermissionDenied( string $reason ): self {
return new self( self::PERMISSION_DENIED, 'Access to resource is denied', [ self::CONTEXT_DENIAL_REASON => $reason ] );
public static function newPermissionDenied( string $reason, array $denialContext = [] ): self {
$error = new self( self::PERMISSION_DENIED, 'Access to resource is denied', [ self::CONTEXT_DENIAL_REASON => $reason ] );
if ( $denialContext ) {
$error->errorContext[self::CONTEXT_DENIAL_CONTEXT] = $denialContext;
}

return $error;
}

public static function newResourceNotFound( string $resourceType ): self {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,26 @@ public function provideInvalidUseCaseErrorData(): Generator {
];
}

/**
* @dataProvider permissionDeniedContextProvider
*/
public function testNewPermissionDenied( UseCaseError $error, array $expectedContext ): void {
$this->assertEquals( $expectedContext, $error->getErrorContext() );
}

public function permissionDeniedContextProvider(): Generator {
yield 'no additional context' => [
UseCaseError::newPermissionDenied( 'some-reason' ),
[ UseCaseError::CONTEXT_DENIAL_REASON => 'some-reason' ],
];

yield 'with additional context' => [
UseCaseError::newPermissionDenied( 'some-other-reason', [ 'some' => 'context' ] ),
[
UseCaseError::CONTEXT_DENIAL_REASON => 'some-other-reason',
UseCaseError::CONTEXT_DENIAL_CONTEXT => [ 'some' => 'context' ],
],
];
}

}

0 comments on commit 1b37a7c

Please sign in to comment.