workhorse_spec.rb 13.7 KB
Newer Older
1 2
require 'spec_helper'

3
describe Gitlab::Workhorse do
4
  set(:project)    { create(:project, :repository) }
5 6 7 8 9 10 11 12 13
  let(:repository) { project.repository }

  def decode_workhorse_header(array)
    key, value = array
    command, encoded_params = value.split(":")
    params = JSON.parse(Base64.urlsafe_decode64(encoded_params))

    [key, command, params]
  end
14

15
  describe ".send_git_archive" do
16 17 18
    let(:ref) { 'master' }
    let(:format) { 'zip' }
    let(:storage_path) { Gitlab.config.gitlab.repository_downloads_path }
19
    let(:base_params) { repository.archive_metadata(ref, storage_path, format, append_sha: nil) }
20 21 22 23 24 25 26 27 28
    let(:gitaly_params) do
      base_params.merge(
        'GitalyServer' => {
          'address' => Gitlab::GitalyClient.address(project.repository_storage),
          'token' => Gitlab::GitalyClient.token(project.repository_storage)
        },
        'GitalyRepository' => repository.gitaly_repository.to_h.deep_stringify_keys
      )
    end
29
    let(:cache_disabled) { false }
30 31

    subject do
32
      described_class.send_git_archive(repository, ref: ref, format: format, append_sha: nil)
33 34
    end

35 36 37 38
    before do
      allow(described_class).to receive(:git_archive_cache_disabled?).and_return(cache_disabled)
    end

39 40
    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(subject)
41

42 43 44 45
      expect(key).to eq('Gitlab-Workhorse-Send-Data')
      expect(command).to eq('git-archive')
      expect(params).to include(gitaly_params)
    end
46

47 48
    context 'when archive caching is disabled' do
      let(:cache_disabled) { true }
49

50 51 52
      it 'tells workhorse not to use the cache' do
        _, _, params = decode_workhorse_header(subject)
        expect(params).to include({ 'DisableCache' => true })
53
      end
54 55
    end

56 57 58 59 60 61
    context "when the repository doesn't have an archive file path" do
      before do
        allow(project.repository).to receive(:archive_metadata).and_return(Hash.new)
      end

      it "raises an error" do
62
        expect { subject }.to raise_error(RuntimeError)
63 64 65
      end
    end
  end
66

67 68 69 70
  describe '.send_git_patch' do
    let(:diff_refs) { double(base_sha: "base", head_sha: "head") }
    subject { described_class.send_git_patch(repository, diff_refs) }

71 72
    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(subject)
73

74 75 76 77 78 79 80 81 82 83 84 85 86
      expect(key).to eq("Gitlab-Workhorse-Send-Data")
      expect(command).to eq("git-format-patch")
      expect(params).to eq({
        'GitalyServer' => {
          address: Gitlab::GitalyClient.address(project.repository_storage),
          token: Gitlab::GitalyClient.token(project.repository_storage)
        },
        'RawPatchRequest' => Gitaly::RawPatchRequest.new(
          repository: repository.gitaly_repository,
          left_commit_id: 'base',
          right_commit_id: 'head'
        ).to_json
      }.deep_stringify_keys)
87 88 89
    end
  end

90 91 92 93 94
  describe '.terminal_websocket' do
    def terminal(ca_pem: nil)
      out = {
        subprotocols: ['foo'],
        url: 'wss://example.com/terminal.ws',
95 96
        headers: { 'Authorization' => ['Token x'] },
        max_session_time: 600
97 98 99 100 101 102 103 104 105 106
      }
      out[:ca_pem] = ca_pem if ca_pem
      out
    end

    def workhorse(ca_pem: nil)
      out = {
        'Terminal' => {
          'Subprotocols' => ['foo'],
          'Url' => 'wss://example.com/terminal.ws',
107 108
          'Header' => { 'Authorization' => ['Token x'] },
          'MaxSessionTime' => 600
109 110 111 112 113 114 115
        }
      }
      out['Terminal']['CAPem'] = ca_pem if ca_pem
      out
    end

    context 'without ca_pem' do
116
      subject { described_class.terminal_websocket(terminal) }
117 118 119 120 121

      it { is_expected.to eq(workhorse) }
    end

    context 'with ca_pem' do
122
      subject { described_class.terminal_websocket(terminal(ca_pem: "foo")) }
123 124 125 126 127

      it { is_expected.to eq(workhorse(ca_pem: "foo")) }
    end
  end

128 129
  describe '.send_git_diff' do
    let(:diff_refs) { double(base_sha: "base", head_sha: "head") }
130
    subject { described_class.send_git_diff(repository, diff_refs) }
131

132 133
    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(subject)
134

135 136 137 138 139 140 141 142 143 144 145 146 147
      expect(key).to eq("Gitlab-Workhorse-Send-Data")
      expect(command).to eq("git-diff")
      expect(params).to eq({
        'GitalyServer' => {
          address: Gitlab::GitalyClient.address(project.repository_storage),
          token: Gitlab::GitalyClient.token(project.repository_storage)
        },
        'RawDiffRequest' => Gitaly::RawDiffRequest.new(
          repository: repository.gitaly_repository,
          left_commit_id: 'base',
          right_commit_id: 'head'
        ).to_json
      }.deep_stringify_keys)
148 149 150
    end
  end

151 152 153 154 155 156 157 158 159 160 161 162 163 164
  describe ".secret" do
    subject { described_class.secret }

    before do
      described_class.instance_variable_set(:@secret, nil)
      described_class.write_secret
    end

    it 'returns 32 bytes' do
      expect(subject).to be_a(String)
      expect(subject.length).to eq(32)
      expect(subject.encoding).to eq(Encoding::ASCII_8BIT)
    end

165
    it 'accepts a trailing newline' do
166
      File.open(described_class.secret_path, 'a') { |f| f.write "\n" }
167 168 169
      expect(subject.length).to eq(32)
    end

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    it 'raises an exception if the secret file cannot be read' do
      File.delete(described_class.secret_path)
      expect { subject }.to raise_exception(Errno::ENOENT)
    end

    it 'raises an exception if the secret file contains the wrong number of bytes' do
      File.truncate(described_class.secret_path, 0)
      expect { subject }.to raise_exception(RuntimeError)
    end
  end

  describe ".write_secret" do
    let(:secret_path) { described_class.secret_path }
    before do
      begin
        File.delete(secret_path)
      rescue Errno::ENOENT
      end

      described_class.write_secret
    end

    it 'uses mode 0600' do
      expect(File.stat(secret_path).mode & 0777).to eq(0600)
    end

    it 'writes base64 data' do
      bytes = Base64.strict_decode64(File.read(secret_path))
      expect(bytes).not_to be_empty
    end
  end

  describe '#verify_api_request!' do
Jacob Vosmaer's avatar
Jacob Vosmaer committed
203
    let(:header_key) { described_class::INTERNAL_API_REQUEST_HEADER }
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    let(:payload) { { 'iss' => 'gitlab-workhorse' } }

    it 'accepts a correct header' do
      headers = { header_key => JWT.encode(payload, described_class.secret, 'HS256') }
      expect { call_verify(headers) }.not_to raise_error
    end

    it 'raises an error when the header is not set' do
      expect { call_verify({}) }.to raise_jwt_error
    end

    it 'raises an error when the header is not signed' do
      headers = { header_key => JWT.encode(payload, nil, 'none') }
      expect { call_verify(headers) }.to raise_jwt_error
    end

    it 'raises an error when the header is signed with the wrong key' do
      headers = { header_key => JWT.encode(payload, 'wrongkey', 'HS256') }
      expect { call_verify(headers) }.to raise_jwt_error
    end

    it 'raises an error when the issuer is incorrect' do
      payload['iss'] = 'somebody else'
      headers = { header_key => JWT.encode(payload, described_class.secret, 'HS256') }
      expect { call_verify(headers) }.to raise_jwt_error
    end

    def raise_jwt_error
      raise_error(JWT::DecodeError)
    end

    def call_verify(headers)
      described_class.verify_api_request!(headers)
    end
  end
239 240 241

  describe '.git_http_ok' do
    let(:user) { create(:user) }
242
    let(:repo_path) { 'ignored but not allowed to be empty in gitlab-workhorse' }
243
    let(:action) { 'info_refs' }
244
    let(:params) do
245 246 247 248
      {
        GL_ID: "user-#{user.id}",
        GL_USERNAME: user.username,
        GL_REPOSITORY: "project-#{project.id}",
249
        ShowAllRefs: false
250
      }
251 252
    end

253
    subject { described_class.git_http_ok(repository, Gitlab::GlRepository::PROJECT, user, action) }
254 255

    it { expect(subject).to include(params) }
256

257
    context 'when the repo_type is a wiki' do
258
      let(:params) do
259 260 261 262
        {
          GL_ID: "user-#{user.id}",
          GL_USERNAME: user.username,
          GL_REPOSITORY: "wiki-#{project.id}",
263
          ShowAllRefs: false
264
        }
265 266
      end

267
      subject { described_class.git_http_ok(repository, Gitlab::GlRepository::WIKI, user, action) }
268

269 270
      it { expect(subject).to include(params) }
    end
271

272
    context 'when Gitaly is enabled' do
273 274
      let(:gitaly_params) do
        {
275 276 277 278
          GitalyServer: {
            address: Gitlab::GitalyClient.address('default'),
            token: Gitlab::GitalyClient.token('default')
          }
279 280 281
        }
      end

282
      before do
283
        allow(Gitlab.config.gitaly).to receive(:enabled).and_return(true)
284 285
      end

286
      it 'includes a Repository param' do
287
        repo_param = {
288
          storage_name: 'default',
289
          relative_path: project.disk_path + '.git',
290
          gl_repository: "project-#{project.id}"
291
        }
292

293
        expect(subject[:Repository]).to include(repo_param)
294 295
      end

296 297 298 299
      context "when git_upload_pack action is passed" do
        let(:action) { 'git_upload_pack' }
        let(:feature_flag) { :post_upload_pack }

300 301
        it 'includes Gitaly params in the returned value' do
          allow(Gitlab::GitalyClient).to receive(:feature_enabled?).with(feature_flag).and_return(true)
302

303
          expect(subject).to include(gitaly_params)
304
        end
305 306

        context 'show_all_refs enabled' do
307
          subject { described_class.git_http_ok(repository, Gitlab::GlRepository::PROJECT, user, action, show_all_refs: true) }
308 309 310

          it { is_expected.to include(ShowAllRefs: true) }
        end
311 312
      end

313 314 315
      context "when git_receive_pack action is passed" do
        let(:action) { 'git_receive_pack' }

316
        it { expect(subject).to include(gitaly_params) }
317 318
      end

319 320 321 322
      context "when info_refs action is passed" do
        let(:action) { 'info_refs' }

        it { expect(subject).to include(gitaly_params) }
323 324

        context 'show_all_refs enabled' do
325
          subject { described_class.git_http_ok(repository, Gitlab::GlRepository::PROJECT, user, action, show_all_refs: true) }
326 327 328

          it { is_expected.to include(ShowAllRefs: true) }
        end
329 330 331 332 333 334
      end

      context 'when action passed is not supported by Gitaly' do
        let(:action) { 'download' }

        it { expect { subject }.to raise_exception('Unsupported action: download') }
335 336
      end
    end
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    context 'when receive_max_input_size has been updated' do
      it 'returns custom git config' do
        allow(Gitlab::CurrentSettings).to receive(:receive_max_input_size) { 1 }

        expect(subject[:GitConfigOptions]).to be_present
      end
    end

    context 'when receive_max_input_size is empty' do
      it 'returns an empty git config' do
        allow(Gitlab::CurrentSettings).to receive(:receive_max_input_size) { nil }

        expect(subject[:GitConfigOptions]).to be_empty
      end
    end
353
  end
354

Kamil Trzcinski's avatar
Kamil Trzcinski committed
355
  describe '.set_key_and_notify' do
356 357 358
    let(:key) { 'test-key' }
    let(:value) { 'test-value' }

Kamil Trzcinski's avatar
Kamil Trzcinski committed
359
    subject { described_class.set_key_and_notify(key, value, overwrite: overwrite) }
360 361 362 363 364 365 366

    shared_examples 'set and notify' do
      it 'set and return the same value' do
        is_expected.to eq(value)
      end

      it 'set and notify' do
367
        expect_any_instance_of(::Redis).to receive(:publish)
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
          .with(described_class::NOTIFICATION_CHANNEL, "test-key=test-value")

        subject
      end
    end

    context 'when we set a new key' do
      let(:overwrite) { true }

      it_behaves_like 'set and notify'
    end

    context 'when we set an existing key' do
      let(:old_value) { 'existing-key' }

      before do
Kamil Trzcinski's avatar
Kamil Trzcinski committed
384
        described_class.set_key_and_notify(key, old_value, overwrite: true)
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
      end

      context 'and overwrite' do
        let(:overwrite) { true }

        it_behaves_like 'set and notify'
      end

      context 'and do not overwrite' do
        let(:overwrite) { false }

        it 'try to set but return the previous value' do
          is_expected.to eq(old_value)
        end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
400
        it 'does not notify' do
401
          expect_any_instance_of(::Redis).not_to receive(:publish)
402 403 404 405 406 407

          subject
        end
      end
    end
  end
408 409 410 411 412 413 414 415

  describe '.send_git_blob' do
    include FakeBlobHelpers

    let(:blob) { fake_blob }

    subject { described_class.send_git_blob(repository, blob) }

416 417
    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(subject)
418

419 420 421 422 423 424 425 426 427 428 429 430 431
      expect(key).to eq('Gitlab-Workhorse-Send-Data')
      expect(command).to eq('git-blob')
      expect(params).to eq({
        'GitalyServer' => {
          address: Gitlab::GitalyClient.address(project.repository_storage),
          token: Gitlab::GitalyClient.token(project.repository_storage)
        },
        'GetBlobRequest' => {
          repository: repository.gitaly_repository.to_h,
          oid: blob.id,
          limit: -1
        }
      }.deep_stringify_keys)
432 433
    end
  end
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

  describe '.send_url' do
    let(:url) { 'http://example.com' }

    subject { described_class.send_url(url) }

    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(subject)

      expect(key).to eq("Gitlab-Workhorse-Send-Data")
      expect(command).to eq("send-url")
      expect(params).to eq({
        'URL' => url,
        'AllowRedirects' => false
      }.deep_stringify_keys)
    end
  end
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

  describe '.send_git_snapshot' do
    let(:url) { 'http://example.com' }

    subject(:request) { described_class.send_git_snapshot(repository) }

    it 'sets the header correctly' do
      key, command, params = decode_workhorse_header(request)

      expect(key).to eq("Gitlab-Workhorse-Send-Data")
      expect(command).to eq('git-snapshot')
      expect(params).to eq(
        'GitalyServer' => {
          'address' => Gitlab::GitalyClient.address(project.repository_storage),
          'token' => Gitlab::GitalyClient.token(project.repository_storage)
        },
        'GetSnapshotRequest' => Gitaly::GetSnapshotRequest.new(
          repository: repository.gitaly_repository
        ).to_json
      )
    end
  end
473
end