kontena-cli 0.16.3 → 0.17.0.pre1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (99) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +1 -0
  3. data/.gitignore +3 -1
  4. data/VERSION +1 -1
  5. data/lib/kontena/callbacks/master/deploy/40_install_ssl_certificate_after_deploy.rb +32 -0
  6. data/lib/kontena/cli/apps/deploy_command.rb +2 -2
  7. data/lib/kontena/cli/apps/scale_command.rb +2 -2
  8. data/lib/kontena/cli/apps/show_command.rb +3 -2
  9. data/lib/kontena/cli/apps/yaml/validations.rb +10 -6
  10. data/lib/kontena/cli/apps/yaml/validator.rb +1 -0
  11. data/lib/kontena/cli/apps/yaml/validator_v2.rb +1 -0
  12. data/lib/kontena/cli/cloud/login_command.rb +66 -64
  13. data/lib/kontena/cli/common.rb +0 -10
  14. data/lib/kontena/cli/grids/logs_command.rb +0 -1
  15. data/lib/kontena/cli/localhost_web_server.rb +11 -3
  16. data/lib/kontena/cli/master/login_command.rb +213 -163
  17. data/lib/kontena/cli/nodes/label_command.rb +2 -0
  18. data/lib/kontena/cli/nodes/labels/add_command.rb +7 -8
  19. data/lib/kontena/cli/nodes/labels/list_command.rb +17 -0
  20. data/lib/kontena/cli/nodes/labels/remove_command.rb +7 -12
  21. data/lib/kontena/cli/nodes/show_command.rb +1 -0
  22. data/lib/kontena/cli/plugins/common.rb +8 -0
  23. data/lib/kontena/cli/plugins/install_command.rb +21 -2
  24. data/lib/kontena/cli/plugins/list_command.rb +4 -2
  25. data/lib/kontena/cli/plugins/search_command.rb +4 -2
  26. data/lib/kontena/cli/registry/create_command.rb +19 -12
  27. data/lib/kontena/cli/registry/remove_command.rb +4 -4
  28. data/lib/kontena/cli/registry_command.rb +0 -1
  29. data/lib/kontena/cli/services/create_command.rb +6 -6
  30. data/lib/kontena/cli/services/deploy_command.rb +8 -4
  31. data/lib/kontena/cli/services/list_command.rb +34 -21
  32. data/lib/kontena/cli/services/logs_command.rb +1 -1
  33. data/lib/kontena/cli/services/scale_command.rb +3 -3
  34. data/lib/kontena/cli/services/services_helper.rb +18 -14
  35. data/lib/kontena/cli/services/show_command.rb +1 -0
  36. data/lib/kontena/cli/services/update_command.rb +6 -6
  37. data/lib/kontena/cli/stack_command.rb +12 -6
  38. data/lib/kontena/cli/stacks/build_command.rb +110 -0
  39. data/lib/kontena/cli/stacks/common.rb +85 -20
  40. data/lib/kontena/cli/stacks/deploy_command.rb +30 -7
  41. data/lib/kontena/cli/stacks/install_command.rb +30 -0
  42. data/lib/kontena/cli/stacks/list_command.rb +74 -14
  43. data/lib/kontena/cli/stacks/logs_command.rb +31 -0
  44. data/lib/kontena/cli/stacks/monitor_command.rb +91 -0
  45. data/lib/kontena/cli/stacks/remove_command.rb +24 -7
  46. data/lib/kontena/cli/stacks/service_generator.rb +115 -0
  47. data/lib/kontena/cli/stacks/service_generator_v2.rb +27 -0
  48. data/lib/kontena/cli/stacks/show_command.rb +65 -13
  49. data/lib/kontena/cli/stacks/upgrade_command.rb +28 -0
  50. data/lib/kontena/cli/stacks/yaml/custom_validators/affinities_validator.rb +19 -0
  51. data/lib/kontena/cli/stacks/yaml/custom_validators/build_validator.rb +22 -0
  52. data/lib/kontena/cli/stacks/yaml/custom_validators/extends_validator.rb +21 -0
  53. data/lib/kontena/cli/stacks/yaml/custom_validators/hooks_validator.rb +54 -0
  54. data/lib/kontena/cli/stacks/yaml/custom_validators/secrets_validator.rb +22 -0
  55. data/lib/kontena/cli/stacks/yaml/reader.rb +219 -0
  56. data/lib/kontena/cli/stacks/yaml/service_extender.rb +78 -0
  57. data/lib/kontena/cli/stacks/yaml/validations.rb +71 -0
  58. data/lib/kontena/cli/stacks/yaml/validator_v3.rb +52 -0
  59. data/lib/kontena/cli/version_command.rb +5 -1
  60. data/lib/kontena/cli/vpn/create_command.rb +20 -17
  61. data/lib/kontena/cli/vpn/remove_command.rb +4 -3
  62. data/lib/kontena/client.rb +21 -20
  63. data/lib/kontena/machine/cert_helper.rb +4 -0
  64. data/lib/kontena/machine/cloud_config/cloudinit.yml +1 -1
  65. data/lib/kontena/main_command.rb +1 -1
  66. data/spec/fixtures/kontena-build.yml +2 -2
  67. data/spec/fixtures/kontena-invalid.yml +1 -1
  68. data/spec/fixtures/kontena-not-hash-service-config.yml +1 -1
  69. data/spec/fixtures/kontena-with-env-file.yml +2 -2
  70. data/spec/fixtures/kontena_build_v3.yml +23 -0
  71. data/spec/fixtures/kontena_v3.yml +20 -0
  72. data/spec/fixtures/stack-internal-extend.yml +11 -0
  73. data/spec/fixtures/stack-with-env-file.yml +21 -0
  74. data/spec/fixtures/stack-with-variables.yml +22 -0
  75. data/spec/kontena/cli/app/scale_spec.rb +3 -1
  76. data/spec/kontena/cli/cloud/login_command_spec.rb +283 -0
  77. data/spec/kontena/cli/master/login_command_spec.rb +324 -145
  78. data/spec/kontena/cli/services/link_command_spec.rb +1 -1
  79. data/spec/kontena/cli/services/secrets/link_command_spec.rb +4 -4
  80. data/spec/kontena/cli/services/secrets/unlink_command_spec.rb +2 -2
  81. data/spec/kontena/cli/services/services_helper_spec.rb +15 -11
  82. data/spec/kontena/cli/services/unlink_command_spec.rb +1 -1
  83. data/spec/kontena/cli/stacks/deploy_command_spec.rb +26 -0
  84. data/spec/kontena/cli/stacks/install_command_spec.rb +54 -0
  85. data/spec/kontena/cli/stacks/list_command_spec.rb +27 -0
  86. data/spec/kontena/cli/stacks/remove_command_spec.rb +45 -0
  87. data/spec/kontena/cli/stacks/service_generator_spec.rb +385 -0
  88. data/spec/kontena/cli/stacks/service_generator_v2_spec.rb +74 -0
  89. data/spec/kontena/cli/stacks/show_command_spec.rb +26 -0
  90. data/spec/kontena/cli/stacks/upgrade_command_spec.rb +50 -0
  91. data/spec/kontena/cli/stacks/yaml/reader_spec.rb +370 -0
  92. data/spec/kontena/cli/stacks/yaml/service_extender_spec.rb +128 -0
  93. data/spec/kontena/cli/stacks/yaml/validator_v3_spec.rb +302 -0
  94. data/spec/spec_helper.rb +6 -4
  95. data/spec/support/client_helpers.rb +1 -0
  96. metadata +57 -7
  97. data/lib/kontena/cli/registry/delete_command.rb +0 -18
  98. data/lib/kontena/cli/stacks/create_command.rb +0 -27
  99. data/lib/kontena/cli/stacks/update_command.rb +0 -27
@@ -0,0 +1,52 @@
1
+ require 'hash_validator'
2
+
3
+ module Kontena::Cli::Stacks
4
+ module YAML
5
+ class ValidatorV3
6
+ require_relative 'validations'
7
+ include Validations
8
+
9
+ def initialize
10
+ @schema = common_validations
11
+ @schema['build'] = optional('stacks_valid_build')
12
+ @schema['depends_on'] = optional('array')
13
+ @schema['network_mode'] = optional(%w(host bridge))
14
+ @schema['logging'] = optional({
15
+ 'driver' => optional('string'),
16
+ 'options' => optional(-> (value) { value.is_a?(Hash) })
17
+ })
18
+ Validations::CustomValidators.load
19
+ end
20
+
21
+ ##
22
+ # @param [Hash] yaml
23
+ # @param [TrueClass|FalseClass] strict
24
+ # @return [Array] validation_errors
25
+ def validate(yaml)
26
+ result = {
27
+ errors: [],
28
+ notifications: []
29
+ }
30
+ if yaml.key?('services')
31
+ yaml['services'].each do |service, options|
32
+ unless options.is_a?(Hash)
33
+ result[:errors] << { service => { 'options' => 'must be a mapping not a string'} }
34
+ next
35
+ end
36
+ option_errors = validate_options(options)
37
+ result[:errors] << { service => option_errors.errors } unless option_errors.valid?
38
+ end
39
+ else
40
+ result[:errors] << { 'file' => 'services missing' }
41
+ end
42
+ if yaml.key?('volumes')
43
+ result[:notifications] << { 'volumes' => 'Kontena does not support volumes yet. To persist data just define service as stateful (stateful: true)' }
44
+ end
45
+ if yaml.key?('networks')
46
+ result[:notifications] << { 'networks' => 'Kontena does not support multiple networks yet. You can reference services with Kontena\'s internal DNS (service_name.kontena.local)' }
47
+ end
48
+ result
49
+ end
50
+ end
51
+ end
52
+ end
@@ -3,9 +3,13 @@ require_relative 'version'
3
3
  class Kontena::Cli::VersionCommand < Kontena::Command
4
4
  include Kontena::Cli::Common
5
5
 
6
+ option "--cli", :flag, "Only CLI version"
7
+
6
8
  def execute
7
- url = api_url rescue nil
8
9
  puts "cli: #{Kontena::Cli::VERSION}"
10
+ return if cli?
11
+
12
+ url = api_url rescue nil
9
13
  if url
10
14
  resp = JSON.parse(client.http_client.get(path: '/').body) rescue nil
11
15
  if resp
@@ -20,24 +20,27 @@ module Kontena::Cli::Vpn
20
20
  vpn_ip = node_vpn_ip(node)
21
21
  data = {
22
22
  name: 'vpn',
23
- stateful: true,
24
- image: 'kontena/openvpn:ethwe',
25
- ports: [
26
- {
27
- container_port: '1194',
28
- node_port: '1194',
29
- protocol: 'udp'
30
- }
31
- ],
32
- cap_add: ['NET_ADMIN'],
33
- env: ["OVPN_SERVER_URL=udp://#{vpn_ip}:1194"],
34
- affinity: ["node==#{node['name']}"]
23
+ services: [
24
+ name: 'server',
25
+ stateful: true,
26
+ image: 'kontena/openvpn:ethwe',
27
+ ports: [
28
+ {
29
+ container_port: '1194',
30
+ node_port: '1194',
31
+ protocol: 'udp'
32
+ }
33
+ ],
34
+ cap_add: ['NET_ADMIN'],
35
+ env: ["OVPN_SERVER_URL=udp://#{vpn_ip}:1194"],
36
+ affinity: ["node==#{node['name']}"]
37
+ ]
35
38
  }
36
- client(token).post("grids/#{current_grid}/services", data)
37
- client(token).post("services/#{current_grid}/vpn/deploy", {})
38
- name = 'vpn'
39
- spinner "deploying #{name.colorize(:cyan)} service " do
40
- wait_for_deploy_to_finish(token, parse_service_id('vpn'))
39
+ client(token).post("grids/#{current_grid}/stacks", data)
40
+ client(token).post("stacks/#{current_grid}/vpn/deploy", {})
41
+ spinner "Deploying vpn service " do
42
+ sleep 1 while client(token).get("stacks/#{current_grid}/vpn")['state'] == 'deploying'
43
+ sleep 1 while client(token).get("stacks/#{current_grid}/vpn")['state'] == 'running'
41
44
  end
42
45
  spinner "generating #{name.colorize(:cyan)} keys (this will take a while) " do
43
46
  wait_for_configuration_to_finish(token)
@@ -10,11 +10,12 @@ module Kontena::Cli::Vpn
10
10
  token = require_token
11
11
  confirm unless forced?
12
12
  name = 'vpn'
13
- vpn = client(token).get("services/#{current_grid}/#{name}") rescue nil
14
- exit_with_error("#{name} service does not exist") if vpn.nil?
13
+
14
+ vpn = client(token).get("stacks/#{current_grid}/vpn") rescue nil
15
+ exit_with_error("VPN stack does not exist") if vpn.nil?
15
16
 
16
17
  spinner "Removing #{name.colorize(:cyan)} service " do
17
- client(token).delete("services/#{current_grid}/vpn")
18
+ client(token).delete("stacks/#{current_grid}/vpn")
18
19
  end
19
20
  end
20
21
  end
@@ -51,15 +51,28 @@ module Kontena
51
51
  @logger.progname = 'CLIENT'
52
52
 
53
53
  @options[:default_headers] ||= {}
54
- Excon.defaults[:ssl_verify_peer] = false if ignore_ssl_errors?
55
54
 
56
- @http_client = Excon.new(
57
- api_url,
55
+ excon_opts = {
58
56
  omit_default_port: true,
59
57
  connect_timeout: ENV["EXCON_CONNECT_TIMEOUT"] ? ENV["EXCON_CONNECT_TIMEOUT"].to_i : 5,
60
58
  read_timeout: ENV["EXCON_READ_TIMEOUT"] ? ENV["EXCON_READ_TIMEOUT"].to_i : 30,
61
- write_timeout: ENV["EXCON_WRITE_TIMEOUT"] ? ENV["EXCON_WRITE_TIMEOUT"].to_i : 5
62
- )
59
+ write_timeout: ENV["EXCON_WRITE_TIMEOUT"] ? ENV["EXCON_WRITE_TIMEOUT"].to_i : 5,
60
+ ssl_verify_peer: ignore_ssl_errors? ? false : true
61
+ }
62
+
63
+ cert_file = File.join(Dir.home, "/.kontena/certs/#{uri.host}.pem")
64
+ if File.exist?(cert_file) && File.readable?(cert_file)
65
+ excon_opts[:ssl_ca_file] = cert_file
66
+ key = OpenSSL::X509::Certificate.new(File.read(cert_file))
67
+ if key.issuer.to_s == "/C=FI/O=Test/OU=Test/CN=Test"
68
+ logger.debug "Key looks like a self-signed cert made by Kontena CLI, setting verify_peer_host to 'Test'"
69
+ excon_opts[:ssl_verify_peer_host] = 'Test'
70
+ end
71
+ end
72
+
73
+ logger.debug "Excon opts: #{excon_opts.inspect}"
74
+
75
+ @http_client = Excon.new(api_url, excon_opts)
63
76
 
64
77
  @default_headers = {
65
78
  ACCEPT => CONTENT_JSON,
@@ -107,20 +120,6 @@ module Kontena
107
120
  end
108
121
  end
109
122
 
110
- # OAuth2 client_id from ENV KONTENA_CLIENT_ID or client CLIENT_ID constant
111
- #
112
- # @return [String]
113
- def client_id
114
- ENV['KONTENA_CLIENT_ID'] || CLIENT_ID
115
- end
116
-
117
- # OAuth2 client_secret from ENV KONTENA_CLIENT_SECRET or client CLIENT_SECRET constant
118
- #
119
- # @return [String]
120
- def client_secret
121
- ENV['KONTENA_CLIENT_SECRET'] || CLIENT_SECRET
122
- end
123
-
124
123
  # Requests path supplied as argument and returns true if the request was a success.
125
124
  # For checking if the current authentication is valid.
126
125
  #
@@ -146,7 +145,7 @@ module Kontena
146
145
  return nil unless token_account
147
146
  return nil unless token_account['token_endpoint']
148
147
 
149
- request(
148
+ response = request(
150
149
  http_method: token_account['token_method'].downcase.to_sym,
151
150
  path: token_account['token_endpoint'],
152
151
  headers: { CONTENT_TYPE => token_account['token_post_content_type'] },
@@ -159,6 +158,8 @@ module Kontena
159
158
  expects: [200,201],
160
159
  auth: false
161
160
  )
161
+ response['expires_at'] ||= in_to_at(response['expires_in'])
162
+ response
162
163
  end
163
164
 
164
165
  # Return server version from a Kontena master by requesting '/'
@@ -4,6 +4,10 @@ module Kontena
4
4
  module Machine
5
5
  module CertHelper
6
6
 
7
+ def certificate_public_key(cert)
8
+ cert[/(-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----)/m, 1]
9
+ end
10
+
7
11
  def generate_self_signed_cert
8
12
  key = OpenSSL::PKey::RSA.new(2048)
9
13
  public_key = key.public_key
@@ -11,7 +11,7 @@ write_files:
11
11
  - path: /etc/systemd/system/docker.service.d/50-kontena.conf
12
12
  content: |
13
13
  [Service]
14
- Environment='DOCKER_OPTS=--insecure-registry="10.81.0.0/19" --bip="<%= docker_bip %>"'
14
+ Environment='DOCKER_OPTS=--insecure-registry="10.81.0.0/16" --bip="<%= docker_bip %>"'
15
15
  - path: /etc/sysctl.d/99-inotify.conf
16
16
  owner: root
17
17
  permissions: 0644
@@ -35,7 +35,7 @@ class Kontena::MainCommand < Kontena::Command
35
35
  subcommand "logout", "Logout from Kontena Masters or Kontena Cloud accounts", Kontena::Cli::LogoutCommand
36
36
  subcommand "grid", "Grid specific commands", Kontena::Cli::GridCommand
37
37
  subcommand "app", "App specific commands", Kontena::Cli::AppCommand
38
- subcommand "stack", "Stack specific commands", Kontena::Cli::StackCommand if experimental?
38
+ subcommand "stack", "Stack specific commands", Kontena::Cli::StackCommand
39
39
  subcommand "service", "Service specific commands", Kontena::Cli::ServiceCommand
40
40
  subcommand "vault", "Vault specific commands", Kontena::Cli::VaultCommand
41
41
  subcommand "certificate", "LE Certificate specific commands", Kontena::Cli::CertificateCommand
@@ -3,7 +3,7 @@ wordpress:
3
3
  image: registry.kontena.local/wordpress:latest
4
4
  stateful: true
5
5
  environment:
6
- WORDPRESS_DB_PASSWORD: %{project}_secret
6
+ WORDPRESS_DB_PASSWORD: ${project}_secret
7
7
  instances: 2
8
8
  deploy:
9
9
  strategy: ha
@@ -13,4 +13,4 @@ mysql:
13
13
  service: mysql
14
14
  stateful: true
15
15
  environment:
16
- - MYSQL_ROOT_PASSWORD=%{project}_secret
16
+ - MYSQL_ROOT_PASSWORD=${project}_secret
@@ -1,4 +1,4 @@
1
1
  wordpress:
2
2
  stateful: 'true'
3
3
  environment:
4
- WORDPRESS_DB_PASSWORD: %{project}_secret
4
+ WORDPRESS_DB_PASSWORD: ${project}_secret
@@ -1,3 +1,3 @@
1
1
  version: '2'
2
2
  services:
3
- wordpress: 'service config cannot be string'
3
+ wordpress: 'service config cannot be string'
@@ -5,7 +5,7 @@ wordpress:
5
5
  stateful: true
6
6
  env_file: .env
7
7
  environment:
8
- WORDPRESS_DB_PASSWORD: %{project}_secret
8
+ WORDPRESS_DB_PASSWORD: ${project}_secret
9
9
  instances: 2
10
10
  deploy:
11
11
  strategy: ha
@@ -15,4 +15,4 @@ mysql:
15
15
  service: mysql
16
16
  stateful: true
17
17
  environment:
18
- - MYSQL_ROOT_PASSWORD=%{project}_secret
18
+ - MYSQL_ROOT_PASSWORD=${project}_secret
@@ -0,0 +1,23 @@
1
+ stack: user/stackname
2
+ version: 0.1.1
3
+ services:
4
+ mysql:
5
+ stateful: true
6
+ environment:
7
+ - MYSQL_ROOT_PASSWORD=${project}_secret
8
+
9
+ webapp:
10
+ image: webapp
11
+ build:
12
+ context: .
13
+ args:
14
+ - foo=bar
15
+ - baz=baf
16
+
17
+ some_app:
18
+ image: some_app
19
+ build:
20
+ context: .
21
+ args:
22
+ foo: bar
23
+ baz:
@@ -0,0 +1,20 @@
1
+ stack: user/stackname
2
+ version: 0.1.1
3
+ services:
4
+ wordpress:
5
+ extends:
6
+ file: docker-compose_v2.yml
7
+ service: wordpress
8
+ stateful: true
9
+ environment:
10
+ WORDPRESS_DB_PASSWORD: ${STACK}_secret
11
+ instances: 2
12
+ deploy:
13
+ strategy: ha
14
+ mysql:
15
+ extends:
16
+ file: docker-compose_v2.yml
17
+ service: mysql
18
+ stateful: true
19
+ environment:
20
+ - MYSQL_ROOT_PASSWORD=${STACK}_secret
@@ -0,0 +1,11 @@
1
+ stack: user/stackname
2
+ version: 0.1.1
3
+ services:
4
+ base:
5
+ stateful: true
6
+ instances: 2
7
+ deploy:
8
+ strategy: ha
9
+ app:
10
+ extends: base
11
+ stateful: true
@@ -0,0 +1,21 @@
1
+ stack: user/stackname
2
+ version: 0.1.1
3
+ services:
4
+ wordpress:
5
+ extends:
6
+ file: docker-compose_v2.yml
7
+ service: wordpress
8
+ stateful: true
9
+ env_file: .env
10
+ environment:
11
+ WORDPRESS_DB_PASSWORD: ${STACK}_secret
12
+ instances: 2
13
+ deploy:
14
+ strategy: ha
15
+ mysql:
16
+ extends:
17
+ file: docker-compose_v2.yml
18
+ service: mysql
19
+ stateful: true
20
+ environment:
21
+ - MYSQL_ROOT_PASSWORD=${STACK}_secret
@@ -0,0 +1,22 @@
1
+ stack: user/stackname
2
+ version: 0.1.1
3
+ services:
4
+ wordpress:
5
+ extends:
6
+ file: docker-compose_v2.yml
7
+ service: wordpress
8
+ image: wordpress:$TAG
9
+ stateful: true
10
+ environment:
11
+ - WORDPRESS_DB_PASSWORD=${STACK}_secret
12
+ instances: 2
13
+ deploy:
14
+ strategy: ha
15
+ mysql:
16
+ extends:
17
+ file: docker-compose_v2.yml
18
+ service: mysql
19
+ image: ${MYSQL_IMAGE}
20
+ stateful: true
21
+ environment:
22
+ - INTERNAL_VAR=$$INTERNAL_VAR
@@ -42,7 +42,9 @@ describe Kontena::Cli::Apps::ScaleCommand do
42
42
 
43
43
  it 'scales given service' do
44
44
  allow(File).to receive(:read).with("#{Dir.getwd}/kontena.yml").and_return(kontena_yml_no_instances)
45
- expect(subject).to receive(:scale_service).with(duck_type(:access_token),'kontena-test-wordpress',3)
45
+ allow(subject).to receive(:wait_for_deploy_to_finish).and_return(true)
46
+ expect(subject).to receive(:scale_service).with(duck_type(:access_token), 'kontena-test-wordpress', 3)
47
+
46
48
  subject.run(['wordpress', 3])
47
49
  end
48
50
 
@@ -0,0 +1,283 @@
1
+ require_relative "../../../spec_helper"
2
+ require 'kontena/cli/cloud/login_command'
3
+ require 'kontena/cli/localhost_web_server'
4
+ require 'launchy'
5
+
6
+ describe Kontena::Cli::Cloud::LoginCommand do
7
+
8
+ include ClientHelpers
9
+
10
+ let(:subject) do
11
+ described_class.new(File.basename($0))
12
+ end
13
+
14
+ let(:config) { double(:config) }
15
+ let(:client) { double(:client) }
16
+
17
+ before(:each) do
18
+ allow(subject).to receive(:config).and_return(config)
19
+ allow(Kontena::Client).to receive(:new).and_return(client)
20
+ end
21
+
22
+ it 'should give error if trying to use --code and --force' do
23
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
24
+ subject.run(['--code', 'abcd', '--force'])
25
+ end
26
+
27
+ it 'should give error if trying to use --token and --force' do
28
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
29
+ subject.run(['--token', 'abcd', '--force'])
30
+ end
31
+
32
+ it 'should give error if trying to use --token and --code' do
33
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
34
+ subject.run(['--token', 'abcd', '--code', 'defg'])
35
+ end
36
+
37
+ context 'when config has token' do
38
+ let(:account) do
39
+ account = Kontena::Cli::Config::Account.new(Kontena::Cli::Config.kontena_account_data)
40
+ account.token = Kontena::Cli::Config::Token.new(access_token: 'foofoo', parent_type: :account, parent_name: 'kontena')
41
+ account.username = 'testuser'
42
+ account
43
+ end
44
+
45
+ before(:each) do
46
+ expect(subject).to receive(:kontena_account).at_least(:once).and_return(account)
47
+ end
48
+
49
+ it 'should check if the token works and not authenticate again if it does' do
50
+ expect(client).to receive(:authentication_ok?).with(account.userinfo_endpoint).and_return(true)
51
+ expect(subject).to receive(:finish).and_return(true)
52
+ subject.run([])
53
+ end
54
+
55
+ it 'should not use the token from config when --token given' do
56
+ expect(client).to receive(:authentication_ok?).with(account.userinfo_endpoint).and_return(true)
57
+ expect(subject).to receive(:finish).and_return(true)
58
+ subject.run(['--token', 'abcd'])
59
+ expect(account.token.access_token).to eq 'abcd'
60
+ end
61
+
62
+ it 'should not use the token from config when --code given' do
63
+ expect(client).to receive(:authentication_ok?).with(account.userinfo_endpoint).and_return(true)
64
+ expect(subject).to receive(:use_authorization_code).with('abcd')
65
+ expect(subject).not_to receive(:web_flow)
66
+ expect(subject).to receive(:finish).and_return(true)
67
+ subject.run(['--code', 'abcd'])
68
+ end
69
+
70
+ it 'should not use the token from config when --force given' do
71
+ expect(client).not_to receive(:authentication_ok?)
72
+ expect(subject).to receive(:web_flow).and_return(true)
73
+ expect(subject).to receive(:finish).and_return(true)
74
+ subject.run(['--force'])
75
+ end
76
+ end
77
+
78
+ context 'when config does not have a token' do
79
+ let(:account) do
80
+ account = Kontena::Cli::Config::Account.new(Kontena::Cli::Config.kontena_account_data)
81
+ account.token = Kontena::Cli::Config::Token.new(access_token: nil, parent_type: :account, parent_name: 'kontena')
82
+ account.username = 'testuser'
83
+ account
84
+ end
85
+
86
+ before(:each) do
87
+ expect(subject).to receive(:kontena_account).at_least(:once).and_return(account)
88
+ end
89
+
90
+ it 'should use --code if given' do
91
+ expect(client).to receive(:authentication_ok?).with(account.userinfo_endpoint).and_return(true)
92
+ expect(client).to receive(:exchange_code).with('abcd').and_return({
93
+ 'access_token' => 'abcdefg'
94
+ })
95
+ expect(subject).not_to receive(:web_flow)
96
+ expect(subject).to receive(:finish).and_return(true)
97
+ subject.run(['--code', 'abcd'])
98
+ expect(account.token.access_token).to eq 'abcdefg'
99
+ end
100
+
101
+ it 'should use the --token if given' do
102
+ expect(client).to receive(:authentication_ok?).with(account.userinfo_endpoint).and_return(true)
103
+ expect(subject).to receive(:finish).and_return(true)
104
+ subject.run(['--token', 'abcd'])
105
+ expect(account.token.access_token).to eq 'abcd'
106
+ end
107
+
108
+ it 'should enter the webflow if --force given' do
109
+ expect(client).not_to receive(:authentication_ok?)
110
+ expect(subject).to receive(:web_flow).and_return(true)
111
+ expect(subject).to receive(:finish).and_return(true)
112
+ subject.run(['--force'])
113
+ end
114
+
115
+ it 'should enter the webflow if --force not given' do
116
+ expect(client).not_to receive(:authentication_ok?)
117
+ expect(subject).to receive(:web_flow).and_return(true)
118
+ expect(subject).to receive(:finish).and_return(true)
119
+ subject.run([])
120
+ end
121
+ end
122
+
123
+ context 'when performing web flow' do
124
+ let(:account) do
125
+ account = Kontena::Cli::Config::Account.new(Kontena::Cli::Config.kontena_account_data)
126
+ account.token = Kontena::Cli::Config::Token.new(access_token: nil, parent_type: :account, parent_name: 'kontena')
127
+ account
128
+ end
129
+
130
+ let(:webserver) { double(:webserver) }
131
+
132
+ before(:each) do
133
+ expect(subject).to receive(:kontena_account).at_least(:once).and_return(account)
134
+ allow(subject).to receive(:any_key_to_continue).and_return(true)
135
+ end
136
+
137
+ context 'cloud returns a token' do
138
+ it 'starts a web server, opens a a browser, parses the response and updates the token' do
139
+ expect(Kontena::LocalhostWebServer).to receive(:new).and_return(webserver)
140
+ expect(webserver).to receive(:port).and_return(1234)
141
+ expect(webserver).to receive(:serve_one).and_return({
142
+ 'access_token' => 'abcd'
143
+ })
144
+ expect(Launchy).to receive(:open).and_return(true)
145
+ expect(subject).to receive(:finish).and_return(true)
146
+ subject.run([])
147
+ expect(account.token.access_token).to eq 'abcd'
148
+ end
149
+ end
150
+
151
+ context 'cloud returns a code' do
152
+ it 'starts a web server, opens a a browser, parses the response and updates the token' do
153
+ expect(Kontena::LocalhostWebServer).to receive(:new).and_return(webserver)
154
+ expect(webserver).to receive(:port).and_return(1234)
155
+ expect(webserver).to receive(:serve_one).and_return({
156
+ 'code' => 'abcd'
157
+ })
158
+ expect(Launchy).to receive(:open).and_return(true)
159
+ expect(client).to receive(:exchange_code).with('abcd').and_return({
160
+ 'access_token' => 'abcdefg'
161
+ })
162
+ expect(subject).to receive(:finish).and_return(true)
163
+ subject.run([])
164
+ expect(account.token.access_token).to eq 'abcdefg'
165
+ end
166
+ end
167
+
168
+ context 'cloud returns an error' do
169
+ it 'starts a web server, opens a a browser, parses the response and updates the token' do
170
+ expect(Kontena::LocalhostWebServer).to receive(:new).and_return(webserver)
171
+ expect(webserver).to receive(:port).and_return(1234)
172
+ expect(webserver).to receive(:serve_one).and_return({
173
+ 'error' => 'foo'
174
+ })
175
+ expect(Launchy).to receive(:open).and_return(true)
176
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
177
+ subject.run([])
178
+ end
179
+ end
180
+ end
181
+
182
+ context 'methods' do
183
+ let(:account) do
184
+ account = Kontena::Cli::Config::Account.new(Kontena::Cli::Config.kontena_account_data)
185
+ account.token = Kontena::Cli::Config::Token.new(access_token: 'foofoo', parent_type: :account, parent_name: 'kontena')
186
+ account
187
+ end
188
+
189
+ before(:each) do
190
+ allow(subject).to receive(:kontena_account).and_return(account)
191
+ end
192
+
193
+ describe '#finish' do
194
+ it 'updates user info, sets the current account, writes the config and displays login info' do
195
+ expect(subject).to receive(:kontena_account).at_least(:once).and_return(account)
196
+ allow(config).to receive(:reset_instance).and_return(true)
197
+ allow(config).to receive(:display_logo).and_return(true)
198
+ allow(subject).to receive(:reset_cloud_client).and_return(true)
199
+ expect(subject).to receive(:display_login_info).and_return(true)
200
+ expect(subject).to receive(:update_userinfo).and_return(true)
201
+ expect(config).to receive(:current_account=).and_return(true)
202
+ expect(config).to receive(:write).and_return(true)
203
+ subject.finish
204
+ end
205
+ end
206
+
207
+ describe '#use_authorization_code' do
208
+ it 'should use #exchange_code on client' do
209
+ expect(client).to receive(:exchange_code).with('abcd').and_return(true)
210
+ allow(subject).to receive(:update_token).and_return(true)
211
+ subject.use_authorization_code('abcd')
212
+ end
213
+
214
+ it 'should update the account token' do
215
+ expect(client).to receive(:exchange_code).with('abcd').and_return(
216
+ 'access_token' => 'token'
217
+ )
218
+ subject.use_authorization_code('abcd')
219
+ expect(account.token.access_token).to eq 'token'
220
+ end
221
+ end
222
+
223
+ describe '#update_userinfo' do
224
+ it 'should make a get request to account userinfo endpoint' do
225
+ expect(client).to receive(:get).with('/' + account.userinfo_endpoint.split('/').last).and_return(nil)
226
+ allow(subject).to receive(:exit_with_error)
227
+ subject.update_userinfo
228
+ end
229
+
230
+ it 'should update account username' do
231
+ expect(client).to receive(:get).and_return(
232
+ 'data' => {
233
+ 'attributes' => {
234
+ 'username' => 'foofoo'
235
+ }
236
+ }
237
+ )
238
+ expect(account).to receive(:username=).with('foofoo')
239
+ subject.update_userinfo
240
+ end
241
+
242
+ it 'should exit with error if cloud responds with error' do
243
+ expect(client).to receive(:get).and_return('error' => 'foo')
244
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
245
+ subject.update_userinfo
246
+ end
247
+
248
+ it 'should exit with error if cloud responds with something silly' do
249
+ expect(client).to receive(:get).and_return('foo')
250
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
251
+ subject.update_userinfo
252
+ end
253
+ end
254
+
255
+ describe '#update_token' do
256
+ it 'should exchange code if response has code' do
257
+ expect(subject).to receive(:use_authorization_code).with('abcd').and_return({})
258
+ subject.update_token({'code' => 'abcd'})
259
+ end
260
+
261
+ it 'should update the token of kontena account' do
262
+ subject.update_token(
263
+ 'access_token' => 'token',
264
+ 'refresh_token' => 'refresh',
265
+ 'expires_in' => 123,
266
+ 'expires_at' => 12345
267
+ )
268
+ expect(account.token.access_token).to eq 'token'
269
+ expect(account.token.refresh_token).to eq 'refresh'
270
+ expect(account.token.expires_at).to eq 12345
271
+ end
272
+
273
+ it 'should give error when response has error' do
274
+ expect(subject).to receive(:exit_with_error).and_throw(:exit_with_error)
275
+ subject.update_token('error' => 'fail!')
276
+ end
277
+
278
+ it 'should raise if response is not a hash' do
279
+ expect{subject.update_token('foo')}.to raise_error(TypeError)
280
+ end
281
+ end
282
+ end
283
+ end