Class: Aspera::Plugins::Shares::Commands

Inherits:
Cli::Plugins::Base show all
Includes:
Cli::Plugins::BasicAuth
Defined in:
lib/aspera/plugins/shares/commands.rb

Overview

Plugin for Aspera Shares v1

Constant Summary collapse

API_SCHEMA =

Key of the Shares API in the schemas of the bundle (manifest), with the path prefix of the admin API

'shares+/api/v1'
NODE_API_PATH =

path for node API after base url

'node_api'
ADMIN_API_PATH =

path for node admin after base url

'api/v1'
AUTH_API_PATH =

path for authentication (SAML login page, OAuth token) after base url

'auth'
REDIRECT_LOCALHOST =

default URL that receives the tokens, with auth web and ui.web_auth=port

'http://localhost:12345'
AUTH_TYPES =
%i[basic web].freeze
SAML_IMPORT_MANDATORY =
%w[id name_id].freeze
SAML_IMPORT_ALLOWED =
(%w[email given_name surname] + SAML_IMPORT_MANDATORY).freeze
USR_GRP_SETTINGS =

common to users and groups

%i[transfer_settings app_authorizations share_permissions].freeze
TRANSFER_SETTINGS_OPS =

transfer_settings supports delete (resets to global inheritance); app_authorizations and share_permissions do not

%i[show modify delete].freeze
SHARE_PERMISSIONS_OPS =

share_permissions is read-only (Rails only exposes index+show)

%i[list show].freeze
GROUP_USERS_OPS =

group users (all): Rails only exposes index+show+update+destroy (no create)

(Operations::ALL - %i[create]).freeze
LOCAL_GROUP_USERS_OPS =

local group users: same operations (no create), via data/local_groups/id/local_users

GROUP_USERS_OPS
GROUP_USERS_ARGS =

Arguments of group users commands, by operation

{
  show:   [{name: :user_id, type: :identifier}],
  modify: [{name: :user_id, type: :identifier}, {name: :user, type: Hash}],
  delete: [{name: :user_id, type: :identifier}]
}.freeze

Constants inherited from Cli::Plugins::Base

Cli::Plugins::Base::FILTER_ARGS

Instance Attribute Summary

Attributes inherited from Cli::Plugins::Base

#context, #help_path

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Cli::Plugins::BasicAuth

#basic_auth_api, included

Methods included from Cli::Option::Declarator

#declare_options, #option, #option_specs, #register_option_spec

Methods inherited from Cli::Plugins::Base

#action_for, application_name, #bulk_result, #check_argument_access, command, command_registry, commands_under, #config, #crud_api, crud_commands, declare_options, define_action_method, #dispatch_child, #dispatch_from_registry, #dispatch_leaf, #dispatch_mount, #entity_create, #entity_delete, #entity_list, #entity_modify, entity_noun, #entity_res_path, #entity_show, #execute_action, #execute_leaf, file_matcher, #formatter, #generate_help, #http_config, include_mounts, #invoke_action, operation_description, option_sources, option_specs, #options, #persistency, #poll_result, #presets, #progress_bar, #query_read_delete, register_option_spec, #resolve_argument, #resolve_arguments, #transfer, use_options, used_option_sources, #validate_registry

Constructor Details

#initialize(**_) ⇒ Commands

Returns a new instance of Commands.



160
161
162
163
# File 'lib/aspera/plugins/shares/commands.rb', line 160

def initialize(**_)
  super
  @api_shares_admin = nil
end

Class Method Details

.detect(address_or_url) ⇒ Hash, NilClass

Returns:



95
96
97
98
99
100
101
102
103
104
# File 'lib/aspera/plugins/shares/commands.rb', line 95

def detect(address_or_url)
  address_or_url = "https://#{address_or_url}" unless address_or_url.match?(%r{^[a-z]{1,6}://})
  health = health_check(address_or_url)
  return unless health[:api].is_a?(String)
  return {
    version: health[:version].is_a?(String) ? health[:version] : 'unknown',
    url:     address_or_url,
    saml:    health[:saml] || false
  }
end

.health_check(url) ⇒ Hash

Check various endpoints on Shares

Returns:

  • (Hash) —

    with version, ping, api



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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/aspera/plugins/shares/commands.rb', line 38

def health_check(url)
  result = {}
  # Get version from main page
  result[:version] =
    begin
      version = nil
       = Rest::Client
        .new(base_url: url, redirect_max: 2)
        .read('', headers: {'Accept'=>'text/html'})
      Aspera.assert(.include?('aspera-Shares')) { 'not Shares' }
      if (m = .match(/\(v([0-9a-f.]+)\)/))
        version = m[1]
        if (m = .match(/Patch level ([0-9]+)/))
          version = "#{version} #{m[0]}"
        end
      end
      result[:saml] = .include?('/auth/saml')
      version.nil? ? 'no version' : version
    rescue => e
      e
    end
  result[:ping] =
    begin
      Rest::Client
        .new(base_url: "#{url}/#{NODE_API_PATH}")
        .read('ping', headers: {'Content-Type' => Mime::JSON})
      'ping ok'
    rescue => e
      e
    end
  result[:api] =
    begin
      data, resp = Rest::Client
        .new(base_url: "#{url}/#{NODE_API_PATH}", redirect_max: 1)
        .read('info', exception: false, ret: :both)
      # shall fail: shares requires auth, but we check error message
      if resp.code.to_s.eql?('401') && data&.dig('error', 'user_message')&.include?('authentication failed')
        'available'
      else
        raise "not found (#{resp.code})"
      end
    rescue => e
      e
    end
  # Native JSON health check endpoint (no auth required)
  result[:system] =
    begin
      Rest::Client
        .new(base_url: url)
        .read('health_check')
    rescue => e
      e
    end
  result
end

Instance Method Details

#action_health ⇒ Object

--- health ---



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/aspera/plugins/shares/commands.rb', line 472

def action_health(**)
  nagios = Nagios.new
  shares_url = options.get_option(:url, mandatory: true)
  health = self.class.health_check(shares_url)
  nagios.add_ok('version', health[:version]) if health[:version].is_a?(String)
  if health[:ping].is_a?(String)
    nagios.add_ok('ping', health[:ping])
  else
    nagios.add_critical('ping', health[:ping].to_s)
  end
  if health[:api].is_a?(String)
    nagios.add_ok('API', health[:api])
  else
    nagios.add_critical('API', health[:api].to_s)
  end
  if health[:system].is_a?(Hash)
    sys = health[:system]
    # one status item for the license (standard or entitlement)
    if sys['valid_license'] || sys['entitled']
      nagios.add_ok('license', sys['entitled'] ? 'entitled' : 'valid')
    else
      nagios.add_critical('license', 'invalid')
    end
    # one status item per configured node
    (sys['nodes'] || []).each do |node|
      if node['status'].to_s.casecmp('active').zero?
        nagios.add_ok("node #{node['id']}", node['status'])
      else
        nagios.add_critical("node #{node['id']}", node['status'])
      end
    end
  else
    nagios.add_critical('system', health[:system].to_s)
  end
  Cli::Result::ObjectList.new(nagios.status_list)
end

#basic_auth_params(subpath = nil) ⇒ Hash

With auth web, the user authenticates with a browser (SAML), and the REST API uses the OAuth token. Otherwise: user and password.

Parameters:

  • subpath (String, nil) (defaults to: nil) —

    Path of API after base URL

Returns:

  • (Hash) —

    Parameters of Rest::Client



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/aspera/plugins/shares/commands.rb', line 169

def basic_auth_params(subpath = nil)
  return super unless options.get_option(:auth).eql?(:web)
  url = options.get_option(:url, mandatory: true)
  username = options.get_option(:username)
  return {
    base_url: subpath.nil? ? url : "#{url}/#{subpath}",
    auth:     {
      type:         :oauth2,
      base_url:     "#{url}/#{AUTH_API_PATH}",
      grant_method: :shares_web,
      redirect_uri: options.get_option(:redirect_uri) || REDIRECT_LOCALHOST,
      # a token is cached for each user, if known
      cache_ids:    [username].compact
    }
  }
end

#lookup_share_id(field, value) ⇒ Object

Lookup a share id by field/value using the admin API.



459
460
461
# File 'lib/aspera/plugins/shares/commands.rb', line 459

def lookup_share_id(field, value, **)
  Rest::List.lookup_entity_generic(field: field, value: value, entity: 'share') { @api_shares_admin.read('data/shares') }['id']
end

#lookup_share_id_user(field, value) ⇒ Object

Lookup a share id by field/value using the user-level API (for share event create).



464
465
466
467
468
# File 'lib/aspera/plugins/shares/commands.rb', line 464

def lookup_share_id_user(field, value, **)
  data = basic_auth_api(ADMIN_API_PATH).read('shares')
  data = data['shares'] if data.is_a?(Hash)
  Rest::List.lookup_entity_generic(field: field, value: value, entity: 'share') { data }['id']
end

#setup_admin ⇒ Hash

Build the admin REST API and store in ivar.

Returns:

  • (Hash) —

    empty ctx (state stored in @api_shares_admin)



447
448
449
450
# File 'lib/aspera/plugins/shares/commands.rb', line 447

def setup_admin(**)
  @api_shares_admin = basic_auth_api(ADMIN_API_PATH)
  {}
end

#setup_share_permissions(share_id:) ⇒ Hash

share_id: resolved by Phase A via arguments:(:identifier, lookup: :lookup_share_id) on the perm_type node

Returns:

  • (Hash) —

    ctx with API path of user and group permissions of the share



454
455
456
# File 'lib/aspera/plugins/shares/commands.rb', line 454

def setup_share_permissions(share_id:, **)
  %i[user_permissions group_permissions].to_h { |perm_type| [:"share_#{perm_type}", "data/shares/#{share_id}/#{perm_type}"] }
end

#shares_node_plugin ⇒ Node

files - mount target: Node plugin on the Shares node API. Node::Api (not plain Rest::Client) so that Node commands using its helpers work (e.g. spec, transport).

Returns:



441
442
443
# File 'lib/aspera/plugins/shares/commands.rb', line 441

def shares_node_plugin(**)
  Node::Commands.new(context: context, api: Node::Api.new(**basic_auth_params(NODE_API_PATH)))
end

#wizard(wizard, app_url) ⇒ Hash

Returns :preset_value, :test_args.

Parameters:

  • wizard (Wizard) —

    The wizard object

  • app_url (String) —

    Tested URL

Returns:

  • (Hash) —

    :preset_value, :test_args



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/aspera/plugins/shares/commands.rb', line 110

def wizard(wizard, app_url)
  auth_type = if !options.option_def(:auth).source.eql?(:default)
    options.get_option(:auth)
  elsif options.get_option(:password)
    :basic
  else
    saml_detected = begin
      self.class.health_check(app_url)[:saml] || false
    rescue StandardError
      false
    end
    formatter.display_status('SAML authentication is available.') if saml_detected
    if wizard.required
      formatter.display_status('Select authentication method:')
      options.prompt_user_input_in_list('auth', AUTH_TYPES)
    else
      saml_detected ? :web : :basic
    end
  end

  case auth_type
  when :web
    username = options.get_option(:username)
    preset_ids = username && !username.empty? ? [username] : ['web']
    preset_value = {
      url:  app_url,
      auth: :web.to_s
    }
    preset_value[:username] = username if username && !username.empty?
    redirect_uri = options.get_option(:redirect_uri)
    preset_value[:redirect_uri] = redirect_uri if redirect_uri
    {
      preset_ids:   preset_ids,
      preset_value: preset_value,
      test_args:    'files browse /'
    }
  when :basic
    username = options.get_option(:username, mandatory: true)
    {
      preset_ids:   [username],
      preset_value: {
        url:      app_url,
        username: username,
        password: options.get_option(:password, mandatory: true)
      },
      test_args:    'files browse /'
    }
  end
end