Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release/1.8.2 #663

Merged
merged 159 commits into from
Jun 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
159 commits
Select commit Hold shift + click to select a range
303dda1
Refactoring current tests
VakarisZ Mar 30, 2020
0fc5615
Further improving and refactoring performance test code
VakarisZ Apr 9, 2020
367017a
Refactored and further improved performance test code structure
VakarisZ Apr 10, 2020
0e2a3a5
Merge remote-tracking branch 'upstream/develop' into map_generation_test
VakarisZ Apr 10, 2020
5fa27c1
Bugfixes and debugging comments removed
VakarisZ Apr 15, 2020
7d397da
Added telemetry collection
VakarisZ Apr 15, 2020
a400da2
Added ability to export test telemetries to directory
VakarisZ Apr 15, 2020
1ccbb3d
Finished fabricated monkey telemetry sending
VakarisZ Apr 16, 2020
636c8f6
Added the ability to forge more intricate setup telemetries + small b…
VakarisZ Apr 20, 2020
b6e0e30
Splitting classes into multiple files
VakarisZ Apr 20, 2020
78b0186
Finished telemetry fabrication
VakarisZ Apr 23, 2020
91d6811
Refactored root endpoint and added service hook for things that shoul…
VakarisZ Apr 23, 2020
986e527
Finished telemetry performance test (time measurements, refactoring)
VakarisZ Apr 23, 2020
baa1598
Added progress bars, optimized imports, fixed bug that happened on bi…
VakarisZ Apr 24, 2020
41ae125
Fixed telemetry performance test logging bugs and improved logging to…
VakarisZ Apr 24, 2020
aa21e86
Merge pull request #628 from guardicore/release/1.8.0
ShayNehmad Apr 27, 2020
1afbe3d
Improved ZT event aggregation performance
VakarisZ Apr 28, 2020
ac740d3
Merge pull request #631 from guardicore/master
ShayNehmad Apr 28, 2020
67c8b48
Merge pull request #619 from VakarisZ/map_generation_test
VakarisZ Apr 28, 2020
55d3fd5
More improvement on telemetry fabrication logging
VakarisZ Apr 28, 2020
1352747
Removed debugging comments
VakarisZ Apr 29, 2020
1a78479
Fixed a typo in supported_request_method.py filename
VakarisZ Apr 29, 2020
6930e9d
Merge branch 'monkey_telemetry_fabrication' into performance_fixes
VakarisZ Apr 29, 2020
564f9a2
Add lodash minimizer. Saves roughly 50kib but for free.
Apr 29, 2020
d5b659c
Change to deep linking forteawesome images. This is because webpack d…
Apr 29, 2020
c7a94be
Revert lodash minimizer due to bugs that I didn't want to debug.
Apr 29, 2020
a645abd
Updated babel, updated polyfill definitions to include only modern br…
Apr 29, 2020
116de3e
Actually use the eslint plugins we install. Use react plugin for eslint
Apr 29, 2020
572b90d
Remove unused imports
Apr 29, 2020
2f7eb05
Add DNS prefetch for google fonts and bootstrap CSS to index.html
Apr 29, 2020
8d0ae1c
Merge font requests to save time
Apr 29, 2020
92504f8
Switch DNS prefetch to preconnect.
Apr 29, 2020
5101c50
Move font display tag to HTML query, to avoid questions on where to s…
Apr 29, 2020
375bb70
Move to only using modern imports
Apr 30, 2020
345d6d0
Update css-loader
Apr 30, 2020
83c2ba7
Change PTH icons to 8bit to save size.
Apr 30, 2020
b97478a
Remove unused icons
Apr 30, 2020
f73beac
Implemented map/report generation tests which are based on telemetrie…
VakarisZ Apr 30, 2020
8603d18
Added a profiling decorator, that can be used on methods to get their…
VakarisZ Apr 30, 2020
4dcae80
Improved ZT report generation performance.
VakarisZ Apr 30, 2020
9be8d4a
Fixed log paths for profiling decorator
VakarisZ Apr 30, 2020
7a13e71
More simple ZT performance improvements and profiler decorator bugfix
VakarisZ Apr 30, 2020
32515e0
Hide a lot of eslint warnings.
May 1, 2020
9530330
Balance by fixing a bunch of small eslint and general code hint warnings
May 1, 2020
d403ea9
Hide more errors :(
May 1, 2020
e508540
Fix really random linting errors from flake8
May 1, 2020
431daa1
Reduce number of flake8 warnings to 100.
May 1, 2020
d7c0b7d
Revert hiding error and just display it instead
May 1, 2020
24dc84c
Bring back eslint errors, raise travisCI threshold :(
May 1, 2020
fc46eec
Turn errors into warnings.
May 1, 2020
a31fffa
Add attack technique description
shreyamalviya Mar 26, 2020
41754cb
Add technique report
shreyamalviya Mar 26, 2020
943541a
Link attack report to send to client
shreyamalviya Mar 26, 2020
141abfe
Add report UI
shreyamalviya Mar 26, 2020
7a3f747
Map "Back door user" PBA with "Create account" attack technique
shreyamalviya Apr 12, 2020
0394b84
Tiny changes according to review
shreyamalviya Apr 24, 2020
e164f53
Remove unwanted code (for mapping config to matrix [T1136])
shreyamalviya Apr 24, 2020
749c37f
Add check for "Communicate as new user" PBA in T1136
shreyamalviya Apr 24, 2020
cdf65ae
Post breach typo in configuration_schema fix
VakarisZ Apr 27, 2020
319c1c2
Remove redundant code (which was mapping matrix to PBA config)
shreyamalviya Apr 27, 2020
3bfdcb9
Undo line deletion
shreyamalviya May 4, 2020
9470ba9
Merge pull request #634 from acepace/feature/UI_games
VakarisZ May 4, 2020
f3ec436
Merge pull request #582 from shreyamalviya/map-create-user-pba-to-matrix
VakarisZ May 4, 2020
8a385ec
Style fix for modal window and report tabs
VakarisZ May 4, 2020
4c27ea4
Fix a few more. Re set the number of flake warnings to be higher :(
May 5, 2020
2f4904d
Merge branch 'develop' into bugfix/random_pep
May 5, 2020
1de511b
Remove some more PEP8
May 5, 2020
115cb05
Remove flake8 warnings on import not in start of module. Possible alt…
May 5, 2020
d502154
Merge pull request #636 from acepace/bugfix/random_pep
ShayNehmad May 6, 2020
4073e2f
Fixed zero trust bug where all events had the same timestamp
VakarisZ May 6, 2020
571682f
Refactored ZT events sending and display on report to improve perform…
VakarisZ May 6, 2020
9aff40d
Fake IP's don't get out of range, fixed typo in requirements and adde…
VakarisZ May 7, 2020
a98b348
Merge remote-tracking branch 'upstream/develop' into monkey_telemetry…
VakarisZ May 7, 2020
73832bd
Updated PERFORMANCE.conf to include all machines and a lot of segment…
VakarisZ May 7, 2020
10d1e7d
Fixed monkey ignoring depth restrictions
VakarisZ May 8, 2020
bd18893
Added depth logging for easier debugging down the line
ShayNehmad May 10, 2020
07330ff
Fix build problem
ShayNehmad May 10, 2020
f070517
Merge pull request #642 from guardicore/bugfix/monkey_depth_fix
ShayNehmad May 10, 2020
fdfa57e
Fix import typo
ShayNehmad May 10, 2020
bb54d4f
Merge branch 'develop' into hotfix/fix-ui-build-problems
ShayNehmad May 11, 2020
ca49eb7
Update node sass version
ShayNehmad May 11, 2020
f94098a
Merge remote-tracking branch 'upstream/develop' into security_perform…
VakarisZ May 11, 2020
69f9780
Trying to fight with NPM
ShayNehmad May 11, 2020
735aac9
Remove pywin32 requirement, it's a subset requirement of wmi.
May 11, 2020
1f11173
Remove reg_utils, unused file.
May 11, 2020
23d7ef4
Update travis script to use npm ci as well
ShayNehmad May 11, 2020
e189e96
Improved the dir structure of telem parsing, other minor CR comments …
VakarisZ May 11, 2020
c1de951
Update NPM dependency to latest
ShayNehmad May 11, 2020
3f83176
Fix syntax (and add comment for future travelers)
ShayNehmad May 11, 2020
08f46a8
Merge branch 'monkey_telemetry_fabrication' into zt_performance_fixes
VakarisZ May 11, 2020
6cf8130
Load NVM after installing in TravisCI script
ShayNehmad May 11, 2020
e73c1d0
Merge pull request #643 from guardicore/hotfix/fix-ui-build-problems
ShayNehmad May 11, 2020
67b7d0b
Improved telemetry fabrication logging and failing if telemetry folde…
VakarisZ May 11, 2020
c700412
Merge pull request #644 from acepace/bugfix/remove_wmi_requirement_fr…
ShayNehmad May 11, 2020
3fcc944
Merge pull request #632 from VakarisZ/monkey_telemetry_fabrication
VakarisZ May 11, 2020
7663615
Merge branch 'monkey_telemetry_fabrication' into zt_performance_fixes
VakarisZ May 11, 2020
9b350b8
Minor fixes and improvements
VakarisZ May 11, 2020
c1f52ee
Added a short summary sentence over each table in the security report
ShayNehmad May 11, 2020
85b5a15
Fixed code review comments - JS linting and readability
ShayNehmad May 12, 2020
2debe98
Profiling decorator: added readme and profiler logs added to gitignore
VakarisZ May 12, 2020
ee6b122
Minor improvements
VakarisZ May 12, 2020
0e4242b
Gitignore changed to ignore all "profiler_logs" dirs
VakarisZ May 12, 2020
3d97cb3
Merge branch 'zt_performance_fixes' into security_performance_fixes
VakarisZ May 12, 2020
991cbec
Added cmd options to disable interaction with GCP and run quick perfo…
VakarisZ May 13, 2020
a8e94a9
Added fixtures to skip tests failing due to mongoengine
VakarisZ May 13, 2020
cff9230
Merge remote-tracking branch 'upstream/develop' into zt_performance_f…
VakarisZ May 13, 2020
1942109
Merge branch 'zt_performance_fixes' into security_performance_fixes
VakarisZ May 13, 2020
ee7051f
Smallfixes on persistance/create user attack technique
VakarisZ May 13, 2020
e159231
Merge pull request #646 from guardicore/635/scanned-servers-summary-s…
ShayNehmad May 13, 2020
5dd6b40
Merge pull request #647 from guardicore/feature/attack_create_user_fix
ShayNehmad May 13, 2020
a360e85
Fixed a bug of multiple telemetry exports in a single island run.
VakarisZ May 13, 2020
87e50d3
Small fixes: island reset added to telemetry performance test, fixed …
VakarisZ May 14, 2020
54ac059
Prototype changes that fix redundant exploitations, but break multipl…
VakarisZ May 15, 2020
698a139
Removed unnecessary UI warning about config change not working if mon…
VakarisZ May 19, 2020
0e54b78
Changes that allow to avoid monkey exploitation redundancy: checking …
VakarisZ May 20, 2020
507bf43
Renamed monkey_island.cc.utils to monkey_island.cc.network_utils as i…
VakarisZ May 20, 2020
c817415
Fixed "is monkey running on island" check by splitting port from ip s…
VakarisZ May 20, 2020
5276789
Removed the mechanism of adding exploited machines to blocked machine…
VakarisZ May 20, 2020
ab025d9
Merge remote-tracking branch 'upstream/develop' into zt_performance_f…
VakarisZ May 20, 2020
eb226f0
Merge remote-tracking branch 'upstream/develop' into zt_performance_f…
VakarisZ May 20, 2020
44cb87a
Minor js readability improvement
VakarisZ May 20, 2020
1f79c16
Merge pull request #645 from guardicore/feature/zt_performance_fixes
VakarisZ May 20, 2020
2cbe9c1
Merge branch 'zt_performance_fixes' into exploitation_redundancy_fix
VakarisZ May 20, 2020
5def120
Merge remote-tracking branch 'upstream/develop' into exploitation_red…
VakarisZ May 20, 2020
8d2b879
nvm comes pre-installed on travis images, so we're fine
ShayNehmad May 20, 2020
d412502
Merge pull request #652 from guardicore/hotfix/remove-faulty-install-…
ShayNehmad May 20, 2020
ca1ee90
Hadoop bugfix, minor readability improvement
VakarisZ May 20, 2020
f941c9c
Added port not null check on island resource
VakarisZ May 21, 2020
598872a
UI crash due to multiple redundant telemetry requests fix
VakarisZ May 21, 2020
30be271
Map jitter fix
VakarisZ May 21, 2020
436472b
Added parameter logging on monkey start, fixed bug where dropper laun…
VakarisZ May 21, 2020
bda9b04
Added "build_command_explicitly()" UT and improved it a bit
VakarisZ May 21, 2020
c730605
UI crash due to multiple redundant telemetry requests fix
VakarisZ May 21, 2020
c75190e
Map jitter fix
VakarisZ May 21, 2020
04b00b5
Revert "UI crash due to multiple redundant telemetry requests fix"
VakarisZ May 22, 2020
bd0b1c1
Refactored monkey local config keys into a constant
VakarisZ May 22, 2020
9864720
Get node label performance improvement and small BB test changes
VakarisZ May 22, 2020
2cf9c9c
Fix minor linter issues
ShayNehmad May 24, 2020
1ce2037
Merge remote-tracking branch 'upstream/feature/exploitation_redundanc…
VakarisZ May 25, 2020
1e812b9
Revert "Map jitter fix"
VakarisZ May 25, 2020
3405f29
Added small readability changes
VakarisZ May 25, 2020
ed27689
Merge pull request #650 from guardicore/feature/exploitation_redundan…
VakarisZ May 25, 2020
f1f7859
Merge remote-tracking branch 'upstream/develop' into ui_performance_f…
VakarisZ May 25, 2020
43a94b6
Merge remote-tracking branch 'upstream/develop' into ui_performance_f…
VakarisZ May 25, 2020
05c99c4
Merge pull request #654 from guardicore/feature/ui_performance_fixes
VakarisZ May 26, 2020
5ea4a90
Bump path version
ShayNehmad May 26, 2020
1ed49c6
Fixed smb exploiter bug where vulnerable port was not passed
VakarisZ May 26, 2020
8cf9c9f
Explicitly set vulnerable port to None
VakarisZ May 26, 2020
ffda4e8
Merge pull request #664 from guardicore/feature/smb_vulnerable_port_fix
VakarisZ May 26, 2020
50dcfa3
Merge remote-tracking branch 'upstream/develop' into release/1.8.2
VakarisZ May 26, 2020
090beb6
We forgot to call onClose for the button :grey_exclamation:
ShayNehmad May 27, 2020
d430b91
Merge pull request #666 from guardicore/665/reset-env-button-state-bug
VakarisZ May 27, 2020
e1229ba
The Missing Binaries modal works but in a non-elegant way
ophirharpazg May 27, 2020
a4d4f62
Raise a modal indicating that Monkey binaries are missing.
ophirharpazg May 27, 2020
02bdf4b
Added text to the missing-binaries modal
ophirharpazg May 27, 2020
a07ec92
formatting of the binaries path
ophirharpazg May 28, 2020
33ef1f6
Merge pull request #670 from guardicore/485/handle-missing-binaries
ShayNehmad May 31, 2020
ca87ff1
Merge branch 'develop' into release/1.8.2
ShayNehmad Jun 3, 2020
9ea6718
Moved a function into common, since Monkey doesn't have ring as a dep…
ShayNehmad Jun 3, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,11 @@ MonkeyZoo/*
!MonkeyZoo/config.tf
!MonkeyZoo/MonkeyZooDocs.pdf

# Exported monkey telemetries
/monkey/telem_sample/

# Profiling logs
profiler_logs/

# vim swap files
*.swp
30 changes: 21 additions & 9 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# Infection Monkey travis.yml. See Travis documentation for information about this file structure.

# If you change this file, you can validate using Travis CI's Build Config Explorer https://config.travis-ci.com/explore

group: travis_latest

language: python

cache: pip
cache:
- pip
- directories:
- "$HOME/.npm"

python:
- 3.7
Expand All @@ -18,6 +23,16 @@ install:
- pip install coverage # for code coverage
- pip install -r monkey/infection_monkey/requirements.txt # for unit tests

# node + npm + eslint
- node --version
- npm --version
- nvm --version
- nvm install node
- nvm use node
- npm i -g eslint
- node --version
- npm --version

before_script:
# Set the server config to `testing`. This is required for for the UTs to pass.
- python monkey/monkey_island/cc/set_server_config.py testing
Expand All @@ -36,7 +51,7 @@ script:
## Display the linter issues
- cat flake8_warnings.txt
## Make sure that we haven't increased the amount of warnings.
- PYTHON_WARNINGS_AMOUNT_UPPER_LIMIT=190
- PYTHON_WARNINGS_AMOUNT_UPPER_LIMIT=120
- if [ $(tail -n 1 flake8_warnings.txt) -gt $PYTHON_WARNINGS_AMOUNT_UPPER_LIMIT ]; then echo "Too many python linter warnings! Failing this build. Lower the amount of linter errors in this and try again. " && exit 1; fi

## Run unit tests
Expand All @@ -48,13 +63,10 @@ script:

# Check JS code. The npm install must happen AFTER the flake8 because the node_modules folder will cause a lot of errors.
- cd monkey_island/cc/ui
- npm i
- npm i -g eslint
- cd -
- cd monkey_island/cc/ui
- eslint ./src --quiet
- JS_WARNINGS_AMOUNT_UPPER_LIMIT=37
- eslint ./src --max-warnings $JS_WARNINGS_AMOUNT_UPPER_LIMIT
- npm ci # See https://docs.npmjs.com/cli/ci.html
- eslint ./src --quiet # Test for errors
- JS_WARNINGS_AMOUNT_UPPER_LIMIT=490
- eslint ./src --max-warnings $JS_WARNINGS_AMOUNT_UPPER_LIMIT # Test for max warnings

after_success:
# Upload code coverage results to codecov.io, see https://github.com/codecov/codecov-bash for more information
Expand Down
1 change: 1 addition & 0 deletions envs/monkey_zoo/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
logs/
/blackbox/tests/performance/telem_sample
33 changes: 30 additions & 3 deletions envs/monkey_zoo/blackbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,37 @@ In order to execute the entire test suite, you must know the external IP of the
this information in the GCP Console `Compute Engine/VM Instances` under _External IP_.

#### Running in command line
Run the following command:
Blackbox tests have following parameters:
- `--island=IP` Sets island's IP
- `--no-gcp` (Optional) Use for no interaction with the cloud (local test).
- `--quick-performance-tests` (Optional) If enabled performance tests won't reset island and won't send telemetries,
instead will just test performance of endpoints in already present island state.

`monkey\envs\monkey_zoo\blackbox>python -m pytest --island=35.207.152.72:5000 test_blackbox.py`
Example run command:

`monkey\envs\monkey_zoo\blackbox>python -m pytest -s --island=35.207.152.72:5000 test_blackbox.py`

#### Running in PyCharm
Configure a PyTest configuration with the additional argument `--island=35.207.152.72` on the
Configure a PyTest configuration with the additional arguments `-s --island=35.207.152.72` on the
`monkey\envs\monkey_zoo\blackbox`.

### Running telemetry performance test

**Before running performance test make sure browser is not sending requests to island!**

To run telemetry performance test follow these steps:
1. Gather monkey telemetries.
1. Enable "Export monkey telemetries" in Configuration -> Internal -> Tests if you don't have
exported telemetries already.
2. Run monkey and wait until infection is done.
3. All telemetries are gathered in `monkey/telem_sample`
2. Run telemetry performance test.
1. Move directory `monkey/test_telems` to `envs/monkey_zoo/blackbox/tests/performance/test_telems`
2. (Optional) Use `envs/monkey_zoo/blackbox/tests/performance/utils/telem_parser.py` to multiply
telemetries gathered.
1. Run `telem_parser.py` script with working directory set to `monkey\envs\monkey_zoo\blackbox`
2. Pass integer to indicate the multiplier. For example running `telem_parser.py 4` will replicate
telemetries 4 times.
3. If you're using pycharm check "Emulate terminal in output console" on debug/run configuraion.
3. Performance test will run as part of BlackBox tests or you can run it separately by adding
`-k 'test_telem_performance'` option.
57 changes: 23 additions & 34 deletions envs/monkey_zoo/blackbox/analyzers/performance_analyzer.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,48 @@
import logging
from datetime import timedelta
from typing import Dict

from envs.monkey_zoo.blackbox.analyzers.analyzer import Analyzer
from envs.monkey_zoo.blackbox.island_client.monkey_island_client import MonkeyIslandClient
from envs.monkey_zoo.blackbox.tests.performance.performance_test_config import PerformanceTestConfig

MAX_ALLOWED_SINGLE_PAGE_TIME = timedelta(seconds=2)
MAX_ALLOWED_TOTAL_TIME = timedelta(seconds=5)

REPORT_URLS = [
"api/report/security",
"api/attack/report",
"api/report/zero_trust/findings",
"api/report/zero_trust/principles",
"api/report/zero_trust/pillars"
]

logger = logging.getLogger(__name__)
LOGGER = logging.getLogger(__name__)


class PerformanceAnalyzer(Analyzer):

def __init__(self, island_client: MonkeyIslandClient, break_if_took_too_long=False):
self.break_if_took_too_long = break_if_took_too_long
self.island_client = island_client

def analyze_test_results(self) -> bool:
if not self.island_client.is_all_monkeys_dead():
raise RuntimeError("Can't test report times since not all Monkeys have died.")
def __init__(self, performance_test_config: PerformanceTestConfig, endpoint_timings: Dict[str, timedelta]):
self.performance_test_config = performance_test_config
self.endpoint_timings = endpoint_timings

# Collect timings for all pages
self.island_client.clear_caches()
report_resource_to_response_time = {}
for url in REPORT_URLS:
report_resource_to_response_time[url] = self.island_client.get_elapsed_for_get_request(url)

# Calculate total time and check each page
def analyze_test_results(self):
# Calculate total time and check each endpoint
single_page_time_less_then_max = True
total_time = timedelta()
for page, elapsed in report_resource_to_response_time.items():
logger.info(f"page {page} took {str(elapsed)}")
for endpoint, elapsed in self.endpoint_timings.items():
total_time += elapsed
if elapsed > MAX_ALLOWED_SINGLE_PAGE_TIME:
if elapsed > self.performance_test_config.max_allowed_single_page_time:
single_page_time_less_then_max = False

total_time_less_then_max = total_time < MAX_ALLOWED_TOTAL_TIME
total_time_less_then_max = total_time < self.performance_test_config.max_allowed_total_time

logger.info(f"total time is {str(total_time)}")
PerformanceAnalyzer.log_slowest_endpoints(self.endpoint_timings)
LOGGER.info(f"Total time is {str(total_time)}")

performance_is_good_enough = total_time_less_then_max and single_page_time_less_then_max

if self.break_if_took_too_long and not performance_is_good_enough:
logger.warning(
if self.performance_test_config.break_on_timeout and not performance_is_good_enough:
LOGGER.warning(
"Calling breakpoint - pausing to enable investigation of island. Type 'c' to continue once you're done "
"investigating. Type 'p timings' and 'p total_time' to see performance information."
)
breakpoint()

return performance_is_good_enough

@staticmethod
def log_slowest_endpoints(endpoint_timings, max_endpoints_to_display=100):
slow_endpoint_list = list(endpoint_timings.items())
slow_endpoint_list.sort(key=lambda x: x[1], reverse=True)
slow_endpoint_list = slow_endpoint_list[:max_endpoints_to_display]
for endpoint in slow_endpoint_list:
LOGGER.info(f"{endpoint[0]} took {str(endpoint[1])}")
17 changes: 16 additions & 1 deletion envs/monkey_zoo/blackbox/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,23 @@
def pytest_addoption(parser):
parser.addoption("--island", action="store", default="",
help="Specify the Monkey Island address (host+port).")
parser.addoption("--no-gcp", action="store_true", default=False,
help="Use for no interaction with the cloud.")
parser.addoption("--quick-performance-tests", action="store_true", default=False,
help="If enabled performance tests won't reset island and won't send telemetries, "
"instead will just test performance of already present island state.")


@pytest.fixture(scope='module')
@pytest.fixture(scope='session')
def island(request):
return request.config.getoption("--island")


@pytest.fixture(scope='session')
def no_gcp(request):
return request.config.getoption("--no-gcp")


@pytest.fixture(scope='session')
def quick_performance_tests(request):
return request.config.getoption("--quick-performance-tests")
16 changes: 3 additions & 13 deletions envs/monkey_zoo/blackbox/island_client/monkey_island_client.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from datetime import timedelta
from time import sleep
import json

import logging
from time import sleep

from bson import json_util

from envs.monkey_zoo.blackbox.island_client.monkey_island_requests import MonkeyIslandRequests
Expand Down Expand Up @@ -31,7 +31,7 @@ def import_config(self, config_contents):

@avoid_race_condition
def run_monkey_local(self):
response = self.requests.post_json("api/local-monkey", dict_data={"action": "run"})
response = self.requests.post_json("api/local-monkey", data={"action": "run"})
if MonkeyIslandClient.monkey_ran_successfully(response):
LOGGER.info("Running the monkey.")
else:
Expand Down Expand Up @@ -96,13 +96,3 @@ def clear_caches(self):
response = self.requests.get("api/test/clear_caches")
response.raise_for_status()
return response

def get_elapsed_for_get_request(self, url):
response = self.requests.get(url)
if response.ok:
LOGGER.debug(f"Got ok for {url} content peek:\n{response.content[:120].strip()}")
return response.elapsed
else:
LOGGER.error(f"Trying to get {url} but got unexpected {str(response)}")
# instead of raising for status, mark failed responses as maxtime
return timedelta.max()
40 changes: 37 additions & 3 deletions envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from typing import Dict
from datetime import timedelta


import requests
import functools

# SHA3-512 of '1234567890!@#$%^&*()_nothing_up_my_sleeve_1234567890!@#$%^&*()'
from envs.monkey_zoo.blackbox.island_client.supported_request_method import SupportedRequestMethod

import logging

# SHA3-512 of '1234567890!@#$%^&*()_nothing_up_my_sleeve_1234567890!@#$%^&*()'
NO_AUTH_CREDS = '55e97c9dcfd22b8079189ddaeea9bce8125887e3237b800c6176c9afa80d2062' \
'8d2c8d0b1538d2208c1444ac66535b764a3d902b35e751df3faec1e477ed3557'
LOGGER = logging.getLogger(__name__)
Expand All @@ -14,6 +20,26 @@ class MonkeyIslandRequests(object):
def __init__(self, server_address):
self.addr = "https://{IP}/".format(IP=server_address)
self.token = self.try_get_jwt_from_server()
self.supported_request_methods = {SupportedRequestMethod.GET: self.get,
SupportedRequestMethod.POST: self.post,
SupportedRequestMethod.PATCH: self.patch,
SupportedRequestMethod.DELETE: self.delete}

def get_request_time(self, url, method: SupportedRequestMethod, data=None):
response = self.send_request_by_method(url, method, data)
if response.ok:
LOGGER.debug(f"Got ok for {url} content peek:\n{response.content[:120].strip()}")
return response.elapsed
else:
LOGGER.error(f"Trying to get {url} but got unexpected {str(response)}")
# instead of raising for status, mark failed responses as maxtime
return timedelta.max

def send_request_by_method(self, url, method=SupportedRequestMethod.GET, data=None):
if data:
return self.supported_request_methods[method](url, data)
else:
return self.supported_request_methods[method](url)

def try_get_jwt_from_server(self):
try:
Expand Down Expand Up @@ -55,12 +81,20 @@ def post(self, url, data):
verify=False)

@_Decorators.refresh_jwt_token
def post_json(self, url, dict_data):
def post_json(self, url, data: Dict):
return requests.post(self.addr + url, # noqa: DUO123
json=dict_data,
json=data,
headers=self.get_jwt_header(),
verify=False)

@_Decorators.refresh_jwt_token
def patch(self, url, data: Dict):
return requests.patch(self.addr + url, # noqa: DUO123
data=data,
headers=self.get_jwt_header(),
verify=False
)

@_Decorators.refresh_jwt_token
def delete(self, url):
return requests.delete( # noqa: DOU123
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from enum import Enum


class SupportedRequestMethod(Enum):
GET = "GET"
POST = "POST"
PATCH = "PATCH"
DELETE = "DELETE"
Loading