Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ADVAPP-23]: Implement authorization methodology for querying particular fields #536

Merged
merged 3 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app-modules/care-team/graphql/care-team.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ input CareTeamEducatablesQuery {

input CareTeamsQuery {
id: UUID
user: UserQuery
user: UsersQuery
educatable: CareTeamEducatablesQuery @morphToRelation
educatable_id: EducatableId
educatable_type: EducatableType
Expand Down
4 changes: 2 additions & 2 deletions app-modules/interaction/graphql/interaction.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type Interaction
description: String!

"The User related to the interaction."
user: User @belongsTo
user: User @belongsTo @canResolved(ability: "view")

"The Interactable related to the interaction."
interactable: Interactable @morphTo
Expand Down Expand Up @@ -71,7 +71,7 @@ input InteractionsQuery {
id: UUID
subject: String
description: String
user: UserQuery
user: UsersQuery
interactable: InteractionInteractablesQuery @morphToRelation
interactable_id: InteractableId
interactable_type: InteractableType
Expand Down
2 changes: 1 addition & 1 deletion app-modules/notification/graphql/subscription.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ input UserSubscriptionSubscribablesQuery {

input SubscriptionsQuery {
id: UUID
user: UserQuery
user: UsersQuery
subscribable: UserSubscriptionSubscribablesQuery @morphToRelation
subscribable_id: EducatableId
subscribable_type: EducatableType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type ServiceRequestAssignment
service_request: ServiceRequest @belongsTo

"The user of the assignment."
user: User @belongsTo
user: User @belongsTo @canResolved(ability: "view")

# "The role of the assignment."
# role: ServiceRequestAssignmentRole @belongsTo
Expand Down
76 changes: 76 additions & 0 deletions app/GraphQL/Directives/CanUseInQueryDirective.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
<COPYRIGHT>

Copyright © 2016-2024, Canyon GBS LLC. All rights reserved.

Advising App™ is licensed under the Elastic License 2.0. For more details,
see https://github.com/canyongbs/advisingapp/blob/main/LICENSE.

Notice:

- You may not provide the software to third parties as a hosted or managed
service, where the service provides users with access to any substantial set of
the features or functionality of the software.
- You may not move, change, disable, or circumvent the license key functionality
in the software, and you may not remove or obscure any functionality in the
software that is protected by the license key.
- You may not alter, remove, or obscure any licensing, copyright, or other notices
of the licensor in the software. Any use of the licensor’s trademarks is subject
to applicable law.
- Canyon GBS LLC respects the intellectual property rights of others and expects the
same in return. Canyon GBS™ and Advising App™ are registered trademarks of
Canyon GBS LLC, and we are committed to enforcing and protecting our trademarks
vigorously.
- The software solution, including services, infrastructure, and code, is offered as a
Software as a Service (SaaS) by Canyon GBS LLC.
- Use of this software implies agreement to the license terms and conditions as stated
in the Elastic License 2.0.

For more information or inquiries please visit our website at
https://www.canyongbs.com or contact us via email at legal@canyongbs.com.

</COPYRIGHT>
*/

namespace App\GraphQL\Directives;

use RuntimeException;
use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Builder;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;

final class CanUseInQueryDirective extends BaseDirective
{
public static function definition(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
Check a Laravel Policy to ensure the current user is authorized to use this field in a query.
"""
directive @canUseInQuery(
"""
The ability to check permissions for.
"""
ability: String!

) repeatable on FIELD_DEFINITION
GRAPHQL;
}

public function authorize(object $builder): void
{
if (! $builder instanceof Builder) {
throw new RuntimeException('Query must be instance of [' . Builder::class . '] in order to extract the model for [@canUseInQuery].');
}

$arguments = $this->directiveNode->arguments;

if (! $arguments->offsetExists(0)) {
throw new RuntimeException('[@canUseInQuery] directive must have at least one ability to check.');
}

Gate::authorize($arguments->offsetGet(0)->value->value, $builder->getModel());
}
}
8 changes: 8 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
use AdvisingApp\Team\Models\Team;
use Spatie\MediaLibrary\HasMedia;
use App\Support\HasAdvancedFilter;
use Illuminate\Support\Collection;
use AdvisingApp\Team\Models\TeamUser;
use App\Filament\Resources\UserResource;
use Filament\Models\Contracts\HasAvatar;
Expand Down Expand Up @@ -84,6 +85,7 @@
use AdvisingApp\Timeline\Models\Contracts\HasFilamentResource;
use AdvisingApp\Authorization\Models\Pivots\RoleGroupUserPivot;
use AdvisingApp\ServiceManagement\Models\ChangeRequestResponse;
use AdvisingApp\Authorization\Models\Concerns\DefinesPermissions;
use AdvisingApp\InAppCommunication\Models\TwilioConversationUser;
use AdvisingApp\Audit\Models\Concerns\Auditable as AuditableTrait;
use AdvisingApp\Notification\Models\Contracts\NotifiableInterface;
Expand All @@ -96,6 +98,7 @@
*/
class User extends Authenticatable implements HasLocalePreference, FilamentUser, Auditable, HasMedia, HasAvatar, NotifiableInterface, HasFilamentResource
{
use DefinesPermissions;
use HasFactory;
use HasAdvancedFilter;
use Notifiable;
Expand Down Expand Up @@ -490,6 +493,11 @@ public function revokeLicense(LicenseType $type): bool
return (bool) $this->licenses()->where('type', $type)->delete();
}

public function getApiPermissions(): Collection
{
return collect(['view-email', ...$this->apiPermissions()]);
}

protected function serializeDate(DateTimeInterface $date): string
{
return $date->format(config('project.datetime_format') ?? 'Y-m-d H:i:s');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

/*
<COPYRIGHT>

Copyright © 2016-2024, Canyon GBS LLC. All rights reserved.

Advising App™ is licensed under the Elastic License 2.0. For more details,
see https://github.com/canyongbs/advisingapp/blob/main/LICENSE.

Notice:

- You may not provide the software to third parties as a hosted or managed
service, where the service provides users with access to any substantial set of
the features or functionality of the software.
- You may not move, change, disable, or circumvent the license key functionality
in the software, and you may not remove or obscure any functionality in the
software that is protected by the license key.
- You may not alter, remove, or obscure any licensing, copyright, or other notices
of the licensor in the software. Any use of the licensor’s trademarks is subject
to applicable law.
- Canyon GBS LLC respects the intellectual property rights of others and expects the
same in return. Canyon GBS™ and Advising App™ are registered trademarks of
Canyon GBS LLC, and we are committed to enforcing and protecting our trademarks
vigorously.
- The software solution, including services, infrastructure, and code, is offered as a
Software as a Service (SaaS) by Canyon GBS LLC.
- Use of this software implies agreement to the license terms and conditions as stated
in the Elastic License 2.0.

For more information or inquiries please visit our website at
https://www.canyongbs.com or contact us via email at legal@canyongbs.com.

</COPYRIGHT>
*/

namespace App\Overrides\LastDragon_ru\LaraASP\GraphQL\SearchBy\Definitions;

use App\GraphQL\Directives\CanUseInQueryDirective;
use LastDragon_ru\LaraASP\GraphQL\Builder\Property;
use Nuwave\Lighthouse\Execution\Arguments\ArgumentSet;
use LastDragon_ru\LaraASP\GraphQL\Utils\ArgumentFactory;
use LastDragon_ru\LaraASP\GraphQL\Builder\Contracts\Operator;
use LastDragon_ru\LaraASP\GraphQL\Builder\Exceptions\Client\ConditionEmpty;
use LastDragon_ru\LaraASP\GraphQL\Builder\Exceptions\Client\ConditionTooManyOperators;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Definitions\SearchByDirective as BaseSearchByDirective;

class SearchByDirective extends BaseSearchByDirective
{
/**
* @template T of object
*
* @param T $builder
*
* @return T
*/
protected function call(object $builder, Property $property, ArgumentSet $operator): object
{
// Arguments?
if (count($operator->arguments) > 1) {
throw new ConditionTooManyOperators(
ArgumentFactory::getArgumentsNames($operator),
);
}

// Operator & Value
$op = null;
$value = null;

foreach ($operator->arguments as $name => $argument) {
$operators = [];

foreach ($argument->directives as $directive) {
if ($directive instanceof CanUseInQueryDirective) {
$directive->authorize($builder);
}

if ($directive instanceof Operator) {
$operators[] = $directive;
}
}

$property = $property->getChild($name);
$value = $argument;
$op = reset($operators);

if (count($operators) > 1) {
throw new ConditionTooManyOperators(
array_map(
static function (Operator $operator): string {
return $operator::getName();
},
$operators,
),
);
}
}

// Operator?
if (! $op || ! $value) {
throw new ConditionEmpty();
}

// Return
return $op->call($this, $builder, $property, $value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/*
<COPYRIGHT>

Copyright © 2016-2024, Canyon GBS LLC. All rights reserved.

Advising App™ is licensed under the Elastic License 2.0. For more details,
see https://github.com/canyongbs/advisingapp/blob/main/LICENSE.

Notice:

- You may not provide the software to third parties as a hosted or managed
service, where the service provides users with access to any substantial set of
the features or functionality of the software.
- You may not move, change, disable, or circumvent the license key functionality
in the software, and you may not remove or obscure any functionality in the
software that is protected by the license key.
- You may not alter, remove, or obscure any licensing, copyright, or other notices
of the licensor in the software. Any use of the licensor’s trademarks is subject
to applicable law.
- Canyon GBS LLC respects the intellectual property rights of others and expects the
same in return. Canyon GBS™ and Advising App™ are registered trademarks of
Canyon GBS LLC, and we are committed to enforcing and protecting our trademarks
vigorously.
- The software solution, including services, infrastructure, and code, is offered as a
Software as a Service (SaaS) by Canyon GBS LLC.
- Use of this software implies agreement to the license terms and conditions as stated
in the Elastic License 2.0.

For more information or inquiries please visit our website at
https://www.canyongbs.com or contact us via email at legal@canyongbs.com.

</COPYRIGHT>
*/

namespace App\Overrides\LastDragon_ru\LaraASP\GraphQL\SearchBy\Types;

use App\GraphQL\Directives\CanUseInQueryDirective;
use Nuwave\Lighthouse\Support\Contracts\Directive;
use LastDragon_ru\LaraASP\GraphQL\Builder\Manipulator;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Types\Condition as BaseCondition;

class Condition extends BaseCondition
{
protected function isFieldDirectiveAllowed(Manipulator $manipulator, Directive $directive): bool
{
if ($directive instanceof CanUseInQueryDirective) {
return true;
}

return parent::isFieldDirectiveAllowed($manipulator, $directive);
}
}
8 changes: 8 additions & 0 deletions app/Policies/UserPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ public function view(Authenticatable $authenticatable, User $model): Response
);
}

public function viewEmail(Authenticatable $authenticatable): Response
{
return $authenticatable->canOrElse(
abilities: ['user.view-email'],
denyResponse: 'You do not have permission to view user email addresses.'
);
}

public function create(Authenticatable $authenticatable): Response
{
return $authenticatable->canOrElse(
Expand Down
7 changes: 7 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use OpenSearch\Migrations\Filesystem\MigrationStorage;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Types\Condition as GraphQLSearchByTypesCondition;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Definitions\SearchByDirective as GraphQLSearchByDirectiveAlias;
use App\Overrides\LastDragon_ru\LaraASP\GraphQL\SearchBy\Types\Condition as GraphQLSearchByTypesConditionOverride;
use App\Overrides\LastDragon_ru\LaraASP\GraphQL\SearchBy\Definitions\SearchByDirective as GraphQLSearchByDirectiveOverride;

class AppServiceProvider extends ServiceProvider
{
Expand All @@ -52,6 +56,9 @@ class AppServiceProvider extends ServiceProvider
public function register(): void
{
$this->app->singleton('originalAppKey', fn () => config('app.key'));

$this->app->bind(GraphQLSearchByTypesCondition::class, GraphQLSearchByTypesConditionOverride::class);
$this->app->bind(GraphQLSearchByDirectiveAlias::class, GraphQLSearchByDirectiveOverride::class);
}

/**
Expand Down
1 change: 1 addition & 0 deletions config/roles/api/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
'report_prospect.access',
'journey_menu.access',
'license_settings.manage',
'user.view-email',
],

'model' => [
Expand Down
15 changes: 7 additions & 8 deletions graphql/user.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ type User @model(class: "user") {
id: UUID!

"Unique email address."
email: String!
email: String! @canRoot(ability: "viewEmail")
}

input UserQuery {
input UsersQuery {
"Unique primary key."
id: UUID!
id: UUID

"Users email address."
email: String!
email: String @canUseInQuery(ability: "viewEmail")
}

type UserQueries {
Expand All @@ -30,10 +30,9 @@ type UserQueries {
): User @find @canResolved(ability: "view")

"List multiple users."
list(
"Filters by name. Accepts SQL LIKE wildcards `%` and `_`."
name: String @where(operator: "like")
): [User!]! @paginate @canModel(ability: "viewAny")
list(where: UsersQuery @searchBy): [User!]!
@paginate
@canModel(ability: "viewAny")
}

extend type Query {
Expand Down