-
Notifications
You must be signed in to change notification settings - Fork 72
/
test_lib_stormtypes.py
3873 lines (2993 loc) · 156 KB
/
test_lib_stormtypes.py
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
import bz2
import gzip
import json
import base64
import asyncio
import hashlib
import binascii
import datetime
import contextlib
from datetime import timezone as tz
from unittest import mock
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.modelrev as s_modelrev
import synapse.lib.provenance as s_provenance
import synapse.lib.stormtypes as s_stormtypes
import synapse.tests.utils as s_test
from synapse.tests.utils import alist
MINSECS = 60
HOURSECS = 60 * MINSECS
DAYSECS = 24 * HOURSECS
class Newp:
def __bool__(self):
raise s_exc.SynErr(mesg='newp')
def __int__(self):
raise s_exc.SynErr(mesg='newp')
def __str__(self):
raise s_exc.SynErr(mesg='newp')
def __repr__(self):
return 'Newp'
class StormTypesTest(s_test.SynTest):
async def test_stormtypes_gates(self):
async with self.getTestCore() as core:
viewiden = await core.callStorm('return($lib.view.get().iden)')
gate = await core.callStorm('return($lib.auth.gates.get($lib.view.get().iden))')
self.eq(gate.get('iden'), viewiden)
# default view should only have root user as admin and all as read
self.eq(gate['users'][0], {
'iden': core.auth.rootuser.iden,
'admin': True,
'rules': (),
})
self.eq(gate['roles'][0], {
'iden': core.auth.allrole.iden,
'admin': False,
'rules': (
(True, ('view', 'read')),
),
})
gates = await core.callStorm('return($lib.auth.gates.list())')
self.isin(viewiden, [g['iden'] for g in gates])
async def test_storm_node_tags(self):
async with self.getTestCore() as core:
await core.nodes('[ test:comp=(20, haha) +#foo +#bar test:comp=(30, hoho) ]')
q = '''
test:comp
for $tag in $node.tags() {
-> test:int [ +#$tag ]
}
'''
await core.nodes(q)
self.len(1, await core.nodes('test:int#foo'))
self.len(1, await core.nodes('test:int#bar'))
q = '''
test:comp
for $tag in $node.tags(fo*) {
-> test:int [ -#$tag ]
}
'''
await core.nodes(q)
self.len(0, await core.nodes('test:int#foo'))
self.len(1, await core.nodes('test:int#bar'))
async def test_node_globtags(self):
def check_fire_mesgs(storm_mesgs, expected_data):
tmesgs = [m[1] for m in storm_mesgs if m[0] == 'storm:fire']
self.len(1, tmesgs)
test_data = set(tmesgs[0].get('data', {}).get('globs'))
self.eq(test_data, expected_data)
async with self.getTestCore() as core:
q = '''[test:str=woot
+#foo.bar.baz.faz
+#foo.bar.jaz.faz
+#foo.knight.day.faz]'''
nodes = await core.nodes(q)
self.len(1, nodes)
# explicit behavior tests
q = 'test:str=woot $globs=$node.globtags("foo.*.*.faz") $lib.fire(test, globs=$globs) -test:str'
mesgs = await core.stormlist(q)
e = {('bar', 'baz'), ('bar', 'jaz'), ('knight', 'day')}
check_fire_mesgs(mesgs, e)
q = 'test:str=woot $globs=$node.globtags("foo.bar.*") $lib.fire(test, globs=$globs) -test:str'
mesgs = await core.stormlist(q)
e = {'baz', 'jaz'}
check_fire_mesgs(mesgs, e)
q = 'test:str=woot $globs=$node.globtags("foo.bar.*.*") $lib.fire(test, globs=$globs) -test:str'
mesgs = await core.stormlist(q)
e = {('baz', 'faz'), ('jaz', 'faz')}
check_fire_mesgs(mesgs, e)
q = 'test:str=woot $globs=$node.globtags("foo.bar.**") $lib.fire(test, globs=$globs) -test:str'
mesgs = await core.stormlist(q)
e = {'baz', 'baz.faz', 'jaz', 'jaz.faz'}
check_fire_mesgs(mesgs, e)
q = 'test:str=woot $globs=$node.globtags("foo.bar.*.*.*") $lib.fire(test, globs=$globs) -test:str'
mesgs = await core.stormlist(q)
e = set()
check_fire_mesgs(mesgs, e)
# For loop example for a single-match case
q = '''test:str=woot
for $part in $node.globtags("foo.bar.*") {
[test:str=$part]
}'''
mesgs = await core.stormlist(q)
self.len(1, await core.nodes('test:str=baz'))
self.len(1, await core.nodes('test:str=jaz'))
# For loop example for a multi-match case
q = '''test:str=woot
for ($part1, $part2, $part3) in $node.globtags("foo.*.*.*") {
[test:str=$part1] -test:str=woot [+#$part3]
}'''
mesgs = await core.stormlist(q)
self.len(1, await core.nodes('test:str=bar'))
self.len(1, await core.nodes('test:str=knight'))
self.len(2, await core.nodes('#faz'))
async def test_storm_lib_base(self):
pdef = {
'name': 'foo',
'desc': 'test',
'version': (0, 0, 1),
'synapse_minversion': (2, 8, 0),
'modules': [
{
'name': 'test',
'storm': 'function f(a) { return ($a) }',
}
],
'commands': [
],
}
async with self.getTestCore() as core:
with self.raises(s_exc.NoSuchType):
await core.nodes('$lib.cast(newp, asdf)')
with self.raises(s_exc.NoSuchType):
await core.nodes('$lib.trycast(newp, asdf)')
self.true(await core.callStorm('return($lib.trycast(inet:ipv4, 1.2.3.4).0)'))
self.false(await core.callStorm('return($lib.trycast(inet:ipv4, asdf).0)'))
self.eq(None, await core.callStorm('return($lib.trycast(inet:ipv4, asdf).1)'))
self.eq(0x01020304, await core.callStorm('return($lib.trycast(inet:ipv4, 1.2.3.4).1)'))
self.true(await core.callStorm('$x=(foo,bar) return($x.has(foo))'))
self.false(await core.callStorm('$x=(foo,bar) return($x.has(newp))'))
self.false(await core.callStorm('$x=(foo,bar) return($x.has((foo,bar)))'))
await core.addStormPkg(pdef)
nodes = await core.nodes('[ inet:asn=$lib.min(20, 0x30) ]')
self.len(1, nodes)
self.eq(20, nodes[0].ndef[1])
nodes = await core.nodes('[ inet:asn=$lib.min(20, (10, 30)) ]')
self.len(1, nodes)
self.eq(10, nodes[0].ndef[1])
nodes = await core.nodes('[ inet:asn=$lib.max(20, 0x30) ]')
self.len(1, nodes)
self.eq(0x30, nodes[0].ndef[1])
nodes = await core.nodes('[ inet:asn=$lib.max(20, (10, 30)) ]')
self.len(1, nodes)
self.eq(30, nodes[0].ndef[1])
nodes = await core.nodes('[ inet:asn=$lib.len(asdf) ]')
self.len(1, nodes)
self.eq(4, nodes[0].ndef[1])
nodes = await core.nodes('[ test:str=$lib.guid() test:str=$lib.guid() ]')
self.len(2, nodes)
self.true(s_common.isguid(nodes[0].ndef[1]))
self.true(s_common.isguid(nodes[1].ndef[1]))
self.ne(nodes[0].ndef[1], nodes[1].ndef[1])
nodes = await core.nodes('[ test:str=$lib.guid(hehe,haha) test:str=$lib.guid(hehe,haha) ]')
self.len(2, nodes)
self.true(s_common.isguid(nodes[0].ndef[1]))
self.true(s_common.isguid(nodes[1].ndef[1]))
self.eq(nodes[0].ndef[1], nodes[1].ndef[1])
async with core.getLocalProxy() as prox:
mesgs = [m async for m in prox.storm('$lib.print("hi there")') if m[0] == 'print']
self.len(1, mesgs)
self.stormIsInPrint('hi there', mesgs)
mesgs = [m async for m in prox.storm('[ inet:fqdn=vertex.link inet:fqdn=woot.com ] $lib.print(:zone)')]
mesgs = [m for m in mesgs if m[0] == 'print']
self.len(2, mesgs)
self.eq('vertex.link', mesgs[0][1]['mesg'])
self.eq('woot.com', mesgs[1][1]['mesg'])
mesgs = [m async for m in prox.storm("$lib.print('woot at: {s} {num}', s=hello, num=$(42+43))")]
self.stormIsInPrint('woot at: hello 85', mesgs)
# lib.sorted()
q = '''
$set = $lib.set(c, b, a)
for $x in $lib.sorted($set) {
[ test:str=$x ]
}
'''
nodes = await core.nodes(q)
self.len(3, nodes)
self.eq(nodes[0].ndef[1], 'a')
self.eq(nodes[1].ndef[1], 'b')
self.eq(nodes[2].ndef[1], 'c')
q = '''
$set = $lib.set(c, b, a)
for $x in $lib.sorted($set, reverse=$lib.true) {
[ test:str=$x ]
}
'''
nodes = await core.nodes(q)
self.len(3, nodes)
self.eq(nodes[0].ndef[1], 'c')
self.eq(nodes[1].ndef[1], 'b')
self.eq(nodes[2].ndef[1], 'a')
# $lib.import
q = '$test = $lib.import(test) $lib.print($test)'
msgs = await core.stormlist(q)
self.stormIsInPrint('stormtypes.Lib object', msgs)
q = '$test = $lib.import(newp)'
msgs = await core.stormlist(q)
erfo = [m for m in msgs if m[0] == 'err'][0]
self.eq(erfo[1][0], 'NoSuchName')
self.eq(erfo[1][1].get('name'), 'newp')
# lib.len()
opts = {
'vars': {
'true': True,
'list': [1, 2, 3],
'dict': {'k1': 'v1', 'k2': 'v2'},
'str': '1138',
'bytes': b'o'
}
}
self.eq(4, await core.callStorm('return($lib.len($str))', opts=opts))
self.eq(3, await core.callStorm('return($lib.len($list))', opts=opts))
self.eq(2, await core.callStorm('return($lib.len($dict))', opts=opts))
self.eq(1, await core.callStorm('return($lib.len($bytes))', opts=opts))
with self.raises(s_exc.StormRuntimeError) as cm:
await core.nodes('$lib.print($lib.len($true))', opts=opts)
self.eq(cm.exception.get('mesg'), 'Object builtins.bool does not have a length.')
mesgs = await core.stormlist('$lib.pprint(newp, clamp=2)')
errs = [m[1] for m in mesgs if m[0] == 'err']
self.len(1, errs)
err = errs[0]
self.eq(err[0], 'StormRuntimeError')
self.isin('Invalid clamp length.', err[1].get('mesg'))
# lib.range()
q = 'for $v in $lib.range($stop, start=$start, step=$step) { $lib.fire(range, v=$v) }'
async def getseqn(genr, name, key):
seqn = []
async for mtyp, info in genr:
if mtyp != 'storm:fire':
continue
self.eq(info.get('type'), name)
seqn.append(info.get('data', {}).get(key))
return seqn
opts = {'vars': {'stop': 3, 'start': None, 'step': None}}
items = await getseqn(core.storm(q, opts), 'range', 'v')
self.eq(items, [0, 1, 2])
opts = {'vars': {'stop': 3, 'start': 1, 'step': None}}
items = await getseqn(core.storm(q, opts), 'range', 'v')
self.eq(items, [1, 2])
opts = {'vars': {'stop': 5, 'start': 0, 'step': 2}}
items = await getseqn(core.storm(q, opts), 'range', 'v')
self.eq(items, [0, 2, 4])
opts = {'vars': {'stop': 0, 'start': 4, 'step': None}}
items = await getseqn(core.storm(q, opts), 'range', 'v')
self.eq(items, [])
opts = {'vars': {'stop': 0, 'start': 4, 'step': -1}}
items = await getseqn(core.storm(q, opts), 'range', 'v')
self.eq(items, [4, 3, 2, 1])
async def test_storm_lib_ps(self):
async with self.getTestCore() as core:
evnt = asyncio.Event()
iden = None
async def runLongStorm():
q = f'[ test:str=foo test:str={"x"*100} ] | sleep 10 | [ test:str=endofquery ]'
async for mesg in core.storm(q):
nonlocal iden
if mesg[0] == 'init':
iden = mesg[1]['task']
evnt.set()
task = core.schedCoro(runLongStorm())
self.true(await asyncio.wait_for(evnt.wait(), timeout=6))
# Verify that the long query got truncated
msgs = await core.stormlist('ps.list')
for msg in msgs:
if msg[0] == 'print' and 'xxx...' in msg[1]['mesg']:
self.eq(120, len(msg[1]['mesg']))
self.stormIsInPrint('xxx...', msgs)
self.stormIsInPrint('name: storm', msgs)
self.stormIsInPrint('user: root', msgs)
self.stormIsInPrint('status: None', msgs)
self.stormIsInPrint('2 tasks found.', msgs)
self.stormIsInPrint('start time: 2', msgs)
self.stormIsInPrint(f'task iden: {iden}', msgs)
# Verify we see the whole query
msgs = await core.stormlist('ps.list --verbose')
self.stormIsInPrint('endofquery', msgs)
msgs = await core.stormlist(f'ps.kill {iden}')
self.stormIsInPrint('kill status: True', msgs)
self.true(task.done())
msgs = await core.stormlist('ps.list')
self.stormIsInPrint('1 tasks found.', msgs)
bond = await core.auth.addUser('bond')
async with core.getLocalProxy(user='bond') as prox:
evnt = asyncio.Event()
iden = None
async def runLongStorm():
async for mesg in core.storm('[ test:str=foo test:str=bar ] | sleep 10'):
nonlocal iden
if mesg[0] == 'init':
iden = mesg[1]['task']
evnt.set()
task = core.schedCoro(runLongStorm())
self.true(await asyncio.wait_for(evnt.wait(), timeout=6))
msgs = await core.stormlist('ps.list')
self.stormIsInPrint('2 tasks found.', msgs)
self.stormIsInPrint(f'task iden: {iden}', msgs)
msgs = await alist(prox.storm('ps.list'))
self.stormIsInPrint('1 tasks found.', msgs)
# Try killing from the unprivileged user
msgs = await alist(prox.storm(f'ps.kill {iden}'))
self.stormIsInErr('Provided iden does not match any processes.', msgs)
# Try a kill with a numeric identifier - this won't match
msgs = await alist(prox.storm(f'ps.kill 123412341234'))
self.stormIsInErr('Provided iden does not match any processes.', msgs)
# Give user explicit permissions to list
await core.addUserRule(bond.iden, (True, ('task', 'get')))
# Match all tasks
msgs = await alist(prox.storm(f"ps.kill ''"))
self.stormIsInErr('Provided iden matches more than one process.', msgs)
msgs = await alist(prox.storm('ps.list'))
self.stormIsInPrint(f'task iden: {iden}', msgs)
# Give user explicit license to kill
await core.addUserRule(bond.iden, (True, ('task', 'del')))
# Kill the task as the user
msgs = await alist(prox.storm(f'ps.kill {iden}'))
self.stormIsInPrint('kill status: True', msgs)
self.true(task.done())
# Kill a task that doesn't exist
self.false(await core.kill(bond, 'newp'))
async def test_storm_lib_query(self):
async with self.getTestCore() as core:
# basic
q = '''
$foo = ${ [test:str=theevalthatmendo] }
$foo.exec()
'''
await core.nodes(q)
nodes = await core.nodes('test:str=theevalthatmendo')
self.len(1, nodes)
# exec vars do not populate upwards
q = '''
$foo = "that is one neato burrito"
$baz = ${ $bar=$lib.str.concat(wompwomp, $lib.guid()) $lib.print("in exec") }
$baz.exec()
$lib.print("post exec {bar}", bar=$bar)
[ test:str=$foo ]
'''
with self.raises(s_exc.NoSuchVar):
await core.nodes(q)
# make sure returns work
q = '''
$foo = $(10)
$bar = ${ return ( $($foo+1) ) }
[test:int=$bar.exec()]
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(nodes[0].ndef, ('test:int', 11))
# make sure it inherits the runt it's created in, not exec'd in
q = '''
$foo = ${$lib.print("look ma, my runt") $bing = $(0) }
function foofunc() {
$bing = $(99)
yield $foo.exec()
$lib.print("bing is now {bing}", bing=$bing)
return ($(0))
}
$foofunc()
'''
msgs = await core.stormlist(q)
self.stormIsInPrint('look ma, my runt', msgs)
self.stormIsInPrint('bing is now 99', msgs)
# vars may be captured for each node flowing through them
q = '''[(test:int=100 :loc=us.va) (test:int=200 :loc=us.ca)] $foo=:loc
$q = ${ $lib.print($foo) } $q.exec()'''
msgs = await core.stormlist(q)
self.stormIsInPrint('us.va', msgs)
self.stormIsInPrint('us.ca', msgs)
# Yield/iterator behavior
nodes = await core.nodes('''
function foo(x) {
return(${
[ inet:ipv4=$x ]
})
}
[it:dev:str=1.2.3.4]
$genr = $foo($node.repr())
-> { yield $genr }
''')
self.len(1, nodes)
self.eq(nodes[0].ndef, ('inet:ipv4', 0x01020304))
nodes = await core.nodes('''
function foo(x) {
return( ${ [ inet:ipv4=$x ] } )
}
[it:dev:str=5.5.5.5]
$genr = $foo($node.repr())
$genr.exec()
''')
self.len(1, await core.nodes('inet:ipv4=5.5.5.5'))
msgs = await core.stormlist('''
$embed = ${[inet:ipv4=1.2.3.4]}
for $xnode in $embed {
$lib.print($xnode.repr())
}
''')
self.stormIsInPrint('1.2.3.4', msgs)
q = '''[test:int=1 test:int=2]
$currentNode = $node
$q=${ [test:str=$currentNode.value()] }
yield $q
'''
nodes = await core.nodes(q)
self.len(4, nodes)
self.eq({n.ndef for n in nodes},
{('test:int', 1), ('test:int', 2), ('test:str', '1'), ('test:str', '2')})
# You can toprim() as Query object.
q = '''$q=${ $lib.print('fire in the hole') } $lib.fire('test', q=$q)
'''
msgs = await core.stormlist(q)
fires = [m for m in msgs if m[0] == 'storm:fire']
self.len(1, fires)
self.eq(fires[0][1].get('data').get('q'),
"$lib.print('fire in the hole')")
async def test_storm_lib_node(self):
async with self.getTestCore() as core:
nodes = await core.nodes('[ test:str=woot :tick=2001] [ test:int=$node.isform(test:str) ] +test:int')
self.eq(1, nodes[0].ndef[1])
q = 'test:str=woot $lib.fire(name=pode, pode=$node.pack(dorepr=True))'
msgs = await core.stormlist(q, opts={'repr': True})
pode = [m[1] for m in msgs if m[0] == 'node'][0]
apode = [m[1].get('data').get('pode') for m in msgs if m[0] == 'storm:fire'][0]
self.eq(pode[0], ('test:str', 'woot'))
pode[1].pop('path')
self.eq(pode, apode)
async def test_storm_lib_dict(self):
async with self.getTestCore() as core:
nodes = await core.nodes('$blah = $lib.dict(foo=vertex.link) [ inet:fqdn=$blah.foo ]')
self.len(1, nodes)
self.eq('vertex.link', nodes[0].ndef[1])
self.eq(2, await core.callStorm('$d=$lib.dict(k1=1, k2=2) return($lib.len($d))'))
async def test_storm_lib_str(self):
async with self.getTestCore() as core:
q = '$v=vertex $l=link $fqdn=$lib.str.concat($v, ".", $l)' \
' [ inet:email=$lib.str.format("visi@{domain}", domain=$fqdn) ]'
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq('visi@vertex.link', nodes[0].ndef[1])
nodes = await core.nodes('$s = woot [ test:int=$s.startswith(w) ]')
self.eq(1, nodes[0].ndef[1])
nodes = await core.nodes('$s = woot [ test:int=$s.endswith(visi) ]')
self.eq(0, nodes[0].ndef[1])
nodes = await core.nodes('$s = woot [ test:str=$s.rjust(10) ]')
self.eq(' woot', nodes[0].ndef[1])
nodes = await core.nodes('$s = woot [ test:str=$s.ljust(10) ]')
self.eq('woot ', nodes[0].ndef[1])
sobj = s_stormtypes.Str('beepbeep')
self.len(8, sobj)
nodes = await core.nodes('$s = (foo, bar, baz) [ test:str=$lib.str.join(".", $s) ]')
self.eq('foo.bar.baz', nodes[0].ndef[1])
nodes = await core.nodes('$s = foo-bar-baz [ test:str=$s.replace("-", ".") ]')
self.eq('foo.bar.baz', nodes[0].ndef[1])
nodes = await core.nodes('$s = foo-bar-baz [ test:str=$s.replace("-", ".", 1) ]')
self.eq('foo.bar-baz', nodes[0].ndef[1])
q = '$foo=" foo " return ( $foo.strip() )'
self.eq('foo', await core.callStorm(q))
q = '$foo=" foo " return ( $foo.lstrip() )'
self.eq('foo ', await core.callStorm(q))
q = '$foo=" foo " return ( $foo.rstrip() )'
self.eq(' foo', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.strip(quxk) )'
self.eq('ickbrownfo', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.lstrip(quxk) )'
self.eq('ickbrownfox', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.rstrip(quxk) )'
self.eq('quickbrownfo', await core.callStorm(q))
q = '$foo="QuickBrownFox" return ( $foo.lower() )'
self.eq('quickbrownfox', await core.callStorm(q))
q = '$foo="QuickBrownFox" return ( $foo.upper() )'
self.eq('QUICKBROWNFOX', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice(5) )'
self.eq('brownfox', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice(5, 10) )'
self.eq('brown', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice((-8)) )'
self.eq('brownfox', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice(0, (-3)) )'
self.eq('quickbrown', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice(55, 42) )'
self.eq('', await core.callStorm(q))
q = '$foo="quickbrownfox" return ( $foo.slice("newp") )'
await self.asyncraises(s_exc.BadCast, core.callStorm(q))
q = '$foo="foobar" return ( $foo.reverse() )'
self.eq('raboof', await core.callStorm(q))
# tuck the regx tests in with str
self.true(await core.callStorm(r'''return($lib.regex.matches('^foo', foobar))'''))
self.true(await core.callStorm(r'''return($lib.regex.matches('foo', FOOBAR, $lib.regex.flags.i))'''))
self.false(await core.callStorm(r'''return($lib.regex.matches('^foo$', foobar))'''))
self.false(await core.callStorm(f'return($lib.regex.matches(foo, " foobar"))'))
self.eq(('oo',), await core.callStorm(r'''return($lib.regex.search('([aeiou]+)', foobar))'''))
self.eq(('foo', 'baz'), await core.callStorm('return($lib.regex.search("(foo)bar(baz)", foobarbaz))'))
self.eq((), await core.callStorm('return($lib.regex.search(foo, foobar))'))
self.none(await core.callStorm('return($lib.regex.search(foo, bat))'))
async def test_storm_lib_bytes_gzip(self):
async with self.getTestCore() as core:
async with await core.snap() as snap:
hstr = 'ohhai'
ghstr = base64.urlsafe_b64encode((gzip.compress(hstr.encode()))).decode()
mstr = 'ohgood'
n2 = s_common.guid()
n3 = s_common.guid()
node1 = await snap.addNode('graph:node', '*', {'data': ghstr})
node2 = await snap.addNode('graph:node', '*', {'data': mstr})
text = f'''
graph:node={node1.ndef[1]}
$gzthing = :data
$foo = $lib.base64.decode($gzthing).gunzip()
$lib.print($foo)
[ graph:node={n2} :data=$foo.decode() ]
'''
await core.stormlist(text)
# make sure we gunzip correctly
opts = {'vars': {'iden': n2}}
nodes = await snap.nodes('graph:node=$iden', opts=opts)
self.len(1, nodes)
self.eq(hstr, nodes[0].get('data'))
# gzip
text = f'''
graph:node={node2.ndef[1]}
$bar = :data
[ graph:node={n3} :data=$lib.base64.encode($bar.encode().gzip()) ]
'''
await core.stormlist(text)
# make sure we gzip correctly
opts = {'vars': {'iden': n3}}
nodes = await snap.nodes('graph:node=$iden', opts=opts)
self.len(1, nodes)
self.eq(mstr.encode(), gzip.decompress(base64.urlsafe_b64decode(nodes[0].props['data'])))
async def test_storm_lib_bytes_bzip(self):
async with self.getTestCore() as core:
async with await core.snap() as snap:
hstr = 'ohhai'
ghstr = base64.urlsafe_b64encode((bz2.compress(hstr.encode()))).decode()
mstr = 'ohgood'
ggstr = base64.urlsafe_b64encode((bz2.compress(mstr.encode()))).decode()
n2 = s_common.guid()
n3 = s_common.guid()
node1 = await snap.addNode('graph:node', '*', {'data': ghstr})
node2 = await snap.addNode('graph:node', '*', {'data': mstr})
text = '''
graph:node={valu}
$bzthing = :data
$foo = $lib.base64.decode($bzthing).bunzip()
$lib.print($foo)
[ graph:node={n2} :data=$foo.decode() ]
'''
text = text.format(valu=node1.ndef[1], n2=n2)
await core.stormlist(text)
# make sure we bunzip correctly
opts = {'vars': {'iden': n2}}
nodes = await snap.nodes('graph:node=$iden', opts=opts)
self.len(1, nodes)
self.eq(hstr, nodes[0].props['data'])
# bzip
text = '''
graph:node={valu}
$bar = :data
[ graph:node={n3} :data=$lib.base64.encode($bar.encode().bzip()) ]
'''
text = text.format(valu=node2.ndef[1], n3=n3)
await core.stormlist(text)
# make sure we bzip correctly
opts = {'vars': {'iden': n3}}
nodes = await snap.nodes('graph:node=$iden', opts=opts)
self.len(1, nodes)
self.eq(ggstr, nodes[0].props['data'])
async def test_storm_lib_bytes_json(self):
async with self.getTestCore() as core:
async with await core.snap() as snap:
foo = {'a': 'ohhai'}
ghstr = json.dumps(foo)
n2 = s_common.guid()
node1 = await snap.addNode('graph:node', '*', {'data': ghstr})
text = '''
graph:node={valu}
$jzthing = :data
$foo = $jzthing.encode().json()
[ graph:node={n2} :data=$foo ]
'''
text = text.format(valu=node1.ndef[1], n2=n2)
await core.stormlist(text)
# make sure we json loaded correctly
opts = {'vars': {'iden': n2}}
nodes = await snap.nodes('graph:node=$iden', opts=opts)
self.len(1, nodes)
self.eq(foo, nodes[0].props['data'])
async def test_storm_lib_list(self):
async with self.getTestCore() as core:
# Base List object behavior
q = '''// $lib.list ctor
$list=$lib.list(1,2,3)
// __len__
$lib.print('List size is {len}', len=$lib.len($list))
// aiter/iter method
$sum = $(0)
for $valu in $list {
$sum = $( $sum + $valu)
}
$lib.print('Sum is {sum}', sum=$sum)
// Append method
$list.append(4)
// size method
$lib.print('List size is now {len}', len=$list.size())
// Access the values by index
$lib.print('List[0]={zero}, List[-1]={neg1}', zero=$list.index(0), neg1=$list.index(-1))
$sum = $(0)
for $valu in $list {
$sum = $( $sum + $valu)
}
$lib.print('Sum is now {sum}', sum=$sum)
// Empty lists may also be made
$elst=$lib.list()
$lib.print('elst size is {len}', len=$lib.len($elst))
'''
msgs = await core.stormlist(q)
self.stormIsInPrint('List size is 3', msgs)
self.stormIsInPrint('Sum is 6', msgs)
self.stormIsInPrint('List[0]=1, List[-1]=4', msgs)
self.stormIsInPrint('List size is now 4', msgs)
self.stormIsInPrint('Sum is now 10', msgs)
self.stormIsInPrint('elst size is 0', msgs)
# Convert primitive python objects to List objects
q = '$v=(foo,bar,baz) [ test:str=$v.index(1) test:int=$v.length() ]'
nodes = await core.nodes(q)
self.eq(nodes[0].ndef, ('test:str', 'bar'))
self.eq(nodes[1].ndef, ('test:int', 3))
# Python Tuples can be treated like a List object for accessing via data inside of.
q = '[ test:comp=(10,lol) ] $x=$node.ndef().index(1).index(1) [ test:str=$x ]'
nodes = await core.nodes(q)
self.eq(nodes[0].ndef, ('test:str', 'lol'))
# sad case - index out of bounds.
q = 'test:comp=(10,lol) $x=$node.ndef().index(2)'
mesgs = await core.stormlist(q)
errs = [m[1] for m in mesgs if m[0] == 'err']
self.len(1, errs)
self.eq(errs[0][0], 'StormRuntimeError')
self.eq('bar', await core.callStorm('$foo = (foo, bar) return($foo.1)'))
self.eq('foo', await core.callStorm('$foo = (foo, bar) return($foo."-2")'))
self.eq('bar', await core.callStorm('$foo = (foo, bar) return($foo.pop())'))
with self.raises(s_exc.StormRuntimeError):
await core.callStorm('$lib.list().pop()')
async def test_storm_lib_fire(self):
async with self.getTestCore() as core:
text = '$lib.fire(foo:bar, baz=faz)'
gotn = [mesg for mesg in await core.stormlist(text) if mesg[0] == 'storm:fire']
self.len(1, gotn)
self.eq(gotn[0][1]['type'], 'foo:bar')
self.eq(gotn[0][1]['data']['baz'], 'faz')
async def test_storm_node_repr(self):
text = '''
[ inet:ipv4=1.2.3.4 :loc=us]
$ipv4 = $node.repr()
$loc = $node.repr(loc)
$latlong = $node.repr(latlong, defv="??")
$valu = $lib.str.format("{ipv4} in {loc} at {latlong}", ipv4=$ipv4, loc=$loc, latlong=$latlong)
[ test:str=$valu ]
+test:str
'''
async with self.getTestCore() as core:
nodes = await core.nodes(text)
self.len(1, nodes)
self.eq(nodes[0].ndef[1], '1.2.3.4 in us at ??')
mesgs = await core.stormlist('inet:ipv4 $repr=$node.repr(newp)')
err = mesgs[-2][1]
self.eq(err[0], 'NoSuchProp')
self.eq(err[1].get('prop'), 'newp')
self.eq(err[1].get('form'), 'inet:ipv4')
async def test_storm_csv(self):
async with self.getTestCore() as core:
await core.nodes('[test:str=1234 :tick=2001]')
await core.nodes('[test:str=9876 :tick=3001]')
q = "test:str " \
"$tick=$node.repr(tick) " \
"$lib.csv.emit($node.form(), $node.value(), $tick, table=mytable)"
mesgs = await core.stormlist(q, {'show': ('err', 'csv:row')})
csv_rows = [m for m in mesgs if m[0] == 'csv:row']
self.len(2, csv_rows)
csv_rows.sort(key=lambda x: x[1].get('row')[1])
self.eq(csv_rows[0],
('csv:row', {'row': ['test:str', '1234', '2001/01/01 00:00:00.000'],
'table': 'mytable'}))
self.eq(csv_rows[1],
('csv:row', {'row': ['test:str', '9876', '3001/01/01 00:00:00.000'],
'table': 'mytable'}))
q = 'test:str $hehe=$node.props.hehe $lib.csv.emit(:tick, $hehe)'
mesgs = await core.stormlist(q, {'show': ('err', 'csv:row')})
csv_rows = [m for m in mesgs if m[0] == 'csv:row']
self.len(2, csv_rows)
self.eq(csv_rows[0], ('csv:row', {'row': [978307200000, None], 'table': None}))
self.eq(csv_rows[1], ('csv:row', {'row': [32535216000000, None], 'table': None}))
# Sad path case...
q = '''
[ test:str=woot ]
$lib.csv.emit($path)
'''
mesgs = await core.stormlist(q, {'show': ('err', 'csv:row')})
err = mesgs[-2]
self.eq(err[1][0], 'NoSuchType')
async def test_storm_text(self):
async with self.getTestCore() as core:
nodes = await core.nodes('''
[ test:int=10 ] $text=$lib.text(hehe) { +test:int>=10 $text.add(haha) }
[ test:str=$text.str() ] +test:str''')
self.len(1, nodes)
self.eq(nodes[0].ndef, ('test:str', 'hehehaha'))
q = '''$t=$lib.text(beepboop) $lib.print($lib.len($t))
$t.add("more!") $lib.print($lib.len($t))
'''
msgs = await core.stormlist(q)
self.stormIsInPrint('8', msgs)
self.stormIsInPrint('13', msgs)
async def test_storm_set(self):
async with self.getTestCore() as core:
await core.nodes('[inet:ipv4=1.2.3.4 :asn=20]')
await core.nodes('[inet:ipv4=5.6.7.8 :asn=30]')
q = '''
$set = $lib.set()
inet:ipv4 $set.add(:asn)
[ graph:node="*" ] +graph:node [ :data=$set.list() ]
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(tuple(sorted(nodes[0].get('data'))), (20, 30))
q = '''
$set = $lib.set()
inet:ipv4 $set.adds((:asn,:asn))
[ graph:node="*" ] +graph:node [ :data=$set.list() ]
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(tuple(sorted(nodes[0].get('data'))), (20, 30))
q = '''
$set = $lib.set()
inet:ipv4 $set.adds((:asn,:asn))
{ +:asn=20 $set.rem(:asn) }
[ graph:node="*" ] +graph:node [ :data=$set.list() ]
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(tuple(sorted(nodes[0].get('data'))), (30,))
q = '''
$set = $lib.set()
inet:ipv4 $set.add(:asn)
$set.rems((:asn,:asn))
[ graph:node="*" ] +graph:node [ :data=$set.list() ]
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(tuple(sorted(nodes[0].get('data'))), ())
q = '$set = $lib.set(a, b, c, b, a) [test:int=$set.size()]'
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(nodes[0].ndef, ('test:int', 3))
q = '''$set = $lib.set(a, b, c)
for $v in $set {
$lib.print('set valu: {v}', v=$v)
}
'''
mesgs = await core.stormlist(q)
self.stormIsInPrint('set valu: a', mesgs)
self.stormIsInPrint('set valu: b', mesgs)
self.stormIsInPrint('set valu: c', mesgs)
q = '''
$set = $lib.set()
$set.add(foo)
if $set.has(foo) { [ test:str=asdf ] }
'''
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(nodes[0].ndef, ('test:str', 'asdf'))
async def test_storm_path(self):
async with self.getTestCore() as core:
await core.nodes('[ inet:dns:a=(vertex.link, 1.2.3.4) ]')
q = '''
inet:fqdn=vertex.link -> inet:dns:a -> inet:ipv4
$idens = $path.idens()
[ graph:node="*" ] +graph:node [ :data=$idens ]
'''
idens = (
'02488bc284ffd0f60f474d5af66a8c0cf89789f766b51fde1d3da9b227005f47',
'20153b758f9d5eaaa38e4f4a65c36da797c3e59e549620fa7c4895e1a920991f',
'3ecd51e142a5acfcde42c02ff5c68378bfaf1eaf49fe9721550b6e7d6013b699',
)
nodes = await core.nodes(q)
self.len(1, nodes)
self.eq(tuple(sorted(nodes[0].get('data'))), idens)
opts = {'vars': {'testvar': 'test'}}
text = "[ test:str='123' ] $testkey=testvar [ test:str=$path.vars.$testkey ]"
nodes = await core.nodes(text, opts=opts)
self.len(2, nodes)