subtype 'FilePath'
=> as 'Str'
=> where { m{^[\w/_.-]{1,80}\z} }
=> message { "I don't trust file name '$_'" };
has logfile => (
traits => [qw( Untaint )],
is => 'rw',
isa => 'FilePath',
default => '/var/log/walrus.log',
);
Or if you want to allow any untainted value:
subtype 'FilePath'
=> as 'Str'
=> where { !tainted($_) || m{^[\w/_.-]{1,80}\z} }
=> message { "I don't trust file name '$_'" };
has logfile => (
traits => [qw( Untaint )],
is => 'rw',
isa => 'FilePath',
default => '/var/log/walrus.log',
);
However, I don't see anything like that on CPAN, and writing it is bound to be a bit complex. Instead, you could use coercion.
subtype 'FilePath'
=> as 'Str'
=> where { m{^[\w/_.-]{1,80}\z} }
=> message { "I don't trust file name '$_'" };
coerce 'FilePath'
=> from 'Str'
=> via { /(.*)/s; $1 }; # Will be validated soon.
has logfile => (
is => 'rw',
isa => 'FilePath',
default => '/var/log/walrus.log',
coerce => 1,
);
As you can see, it's a bit icky since the tainting has to be removed before the validation. Also, it prevents having a looser check when the value isn't tainted.
Untested.
Notes:
- Removed useless captures from regex patterns for speed.
- Substituted "\z" for "$" since "$" can allow a newline.
- "\w" is includes a suprising number of characters. You may want to pick something stricter.
- "_" is already included in "\w".
- Removed useless escaping from character classes for readability.
|