ハウツーガイド - CLIでのテストlambdaの実行
このセグメントでは、テストlambda関数のCLIコマンドを実行する方法について説明します。
前提条件
- Workato SDK Gemをインストール済みで、実行できること。詳細については、はじめにガイドを参照してください。
- 少なくとも認証(コネクションキー)とテストlambdaが定義されたコネクターがあること。以下に示すサンプルを使用すること。
- 動作する認証情報のセットがあること。サンプルコネクタコードを使用している場合は、そのコネクタに適した認証情報があることを確認してください。
このガイドでは、次の方法について説明します。
シンプル認証シナリオのテストlambdaの呼び出し
シンプル認証シナリオには、Basic認証、APIキー、または同様の形式が含まれます。この認証の基準は、ユーザーが指定する認証情報だけで認証に必要なすべてが揃うことです。アクセストークンの取得など、追加のフォローアップ手順は不要です。
高度な認証シナリオのテストlambdaの呼び出し
高度な認証シナリオとは、ユーザーが指定した入力を使用して、後で別の認証情報セットを取得する場合です。たとえば、OAuth 2.0クライアント認証情報フローで認証する場合、ユーザーがクライアントIDとシークレットを渡すと、それらを使用して
acquire:lambdaでアクセストークンを取得します。OAuth2(Auth code grant)シナリオのテストlambdaの呼び出し
コネクションのタイプが
oauth2に設定されている場合。
テストlambdaを実行する理由
このコネクションテストlambdaは、OAuth2(Auth code grant)コネクションを除き、ユーザーがコネクションのすべての入力を指定した後、初めて接続を試みるときに実行されます。
さらに、OAuth 2(Auth code grant)を含むすべての認証タイプでは、レシピの初回開始時にコネクションがまだ有効であることを確認するためにテストlambdaが呼び出されます。
OAuth2で初回コネクション時にテストlambdaが不要な理由
OAuth2(Auth code grant)コネクションは、OAuth2トークンエンドポイントからトークンが取得されたときにWorkatoによって確認されます。認可サーバーから有効なトークンを受信すると、コネクションは有効と見なされます。したがって、追加のコネクションテストを実行する必要はありません。
Simple Authのテストlambdaの呼び出し
サンプルコネクター
connector.rb内のコード。
{
title: 'Chargebee-demo',
connection: {
fields: [
{
name: 'api_key',
control_type: 'password',
hint: 'You can find your API key final change3' \
"under 'Settings'=>'Configure Chargebee'=>'API Keys and Webhooks'" \
" in Chargebee's web console.",
label: 'Your API Key'
},
{
name: 'domain',
control_type: 'subdomain',
url: 'chargebee.com'
}
],
authorization: {
type: 'basic_auth',
apply: lambda do |connection|
user(connection['api_key'])
end
},
base_uri: lambda do |connection|
"https://#{connection['domain']}.chargebee.com"
end
},
test: lambda do |_connection|
get('/api/v2/plans', limit: 1)
end,
}settings.yaml.enc内の認証情報。
api_key: valid_api_key
domain: valid_domainテストlambdaの実行
コマンドを実行すると
$ workato exec test出力は次のようになります
{
"list": [
{
"plan": {
"id": "cool-product",
"name": "cool product",
"price": 10000,
"period": 2,
"period_unit": "week",
"pricing_model": "flat_fee",
"free_quantity": 0,
"status": "active",
"enabled_in_hosted_pages": true,
"enabled_in_portal": false,
"addon_applicability": "all",
"is_shippable": false,
"updated_at": 1630235299,
"giftable": false,
"resource_version": 1630235299389,
"object": "plan",
"charge_model": "flat_fee",
"taxable": true,
"currency_code": "SGD",
"show_description_in_invoices": true,
"show_description_in_quotes": false,
}
}
],
"next_offset": "[\"10000\",\"487940\"]"
}これは定義したtest lambdaのリテラル出力ですが、Workatoが重視するのは実際の出力そのものではなく、リクエストが正常に実行されたことです。
TIP
--verboseなどの他のオプションを使用して、output_fieldsの構築時に送信されたHTTPリクエストの詳細ログを確認したり、--outputを使用して関数の出力をJSONファイルに保存したりすることもできます。
高度なAuthのテストlambdaの呼び出し
サンプルコネクター - 高度な認証
connector.rb内のコード。
{
name: "Percolate",
connection: {
fields: [
{ name: "client_id",
optional: false,
hint: "To create client ID, the system admin or manager can click " \
"<a href='https://percolate.com/app/settings/developer/apps/new' " \
"target='_blank'>here</a> to register a new client application." },
{ name: "client_secret",
control_type: "password",
optional: false,
hint: "To create client secret, the system admin or manager can click" \
" <a href='https://percolate.com/app/settings/developer/apps/new' " \
"target='_blank'>here</a> to register a new client application." },
{ name: "environment",
optional: false,
control_type: "select",
pick_list: [%w[Production production], %w[Sandbox sandbox],
%w[Internal internal]] }
],
authorization: {
type: "custom_auth",
acquire: lambda do |connection|
hash = Base64.encode64("client:#{connection['client_id']}:#{connection['client_secret']}").gsub("\n", "")
post("https://percolate.com/auth/v5/token/")
.payload(grant_type: "client_credentials")
.headers(Authorization: "Basic " + hash)
.request_format_www_form_urlencoded
.after_response do |_code, body, headers|
body["headers"] = headers
body
end
end,
detect_on: [401, 403],
refresh_on: [401, 403],
apply: lambda do |connection|
if current_url.include?("https://percolate.com")
headers(Authorization: "Bearer #{connection['access_token']}")
end
end
},
base_uri: lambda do |_connection|
"https://percolate.com"
end
},
test: lambda do |_connection|
get("/api/v5/me")
end,
}settings.yaml.enc内の認証情報。
client_id: valid_client_id
client_secret: valid_client_secret
environment: productionテストlambdaの実行
コマンドを実行すると
workato exec test --verbose出力は次のようになる場合があります
SETTINGS
{
"client_id": "valid_client_id",
"client_secret": "valid_client_secret",
"environment": "production",
}
INPUT
{
}
RestClient.get "https://percolate.com/api/v5/me", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer ", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 401 Unauthorized | application/json 65 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
RestClient.post "https://percolate.com/auth/v5/token/", "grant_type=client_credentials", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Basic ", "Content-Length"=>"29", "Content-Type"=>"application/x-www-form-urlencoded", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 200 OK | application/json 25 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
Refresh token triggered on response "401 Unauthorized"
Update settings file with new connection attributes? (Yes or No)まず、出力は、コネクションテストlambda(api/v5/meエンドポイント)が401レスポンスを返したため、設定ファイルにaccess_tokenがないことを示しています。
これにより、acquire lambda(auth/v5/tokenエンドポイント)がトリガーされます。 acquire lambdaは、認可エンドポイントへのPOST API呼び出しです。これが発生すると、acquireブロックの出力がconnectionハッシュにマージされます。これはWorkatoプラットフォームでの動作と同じで、acquire lambdaはrefresh_onがシグナルを出した場合にのみ呼び出されます。
acquire lambdaのrefresh_on属性は、現在のアクセストークンの有効期限が切れた場合にトリガーされ、新しいアクセストークンを取得します。これは、コネクションテストlambdaまたはその他のlambdaを呼び出すたびにトリガーされます。
最後に、Gemは設定ファイルを上書きする権限を求めます。これはWorkatoプラットフォーム上のconnectionハッシュと同義です。 "Yes"と入力すると、Gemはacquire lambdaの出力で設定ファイルを更新します。
Update settings file with new connection attributes? (Yes or No) Yes
RestClient.get "https://percolate.com/api/v5/me", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer example_token", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 200 OK | application/json 65 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
OUTPUT
# Output of the test lambdasettings.yaml.enc内の認証情報が更新されます。
client_id: valid_client_id
client_secret: valid_client_secret
environment: production
id: token:example_token
expires_in: 2592000
updated_at: '2021-08-30T14:54:35+00:00'
user_id: user:130135
grant_id: grant:1216779461986395763
access_token: example_token
token_type: bearerOAuth2(Auth code grant)シナリオのテストlambdaの呼び出し
Auth code grantフローでは、Workato Gemを使用してworkato oauth2コマンドでOAuth2フローをエミュレートできます。この動作により、エンドユーザーにOAuth2エクスペリエンスがどのように見えるかをすばやくデバッグして理解できます。
サンプルコネクター - OAuth 2コネクター
connector.rb内のコード。
{
title: 'TrackVia',
connection: {
fields: [
{
name: 'custom_domain',
control_type: 'subdomain',
label: 'TrackVia subdomain',
hint: 'Enter your TrackVia subdomain. e.g. customdomain.trackvia.com. By default, <b>go.trackvia.com</b> will be used.',
optional: 'true'
},
{
name: 'account_id',
control_type: :number,
label: 'Account ID',
hint: 'Specify the account to connect to',
optional: true
},
{
name: 'client_id',
control_type: :text,
label: 'TrackVia App Client ID',
hint: 'Enter the Client ID of your own OAuth app registered on TrackVia',
optional: 'false'
},
{
name: 'client_secret',
control_type: :text,
label: 'TrackVia App Client secret',
hint: 'Enter the Client secret of your own OAuth app registered on TrackVia',
optional: 'false'
}
],
authorization: {
type: 'oauth2',
authorization_url: lambda { |connection|
"https://#{connection['custom_domain'].presence || 'go.trackvia.com'}/oauth/authorize?response_type=code"
},
acquire: lambda do |connection, auth_code, redirect_uri|
url = "https://#{connection['custom_domain'].presence || 'go.trackvia.com'}"
response = post("#{url}/oauth/token").payload(
redirect_uri: redirect_uri,
grant_type: 'authorization_code',
code: auth_code,
client_id: connection['client_id'],
client_secret: connection['client_secret']
).request_format_www_form_urlencoded
user_key = get("#{url}/3scale/openapiapps").params(access_token: response['access_token']).dig(0, 'userKey')
[
response,
nil,
{
user_key: user_key
}
]
end,
refresh: lambda do |connection, refresh_token|
url = "https://#{connection['custom_domain'].presence || 'go.trackvia.com'}"
post("#{url}/oauth/token").payload(
client_id: connection['client_id'],
client_secret: connection['client_secret'],
grant_type: 'refresh_token',
refresh_token: refresh_token
).request_format_www_form_urlencoded
end,
refresh_on: [401, 403],
apply: lambda { |connection, access_token|
params(user_key: connection['user_key'])
headers(Authorization: "Bearer #{access_token}")
headers('account-id': connection['account_id']) if connection['account_id'].present?
}
},
base_uri: lambda do |connection|
if connection['custom_domain'].presence
"https://#{connection['custom_domain']}/openapi/"
else
"https://go.trackvia.com/openapi/"
end
end
},
test: lambda do |connection|
get('views')
end,
}settings.yaml.enc内の認証情報。
client_id: valid_client_id
client_secret: valid_client_secretこれで、次のコマンドを実行して、ブラウザーポップアップを含むOAuth2 Authorization codeフローを進めることができます。 OAuth2フローの詳細なログ記録を有効にするには、--verboseを含めます。
workato oauth2 --verboseこれにより、ブラウザーポップアップからauthorization_urlの出力URLまでのフロー全体がシミュレートされ、コールバックURLでAuth Codeを受信し、さらにtoken_url lambdaまたはacquire lambdaに含まれる後続の呼び出しも実行されます。最後に、フローはOAuth2フローから受信した最新の認証情報セットでsettings.yamlファイルを更新します。
SDK GemはWorkatoでOAuth2フローをエミュレートします
フローの最後には、最新の認証情報で更新されたsettings.yaml.encファイルがあるはずです。
client_id: valid_client_id
client_secret: valid_client_secret
user_key: valid_user_key
tokenType: bearer
expires_in: 299
expiration: '2021-10-19T15:36:39.221+0000'
scope:
- trust
- read
- write
apiVersion: '22.18'
access_token: valid_access_token
refresh_token: valid_refresh_tokenテストlambdaの実行
フローを正常に完了した後は、同じworkato exec testコマンドを使用して、リクエストでトークンを適切に適用していることを確認できます。
トークンを受信したタイミングによっては、Gemからアクセストークンを更新するかどうか(有効期限が切れている場合)を尋ねる中間コマンドが表示されることもあります。これは、refresh_onブロックをトリガーするレスポンスを持つHTTPリクエストが行われたときに実行されます。 yesを選択すると、Gemは最新の認証情報で設定ファイルを更新します。
$ workato exec test --verbose出力は次のようになる場合があります
SETTINGS
{
"client_id": "valid_client_id",
"client_secret": "valid_client_secret",
"user_key": "valid_user_key",
"tokenType": "bearer",
"expires_in": "299",
"expiration": "2021-10-19T15:36:39.221+0000",
"scope": ["trust", "read", "write"],
"apiVersion": "2.18",
"access_token": "valid_access_token",
"refresh_token": "valid_refresh_token"
}
INPUT
{
}
RestClient.get "https://go.trackvia.com/openapi/views", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer valid_access_token", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 401 Unauthorized | application/json 65 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
RestClient.post "https://go.trackvia.com/oauth/token", "grant_type"=>"client_credentials", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "refresh_token"=>"valid_refresh_token", "Content-Length"=>"29", "Content-Type"=>"application/x-www-form-urlencoded", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 200 OK | application/json 25 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
Refresh token triggered on response "401 Unauthorized"
Updated settings file with new connection attributes? (Yes or No)まず、出力は、コネクションテストlambda(openapi/viewsエンドポイント)が401レスポンスを返したため、設定ファイルに有効なaccess_tokenがないことを示しています。アクセストークンの有効期限が切れている可能性があります。
これにより、acquire lambda(/oauth/tokenエンドポイント)がトリガーされます。 acquire lambdaは、認可エンドポイントへのPOST API呼び出しです。これが発生すると、acquireブロックの出力がconnectionハッシュにマージされます。これはWorkatoプラットフォームでの動作と同じで、acquire lambdaはrefresh_onがシグナルを出した場合にのみ呼び出されます。
acquire lambdaのrefresh_on属性は、現在のアクセストークンの有効期限が切れた場合にトリガーされ、新しいアクセストークンを取得します。これは、コネクションテストlambdaまたはその他のlambdaを呼び出すたびにトリガーされます。
最後に、Gemは設定ファイルを上書きする権限を求めます。これはWorkatoプラットフォーム上のconnectionハッシュと同義です。 "Yes"と入力すると、Gemはacquire lambdaの出力で設定ファイルを更新します。
Updated settings file with new connection attributes? (Yes or No) Yes
RestClient.get "https://go.trackvia.com/openapi/views", "Accept"=>"application/json", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer new_valid_access_token", "User-Agent"=>"rest-client/2.0.2 (darwin19.6.0 x86_64) ruby/2.4.10p364"
# => 200 OK | application/json 65 bytes
Progress: |=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=|
OUTPUT
# Output of the test lambdasettings.yaml.enc内の認証情報が更新されます。
client_id: valid_client_id
client_secret: valid_client_secret
user_key: valid_user_key
tokenType: bearer
expires_in: 299
expiration: '2021-10-19T15:41:39.221+0000'
scope:
- trust
- read
- write
apiVersion: '22.18'
access_token: new_valid_access_token
refresh_token: new_valid_refresh_tokenメモ
workato execを使用して、acquireやrefreshなど、authorizationハッシュ内のlambdaを実行することもできます。とはいえ、settings.yamlファイルの更新を自動的に処理するworkato exec testとworkato oauth2を使用することを強くお勧めします。
最終更新日: