Commit 7182e75

mo <mo.khan@gmail.com>
2017-12-24 05:16:21
case -> hash lookup.
1 parent 6cf9160
lib/saml/kit/document.rb
@@ -67,26 +67,28 @@ module Saml
       end
 
       class << self
+        XPATH = [
+          "/samlp:AuthnRequest",
+          "/samlp:LogoutRequest",
+          "/samlp:LogoutResponse",
+          "/samlp:Response",
+        ].join("|")
+
         # Returns the raw xml as a Saml::Kit SAML document.
         #
         # @param xml [String] the raw xml string.
         # @param configuration [Saml::Kit::Configuration] the configuration to use for unpacking the document.
         def to_saml_document(xml, configuration: Saml::Kit.configuration)
-          hash = Hash.from_xml(xml)
-          if hash['Response'].present?
-            Response.new(xml, configuration: configuration)
-          elsif hash['LogoutResponse'].present?
-            LogoutResponse.new(xml, configuration: configuration)
-          elsif hash['AuthnRequest'].present?
-            AuthenticationRequest.new(xml, configuration: configuration)
-          elsif hash['LogoutRequest'].present?
-            LogoutRequest.new(xml, configuration: configuration)
-          else
-            InvalidDocument.new(xml)
-          end
+          constructor = {
+            "AuthnRequest" => Saml::Kit::AuthenticationRequest,
+            "LogoutRequest" => Saml::Kit::LogoutRequest,
+            "LogoutResponse" => Saml::Kit::LogoutResponse,
+            "Response" => Saml::Kit::Response,
+          }[Saml::Kit::Xml.new(xml).find_by(XPATH).name] || InvalidDocument
+          constructor.new(xml, configuration: configuration)
         rescue => error
           Saml::Kit.logger.error(error)
-          InvalidDocument.new(xml)
+          InvalidDocument.new(xml, configuration: configuration)
         end
 
         # @!visibility private
lib/saml/kit/invalid_document.rb
@@ -6,7 +6,7 @@ module Saml
         model.errors[:base] << model.error_message(:invalid)
       end
 
-      def initialize(xml)
+      def initialize(xml, configuration: nil)
         super(xml, name: "InvalidDocument")
       end
 
lib/saml/kit/xml.rb
@@ -60,7 +60,7 @@ module Saml
       end
 
       def validate_certificates(now = Time.current)
-        return unless find_by('//ds:Signature').present?
+        return if find_by('//ds:Signature').nil?
 
         x509_certificates.each do |certificate|
           inactive = now < certificate.not_before
spec/saml/document_spec.rb
@@ -43,5 +43,10 @@ RSpec.describe Saml::Kit::Document do
       result = subject.to_saml_document("NOT XML")
       expect(result).to be_instance_of(Saml::Kit::InvalidDocument)
     end
+
+    it 'returns an invalid document when given nil' do
+      result = subject.to_saml_document(nil)
+      expect(result).to be_instance_of(Saml::Kit::InvalidDocument)
+    end
   end
 end