about summary refs log tree commit diff
path: root/app/helpers/autoreject_helper.rb
blob: 9a2b48a8873393f492bc9fdcf256821d63fc5abf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
module AutorejectHelper
	def should_reject?(uri = nil)
    if uri.nil?
      if @object
        uri = object_uri.start_with?('http') ? object_uri : @object['url']
      elsif @json
        uri = @json['id']
      end
    end

    return if uri.nil?

    domain = uri.scan(/[\w\-]+\.[\w\-]+(?:\.[\w\-]+)*/).first
    blocks = DomainBlock.suspend
    return true if blocks.where(domain: domain).or(blocks.where('domain LIKE ?', "%.#{domain}")).exists?

    return unless @json || @object

    context = @object['@context'] if @object

    if @json
      oid = @json['id']
      if oid
        return true if ENV.fetch('REJECT_IF_ID_STARTS_WITH', '').split.any? { |r| oid.start_with?(r) }
        return true if ENV.fetch('REJECT_IF_ID_CONTAINS', '').split.any? { |r| r.in?(oid) }
      end

      username = @json['preferredUsername'] || @json['username']
      if username && username.is_a?(String)
        username = (@json['actor'] && @json['actor'].is_a?(String)) ? @json['actor'] : ''
        username = username.scan(/(?<=\/user\/|\/@|\/users\/)([^\s\/]+)/).first
      end

      unless username.blank?
        username.downcase!
        return true if ENV.fetch('REJECT_IF_USERNAME_EQUALS', '').split.any? { |r| r == username }
        return true if ENV.fetch('REJECT_IF_USERNAME_STARTS_WITH', '').split.any? { |r| username.start_with?(r) }
        return true if ENV.fetch('REJECT_IF_USERNAME_CONTAINS', '').split.any? { |r| r.in?(username) }
      end

      context = @json['@context'] unless @object && context
    end

    return unless context

    if context.is_a?(Array)
      inline_context = context.find { |item| item.is_a?(Hash) }
      if inline_context
        keys = inline_context.keys
        return true if ENV.fetch('REJECT_IF_CONTEXT_EQUALS', '').split.any? { |r| r.in?(keys) }
        return true if ENV.fetch('REJECT_IF_CONTEXT_STARTS_WITH', '').split.any? { |r| keys.any? { |k| k.start_with?(r) } }
        return true if ENV.fetch('REJECT_IF_CONTEXT_CONTAINS', '').split.any? { |r| keys.any? { |k| r.in?(k) } }
      end
    end

    false
  end

  def autoreject?(uri = nil)
    return false if @options && @options[:imported]
    if should_reject?(uri)
      if @json
        Rails.logger.info("Auto-rejected #{@json['id']} (#{@json['type']})")
        LogWorker.perform_async("Auto-rejected an incoming '#{@json['type']}#{@object && " #{@object['type']}".rstrip}' from #{@json['id']}.")
      elsif uri
        Rails.logger.info("Auto-rejected #{uri}")
        LogWorker.perform_async("Auto-rejected a request to #{uri}.")
      end
      return true
    end
    false
  end
end