How to prevent accidental data leak

Filament uses model policies to prevent unauthorized access. I have had situations where I forgot to add model policies, especially for existing models and I add the resource to Filament. Maybe the solution is a Laravel thing rather than Filament, but how can I prevent such error? More specifically: How can I make Filament blow up (throw Exception or something) when a resource is accessed and the underlying model does not have any policy class?
5 Replies
toeknee
toeknee13mo ago
You could build a trait? Then apply this to the BaseModel override which Checks for a policy with say:
namespace App\Traits;

use Illuminate\Support\Facades\Gate;
use RuntimeException;

trait ChecksPolicy
{
public static function bootChecksPolicy()
{
// Check if a policy is registered for the model
if (Gate::policy(self::class) === null) {
throw new RuntimeException("No policy registered for model " . self::class);
}
}
}
namespace App\Traits;

use Illuminate\Support\Facades\Gate;
use RuntimeException;

trait ChecksPolicy
{
public static function bootChecksPolicy()
{
// Check if a policy is registered for the model
if (Gate::policy(self::class) === null) {
throw new RuntimeException("No policy registered for model " . self::class);
}
}
}
and in your baseModel
<?php

namespace App\Models;

use App\Traits\ChecksPolicy;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
use ChecksPolicy;

// ...
}
<?php

namespace App\Models;

use App\Traits\ChecksPolicy;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
use ChecksPolicy;

// ...
}
awcodes
awcodes13mo ago
I'm wondering if a test would be better. That way you won't have to worry about it breaking the app if it makes it to production without a policy since the test could disable the deploy.
toeknee
toeknee13mo ago
That's a good shout, you could send an email alert instead of throwing an exception. But a test suite would be better
damms005
damms005OP13mo ago
Yeah I mean the whole point is my fault in forgetting to consider auth for newly added resources If I didn't forget that, I definitely would have added policy and then perhaps a test. I was thinking about something that drop-kicks me whenever I forget something like that; similar to what Model::preventLazyLoading() when one forgets to eager-load relationships
toeknee
toeknee13mo ago
But you could create a test, to ensure all models have policies and fail if they don't? It'll also allow models which don't need policies as you can exclude them?

Did you find this page helpful?