Commit f26a9e19 authored by Peter Leitzen's avatar Peter Leitzen

Merge branch 'sha-params-validator' into 'master'

Add custom sha validator

Closes #33767

See merge request gitlab-org/gitlab!26220
parents 99682e5e 1fadf33b
---
title: Add grape custom validator for sha params
merge_request: 26220
author: Rajendra Kadam
type: added
......@@ -14,6 +14,17 @@ module API
end
end
class GitSha < Grape::Validations::Base
def validate_param!(attr_name, params)
sha = params[attr_name]
return if Commit::EXACT_COMMIT_SHA_PATTERN.match?(sha)
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)],
message: "should be a valid sha"
end
end
class Absence < Grape::Validations::Base
def validate_param!(attr_name, params)
return if params.respond_to?(:key?) && !params.key?(attr_name)
......@@ -50,6 +61,7 @@ module API
end
Grape::Validations.register_validator(:file_path, ::API::Helpers::CustomValidators::FilePath)
Grape::Validations.register_validator(:git_sha, ::API::Helpers::CustomValidators::GitSha)
Grape::Validations.register_validator(:absence, ::API::Helpers::CustomValidators::Absence)
Grape::Validations.register_validator(:integer_none_any, ::API::Helpers::CustomValidators::IntegerNoneAny)
Grape::Validations.register_validator(:array_none_any, ::API::Helpers::CustomValidators::ArrayNoneAny)
......@@ -29,6 +29,38 @@ describe API::Helpers::CustomValidators do
end
end
describe API::Helpers::CustomValidators::GitSha do
let(:sha) { RepoHelpers.sample_commit.id }
let(:short_sha) { sha[0, Gitlab::Git::Commit::MIN_SHA_LENGTH] }
let(:too_short_sha) { sha[0, Gitlab::Git::Commit::MIN_SHA_LENGTH - 1] }
subject do
described_class.new(['test'], {}, false, scope.new)
end
context 'valid sha' do
it 'does not raise a validation error' do
expect_no_validation_error('test' => sha)
expect_no_validation_error('test' => short_sha)
end
end
context 'empty params' do
it 'raises a validation error' do
expect_validation_error('test' => nil)
expect_validation_error('test' => '')
end
end
context 'invalid sha' do
it 'raises a validation error' do
expect_validation_error('test' => "#{sha}2") # Sha length > 40
expect_validation_error('test' => 'somestring')
expect_validation_error('test' => too_short_sha) # sha length < MIN_SHA_LENGTH (7)
end
end
end
describe API::Helpers::CustomValidators::FilePath do
subject do
described_class.new(['test'], {}, false, scope.new)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment