armrest 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (55) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +18 -0
  3. data/.rspec +3 -0
  4. data/CHANGELOG.md +7 -0
  5. data/Gemfile +4 -0
  6. data/Guardfile +19 -0
  7. data/LICENSE.txt +201 -0
  8. data/README.md +77 -0
  9. data/Rakefile +14 -0
  10. data/armrest.gemspec +35 -0
  11. data/exe/armrest +14 -0
  12. data/lib/armrest/api/auth/base.rb +8 -0
  13. data/lib/armrest/api/auth/cli.rb +36 -0
  14. data/lib/armrest/api/auth/login.rb +18 -0
  15. data/lib/armrest/api/auth/metadata.rb +51 -0
  16. data/lib/armrest/api/base.rb +133 -0
  17. data/lib/armrest/api/handle_response.rb +23 -0
  18. data/lib/armrest/api/main.rb +34 -0
  19. data/lib/armrest/api/mods.rb +8 -0
  20. data/lib/armrest/api/response.rb +5 -0
  21. data/lib/armrest/api/settings.rb +37 -0
  22. data/lib/armrest/api/version.rb +8 -0
  23. data/lib/armrest/auth.rb +48 -0
  24. data/lib/armrest/autoloader.rb +25 -0
  25. data/lib/armrest/cli/auth.rb +16 -0
  26. data/lib/armrest/cli/base.rb +7 -0
  27. data/lib/armrest/cli/blob_container.rb +29 -0
  28. data/lib/armrest/cli/blob_service.rb +25 -0
  29. data/lib/armrest/cli/help/blob_service/set_properties.md +4 -0
  30. data/lib/armrest/cli/help/completion.md +20 -0
  31. data/lib/armrest/cli/help/completion_script.md +3 -0
  32. data/lib/armrest/cli/help/connect.md +3 -0
  33. data/lib/armrest/cli/help.rb +11 -0
  34. data/lib/armrest/cli/resource_group.rb +29 -0
  35. data/lib/armrest/cli/secret.rb +11 -0
  36. data/lib/armrest/cli/storage_account.rb +32 -0
  37. data/lib/armrest/cli.rb +49 -0
  38. data/lib/armrest/command.rb +89 -0
  39. data/lib/armrest/completer/script.rb +8 -0
  40. data/lib/armrest/completer/script.sh +10 -0
  41. data/lib/armrest/completer.rb +159 -0
  42. data/lib/armrest/logger.rb +6 -0
  43. data/lib/armrest/logging.rb +22 -0
  44. data/lib/armrest/services/base.rb +16 -0
  45. data/lib/armrest/services/blob_container.rb +29 -0
  46. data/lib/armrest/services/blob_service.rb +25 -0
  47. data/lib/armrest/services/key_vault/base.rb +54 -0
  48. data/lib/armrest/services/key_vault/secret.rb +37 -0
  49. data/lib/armrest/services/resource_group.rb +23 -0
  50. data/lib/armrest/services/storage_account.rb +36 -0
  51. data/lib/armrest/version.rb +3 -0
  52. data/lib/armrest.rb +15 -0
  53. data/spec/cli_spec.rb +8 -0
  54. data/spec/spec_helper.rb +29 -0
  55. metadata +281 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c493f5db6bcb59d4a490038ed731e2bdeea4c39dcbbed24b67a15f8d289e982b
4
+ data.tar.gz: 76ae92a89cb3e3402d58270d4f8ed2596cf661dcd3c4e49c2fd8fc07280a552b
5
+ SHA512:
6
+ metadata.gz: cc0ae7d618f8737c1f9e8e27c3cb2bf9b6b2a92e2811fe2108ba695863789980aa5d4ac6e5908a57ffee6b8b85691e628d5bd5828dd385ffc21c12ef35821edd
7
+ data.tar.gz: f01f5ae21d330449c660c3e5d3e0955540ed80c28513cf1cce9d03d9bcbaf17bda73914d27b2ff604447eb221599f23b0908d48b11027b3477a974c0c1426033
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ *.swp
4
+ /.bundle
5
+ /.config
6
+ /.yardoc
7
+ /_yardoc
8
+ /coverage
9
+ /doc/
10
+ /Gemfile.lock
11
+ /InstalledFiles
12
+ /lib/bundler/man
13
+ /pkg
14
+ /rdoc
15
+ /spec/reports
16
+ /test/tmp
17
+ /test/version_tmp
18
+ /tmp
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --require spec_helper
2
+ --color
3
+ --format documentation
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ This project *loosely tries* to adhere to [Semantic Versioning](http://semver.org/), even before v1.0.
5
+
6
+ ## [0.1.0]
7
+ - Initial release.
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem dependencies in armrest.gemspec
4
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,19 @@
1
+ guard "bundler", cmd: "bundle" do
2
+ watch("Gemfile")
3
+ watch(/^.+\.gemspec/)
4
+ end
5
+
6
+ guard :rspec, cmd: "bundle exec rspec" do
7
+ require "guard/rspec/dsl"
8
+ dsl = Guard::RSpec::Dsl.new(self)
9
+
10
+ # RSpec files
11
+ rspec = dsl.rspec
12
+ watch(rspec.spec_helper) { rspec.spec_dir }
13
+ watch(rspec.spec_support) { rspec.spec_dir }
14
+ watch(rspec.spec_files)
15
+
16
+ # Ruby files
17
+ ruby = dsl.ruby
18
+ dsl.watch_spec_files_for(ruby.lib_files)
19
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # Armrest
2
+
3
+ [![BoltOps Badge](https://img.boltops.com/boltops/badges/boltops-badge.png)](https://www.boltops.com)
4
+
5
+ [![Gem Version](https://badge.fury.io/rb/armrest.svg)](https://badge.fury.io/rb/armrest)
6
+
7
+ A very lightweight Azure library that works with the [Azure REST API](https://docs.microsoft.com/en-us/rest/api/azure/), it is not meant to be extensive.
8
+
9
+ This was built because there doesn't seem to be a good library out there with the Azure features that [Terraspace](https://terraspace.cloud/) and [Terraspace Plugin Azurerm](https://github.com/boltops-tools/terraspace_plugin_azurerm) wanted to use:
10
+
11
+ * Auth Chain Provider: env vars -> MSI -> CLI creds. [#6](https://github.com/boltops-tools/terraspace_plugin_azurerm/issues/6)
12
+ * KeyVault secrets via the REST API
13
+
14
+ Also, the [Microsoft Azure SDK for Ruby library was deprecated as of Feb 2021](https://github.com/Azure/azure-sdk-for-ruby/blob/master/docs/README.md) and was officially retired. It's core library [ms_rest_azure.gemspec](https://github.com/Azure/azure-sdk-for-ruby/blob/master/runtime/ms_rest_azure/ms_rest_azure.gemspec#L39) have pinned versions of gems like faraday < 2, which causes gem dependency resolution issues.
15
+
16
+ This library also only makes use of the Ruby standard builtin net/http library so there's no dependency on faraday.
17
+
18
+ Again, this library has no goals of being extensive. Code generated SDKs is the approach that would take for that, but not dedicating the time to do that for this library.
19
+
20
+ ## Usage: Ruby
21
+
22
+ Resource group:
23
+
24
+ ```ruby
25
+ require "armrest"
26
+ resource_group = Armrest::Services::ResourceGroup.new
27
+ resource_group.create_or_update(
28
+ name: "my-resource-group",
29
+ location: "eastus",
30
+ tags: {key1: "value1"},
31
+ )
32
+ ```
33
+
34
+ Refer to the [boltops-tools/terraspace_plugin_azurer](https://github.com/boltops-tools/terraspace_plugin_azurerm) for more examples.
35
+
36
+ ## Usage: CLI
37
+
38
+ The main purpose of gem is to be a Ruby library that Terraspace can interact with. The CLI interface was only built to help quickly test the code with live resources. It's essentially a way to QA. Here are some examples:
39
+
40
+ Auth:
41
+
42
+ armrest auth app
43
+ armrest auth msi
44
+ armrest auth cli
45
+
46
+ The auth chain is: app -> msi -> cli
47
+
48
+ armrest auth chain
49
+
50
+ You can disable MSI with `ARMREST_DISABLE_MSI=1`.
51
+
52
+ Resource Group:
53
+
54
+ armrest resource_group check_existence demo
55
+
56
+ Storage Account:
57
+
58
+ armrest storage_account create demofoobar123v3 --tags name:bob age:8
59
+
60
+ Blob Service:
61
+
62
+ armrest blob_service set_properties --storage-account demofoobar123 --delete-retention-policy days:9 enabled:true --container-delete-retention-policy days:10 enabled:true --is-versioning-enabled
63
+
64
+ Secret:
65
+
66
+ $ export ARMREST_VAULT=demo-dev-vault-test1
67
+ $ armrest secret show demo-dev-pass
68
+ secret1
69
+ $
70
+
71
+ ## Installation
72
+
73
+ Add to your Gemfile
74
+
75
+ Gemfile
76
+
77
+ gem "armrest"
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ task default: :spec
5
+
6
+ RSpec::Core::RakeTask.new
7
+
8
+ require_relative "lib/armrest"
9
+ require "cli_markdown"
10
+ desc "Generates cli reference docs as markdown"
11
+ task :docs do
12
+ mkdir_p "docs/_includes"
13
+ CliMarkdown::Creator.create_all(cli_class: Armrest::CLI, cli_name: "armrest")
14
+ end
data/armrest.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "armrest/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "armrest"
8
+ spec.version = Armrest::VERSION
9
+ spec.authors = ["Tung Nguyen"]
10
+ spec.email = ["tongueroo@gmail.com"]
11
+ spec.summary = "Ruby Azure REST API Library"
12
+ spec.homepage = "https://github.com/boltops-tools/armrest"
13
+ spec.license = "Apache-2.0"
14
+
15
+ spec.files = File.directory?('.git') ? `git ls-files`.split($/) : Dir.glob("**/*")
16
+ spec.bindir = "exe"
17
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_dependency "activesupport"
22
+ spec.add_dependency "azure_info"
23
+ spec.add_dependency "hashie"
24
+ spec.add_dependency "memoist"
25
+ spec.add_dependency "rack"
26
+ spec.add_dependency "rainbow"
27
+ spec.add_dependency "thor"
28
+ spec.add_dependency "zeitwerk"
29
+
30
+ spec.add_development_dependency "bundler"
31
+ spec.add_development_dependency "byebug"
32
+ spec.add_development_dependency "cli_markdown"
33
+ spec.add_development_dependency "rake"
34
+ spec.add_development_dependency "rspec"
35
+ end
data/exe/armrest ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Trap ^C
4
+ Signal.trap("INT") {
5
+ puts "\nCtrl-C detected. Exiting..."
6
+ sleep 0.1
7
+ exit
8
+ }
9
+
10
+ $:.unshift(File.expand_path("../../lib", __FILE__))
11
+ require "armrest"
12
+ require "armrest/cli"
13
+
14
+ Armrest::CLI.start(ARGV)
@@ -0,0 +1,8 @@
1
+ module Armrest::Api::Auth
2
+ class Base < Armrest::Api::Base
3
+ def initialize(options={})
4
+ super
5
+ @camelize_request_data = false
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,36 @@
1
+ require "json"
2
+
3
+ #
4
+ # az account get-access-token : Get a token for utilities to access Azure.
5
+ # The token will be valid for at least 5 minutes with the maximum at 60 minutes. If the
6
+ # subscription argument isn't specified, the current account is used.
7
+ #
8
+ # Arguments
9
+ # --resource : Azure resource endpoints. Default to Azure Resource Manager.
10
+ # --resource-type : Type of well-known resource. Allowed values: aad-graph, arm, batch, data-
11
+ # lake, media, ms-graph, oss-rdbms.
12
+ # --subscription -s : Name or ID of subscription.
13
+ # --tenant -t : Tenant ID for which the token is acquired. Only available for user and
14
+ # service principal account, not for MSI or Cloud Shell account.
15
+ module Armrest::Api::Auth
16
+ class CLI < Base
17
+ class Error < StandardError; end
18
+ class CliError < Error; end
19
+
20
+ def creds
21
+ data = get_access_token
22
+ data.deep_transform_keys { |k| k.underscore } # to normalize the structure to the other classes
23
+ end
24
+
25
+ # Looks like az account get-access-token caches the toke in ~/.azure/accessTokens.json
26
+ # and will update it only when it expires. So dont think we need to handle caching
27
+ def get_access_token
28
+ command = "az account get-access-token -o json --resource #{resource}"
29
+ logger.debug "command: #{command}"
30
+ out = `#{command}`
31
+ JSON.load(out)
32
+ rescue
33
+ raise CliError, 'Error acquiring token from the Azure az CLI'
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,18 @@
1
+ module Armrest::Api::Auth
2
+ class Login < Base
3
+ def endpoint
4
+ "https://login.microsoftonline.com"
5
+ end
6
+
7
+ def creds
8
+ url = "#{tenant_id}/oauth2/token"
9
+ resp = get(url,
10
+ grant_type: "client_credentials",
11
+ client_id: client_id,
12
+ client_secret: client_secret,
13
+ resource: resource,
14
+ )
15
+ load_json(resp)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,51 @@
1
+ # GET 'https://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' HTTP/1.1 Metadata: true
2
+ module Armrest::Api::Auth
3
+ class Metadata < Base
4
+ def initialize(options={})
5
+ @options = options
6
+ end
7
+
8
+ def creds
9
+ url = "metadata/identity/oauth2/token?" + Rack::Utils.build_query(query_params)
10
+ resp = get(url)
11
+ load_json(resp)
12
+ end
13
+
14
+ @@available = nil
15
+ def available?
16
+ return false if ENV['ARMREST_DISABLE_MSI']
17
+ return @@available unless @@available.nil?
18
+ url = "metadata/instance"
19
+ resp = nil
20
+ with_open_timeout(0.5) do
21
+ resp = get(url)
22
+ end
23
+ @@available = resp.code == "200"
24
+ rescue Net::OpenTimeout => e
25
+ logger.debug "#{e.class}: #{e.message}"
26
+ false
27
+ end
28
+
29
+ def query_params
30
+ params = { resource: resource }
31
+ params[:client_id] = client_id if client_id
32
+ params[:object_id] = object_id if @options[:object_id]
33
+ params[:msi_res_id] = msi_res_id if @options[:msi_res_id]
34
+ params
35
+ end
36
+
37
+ # interface method
38
+ def endpoint
39
+ "http://169.254.169.254"
40
+ end
41
+
42
+ # interface method
43
+ def headers
44
+ { Metadata: true }
45
+ end
46
+
47
+ def api_version
48
+ "2021-10-01"
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,133 @@
1
+ require 'net/http'
2
+ require 'rack'
3
+
4
+ module Armrest::Api
5
+ class Base
6
+ extend Memoist
7
+ include Mods
8
+
9
+ def initialize(options={})
10
+ @options = options
11
+ @camelize_request_data = true
12
+ end
13
+
14
+ HTTP_WRITE_METHODS = %w[post patch put delete]
15
+ HTTP_READ_METHODS = %w[get head]
16
+ methods = HTTP_WRITE_METHODS + HTTP_READ_METHODS
17
+ methods.each do |meth|
18
+ define_method(meth) do |path, data={}|
19
+ request("Net::HTTP::#{meth.camelize}".constantize, path, data)
20
+ end
21
+ # IE:
22
+ # def get(path, data={})
23
+ # request(Net::HTTP::Get, path, data)
24
+ # end
25
+ end
26
+
27
+ # Always translate raw json response to ruby Hash
28
+ def request(klass, path, data={})
29
+ path = standarize_path(path)
30
+ url = url(path)
31
+ req = build_request(klass, path, data)
32
+ http = http(url)
33
+ meth = klass.to_s.split('::').last.underscore
34
+ logger.debug "#{meth.upcase} #{url}".color(:yellow)
35
+ # logger.debug "req['Authorization'] #{req['Authorization']}"
36
+
37
+ resp = send_request(http, req)
38
+
39
+ logger.debug "resp #{resp}"
40
+ logger.debug "resp.code #{resp.code}"
41
+ logger.debug "resp.body #{resp.body}"
42
+
43
+ if HTTP_WRITE_METHODS.include?(meth) && resp.code !~ /^20/
44
+ raise Armrest::Error.new(resp)
45
+ end
46
+
47
+ resp
48
+ end
49
+
50
+ MAX_RETRIES = (ENV['ARMREST_MAX_RETRIES'] || 3).to_i
51
+ def send_request(http, req)
52
+ retries = 0
53
+ resp = http.request(req) # send request
54
+ retry_codes = [/^5/, "429"]
55
+ retry_code_detected = retry_codes.detect { |code| resp.code.match(code) }
56
+ if retry_code_detected && retries < MAX_RETRIES
57
+ retries += 1
58
+ delay = 2 ** retries
59
+ logger.debug "retries #{retries} sleep #{delay} and will retry."
60
+ sleep delay
61
+ resp = http.request(req) # send request
62
+ end
63
+ resp
64
+ end
65
+
66
+ def build_request(klass, path, data={})
67
+ data = camelize(data)
68
+ req = klass.new(path) # url includes query string and uri.path does not, must used url
69
+ set_headers!(req)
70
+
71
+ logger.debug "build_request data #{data}"
72
+
73
+ # Note: Need to use to_s for case statement to work right
74
+ case klass.to_s.split('::').last.underscore
75
+ when "delete", "patch", "post", "put"
76
+ text = JSON.dump(data)
77
+ req.body = text
78
+ req.content_length = text.bytesize
79
+ when "get"
80
+ req.set_form_data(data) if data && !data.empty?
81
+ end
82
+
83
+ req
84
+ end
85
+
86
+ def camelize(data)
87
+ return data unless @camelize_request_data
88
+ data.deep_transform_keys { |k| k.to_s.camelize(:lower) }
89
+ end
90
+
91
+ def standarize_path(path)
92
+ path = "/#{path}" unless path.starts_with?('/')
93
+ path = append_api_version(path)
94
+ end
95
+
96
+ def append_api_version(path)
97
+ separator = path.include?('?') ? '&' : '?'
98
+ path + separator + "api-version=#{api_version}"
99
+ end
100
+
101
+ def set_headers!(req)
102
+ headers.each do |k,v|
103
+ req[k.to_s] = v.to_s
104
+ end
105
+ end
106
+
107
+ # interface method
108
+ def headers
109
+ {}
110
+ end
111
+
112
+ def http(url)
113
+ uri = URI(url)
114
+ http = Net::HTTP.new(uri.host, uri.port)
115
+ http.open_timeout = @open_timeout || 30
116
+ http.read_timeout = @read_timeout || 30
117
+ http.use_ssl = true if uri.scheme == 'https'
118
+ http
119
+ end
120
+ memoize :http
121
+
122
+ def with_open_timeout(value)
123
+ saved, @open_timeout = @open_timeout, value
124
+ yield
125
+ @open_timeout = saved
126
+ end
127
+
128
+ # interface method. API endpoint does not include the /. IE: https://login.microsoftonline.com
129
+ def url(path)
130
+ "#{endpoint}#{path}"
131
+ end
132
+ end
133
+ end