Codebase list python-faraday / 62d1b14 tests / test_api_agent.py
62d1b14

Tree @62d1b14 (Download .tar.gz)

test_api_agent.py @62d1b14raw · history · blame

  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
"""
Faraday Penetration Test IDE
Copyright (C) 2019  Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information
"""

from unittest import mock

from posixpath import join
from urllib.parse import urljoin
import pyotp
import pytest

from faraday.server.api.modules.agent import AgentWithWorkspacesView, AgentView
from faraday.server.models import Agent, Command
from tests.factories import AgentFactory, WorkspaceFactory, ExecutorFactory
from tests.test_api_non_workspaced_base import ReadWriteAPITests
from tests.test_api_workspaced_base import ReadOnlyMultiWorkspacedAPITests
from tests import factories
from tests.test_api_workspaced_base import API_PREFIX


def http_req(method, client, endpoint, json_dict, expected_status_codes, follow_redirects=False):
    res = ""
    if method.upper() == "GET":
        res = client.get(endpoint, json=json_dict, follow_redirects=follow_redirects)
    elif method.upper() == "POST":
        res = client.post(endpoint, json=json_dict, follow_redirects=follow_redirects)
    elif method.upper() == "PUT":
        res = client.put(endpoint, json=json_dict, follow_redirects=follow_redirects)
    assert res.status_code in expected_status_codes
    return res


def logout(client, expected_status_codes):
    res = http_req(method="GET",
                   client=client,
                   endpoint="/logout",
                   json_dict=dict(),
                   expected_status_codes=expected_status_codes)
    return res


def get_raw_agent(name="My agent", active=None, token=None, workspaces=None):
    raw_agent = {}
    if name is not None:
        raw_agent["name"] = name
    if active is not None:
        raw_agent["active"] = active
    if token:
        raw_agent["token"] = token
    if workspaces is not None:
        raw_agent["workspaces"] = [
            workspace.name for workspace in workspaces
        ]
    return raw_agent


@pytest.mark.usefixtures('logged_user')
class TestAgentAuthTokenAPIGeneric:

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_get_agent_token(self, faraday_server_config, test_client, session):
        faraday_server_config.agent_registration_secret = None
        res = test_client.get('/v3/agent_token')
        assert 'token' in res.json and 'expires_in' in res.json
        assert len(res.json['token'])

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_token_fails(self, faraday_server_config, test_client, session):
        faraday_server_config.agent_registration_secret = None
        res = test_client.post('/v3/agent_token')
        assert res.status_code == 405


class TestAgentCreationAPI:

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    @pytest.mark.usefixtures('ignore_nplusone')
    def test_create_agent_valid_token(self, faraday_server_config, test_client,
                                      session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        faraday_server_config.agent_token_expiration = 60
        logout(test_client, [302])
        initial_agent_count = len(session.query(Agent).all())
        raw_data = get_raw_agent(
            name='new_agent',
            token=pyotp.TOTP(secret, interval=60).now(),
            workspaces=[workspace, other_workspace]
        )
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 201, (res.json, raw_data)
        assert len(session.query(Agent).all()) == initial_agent_count + 1
        assert workspace.name in res.json['workspaces']
        assert other_workspace.name in res.json['workspaces']
        assert len(res.json['workspaces']) == 2
        workspaces = Agent.query.get(res.json['id']).workspaces
        assert len(workspaces) == 2
        assert workspace in workspaces
        assert other_workspace in workspaces

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_without_name_fails(self, faraday_server_config,
                                             test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        faraday_server_config.agent_token_expiration = 60
        logout(test_client, [302])
        initial_agent_count = len(session.query(Agent).all())
        raw_data = get_raw_agent(
            name=None,
            token=pyotp.TOTP(secret, interval=60).now(),
            workspaces=[workspace]
        )
        res = test_client.post(
            '/v3/agent_registration',
            data=raw_data
        )
        assert res.status_code == 400
        assert len(session.query(Agent).all()) == initial_agent_count

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_invalid_token(self, faraday_server_config,
                                        test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        logout(test_client, [302])
        raw_data = get_raw_agent(
            token="INVALID",
            name="test agent",
            workspaces=[workspace]
        )
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 401

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_agent_token_not_set(self, faraday_server_config,
                                              test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        faraday_server_config.agent_registration_secret = None
        logout(test_client, [302])
        raw_data = get_raw_agent(
            name="test agent",
            workspaces=[workspace],
        )
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 400

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_invalid_payload(self, faraday_server_config,
                                          test_client, session):
        faraday_server_config.agent_registration_secret = None
        logout(test_client, [302])
        raw_data = {"PEPE": 'INVALID'}
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 400

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_empty_workspaces(self, faraday_server_config,
                                           test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        faraday_server_config.agent_token_expiration = 60
        logout(test_client, [302])
        raw_data = get_raw_agent(
            token=pyotp.TOTP(secret, interval=60).now(),
            name="test agent",
            workspaces=[]
        )
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 400

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_inexistent_workspaces(self, faraday_server_config,
                                                test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        faraday_server_config.agent_token_expiration = 60
        logout(test_client, [302])
        raw_data = get_raw_agent(
            token=pyotp.TOTP(secret, interval=60).now(),
            name="test agent",
            workspaces=[]
        )
        raw_data["workspaces"] = ["donotexist"]
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 404

    @mock.patch('faraday.server.api.modules.agent.faraday_server')
    def test_create_agent_workspaces_not_set(self, faraday_server_config,
                                             test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        session.commit()
        secret = pyotp.random_base32()
        faraday_server_config.agent_registration_secret = secret
        faraday_server_config.agent_token_expiration = 60
        logout(test_client, [302])
        raw_data = get_raw_agent(
            name="test agent",
            token=pyotp.TOTP(secret, interval=60).now()
        )
        res = test_client.post('/v3/agent_registration', data=raw_data)
        assert res.status_code == 400


class TestAgentWithWorkspacesAPIGeneric(ReadWriteAPITests):
    model = Agent
    factory = factories.AgentFactory
    view_class = AgentWithWorkspacesView
    api_endpoint = 'agents'
    patchable_fields = ['name']

    def test_create_succeeds(self, test_client):
        with pytest.raises(AssertionError) as exc_info:
            super().test_create_succeeds(test_client)
        assert '405' in exc_info.value.args[0]

    def test_create_fails_with_empty_dict(self, test_client):
        with pytest.raises(AssertionError) as exc_info:
            super().test_create_fails_with_empty_dict(test_client)
        assert '405' in exc_info.value.args[0]

    def workspaced_url(self, workspace, obj=None):
        url = urljoin(API_PREFIX, f"{workspace.name}{self.api_endpoint}")
        if obj is not None:
            id_ = str(obj.id) if isinstance(obj, self.model) else str(obj)
            url = urljoin(url, id_)
        return url

    def create_raw_agent(self, active=False, token="TOKEN",
                         workspaces=None):
        return get_raw_agent(name="My agent", token=token, active=active,
                             workspaces=workspaces)

    def test_create_agent_invalid(self, test_client, session):
        """
            To create new agent use the
            <Rule '/v3/agent_registration/' (POST, OPTIONS)
        """
        initial_agent_count = len(session.query(Agent).all())
        raw_agent = self.create_raw_agent()
        res = test_client.post(self.url(), data=raw_agent)
        assert res.status_code == 405  # the only way to create agents is by using the token!
        assert len(session.query(Agent).all()) == initial_agent_count

    def test_get_not_workspaced(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        agent = AgentFactory.create(workspaces=[workspace], active=True)
        session.commit()
        res = test_client.get(self.url(agent))
        assert res.status_code == 200
        assert len(res.json['workspaces']) == 1
        assert workspace.name in res.json['workspaces'][0]

    def test_update_agent(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        agent = AgentFactory.create(workspaces=[workspace], active=True)
        session.commit()
        raw_agent = self.create_raw_agent(active=False, workspaces=[workspace])
        res = test_client.put(self.url(agent.id), data=raw_agent)
        assert res.status_code == 200, (res.json, raw_agent)
        assert not res.json['active']
        assert len(res.json['workspaces']) == 1
        assert workspace.name in res.json['workspaces'][0]

    def test_update_agent_add_a_workspace(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        agent = AgentFactory.create(workspaces=[workspace],
                                    active=True)
        session.commit()
        raw_agent = self.create_raw_agent(
            workspaces=[workspace, other_workspace]
        )
        res = test_client.put(self.url(agent.id), data=raw_agent)
        assert res.status_code == 200
        assert other_workspace.name in res.json['workspaces']
        assert workspace.name in res.json['workspaces']
        assert len(res.json['workspaces']) == 2
        workspaces = Agent.query.get(agent.id).workspaces
        assert len(workspaces) == 2
        assert workspace in workspaces
        assert other_workspace in workspaces

    def test_update_agent_add_a_inexistent_workspace(self, test_client,
                                                     session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        agent = AgentFactory.create(workspaces=[workspace],
                                    active=True)
        session.commit()
        raw_agent = self.create_raw_agent(
            workspaces=[workspace, other_workspace]
        )
        raw_agent["workspaces"] = ["donotexist"]
        res = test_client.put(self.url(agent.id), data=raw_agent)
        assert res.status_code == 404
        workspaces = Agent.query.get(agent.id).workspaces
        assert len(workspaces) == 1
        assert workspace in workspaces

    def test_update_agent_delete_a_workspace(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        agent = AgentFactory.create(workspaces=[workspace, other_workspace],
                                    active=True)
        session.commit()
        raw_agent = self.create_raw_agent(workspaces=[workspace])
        res = test_client.put(self.url(agent.id), data=raw_agent)
        assert res.status_code == 200
        assert len(res.json['workspaces']) == 1
        assert other_workspace.name not in res.json['workspaces']
        assert workspace.name in res.json['workspaces']
        workspaces = Agent.query.get(agent.id).workspaces
        assert len(workspaces) == 1
        assert workspaces[0] == workspace

    def test_update_bug_case(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        agent = AgentFactory.create(workspaces=[workspace])
        session.add(agent)
        session.commit()
        update_data = {
            "id": 1,
            "name": "Agent test",
            "is_online": True,
            "workspaces": [workspace.name]
        }
        res = test_client.put(self.url(agent.id), data=update_data)
        assert res.status_code == 200, (res.json, update_data)
        assert workspace.name in res.json['workspaces']
        assert len(res.json['workspaces']) == 1

    def test_delete_agent(self, test_client, session):
        initial_agent_count = len(session.query(Agent).all())
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        agent = AgentFactory.create(workspaces=[workspace])
        session.commit()
        assert len(session.query(Agent).all()) == initial_agent_count + 1
        res = test_client.delete(self.url(agent.id))
        assert res.status_code == 204
        assert len(session.query(Agent).all()) == initial_agent_count

    def test_run_fails(self, test_client, session, csrf_token):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        session.commit()
        agent = AgentFactory.create(
            workspaces=[workspace, other_workspace]
        )
        executor = ExecutorFactory.create(agent=agent)

        session.add(executor)
        session.commit()
        payload = {
            'csrf_token': csrf_token,
            'executorData': {
                "args": {
                    "param1": True
                },
                "executor": executor.name
            },
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 404


class TestAgentAPI(ReadOnlyMultiWorkspacedAPITests):
    model = Agent
    factory = factories.AgentFactory
    view_class = AgentView
    api_endpoint = 'agents'

    def test_get_workspaced(self, test_client, session):
        workspace = WorkspaceFactory.create()
        session.add(workspace)
        agent = AgentFactory.create(workspaces=[self.workspace], active=True)
        session.commit()
        res = test_client.get(self.url(agent))
        assert res.status_code == 200
        assert 'workspaces' not in res.json

    def test_get_workspaced_other_fails(self, test_client, session):
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        agent = AgentFactory.create(workspaces=[other_workspace], active=True)
        session.commit()
        res = test_client.get(self.url(agent))
        assert res.status_code == 404

    def test_workspaced_delete(self, session, test_client):
        initial_agent_count = len(session.query(Agent).all())
        other_workspace = WorkspaceFactory.create()
        session.add(other_workspace)
        agent = AgentFactory.create(
            workspaces=[self.workspace, other_workspace]
        )
        session.commit()
        assert len(session.query(Agent).all()) == initial_agent_count + 1
        res = test_client.delete(self.url(agent.id))
        assert res.status_code == 204
        assert len(session.query(Agent).all()) == initial_agent_count + 1
        res = test_client.delete(self.url(agent.id))
        assert res.status_code == 404
        res = test_client.get(self.url(agent.id))
        assert res.status_code == 404
        workspaces = Agent.query.get(agent.id).workspaces
        assert len(workspaces) == 1
        assert other_workspace in workspaces

    def test_run_agent_invalid_missing_executorData(self, csrf_token, session,
                                                    test_client):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        payload = {
            'csrf_token': csrf_token
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 400

    def test_run_agent_invalid_executor_argument(self, session, test_client):
        agent = AgentFactory.create(workspaces=[self.workspace])
        executor = ExecutorFactory.create(agent=agent)

        session.add(executor)
        session.commit()

        payload = {
            'executorData': {
                "args": {
                    "another_param_name": 'param_content'
                },
                "executor": executor.name
            }
        }

        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )

        assert res.status_code == 400

    def test_invalid_body(self, test_client, session):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        res = test_client.post(
            join(self.url(agent), 'run'),
            data='[" broken]"{'
        )
        assert res.status_code == 400

    def test_invalid_content_type(self, test_client, session, csrf_token):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        payload = {
            'csrf_token': csrf_token,
            'executorData': {
                "args": {
                    "param1": True
                },
                "executor": "executor_name"
            },
        }
        headers = [
            ('content-type', 'text/html'),
        ]
        res = test_client.post(
            join(self.url(agent), 'run'),
            data=payload,
            headers=headers)
        assert res.status_code == 400

    def test_invalid_executor(self, test_client, session, csrf_token):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        payload = {
            'csrf_token': csrf_token,
            'executorData': {
                "args": {
                    "param1": True
                },
                "executor": "executor_name"
            },
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 400

    def test_happy_path_valid_json(self, test_client, session, csrf_token):
        agent = AgentFactory.create(workspaces=[self.workspace])
        executor = ExecutorFactory.create(agent=agent)
        executor2 = ExecutorFactory.create(agent=agent)

        session.add(executor)
        session.commit()

        assert agent.last_run is None
        assert executor.last_run is None
        assert executor2.last_run is None

        payload = {
            'csrf_token': csrf_token,
            'executorData': {
                "args": {
                    "param_name": "test"
                },
                "executor": executor.name
            },
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 200
        command_id = res.json["command_id"]
        command = Command.query.filter(Command.workspace_id == self.workspace.id).one()
        assert command_id == command.id
        assert agent.last_run is not None
        assert executor.last_run is not None
        assert executor2.last_run is None
        assert agent.last_run == executor.last_run

    def test_invalid_parameter_type(self, test_client, session, csrf_token):
        agent = AgentFactory.create(workspaces=[self.workspace])
        executor = ExecutorFactory.create(agent=agent)

        session.add(executor)
        session.commit()

        payload = {
            'csrf_token': csrf_token,
            'executorData': {
                "args": {
                    "param_name": ["test"]
                },
                "executor": executor.name
            },
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 400

    def test_invalid_json_on_executorData_breaks_the_api(self, csrf_token,
                                                         session, test_client):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        payload = {
            'csrf_token': csrf_token,
            'executorData': '[][dassa',
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 400

    def test_run_agent(self, session, csrf_token, test_client):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        payload = {
            'csrf_token': csrf_token,
            'executorData': '',
        }
        res = test_client.post(
            join(self.url(agent), 'run'),
            json=payload
        )
        assert res.status_code == 400

    def test_get_manifests(self, session, csrf_token, test_client):
        agent = AgentFactory.create(workspaces=[self.workspace])
        session.add(agent)
        session.commit()
        res = test_client.get(join(self.url(), 'get_manifests'))
        assert res.status_code == 200