test_rpc.py 21.8 KB
Newer Older
1
2
import re

Kevin Morris's avatar
Kevin Morris committed
3
4
5
from http import HTTPStatus
from unittest import mock

6
import orjson
7
import pytest
8
9

from fastapi.testclient import TestClient
Kevin Morris's avatar
Kevin Morris committed
10
from redis.client import Pipeline
11

12
from aurweb import asgi, config, scripts
13
14
15
16
17
18
19
20
21
22
23
24
25
from aurweb.db import begin, create, query
from aurweb.models.account_type import AccountType
from aurweb.models.dependency_type import DependencyType
from aurweb.models.license import License
from aurweb.models.package import Package
from aurweb.models.package_base import PackageBase
from aurweb.models.package_dependency import PackageDependency
from aurweb.models.package_keyword import PackageKeyword
from aurweb.models.package_license import PackageLicense
from aurweb.models.package_relation import PackageRelation
from aurweb.models.package_vote import PackageVote
from aurweb.models.relation_type import RelationType
from aurweb.models.user import User
Kevin Morris's avatar
Kevin Morris committed
26
from aurweb.redis import redis_connection
27
28


29
30
31
@pytest.fixture
def client() -> TestClient:
    yield TestClient(app=asgi.app)
32
33


34
@pytest.fixture(autouse=True)
35
36
def setup(db_test):
    # TODO: Rework this into organized fixtures.
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

    # Create test package details.
    with begin():
        # Get ID types.
        account_type = query(AccountType, AccountType.AccountType == "User").first()

        dependency_depends = query(DependencyType, DependencyType.Name == "depends").first()
        dependency_optdepends = query(DependencyType, DependencyType.Name == "optdepends").first()
        dependency_makedepends = query(DependencyType, DependencyType.Name == "makedepends").first()
        dependency_checkdepends = query(DependencyType, DependencyType.Name == "checkdepends").first()

        relation_conflicts = query(RelationType, RelationType.Name == "conflicts").first()
        relation_provides = query(RelationType, RelationType.Name == "provides").first()
        relation_replaces = query(RelationType, RelationType.Name == "replaces").first()

        # Create database info.
        user1 = create(User,
                       Username="user1",
                       Email="user1@example.com",
                       RealName="Test User 1",
                       Passwd="testPassword",
                       AccountType=account_type)

        user2 = create(User,
                       Username="user2",
                       Email="user2@example.com",
                       RealName="Test User 2",
                       Passwd="testPassword",
                       AccountType=account_type)

        user3 = create(User,
                       Username="user3",
                       Email="user3@example.com",
                       RealName="Test User 3",
                       Passwd="testPassword",
                       AccountType=account_type)

74
75
76
        pkgbase1 = create(PackageBase, Name="big-chungus",
                          Maintainer=user1,
                          Packager=user1)
77
78
79
80
81
82
83

        pkgname1 = create(Package,
                          PackageBase=pkgbase1,
                          Name=pkgbase1.Name,
                          Description="Bunny bunny around bunny",
                          URL="https://example.com/")

84
85
86
        pkgbase2 = create(PackageBase, Name="chungy-chungus",
                          Maintainer=user1,
                          Packager=user1)
87
88
89
90
91
92
93

        pkgname2 = create(Package,
                          PackageBase=pkgbase2,
                          Name=pkgbase2.Name,
                          Description="Wubby wubby on wobba wuubu",
                          URL="https://example.com/")

94
95
96
        pkgbase3 = create(PackageBase, Name="gluggly-chungus",
                          Maintainer=user1,
                          Packager=user1)
97

98
99
100
101
102
103
104
105
106
107
108
        pkgbase4 = create(PackageBase, Name="fugly-chungus",
                          Maintainer=user1,
                          Packager=user1)

        desc = "A Package belonging to a PackageBase with another name."
        create(Package,
               PackageBase=pkgbase4,
               Name="other-pkg",
               Description=desc,
               URL="https://example.com")

109
110
111
112
113
114
        create(Package,
               PackageBase=pkgbase3,
               Name=pkgbase3.Name,
               Description="glurrba glurrba gur globba",
               URL="https://example.com/")

115
        pkgbase4 = create(PackageBase, Name="woogly-chungus")
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

        create(Package,
               PackageBase=pkgbase4,
               Name=pkgbase4.Name,
               Description="wuggla woblabeloop shemashmoop",
               URL="https://example.com/")

        # Dependencies.
        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_depends,
               DepName="chungus-depends")

        create(PackageDependency,
               Package=pkgname2,
               DependencyType=dependency_depends,
               DepName="chungy-depends")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_optdepends,
               DepName="chungus-optdepends",
               DepCondition="=50")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_makedepends,
               DepName="chungus-makedepends")

        create(PackageDependency,
               Package=pkgname1,
               DependencyType=dependency_checkdepends,
               DepName="chungus-checkdepends")

        # Relations.
        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_conflicts,
               RelName="chungus-conflicts")

        create(PackageRelation,
               Package=pkgname2,
               RelationType=relation_conflicts,
               RelName="chungy-conflicts")

        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_provides,
               RelName="chungus-provides",
               RelCondition="<=200")

        create(PackageRelation,
               Package=pkgname1,
               RelationType=relation_replaces,
               RelName="chungus-replaces",
               RelCondition="<=200")

        license = create(License, Name="GPL")

        create(PackageLicense,
               Package=pkgname1,
               License=license)

        for i in ["big-chungus", "smol-chungus", "sizeable-chungus"]:
            create(PackageKeyword,
                   PackageBase=pkgbase1,
                   Keyword=i)

        for i in [user1, user2, user3]:
            create(PackageVote,
                   User=i,
                   PackageBase=pkgbase1,
                   VoteTS=5000)

190
    scripts.popupdate.run_single(pkgbase1)
191

192

Kevin Morris's avatar
Kevin Morris committed
193
194
195
196
197
198
199
200
201
202
203
204
@pytest.fixture
def pipeline():
    redis = redis_connection()
    pipeline = redis.pipeline()

    pipeline.delete("ratelimit-ws:testclient")
    pipeline.delete("ratelimit:testclient")
    one, two = pipeline.execute()

    yield pipeline


205
def test_rpc_singular_info(client: TestClient):
206
207
    # Define expected response.
    expected_data = {
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
        "version": 5,
        "results": [{
            "Name": "big-chungus",
            "Version": "",
            "Description": "Bunny bunny around bunny",
            "URL": "https://example.com/",
            "PackageBase": "big-chungus",
            "NumVotes": 3,
            "Popularity": 0.0,
            "OutOfDate": None,
            "Maintainer": "user1",
            "URLPath": "/cgit/aur.git/snapshot/big-chungus.tar.gz",
            "Depends": ["chungus-depends"],
            "OptDepends": ["chungus-optdepends=50"],
            "MakeDepends": ["chungus-makedepends"],
            "CheckDepends": ["chungus-checkdepends"],
            "Conflicts": ["chungus-conflicts"],
            "Provides": ["chungus-provides<=200"],
            "Replaces": ["chungus-replaces<=200"],
            "License": ["GPL"],
            "Keywords": [
                "big-chungus",
                "sizeable-chungus",
                "smol-chungus"
            ]
        }],
        "resultcount": 1,
        "type": "multiinfo"
    }
237
238

    # Make dummy request.
239
240
241
    with client as request:
        response_arg = request.get(
            "/rpc/?v=5&type=info&arg=chungy-chungus&arg=big-chungus")
242
243
244
245
246
247
248
249
250
251
252
253
254
255

    # Load  request response into Python dictionary.
    response_info_arg = orjson.loads(response_arg.content.decode())

    # Remove the FirstSubmitted LastModified, ID and PackageBaseID keys from
    # reponse, as the key's values aren't guaranteed to match between the two
    # (the keys are already removed from 'expected_data').
    for i in ["FirstSubmitted", "LastModified", "ID", "PackageBaseID"]:
        response_info_arg["results"][0].pop(i)

    # Validate that the new dictionaries are the same.
    assert response_info_arg == expected_data


256
def test_rpc_nonexistent_package(client: TestClient):
257
    # Make dummy request.
258
259
    with client as request:
        response = request.get("/rpc/?v=5&type=info&arg=nonexistent-package")
260
261
262
263
264
265
266
267

    # Load request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert response_data["resultcount"] == 0


268
def test_rpc_multiinfo(client: TestClient):
269
270
    # Make dummy request.
    request_packages = ["big-chungus", "chungy-chungus"]
271
272
273
    with client as request:
        response = request.get(
            "/rpc/?v=5&type=info&arg[]=big-chungus&arg[]=chungy-chungus")
274
275
276
277
278
279
280
281
282
283
284

    # Load request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    for i in response_data["results"]:
        request_packages.remove(i["Name"])

    assert request_packages == []


285
def test_rpc_mixedargs(client: TestClient):
286
287
288
289
    # Make dummy request.
    response1_packages = ["gluggly-chungus"]
    response2_packages = ["gluggly-chungus", "chungy-chungus"]

290
291
292
293
294
295
296
297
298
    with client as request:
        response1 = request.get(
            "/rpc?v=5&arg[]=big-chungus&arg=gluggly-chungus&type=info")
    assert response1.status_code == int(HTTPStatus.OK)

    with client as request:
        response2 = request.get(
            "/rpc?v=5&arg=big-chungus&arg[]=gluggly-chungus&type=info&arg[]=chungy-chungus")
    assert response1.status_code == int(HTTPStatus.OK)
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314

    # Load request response into Python dictionary.
    response1_data = orjson.loads(response1.content.decode())
    response2_data = orjson.loads(response2.content.decode())

    # Validate data.
    for i in response1_data["results"]:
        response1_packages.remove(i["Name"])

    for i in response2_data["results"]:
        response2_packages.remove(i["Name"])

    for i in [response1_packages, response2_packages]:
        assert i == []


315
def test_rpc_no_dependencies(client: TestClient):
316
317
318
319
    """This makes sure things like 'MakeDepends' get removed from JSON strings
    when they don't have set values."""

    expected_response = {
320
321
322
323
324
325
326
        'version': 5,
        'results': [{
            'Name': 'chungy-chungus',
            'Version': '',
            'Description': 'Wubby wubby on wobba wuubu',
            'URL': 'https://example.com/',
            'PackageBase': 'chungy-chungus',
327
            'NumVotes': 0,
328
329
330
331
332
333
334
335
336
337
338
339
            'Popularity': 0.0,
            'OutOfDate': None,
            'Maintainer': 'user1',
            'URLPath': '/cgit/aur.git/snapshot/chungy-chungus.tar.gz',
            'Depends': ['chungy-depends'],
            'Conflicts': ['chungy-conflicts'],
            'License': [],
            'Keywords': []
        }],
        'resultcount': 1,
        'type': 'multiinfo'
    }
340
341

    # Make dummy request.
342
343
    with client as request:
        response = request.get("/rpc/?v=5&type=info&arg=chungy-chungus")
344
345
346
347
348
349
350
351
352
    response_data = orjson.loads(response.content.decode())

    # Remove inconsistent keys.
    for i in ["ID", "PackageBaseID", "FirstSubmitted", "LastModified"]:
        response_data["results"][0].pop(i)

    assert response_data == expected_response


353
def test_rpc_bad_type(client: TestClient):
354
355
    # Define expected response.
    expected_data = {
356
357
358
359
360
361
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'Incorrect request type specified.'
    }
362
363

    # Make dummy request.
364
365
    with client as request:
        response = request.get("/rpc/?v=5&type=invalid-type&arg=big-chungus")
366
367
368
369
370
371
372
373

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


374
def test_rpc_bad_version(client: TestClient):
375
    # Define expected response.
376
377
378
379
380
381
382
    expected_data = {
        'version': 0,
        'resultcount': 0,
        'results': [],
        'type': 'error',
        'error': 'Invalid version specified.'
    }
383
384

    # Make dummy request.
385
386
    with client as request:
        response = request.get("/rpc/?v=0&type=info&arg=big-chungus")
387
388
389
390
391
392
393
394

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


395
def test_rpc_no_version(client: TestClient):
396
    # Define expected response.
397
398
399
400
401
402
403
    expected_data = {
        'version': None,
        'resultcount': 0,
        'results': [],
        'type': 'error',
        'error': 'Please specify an API version.'
    }
404
405

    # Make dummy request.
406
407
    with client as request:
        response = request.get("/rpc/?type=info&arg=big-chungus")
408
409
410
411
412
413
414
415

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


416
def test_rpc_no_type(client: TestClient):
417
418
    # Define expected response.
    expected_data = {
419
420
421
422
423
424
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'No request type/data specified.'
    }
425
426

    # Make dummy request.
427
428
    with client as request:
        response = request.get("/rpc/?v=5&arg=big-chungus")
429
430
431
432
433
434
435
436

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


437
def test_rpc_no_args(client: TestClient):
438
439
    # Define expected response.
    expected_data = {
440
441
442
443
444
445
        'version': 5,
        'results': [],
        'resultcount': 0,
        'type': 'error',
        'error': 'No request type/data specified.'
    }
446
447

    # Make dummy request.
448
449
    with client as request:
        response = request.get("/rpc/?v=5&type=info")
450
451
452
453
454
455
456
457

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert expected_data == response_data


458
def test_rpc_no_maintainer(client: TestClient):
459
    # Make dummy request.
460
461
    with client as request:
        response = request.get("/rpc/?v=5&type=info&arg=woogly-chungus")
462
463
464
465
466
467

    # Load  request response into Python dictionary.
    response_data = orjson.loads(response.content.decode())

    # Validate data.
    assert response_data["results"][0]["Maintainer"] is None
468
469


470
471
472
def test_rpc_suggest_pkgbase(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")
473
474
475
    data = response.json()
    assert data == ["big-chungus"]

476
477
    with client as request:
        response = request.get("/rpc?v=5&type=suggest-pkgbase&arg=chungy")
478
479
    data = response.json()
    assert data == ["chungy-chungus"]
480

481
    # Test no arg supplied.
482
483
    with client as request:
        response = request.get("/rpc?v=5&type=suggest-pkgbase")
484
485
486
    data = response.json()
    assert data == []

487

488
489
490
def test_rpc_suggest(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=suggest&arg=other")
491
492
493
494
    data = response.json()
    assert data == ["other-pkg"]

    # Test non-existent Package.
495
496
    with client as request:
        response = request.get("/rpc?v=5&type=suggest&arg=nonexistent")
497
498
499
    data = response.json()
    assert data == []

500
    # Test no arg supplied.
501
502
    with client as request:
        response = request.get("/rpc?v=5&type=suggest")
503
504
505
    data = response.json()
    assert data == []

506

Kevin Morris's avatar
Kevin Morris committed
507
508
509
510
511
512
513
514
515
def mock_config_getint(section: str, key: str):
    if key == "request_limit":
        return 4
    elif key == "window_length":
        return 100
    return config.getint(section, key)


@mock.patch("aurweb.config.getint", side_effect=mock_config_getint)
516
517
def test_rpc_ratelimit(getint: mock.MagicMock, client: TestClient,
                       pipeline: Pipeline):
Kevin Morris's avatar
Kevin Morris committed
518
519
    for i in range(4):
        # The first 4 requests should be good.
520
521
        with client as request:
            response = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")
Kevin Morris's avatar
Kevin Morris committed
522
523
524
        assert response.status_code == int(HTTPStatus.OK)

    # The fifth request should be banned.
525
526
    with client as request:
        response = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")
Kevin Morris's avatar
Kevin Morris committed
527
528
529
530
531
532
533
534
535
    assert response.status_code == int(HTTPStatus.TOO_MANY_REQUESTS)

    # Delete the cached records.
    pipeline.delete("ratelimit-ws:testclient")
    pipeline.delete("ratelimit:testclient")
    one, two = pipeline.execute()
    assert one and two

    # The new first request should be good.
536
537
    with client as request:
        response = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")
Kevin Morris's avatar
Kevin Morris committed
538
    assert response.status_code == int(HTTPStatus.OK)
539
540


541
542
543
544
545
546
def test_rpc_etag(client: TestClient):
    with client as request:
        response1 = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")

    with client as request:
        response2 = request.get("/rpc?v=5&type=suggest-pkgbase&arg=big")
547
548
549
    assert response1.headers.get("ETag") is not None
    assert response1.headers.get("ETag") != str()
    assert response1.headers.get("ETag") == response2.headers.get("ETag")
550
551


552
553
554
def test_rpc_search_arg_too_small(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=search&arg=b")
555
556
557
558
    assert response.status_code == int(HTTPStatus.OK)
    assert response.json().get("error") == "Query arg too small."


559
560
561
def test_rpc_search(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=search&arg=big")
562
563
564
565
566
567
568
569
    assert response.status_code == int(HTTPStatus.OK)

    data = response.json()
    assert data.get("resultcount") == 1

    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"

570
571
572
    # Test the If-None-Match headers.
    etag = response.headers.get("ETag").strip('"')
    headers = {"If-None-Match": etag}
573
    response = request.get("/rpc?v=5&type=search&arg=big", headers=headers)
574
575
576
    assert response.status_code == int(HTTPStatus.NOT_MODIFIED)
    assert response.content == b''

577
    # No args on non-m by types return an error.
578
    response = request.get("/rpc?v=5&type=search")
579
580
581
    assert response.json().get("error") == "No request type/data specified."


582
583
584
def test_rpc_msearch(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=msearch&arg=user1")
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    data = response.json()

    # user1 maintains 4 packages; assert that we got them all.
    assert data.get("resultcount") == 4
    names = list(sorted(r.get("Name") for r in data.get("results")))
    expected_results = list(sorted([
        "big-chungus",
        "chungy-chungus",
        "gluggly-chungus",
        "other-pkg"
    ]))
    assert names == expected_results

    # Search for a non-existent maintainer, giving us zero packages.
599
    response = request.get("/rpc?v=5&type=msearch&arg=blah-blah")
600
601
602
603
604
    data = response.json()
    assert data.get("resultcount") == 0

    # A missing arg still succeeds, but it returns all orphans.
    # Just verify that we receive no error and the orphaned result.
605
    response = request.get("/rpc?v=5&type=msearch")
606
607
608
609
610
611
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "woogly-chungus"


612
613
614
615
def test_rpc_search_depends(client: TestClient):
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&by=depends&arg=chungus-depends")
616
617
618
619
620
621
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


622
623
624
625
def test_rpc_search_makedepends(client: TestClient):
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&by=makedepends&arg=chungus-makedepends")
626
627
628
629
630
631
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


632
633
634
635
def test_rpc_search_optdepends(client: TestClient):
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&by=optdepends&arg=chungus-optdepends")
636
637
638
639
640
641
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


642
643
644
645
def test_rpc_search_checkdepends(client: TestClient):
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&by=checkdepends&arg=chungus-checkdepends")
646
647
648
649
650
651
    data = response.json()
    assert data.get("resultcount") == 1
    result = data.get("results")[0]
    assert result.get("Name") == "big-chungus"


652
653
654
def test_rpc_incorrect_by(client: TestClient):
    with client as request:
        response = request.get("/rpc?v=5&type=search&by=fake&arg=big")
655
    assert response.json().get("error") == "Incorrect by field specified."
656
657


658
def test_rpc_jsonp_callback(client: TestClient):
659
660
661
662
663
    """ Test the callback parameter.

    For end-to-end verification, the `examples/jsonp.html` file can be
    used to submit jsonp callback requests to the RPC.
    """
664
665
666
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&arg=big&callback=jsonCallback")
667
668
    assert response.headers.get("content-type") == "text/javascript"
    assert re.search(r'^/\*\*/jsonCallback\(.*\)$', response.text) is not None
669
670

    # Test an invalid callback name; we get an application/json error.
671
672
673
    with client as request:
        response = request.get(
            "/rpc?v=5&type=search&arg=big&callback=jsonCallback!")
674
675
    assert response.headers.get("content-type") == "application/json"
    assert response.json().get("error") == "Invalid callback name."