Class: Alchemy::SafeUrlValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Alchemy::SafeUrlValidator
- Defined in:
- app/models/alchemy/safe_url_validator.rb
Overview
Validates that a url does not carry an executable scheme.
Only schemes listed in Alchemy.config.allowed_url_schemes pass. Urls
without a scheme (absolute and relative paths, anchors, queries and
protocol relative urls) pass as well, they cannot carry executable code.
validates_with Alchemy::SafeUrlValidator, attributes: [:url]
Constant Summary collapse
- SCHEME_REGEX =
/\A(?<scheme>[a-z][a-z0-9+.-]*):/i- STRIPPED_CHARS =
Browsers drop these before they parse a url, which makes "java\tscript:" a working "javascript:" url. They have to go before the scheme is read.
/[\u0000-\u0020]/
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
19 20 21 22 23 24 25 26 |
# File 'app/models/alchemy/safe_url_validator.rb', line 19 def validate_each(record, attribute, value) return if value.blank? scheme = SCHEME_REGEX.match(value.to_s.gsub(STRIPPED_CHARS, ""))&.[](:scheme)&.downcase return if scheme.nil? || allowed_schemes.include?(scheme) record.errors.add(attribute, :invalid_url_scheme, scheme: scheme) end |