# -*- coding:binary -*-

require 'spec_helper'

RSpec.describe Msf::Exploit::Remote::HTTP::Nifi::Auth do
  subject do
    mod = ::Msf::Module.new
    mod.extend described_class
    mod
  end

  let(:valid_code) do
    200
  end

  describe '#nifi auth supports_login' do
    it 'returns nil if page can not be reached' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response::E404.new
        res
      end

      expect(subject.supports_login?).to be_nil
    end

    it 'returns nil when key not available' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response.new
        res.code = valid_code
        res.body = '{"foo":"bar"}'
        res
      end

      expect(subject.supports_login?).to be_nil
    end

    it 'returns true when true' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response.new
        res.code = valid_code
        res.body = '{"config":{"supportsLogin":true}}'
        res
      end

      expect(subject.supports_login?).to be true
    end
  end

  describe '#nifi auth retrieve_login_token' do
    it 'returns nil if page can not be reached' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response::E404.new
        res
      end

      expect(subject.retrieve_login_token).to be_nil
    end

    it 'returns nil on bad login' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response.new
        res.code = 400
        res.body = 'The supplied username and password are not valid.'
        res
      end

      expect(subject.retrieve_login_token).to be_nil
    end

    it 'returns access token on successful login' do
      allow(subject).to receive(:send_request_cgi) do
        res = Rex::Proto::Http::Response.new
        res.code = 201
        # 1142 in length for version 1.21.0
        res.body = ('eyJraWQiOiIzNzhiOWUwYS0wOGJlLTRiNW-tYThhNi0yOWZhM2Y3Yz_4NmMiLCJhbGciOiJQUzUxMiJ9.eyJzdWIi' * 12) +
                   'OiJlN2U2OGRhMy1jZmQ1LTQ0YTYtOTdlOS1iYWFlYzg1ZDM2MTQiLCJhdWQiOi'
        res
      end

      expect(subject.retrieve_login_token).to eq(('eyJraWQiOiIzNzhiOWUwYS0wOGJlLTRiNW-tYThhNi0yOWZhM2Y3Yz_4NmMiLCJhbGciOiJQUzUxMiJ9.eyJzdWIi' * 12) +
      'OiJlN2U2OGRhMy1jZmQ1LTQ0YTYtOTdlOS1iYWFlYzg1ZDM2MTQiLCJhdWQiOi')
    end
  end
end
