-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
helpers.lua
2851 lines (2470 loc) · 85.6 KB
/
helpers.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
159
160
161
162
163
164
165
166
167
168
169
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
203
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
------------------------------------------------------------------
-- Collection of utilities to help testing Kong features and plugins.
--
-- @copyright Copyright 2016-2020 Kong Inc. All rights reserved.
-- @license [Apache 2.0](https://opensource.org/licenses/Apache-2.0)
-- @module spec.helpers
local BIN_PATH = "bin/kong"
local TEST_CONF_PATH = os.getenv("KONG_SPEC_TEST_CONF_PATH") or "spec/kong_tests.conf"
local CUSTOM_PLUGIN_PATH = "./spec/fixtures/custom_plugins/?.lua"
local DNS_MOCK_LUA_PATH = "./spec/fixtures/mocks/lua-resty-dns/?.lua"
local GO_PLUGIN_PATH = "./spec/fixtures/go"
local MOCK_UPSTREAM_PROTOCOL = "http"
local MOCK_UPSTREAM_SSL_PROTOCOL = "https"
local MOCK_UPSTREAM_HOST = "127.0.0.1"
local MOCK_UPSTREAM_HOSTNAME = "localhost"
local MOCK_UPSTREAM_PORT = 15555
local MOCK_UPSTREAM_SSL_PORT = 15556
local MOCK_UPSTREAM_STREAM_PORT = 15557
local MOCK_UPSTREAM_STREAM_SSL_PORT = 15558
local MOCK_GRPC_UPSTREAM_PROTO_PATH = "./spec/fixtures/grpc/hello.proto"
local BLACKHOLE_HOST = "10.255.255.255"
local KONG_VERSION = require("kong.meta")._VERSION
local PLUGINS_LIST
local consumers_schema_def = require "kong.db.schema.entities.consumers"
local services_schema_def = require "kong.db.schema.entities.services"
local plugins_schema_def = require "kong.db.schema.entities.plugins"
local routes_schema_def = require "kong.db.schema.entities.routes"
local prefix_handler = require "kong.cmd.utils.prefix_handler"
local dc_blueprints = require "spec.fixtures.dc_blueprints"
local conf_loader = require "kong.conf_loader"
local kong_global = require "kong.global"
local Blueprints = require "spec.fixtures.blueprints"
local pl_stringx = require "pl.stringx"
local constants = require "kong.constants"
local pl_tablex = require "pl.tablex"
local pl_utils = require "pl.utils"
local pl_path = require "pl.path"
local pl_file = require "pl.file"
local version = require "version"
local pl_dir = require "pl.dir"
local pl_Set = require "pl.Set"
local Schema = require "kong.db.schema"
local Entity = require "kong.db.schema.entity"
local cjson = require "cjson.safe"
local utils = require "kong.tools.utils"
local http = require "resty.http"
local nginx_signals = require "kong.cmd.utils.nginx_signals"
local log = require "kong.cmd.utils.log"
local DB = require "kong.db"
local ffi = require "ffi"
local ssl = require "ngx.ssl"
local ws_client = require "resty.websocket.client"
local table_clone = require "table.clone"
local https_server = require "spec.fixtures.https_server"
ffi.cdef [[
int setenv(const char *name, const char *value, int overwrite);
int unsetenv(const char *name);
]]
local kong_exec -- forward declaration
log.set_lvl(log.levels.quiet) -- disable stdout logs in tests
-- Add to package path so dao helpers can insert custom plugins
-- (while running from the busted environment)
do
local paths = {}
table.insert(paths, os.getenv("KONG_LUA_PACKAGE_PATH"))
table.insert(paths, CUSTOM_PLUGIN_PATH)
table.insert(paths, package.path)
package.path = table.concat(paths, ";")
end
--- Returns the OpenResty version.
-- Extract the current OpenResty version in use and returns
-- a numerical representation of it.
-- Ex: `1.11.2.2` -> `11122`
-- @function openresty_ver_num
local function openresty_ver_num()
local nginx_bin = assert(nginx_signals.find_nginx_bin())
local _, _, _, stderr = pl_utils.executeex(string.format("%s -V", nginx_bin))
local a, b, c, d = string.match(stderr or "", "openresty/(%d+)%.(%d+)%.(%d+)%.(%d+)")
if not a then
error("could not execute 'nginx -V': " .. stderr)
end
return tonumber(a .. b .. c .. d)
end
--- Unindent a multi-line string for proper indenting in
-- square brackets.
-- @function unindent
-- @usage
-- local u = helpers.unindent
--
-- u[[
-- hello world
-- foo bar
-- ]]
--
-- -- will return: "hello world\nfoo bar"
local function unindent(str, concat_newlines, spaced_newlines)
str = string.match(str, "(.-%S*)%s*$")
if not str then
return ""
end
local level = math.huge
local prefix = ""
local len
str = str:match("^%s") and "\n" .. str or str
for pref in str:gmatch("\n(%s+)") do
len = #prefix
if len < level then
level = len
prefix = pref
end
end
local repl = concat_newlines and "" or "\n"
repl = spaced_newlines and " " or repl
return (str:gsub("^\n%s*", ""):gsub("\n" .. prefix, repl):gsub("\n$", ""):gsub("\\r", "\r"))
end
--- Set an environment variable
-- @function setenv
-- @param env (string) name of the environment variable
-- @param value the value to set
-- @return true on success, false otherwise
local function setenv(env, value)
return ffi.C.setenv(env, value, 1) == 0
end
--- Unset an environment variable
-- @function setenv
-- @param env (string) name of the environment variable
-- @return true on success, false otherwise
local function unsetenv(env)
return ffi.C.unsetenv(env) == 0
end
--- Write a yaml file.
-- @function make_yaml_file
-- @param content (string) the yaml string to write to the file, if omitted the
-- current database contents will be written using `kong config db_export`.
-- @param filename (optional) if not provided, a temp name will be created
-- @return filename of the file written
local function make_yaml_file(content, filename)
local filename = filename or pl_path.tmpname() .. ".yml"
if content then
local fd = assert(io.open(filename, "w"))
assert(fd:write(unindent(content)))
assert(fd:write("\n")) -- ensure last line ends in newline
assert(fd:close())
else
assert(kong_exec("config db_export "..filename))
end
return filename
end
---------------
-- Conf and DAO
---------------
local conf = assert(conf_loader(TEST_CONF_PATH))
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK
kong_global.set_phase(kong, kong_global.phases.access)
_G.kong.core_cache = {
get = function(self, key)
if key == constants.CLUSTER_ID_PARAM_KEY then
return "123e4567-e89b-12d3-a456-426655440000"
end
end
}
local db = assert(DB.new(conf))
assert(db:init_connector())
db.plugins:load_plugin_schemas(conf.loaded_plugins)
local blueprints = assert(Blueprints.new(db))
local dcbp
local config_yml
--- Iterator over DB strategies.
-- @function each_strategy
-- @param strategies (optional string array) explicit list of strategies to use,
-- defaults to `{ "postgres", "cassandra" }`.
-- @see all_strategies
-- @usage
-- -- repeat all tests for each strategy
-- for _, strategy_name in helpers.each_strategy() do
-- describe("my test set [#" .. strategy .. "]", function()
--
-- -- add your tests here
--
-- end)
-- end
local function each_strategy() -- luacheck: ignore -- required to trick ldoc into processing for docs
end
--- Iterator over all strategies, the DB ones and the DB-less one.
-- To test with DB-less, check the example.
-- @function all_strategies
-- @param strategies (optional string array) explicit list of strategies to use,
-- defaults to `{ "postgres", "cassandra", "off" }`.
-- @see each_strategy
-- @see make_yaml_file
-- @usage
-- -- example of using DB-less testing
--
-- -- use "all_strategies" to iterate over; "postgres", "cassandra", "off"
-- for _, strategy in helpers.all_strategies() do
-- describe(PLUGIN_NAME .. ": (access) [#" .. strategy .. "]", function()
--
-- lazy_setup(function()
--
-- -- when calling "get_db_utils" with "strategy=off", we still use
-- -- "postgres" so we can write the test setup to the database.
-- local bp = helpers.get_db_utils(
-- strategy == "off" and "postgres" or strategy,
-- nil, { PLUGIN_NAME })
--
-- -- Inject a test route, when "strategy=off" it will still be written
-- -- to Postgres.
-- local route1 = bp.routes:insert({
-- hosts = { "test1.com" },
-- })
--
-- -- start kong
-- assert(helpers.start_kong({
-- -- set the strategy
-- database = strategy,
-- nginx_conf = "spec/fixtures/custom_nginx.template",
-- plugins = "bundled," .. PLUGIN_NAME,
--
-- -- The call to "make_yaml_file" will write the contents of
-- -- the database to a temporary file, which filename is returned.
-- -- But only when "strategy=off".
-- declarative_config = strategy == "off" and helpers.make_yaml_file() or nil,
--
-- -- the below lines can be omitted, but are just to prove that the test
-- -- really runs DB-less despite that Postgres was used as intermediary
-- -- storage.
-- pg_host = strategy == "off" and "unknownhost.konghq.com" or nil,
-- cassandra_contact_points = strategy == "off" and "unknownhost.konghq.com" or nil,
-- }))
-- end)
--
-- ... rest of your test file
local function all_strategies() -- luacheck: ignore -- required to trick ldoc into processing for docs
end
do
local def_db_strategies = {"postgres", "cassandra"}
local def_all_strategies = {"postgres", "cassandra", "off"}
local env_var = os.getenv("KONG_DATABASE")
if env_var then
def_db_strategies = { env_var }
def_all_strategies = { env_var }
end
local db_available_strategies = pl_Set(def_db_strategies)
local all_available_strategies = pl_Set(def_all_strategies)
local function iter(strategies, i)
i = i + 1
local strategy = strategies[i]
if strategy then
return i, strategy
end
end
each_strategy = function(strategies)
if not strategies then
return iter, def_db_strategies, 0
end
for i = #strategies, 1, -1 do
if not db_available_strategies[strategies[i]] then
table.remove(strategies, i)
end
end
return iter, strategies, 0
end
all_strategies = function(strategies)
if not strategies then
return iter, def_all_strategies, 0
end
for i = #strategies, 1, -1 do
if not all_available_strategies[strategies[i]] then
table.remove(strategies, i)
end
end
return iter, strategies, 0
end
end
local function truncate_tables(db, tables)
if not tables then
return
end
for _, t in ipairs(tables) do
if db[t] and db[t].schema and not db[t].schema.legacy then
db[t]:truncate()
end
end
end
local function bootstrap_database(db)
local schema_state = assert(db:schema_state())
if schema_state.needs_bootstrap then
assert(db:schema_bootstrap())
end
if schema_state.new_migrations then
assert(db:run_migrations(schema_state.new_migrations, {
run_up = true,
run_teardown = true,
}))
end
end
--- Gets the database utility helpers and prepares the database for a testrun.
-- This will a.o. bootstrap the datastore and truncate the existing data that
-- migth be in it. The BluePrint returned can be used to create test entities
-- in the database.
-- @function get_db_utils
-- @param strategy (optional) the database strategy to use, will default to the
-- strategy in the test configuration.
-- @param tables (optional) tables to truncate, this can be used to accelarate
-- tests if only a few tables are used. By default all tables will be truncated.
-- @param plugins (optional) array of plugins to mark as loaded. Since kong will load all the bundled plugins by default, this is useful for mostly for marking custom plugins as loaded.
-- @return BluePrint, DB
-- @usage
-- local PLUGIN_NAME = "my_fancy_plugin"
-- local bp = helpers.get_db_utils("postgres", nil, { PLUGIN_NAME })
--
-- -- Inject a test route. No need to create a service, there is a default
-- -- service which will echo the request.
-- local route1 = bp.routes:insert({
-- hosts = { "test1.com" },
-- })
-- -- add the plugin to test to the route we created
-- bp.plugins:insert {
-- name = PLUGIN_NAME,
-- route = { id = route1.id },
-- config = {},
-- }
local function get_db_utils(strategy, tables, plugins)
strategy = strategy or conf.database
if tables ~= nil and type(tables) ~= "table" then
error("arg #2 must be a list of tables to truncate", 2)
end
if plugins ~= nil and type(plugins) ~= "table" then
error("arg #3 must be a list of plugins to enable", 2)
end
if plugins then
for _, plugin in ipairs(plugins) do
conf.loaded_plugins[plugin] = true
end
end
-- Clean workspaces from the context - otherwise, migrations will fail,
-- as some of them have dao calls
-- If `no_truncate` is falsey, `dao:truncate` and `db:truncate` are called,
-- and these set the workspace back again to the new `default` workspace
ngx.ctx.workspace = nil
-- DAO (DB module)
local db = assert(DB.new(conf, strategy))
assert(db:init_connector())
bootstrap_database(db)
do
local database = conf.database
conf.database = strategy
conf.database = database
end
db:truncate("plugins")
assert(db.plugins:load_plugin_schemas(conf.loaded_plugins))
-- cleanup the tags table, since it will be hacky and
-- not necessary to implement "truncate trigger" in Cassandra
db:truncate("tags")
_G.kong.db = db
-- cleanup tables
if not tables then
assert(db:truncate())
else
tables[#tables + 1] = "workspaces"
truncate_tables(db, tables)
end
-- blueprints
local bp
if strategy ~= "off" then
bp = assert(Blueprints.new(db))
dcbp = nil
else
bp = assert(dc_blueprints.new(db))
dcbp = bp
end
if plugins then
for _, plugin in ipairs(plugins) do
conf.loaded_plugins[plugin] = false
end
end
if strategy ~= "off" then
local workspaces = require "kong.workspaces"
workspaces.upsert_default(db)
end
-- calculation can only happen here because this function
-- initializes the kong.db instance
PLUGINS_LIST = assert(kong.db.plugins:get_handlers())
table.sort(PLUGINS_LIST, function(a, b)
return a.name:lower() < b.name:lower()
end)
PLUGINS_LIST = pl_tablex.map(function(p)
return { name = p.name, version = p.handler.VERSION, }
end, PLUGINS_LIST)
return bp, db
end
--- Gets the ml_cache instance.
-- @function get_cache
-- @param db the database object
-- @return ml_cache instance
local function get_cache(db)
local worker_events = assert(kong_global.init_worker_events())
local cluster_events = assert(kong_global.init_cluster_events(conf, db))
local cache = assert(kong_global.init_cache(conf,
cluster_events,
worker_events
))
return cache
end
-----------------
-- Custom helpers
-----------------
local resty_http_proxy_mt = {}
local pack = function(...) return { n = select("#", ...), ... } end
local unpack = function(t) return unpack(t, 1, t.n) end
--- Prints all returned parameters.
-- Simple debugging aid, it will pass all received parameters, hence will not
-- influence the flow of the code. See also `fail`.
-- @function intercept
-- @see fail
-- @usage -- modify
-- local a,b = some_func(c,d)
-- -- into
-- local a,b = intercept(some_func(c,d))
local function intercept(...)
local args = pack(...)
print(require("pl.pretty").write(args))
return unpack(args)
end
-- Prepopulate Schema's cache
Schema.new(consumers_schema_def)
Schema.new(services_schema_def)
Schema.new(routes_schema_def)
local plugins_schema = assert(Entity.new(plugins_schema_def))
--- Validate a plugin configuration against a plugin schema.
-- @function validate_plugin_config_schema
-- @param config The configuration to validate. This is not the full schema,
-- only the `config` sub-object needs to be passed.
-- @param schema_def The schema definition
-- @return the validated schema, or nil+error
local function validate_plugin_config_schema(config, schema_def)
assert(plugins_schema:new_subschema(schema_def.name, schema_def))
local entity = {
id = utils.uuid(),
name = schema_def.name,
config = config
}
local entity_to_insert, err = plugins_schema:process_auto_fields(entity, "insert")
if err then
return nil, err
end
local _, err = plugins_schema:validate_insert(entity_to_insert)
if err then return
nil, err
end
return entity_to_insert
end
-- Case insensitive lookup function, returns the value and the original key. Or
-- if not found nil and the search key
-- @usage -- sample usage
-- local test = { SoMeKeY = 10 }
-- print(lookup(test, "somekey")) --> 10, "SoMeKeY"
-- print(lookup(test, "NotFound")) --> nil, "NotFound"
local function lookup(t, k)
local ok = k
if type(k) ~= "string" then
return t[k], k
else
k = k:lower()
end
for key, value in pairs(t) do
if tostring(key):lower() == k then
return value, key
end
end
return nil, ok
end
--- Waits until a specific condition is met.
-- The check function will repeatedly be called (with a fixed interval), until
-- the condition is met, or the
-- timeout value is exceeded.
-- @function wait_until
-- @param f check function that should return `truthy` when the condition has
-- been met
-- @param timeout (optional) maximum time to wait after which an error is
-- thrown, defaults to 5.
-- @return nothing. It returns when the condition is met, or throws an error
-- when it times out.
-- @usage -- wait 10 seconds for a file "myfilename" to appear
-- helpers.wait_until(function() return file_exist("myfilename") end, 10)
local function wait_until(f, timeout, step)
if type(f) ~= "function" then
error("arg #1 must be a function", 2)
end
if timeout ~= nil and type(timeout) ~= "number" then
error("arg #2 must be a number", 2)
end
if step ~= nil and type(step) ~= "number" then
error("arg #3 must be a number", 2)
end
ngx.update_time()
timeout = timeout or 5
step = step or 0.05
local tstart = ngx.time()
local texp = tstart + timeout
local ok, res, err
repeat
ok, res, err = pcall(f)
ngx.sleep(step)
ngx.update_time()
until not ok or res or ngx.time() >= texp
if not ok then
-- report error from `f`, such as assert gone wrong
error(tostring(res), 2)
elseif not res and err then
-- report a failure for `f` to meet its condition
-- and eventually an error return value which could be the cause
error("wait_until() timeout: " .. tostring(err) .. " (after delay: " .. timeout .. "s)", 2)
elseif not res then
-- report a failure for `f` to meet its condition
error("wait_until() timeout (after delay " .. timeout .. "s)", 2)
end
end
local admin_client -- forward declaration
--- Waits for invalidation of a cached key by polling the mgt-api
-- and waiting for a 404 response.
-- @function wait_for_invalidation
-- @param key (string) the cache-key to check
-- @param timeout (optional) in seconds (for default see `wait_until`).
local function wait_for_invalidation(key, timeout)
-- TODO: this code is not used, but is duplicated all over the codebase!
-- search codebase for "/cache/" endpoint
local api_client = admin_client()
wait_until(function()
local res = api_client:get("/cache/" .. key)
res:read_body()
return res.status == 404
end, timeout)
end
--- http_client.
-- An http-client class to perform requests.
--
-- * Based on [lua-resty-http](https://github.com/pintsized/lua-resty-http) but
-- with some modifications
--
-- * Additional convenience methods will be injected for the following methods;
-- "get", "post", "put", "patch", "delete". Each of these methods comes with a
-- built-in assert. The signature of the functions is `client:get(path, opts)`.
--
-- * Body will be formatted according to the "Content-Type" header, see `http_client:send`.
--
-- * Query parameters will be added, see `http_client:send`.
--
-- @section http_client
-- @usage
-- -- example usage of the client
-- local client = helpers.get_proxy_client()
-- -- no need to check for `nil+err` since it is already wrapped in an assert
--
-- local opts = {
-- headers = {
-- ["My-Header"] = "my header value"
-- }
-- }
-- local result = client:get("/services/foo", opts)
-- -- the 'get' is wrapped in an assert, so again no need to check for `nil+err`
--- Send a http request.
-- Based on [lua-resty-http](https://github.com/pintsized/lua-resty-http).
--
-- * If `opts.body` is a table and "Content-Type" header contains
-- `application/json`, `www-form-urlencoded`, or `multipart/form-data`, then it
-- will automatically encode the body according to the content type.
--
-- * If `opts.query` is a table, a query string will be constructed from it and
-- appended to the request path (assuming none is already present).
--
-- * instead of this generic function there are also shortcut functions available
-- for every method, eg. `client:get`, `client:post`, etc. See `http_client`.
--
-- @function http_client:send
-- @param opts table with options. See [lua-resty-http](https://github.com/pintsized/lua-resty-http)
function resty_http_proxy_mt:send(opts)
local cjson = require "cjson"
local utils = require "kong.tools.utils"
opts = opts or {}
-- build body
local headers = opts.headers or {}
local content_type, content_type_name = lookup(headers, "Content-Type")
content_type = content_type or ""
local t_body_table = type(opts.body) == "table"
if string.find(content_type, "application/json") and t_body_table then
opts.body = cjson.encode(opts.body)
elseif string.find(content_type, "www-form-urlencoded", nil, true) and t_body_table then
opts.body = utils.encode_args(opts.body, true, opts.no_array_indexes)
elseif string.find(content_type, "multipart/form-data", nil, true) and t_body_table then
local form = opts.body
local boundary = "8fd84e9444e3946c"
local body = ""
for k, v in pairs(form) do
body = body .. "--" .. boundary .. "\r\nContent-Disposition: form-data; name=\"" .. k .. "\"\r\n\r\n" .. tostring(v) .. "\r\n"
end
if body ~= "" then
body = body .. "--" .. boundary .. "--\r\n"
end
local clength = lookup(headers, "content-length")
if not clength and not opts.dont_add_content_length then
headers["content-length"] = #body
end
if not content_type:find("boundary=") then
headers[content_type_name] = content_type .. "; boundary=" .. boundary
end
opts.body = body
end
-- build querystring (assumes none is currently in 'opts.path')
if type(opts.query) == "table" then
local qs = utils.encode_args(opts.query)
opts.path = opts.path .. "?" .. qs
opts.query = nil
end
local res, err = self:request(opts)
if res then
-- wrap the read_body() so it caches the result and can be called multiple
-- times
local reader = res.read_body
res.read_body = function(self)
if not self._cached_body and not self._cached_error then
self._cached_body, self._cached_error = reader(self)
end
return self._cached_body, self._cached_error
end
end
return res, err
end
-- Implements http_client:get("path", [options]), as well as post, put, etc.
-- These methods are equivalent to calling http_client:send, but are shorter
-- They also come with a built-in assert
for _, method_name in ipairs({"get", "post", "put", "patch", "delete"}) do
resty_http_proxy_mt[method_name] = function(self, path, options)
local full_options = kong.table.merge({ method = method_name:upper(), path = path}, options)
return assert(self:send(full_options))
end
end
function resty_http_proxy_mt:__index(k)
local f = rawget(resty_http_proxy_mt, k)
if f then
return f
end
return self.client[k]
end
--- Creates a http client.
-- Instead of using this client, you'll probably want to use the pre-configured
-- clients available as `proxy_client`, `admin_client`, etc. because these come
-- pre-configured and connected to the underlying Kong test instance.
--
-- @function http_client
-- @param host hostname to connect to
-- @param port port to connect to
-- @param timeout in seconds
-- @return http client
-- @see http_client:send
-- @see proxy_client
-- @see proxy_ssl_client
-- @see admin_client
-- @see admin_ssl_client
local function http_client(host, port, timeout)
timeout = timeout or 10000
local client = assert(http.new())
local _, err = client:connect(host, port)
if err then
error("Could not connect to " .. host .. ":" .. port .. ": " .. err)
end
client:set_timeout(timeout)
return setmetatable({
client = client
}, resty_http_proxy_mt)
end
--- Returns the proxy port.
-- @function get_proxy_port
-- @param ssl (boolean) if `true` returns the ssl port
-- @param http2 (boolean) if `true` returns the http2 port
local function get_proxy_port(ssl, http2)
if ssl == nil then ssl = false end
for _, entry in ipairs(conf.proxy_listeners) do
if entry.ssl == ssl and (http2 == nil or entry.http2 == http2) then
return entry.port
end
end
error("No proxy port found for ssl=" .. tostring(ssl), 2)
end
--- Returns the proxy ip.
-- @function get_proxy_ip
-- @param ssl (boolean) if `true` returns the ssl ip address
-- @param http2 (boolean) if `true` returns the http2 ip address
local function get_proxy_ip(ssl, http2)
if ssl == nil then ssl = false end
for _, entry in ipairs(conf.proxy_listeners) do
if entry.ssl == ssl and (http2 == nil or entry.http2 == http2) then
return entry.ip
end
end
error("No proxy ip found for ssl=" .. tostring(ssl), 2)
end
--- returns a pre-configured `http_client` for the Kong proxy port.
-- @function proxy_client
-- @param timeout (optional, number) the timeout to use
local function proxy_client(timeout)
local proxy_ip = get_proxy_ip(false)
local proxy_port = get_proxy_port(false)
assert(proxy_ip, "No http-proxy found in the configuration")
return http_client(proxy_ip, proxy_port, timeout or 60000)
end
--- returns a pre-configured `http_client` for the Kong SSL proxy port.
-- @function proxy_ssl_client
-- @param timeout (optional, number) the timeout to use
-- @param sni (optional, string) the sni to use
local function proxy_ssl_client(timeout, sni)
local proxy_ip = get_proxy_ip(true, true)
local proxy_port = get_proxy_port(true, true)
assert(proxy_ip, "No https-proxy found in the configuration")
local client = http_client(proxy_ip, proxy_port, timeout or 60000)
assert(client:ssl_handshake(nil, sni, false)) -- explicit no-verify
return client
end
--- returns a pre-configured `http_client` for the Kong admin port.
-- @function admin_client
-- @param timeout (optional, number) the timeout to use
-- @param forced_port (optional, number) if provided will override the port in
-- the Kong configuration with this port
function admin_client(timeout, forced_port)
local admin_ip, admin_port
for _, entry in ipairs(conf.admin_listeners) do
if entry.ssl == false then
admin_ip = entry.ip
admin_port = entry.port
end
end
assert(admin_ip, "No http-admin found in the configuration")
return http_client(admin_ip, forced_port or admin_port, timeout or 60000)
end
--- returns a pre-configured `http_client` for the Kong admin SSL port.
-- @function admin_ssl_client
-- @param timeout (optional, number) the timeout to use
local function admin_ssl_client(timeout)
local admin_ip, admin_port
for _, entry in ipairs(conf.proxy_listeners) do
if entry.ssl == true then
admin_ip = entry.ip
admin_port = entry.port
end
end
assert(admin_ip, "No https-admin found in the configuration")
local client = http_client(admin_ip, admin_port, timeout or 60000)
assert(client:ssl_handshake())
return client
end
----------------
-- HTTP2 and GRPC clients
-- @section Shell-helpers
-- Generate grpcurl flags from a table of `flag-value`. If `value` is not a
-- string, value is ignored and `flag` is passed as is.
local function gen_grpcurl_opts(opts_t)
local opts_l = {}
for opt, val in pairs(opts_t) do
if val ~= false then
opts_l[#opts_l + 1] = opt .. " " .. (type(val) == "string" and val or "")
end
end
return table.concat(opts_l, " ")
end
--- Creates an HTTP/2 client, based on the lua-http library.
-- @function http2_client
-- @param host hostname to connect to
-- @param port port to connect to
-- @param tls boolean indicating whether to establish a tls session
-- @return http2 client
local function http2_client(host, port, tls)
local host = assert(host)
local port = assert(port)
tls = tls or false
-- if Kong/lua-pack is loaded, unload it first
-- so lua-http can use implementation from compat53.string
package.loaded.string.unpack = nil
package.loaded.string.pack = nil
local request = require "http.request"
local req = request.new_from_uri({
scheme = tls and "https" or "http",
host = host,
port = port,
})
req.version = 2
req.tls = tls
if tls then
local http_tls = require "http.tls"
local openssl_ctx = require "openssl.ssl.context"
local n_ctx = http_tls.new_client_context()
n_ctx:setVerify(openssl_ctx.VERIFY_NONE)
req.ctx = n_ctx
end
local meta = getmetatable(req) or {}
meta.__call = function(req, opts)
local headers = opts and opts.headers
local timeout = opts and opts.timeout
for k, v in pairs(headers or {}) do
req.headers:upsert(k, v)
end
local headers, stream = req:go(timeout)
local body = stream:get_body_as_string()
return body, headers
end
return setmetatable(req, meta)
end
--- returns a pre-configured cleartext `http2_client` for the Kong proxy port.
-- @function proxy_client_h2c
-- @return http2 client
local function proxy_client_h2c()
local proxy_ip = get_proxy_ip(false, true)
local proxy_port = get_proxy_port(false, true)
assert(proxy_ip, "No http-proxy found in the configuration")
return http2_client(proxy_ip, proxy_port)
end
--- returns a pre-configured TLS `http2_client` for the Kong SSL proxy port.
-- @function proxy_client_h2
-- @return http2 client
local function proxy_client_h2()
local proxy_ip = get_proxy_ip(true, true)
local proxy_port = get_proxy_port(true, true)
assert(proxy_ip, "No https-proxy found in the configuration")
return http2_client(proxy_ip, proxy_port, true)
end
local exec -- forward declaration
--- Creates a gRPC client, based on the grpcurl CLI.
-- @function grpc_client
-- @param host hostname to connect to
-- @param port port to connect to
-- @param opts table with options supported by grpcurl
-- @return grpc client
local function grpc_client(host, port, opts)
local host = assert(host)
local port = assert(tostring(port))
opts = opts or {}
if not opts["-proto"] then
opts["-proto"] = MOCK_GRPC_UPSTREAM_PROTO_PATH
end
return setmetatable({
opts = opts,
cmd_template = string.format("bin/grpcurl %%s %s:%s %%s", host, port)
}, {
__call = function(t, args)
local service = assert(args.service)
local body = args.body
local t_body = type(body)
if t_body ~= "nil" then
if t_body == "table" then
body = cjson.encode(body)
end
args.opts["-d"] = string.format("'%s'", body)
end
local opts = gen_grpcurl_opts(pl_tablex.merge(t.opts, args.opts, true))
local ok, _, out, err = exec(string.format(t.cmd_template, opts, service), true)
if ok then
return ok, ("%s%s"):format(out or "", err or "")
else
return nil, ("%s%s"):format(out or "", err or "")
end
end