Repository: rails/rails
File: activerecord/lib/active_record/signed_id.rb (Ruby)

Code before:
      #
      # === Examples
      #
      #   User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
      #
      #   signed_id = User.first.signed_id
      #   User.first.destroy
      #   User.find_signed! signed_id # => ActiveRecord::RecordNotFound
      def find_signed!(signed_id, purpose: nil, on_rotation: nil)
        options = { on_rotation: on_rotation }.compact
        if id = signed_id_verifier.verify(signed_id, purpose: combine_signed_id_purposes(purpose), **options)
          find(id)
        end
      end

      # :nodoc:
      def combine_signed_id_purposes(purpose)
        [ base_class.name.underscore, purpose.to_s ].compact_blank.join("/")
      end
    end


    # Returns a signed id that's generated using a preconfigured +ActiveSupport::MessageVerifier+ instance.
    #
    # This signed id is tamper proof, so it's safe to send in an email or otherwise share with the outside world.
    # However, as with any message signed with a +ActiveSupport::MessageVerifier+,
    # {the signed id is not encrypted}[link:classes/ActiveSupport/MessageVerifier.html#class-ActiveSupport::MessageVerifier-label-Signing+is+not+encryption].
    # It's just encoded and protected against tampering.
    #
    # This means that the ID can be decoded by anyone; however, if tampered with (so to point to a different ID),
    # the cryptographic signature will no longer match, and the signed id will be considered invalid and return nil
    # when passed to +find_signed+ (or raise with +find_signed!+).
    #
    # It can furthermore be set to expire (the default is not to expire), and scoped down with a specific purpose.
    # If the expiration date has been exceeded before +find_signed+ is called, the id won't find the designated
    # record. If a purpose is set, this too must match.
    #
    # If you accidentally let a signed id out in the wild that you wish to retract sooner than its expiration date
    # (or maybe you forgot to set an expiration date while meaning to!), you can use the purpose to essentially
    # version the signed_id, like so:
    #
    #   user.signed_id purpose: :v2
    #
    # And you then change your +find_signed+ calls to require this new purpose. Any old signed ids that were not
    # created with the purpose will no longer find the record.
    def signed_id(expires_in: nil, expires_at: nil, purpose: nil)
      raise ArgumentError, "Cannot get a signed_id for a new record" if new_record?

      self.class.signed_id_verifier.generate id, expires_in: expires_in, expires_at: expires_at, purpose: self.class.combine_signed_id_purposes(purpose)
    end
  end

Review comment (security):
`signed_id_verifier_secret` is also a `class_attribute`, which is unfortunate.  That means existing apps could have, for example, set `Post.signed_id_verifier_secret` and `Comment.signed_id_verifier_secret` to different values, and `Post.signed_id_verifier` and `Comment.signed_id_verifier` each have to use those values, respectively.

I have not fully sketched this out, but I would try giving `ActiveRecord::Base` access to `Rails.application.message_verifiers`.  In other words, set something like `ActiveRecord::Base.message_verifiers` in an initializer, and use that instead of `MessageVerifier.new` in this method.


Code after:

        options = { on_rotation: on_rotation }.compact
        if id = signed_id_verifier.verified(signed_id, purpose: combine_signed_id_purposes(purpose), **options)
          find_by primary_key => id
        end
      end

      # Works like find_signed, but will raise an +ActiveSupport::MessageVerifier::InvalidSignature+
      # exception if the +signed_id+ has either expired, has a purpose mismatch, is for another record,
      # or has been tampered with. It will also raise an +ActiveRecord::RecordNotFound+ exception if
      # the valid signed id can't find a record.
      #
      # === Examples
      #
      #   User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
      #
      #   signed_id = User.first.signed_id
      #   User.first.destroy
      #   User.find_signed! signed_id # => ActiveRecord::RecordNotFound
      def find_signed!(signed_id, purpose: nil, on_rotation: nil)
        options = { on_rotation: on_rotation }.compact
        if id = signed_id_verifier.verify(signed_id, purpose: combine_signed_id_purposes(purpose), **options)
          find(id)
        end
      end

      def signed_id_verifier
        if signed_id_verifier_secret
          @signed_id_verifier ||= begin
            secret = signed_id_verifier_secret
            secret = secret.call if secret.respond_to?(:call)

            if secret.nil?
              raise ArgumentError, "You must set ActiveRecord::Base.signed_id_verifier_secret to use signed IDs"
            end

            ActiveSupport::MessageVerifier.new secret, digest: "SHA256", serializer: JSON, url_safe: true
          end
        else
          return _signed_id_verifier if _signed_id_verifier

          if ActiveRecord.message_verifiers.nil?
            raise "You must set ActiveRecord.message_verifiers to use signed IDs"
          end

          ActiveRecord.message_verifiers["active_record/signed_id"]
        end
      end

      # Allows you to pass in a custom verifier used for the signed ids. This also allows you to use different
      # verifiers for different classes. This is also helpful if you need to rotate keys, as you can prepare