From faf48e1dd408288b37d5ec2ab28421931abb6890 Mon Sep 17 00:00:00 2001 From: Benjamin Neff Date: Fri, 1 Sep 2017 02:33:21 +0200 Subject: [PATCH] Extract allowed chars for GUIDs to constant Also: disallow special chars at the end of a GUID --- docs/federation/types.md | 2 ++ lib/diaspora_federation/validators/rules/guid.rb | 6 +++++- .../lib/diaspora_federation/validators/rules/guid_spec.rb | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/federation/types.md b/docs/federation/types.md index 4d1dcd5..2771bff 100644 --- a/docs/federation/types.md +++ b/docs/federation/types.md @@ -31,6 +31,8 @@ A network-wide, unique identifier. A random string of at least 16 and at most 25 * Numbers: `0-9` * Special chars: `-`, `_`, `@`, `.` and `:` + Special chars aren't allowed at the end. + Example: `298962a0b8dc0133e40d406c8f31e210` ## String diff --git a/lib/diaspora_federation/validators/rules/guid.rb b/lib/diaspora_federation/validators/rules/guid.rb index 1405e1c..88ab8e6 100644 --- a/lib/diaspora_federation/validators/rules/guid.rb +++ b/lib/diaspora_federation/validators/rules/guid.rb @@ -6,7 +6,11 @@ module Validation # * Letters: a-z # * Numbers: 0-9 # * Special chars: '-', '_', '@', '.' and ':' + # Special chars aren't allowed at the end. class Guid + # Allowed chars to validate a GUID with a regex + VALID_CHARS = "[0-9A-Za-z\\-_@.:]{15,254}[0-9a-z]".freeze + # The error key for this rule # @return [Symbol] error key def error_key @@ -15,7 +19,7 @@ module Validation # Determines if value is a valid +GUID+ def valid_value?(value) - value.is_a?(String) && value.downcase =~ /\A[0-9a-z\-_@.:]{16,255}\z/ + value.is_a?(String) && value =~ /\A#{VALID_CHARS}\z/ end # This rule has no params. diff --git a/spec/lib/diaspora_federation/validators/rules/guid_spec.rb b/spec/lib/diaspora_federation/validators/rules/guid_spec.rb index d8954dc..3a71404 100644 --- a/spec/lib/diaspora_federation/validators/rules/guid_spec.rb +++ b/spec/lib/diaspora_federation/validators/rules/guid_spec.rb @@ -45,6 +45,14 @@ describe Validation::Rule::Guid do expect(validator.errors).to include(:guid) end + it "fails if the string contains special chars at the end" do + validator = Validation::Validator.new(OpenStruct.new(guid: "abcdef0123456789.")) + validator.rule(:guid, :guid) + + expect(validator).not_to be_valid + expect(validator.errors).to include(:guid) + end + it "fails if the string contains invalid chars" do validator = Validation::Validator.new(OpenStruct.new(guid: "ghijklmnopqrstuvwxyz++")) validator.rule(:guid, :guid)