-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtest_auth.py
More file actions
1243 lines (1010 loc) · 47.8 KB
/
test_auth.py
File metadata and controls
1243 lines (1010 loc) · 47.8 KB
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
"""Tests for authentication module."""
import json
from pathlib import Path
import pytest
from pytest_httpx import HTTPXMock
from notebooklm.auth import (
AuthTokens,
convert_rookiepy_cookies_to_storage_state,
extract_cookies_from_storage,
extract_csrf_from_html,
extract_session_id_from_html,
fetch_tokens,
load_auth_from_storage,
load_httpx_cookies,
)
class TestAuthTokens:
def test_dataclass_fields(self):
"""Test AuthTokens has required fields."""
tokens = AuthTokens(
cookies={"SID": "abc", "HSID": "def"},
csrf_token="csrf123",
session_id="sess456",
)
assert tokens.cookies == {"SID": "abc", "HSID": "def"}
assert tokens.csrf_token == "csrf123"
assert tokens.session_id == "sess456"
def test_cookie_header(self):
"""Test generating cookie header string."""
tokens = AuthTokens(
cookies={"SID": "abc", "HSID": "def"},
csrf_token="csrf123",
session_id="sess456",
)
header = tokens.cookie_header
assert "SID=abc" in header
assert "HSID=def" in header
def test_cookie_header_format(self):
"""Test cookie header uses semicolon separator."""
tokens = AuthTokens(
cookies={"A": "1", "B": "2"},
csrf_token="x",
session_id="y",
)
header = tokens.cookie_header
assert "; " in header
class TestExtractCookies:
def test_extracts_all_google_domain_cookies(self):
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_value", "domain": ".google.com"},
{"name": "HSID", "value": "hsid_value", "domain": ".google.com"},
{
"name": "__Secure-1PSID",
"value": "secure_value",
"domain": ".google.com",
},
{
"name": "OSID",
"value": "osid_value",
"domain": "notebooklm.google.com",
},
{
"name": "ACCOUNT_CHOOSER",
"value": "chooser_value",
"domain": "accounts.google.com",
},
{"name": "OTHER", "value": "other_value", "domain": "other.com"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == "sid_value"
assert cookies["HSID"] == "hsid_value"
assert cookies["__Secure-1PSID"] == "secure_value"
assert cookies["OSID"] == "osid_value"
assert cookies["ACCOUNT_CHOOSER"] == "chooser_value"
assert "OTHER" not in cookies
def test_raises_if_missing_sid(self):
storage_state = {
"cookies": [
{"name": "HSID", "value": "hsid_value", "domain": ".google.com"},
]
}
with pytest.raises(ValueError, match="Missing required cookies"):
extract_cookies_from_storage(storage_state)
def test_handles_empty_cookies_list(self):
"""Test handles empty cookies list."""
storage_state = {"cookies": []}
with pytest.raises(ValueError, match="Missing required cookies"):
extract_cookies_from_storage(storage_state)
def test_handles_missing_cookies_key(self):
"""Test handles missing cookies key."""
storage_state = {}
with pytest.raises(ValueError, match="Missing required cookies"):
extract_cookies_from_storage(storage_state)
class TestExtractCSRF:
def test_extracts_csrf_token(self):
"""Test extracting SNlM0e CSRF token from HTML."""
html = """
<script>window.WIZ_global_data = {
"SNlM0e": "AF1_QpN-xyz123",
"other": "value"
}</script>
"""
csrf = extract_csrf_from_html(html)
assert csrf == "AF1_QpN-xyz123"
def test_extracts_csrf_with_special_chars(self):
"""Test extracting CSRF token with special characters."""
html = '"SNlM0e":"AF1_QpN-abc_123/def"'
csrf = extract_csrf_from_html(html)
assert csrf == "AF1_QpN-abc_123/def"
def test_raises_if_not_found(self):
"""Test raises error if CSRF token not found."""
html = "<html><body>No token here</body></html>"
with pytest.raises(ValueError, match="CSRF token not found"):
extract_csrf_from_html(html)
def test_handles_empty_html(self):
"""Test handles empty HTML."""
with pytest.raises(ValueError, match="CSRF token not found"):
extract_csrf_from_html("")
class TestExtractSessionId:
def test_extracts_session_id(self):
"""Test extracting FdrFJe session ID from HTML."""
html = """
<script>window.WIZ_global_data = {
"FdrFJe": "session_id_abc",
"other": "value"
}</script>
"""
session_id = extract_session_id_from_html(html)
assert session_id == "session_id_abc"
def test_extracts_numeric_session_id(self):
"""Test extracting numeric session ID."""
html = '"FdrFJe":"1234567890123456"'
session_id = extract_session_id_from_html(html)
assert session_id == "1234567890123456"
def test_raises_if_not_found(self):
"""Test raises error if session ID not found."""
html = "<html><body>No session here</body></html>"
with pytest.raises(ValueError, match="Session ID not found"):
extract_session_id_from_html(html)
class TestLoadAuthFromStorage:
def test_loads_from_file(self, tmp_path):
"""Test loading auth from storage state file."""
storage_file = tmp_path / "storage_state.json"
storage_state = {
"cookies": [
{"name": "SID", "value": "sid", "domain": ".google.com"},
{"name": "HSID", "value": "hsid", "domain": ".google.com"},
{"name": "SSID", "value": "ssid", "domain": ".google.com"},
{"name": "APISID", "value": "apisid", "domain": ".google.com"},
{"name": "SAPISID", "value": "sapisid", "domain": ".google.com"},
]
}
storage_file.write_text(json.dumps(storage_state))
cookies = load_auth_from_storage(storage_file)
assert cookies["SID"] == "sid"
assert len(cookies) == 5
def test_raises_if_file_not_found(self, tmp_path):
"""Test raises error if storage file doesn't exist."""
with pytest.raises(FileNotFoundError):
load_auth_from_storage(tmp_path / "nonexistent.json")
def test_raises_if_invalid_json(self, tmp_path):
"""Test raises error if file contains invalid JSON."""
storage_file = tmp_path / "invalid.json"
storage_file.write_text("not valid json")
with pytest.raises(json.JSONDecodeError):
load_auth_from_storage(storage_file)
class TestLoadAuthFromEnvVar:
"""Test NOTEBOOKLM_AUTH_JSON env var support."""
def test_loads_from_env_var(self, tmp_path, monkeypatch):
"""Test loading auth from NOTEBOOKLM_AUTH_JSON env var."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_from_env", "domain": ".google.com"},
{"name": "HSID", "value": "hsid_from_env", "domain": ".google.com"},
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
cookies = load_auth_from_storage()
assert cookies["SID"] == "sid_from_env"
assert cookies["HSID"] == "hsid_from_env"
def test_explicit_path_takes_precedence_over_env_var(self, tmp_path, monkeypatch):
"""Test that explicit path argument overrides NOTEBOOKLM_AUTH_JSON."""
# Set env var
env_storage = {"cookies": [{"name": "SID", "value": "from_env", "domain": ".google.com"}]}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(env_storage))
# Create file with different value
file_storage = {"cookies": [{"name": "SID", "value": "from_file", "domain": ".google.com"}]}
storage_file = tmp_path / "storage_state.json"
storage_file.write_text(json.dumps(file_storage))
# Explicit path should win
cookies = load_auth_from_storage(storage_file)
assert cookies["SID"] == "from_file"
def test_env_var_invalid_json_raises_value_error(self, monkeypatch):
"""Test that invalid JSON in env var raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", "not valid json")
with pytest.raises(ValueError, match="Invalid JSON in NOTEBOOKLM_AUTH_JSON"):
load_auth_from_storage()
def test_env_var_missing_cookies_raises_value_error(self, monkeypatch):
"""Test that missing required cookies raises ValueError."""
storage_state = {"cookies": []} # No SID cookie
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
with pytest.raises(ValueError, match="Missing required cookies"):
load_auth_from_storage()
def test_env_var_takes_precedence_over_file(self, tmp_path, monkeypatch):
"""Test that NOTEBOOKLM_AUTH_JSON takes precedence over default file."""
# Set env var
env_storage = {"cookies": [{"name": "SID", "value": "from_env", "domain": ".google.com"}]}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(env_storage))
# Set NOTEBOOKLM_HOME to tmp_path and create a file there
monkeypatch.setenv("NOTEBOOKLM_HOME", str(tmp_path))
file_storage = {
"cookies": [{"name": "SID", "value": "from_home_file", "domain": ".google.com"}]
}
storage_file = tmp_path / "storage_state.json"
storage_file.write_text(json.dumps(file_storage))
# Env var should win over file (no explicit path)
cookies = load_auth_from_storage()
assert cookies["SID"] == "from_env"
def test_env_var_empty_string_raises_value_error(self, monkeypatch):
"""Test that empty string NOTEBOOKLM_AUTH_JSON raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", "")
with pytest.raises(
ValueError, match="NOTEBOOKLM_AUTH_JSON environment variable is set but empty"
):
load_auth_from_storage()
def test_env_var_whitespace_only_raises_value_error(self, monkeypatch):
"""Test that whitespace-only NOTEBOOKLM_AUTH_JSON raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", " \n\t ")
with pytest.raises(
ValueError, match="NOTEBOOKLM_AUTH_JSON environment variable is set but empty"
):
load_auth_from_storage()
def test_env_var_missing_cookies_key_raises_value_error(self, monkeypatch):
"""Test that NOTEBOOKLM_AUTH_JSON without 'cookies' key raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", '{"origins": []}')
with pytest.raises(
ValueError, match="must contain valid Playwright storage state with a 'cookies' key"
):
load_auth_from_storage()
def test_env_var_non_dict_raises_value_error(self, monkeypatch):
"""Test that non-dict NOTEBOOKLM_AUTH_JSON raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", '["not", "a", "dict"]')
with pytest.raises(
ValueError, match="must contain valid Playwright storage state with a 'cookies' key"
):
load_auth_from_storage()
class TestLoadHttpxCookiesWithEnvVar:
"""Test load_httpx_cookies with NOTEBOOKLM_AUTH_JSON env var."""
def test_loads_cookies_from_env_var(self, monkeypatch):
"""Test loading httpx cookies from NOTEBOOKLM_AUTH_JSON env var."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_val", "domain": ".google.com"},
{"name": "HSID", "value": "hsid_val", "domain": ".google.com"},
{"name": "SSID", "value": "ssid_val", "domain": ".google.com"},
{"name": "APISID", "value": "apisid_val", "domain": ".google.com"},
{"name": "SAPISID", "value": "sapisid_val", "domain": ".google.com"},
{"name": "__Secure-1PSID", "value": "psid1_val", "domain": ".google.com"},
{"name": "__Secure-3PSID", "value": "psid3_val", "domain": ".google.com"},
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
cookies = load_httpx_cookies()
# Verify cookies were loaded
assert cookies.get("SID", domain=".google.com") == "sid_val"
assert cookies.get("HSID", domain=".google.com") == "hsid_val"
assert cookies.get("__Secure-1PSID", domain=".google.com") == "psid1_val"
def test_env_var_invalid_json_raises(self, monkeypatch):
"""Test that invalid JSON in NOTEBOOKLM_AUTH_JSON raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", "not valid json")
with pytest.raises(ValueError, match="Invalid JSON in NOTEBOOKLM_AUTH_JSON"):
load_httpx_cookies()
def test_env_var_empty_string_raises(self, monkeypatch):
"""Test that empty string NOTEBOOKLM_AUTH_JSON raises ValueError."""
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", "")
with pytest.raises(
ValueError, match="NOTEBOOKLM_AUTH_JSON environment variable is set but empty"
):
load_httpx_cookies()
def test_env_var_missing_required_cookies_raises(self, monkeypatch):
"""Test that missing required cookies raises ValueError."""
storage_state = {
"cookies": [
# SID is the minimum required cookie - omitting it should raise
{"name": "HSID", "value": "hsid_val", "domain": ".google.com"},
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
with pytest.raises(ValueError, match="Missing required cookies for downloads"):
load_httpx_cookies()
def test_env_var_filters_non_google_domains(self, monkeypatch):
"""Test that cookies from non-Google domains are filtered out."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_val", "domain": ".google.com"},
{"name": "HSID", "value": "hsid_val", "domain": ".google.com"},
{"name": "SSID", "value": "ssid_val", "domain": ".google.com"},
{"name": "APISID", "value": "apisid_val", "domain": ".google.com"},
{"name": "SAPISID", "value": "sapisid_val", "domain": ".google.com"},
{"name": "__Secure-1PSID", "value": "psid1_val", "domain": ".google.com"},
{"name": "__Secure-3PSID", "value": "psid3_val", "domain": ".google.com"},
{"name": "evil_cookie", "value": "evil_val", "domain": ".evil.com"},
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
cookies = load_httpx_cookies()
# Google cookies should be present
assert cookies.get("SID", domain=".google.com") == "sid_val"
# Non-Google cookies should be filtered out
assert cookies.get("evil_cookie", domain=".evil.com") is None
def test_env_var_missing_cookies_key_raises(self, monkeypatch):
"""Test that storage state without cookies key raises ValueError."""
storage_state = {"origins": []} # Valid JSON but no cookies key
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
with pytest.raises(ValueError, match="must contain valid Playwright storage state"):
load_httpx_cookies()
def test_env_var_malformed_cookie_objects_skipped(self, monkeypatch):
"""Test that malformed cookie objects are skipped gracefully."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_val", "domain": ".google.com"}, # Valid
{"name": "HSID"}, # Missing value and domain - should be skipped
{"value": "val"}, # Missing name - should be skipped
{}, # Empty object - should be skipped
{"name": "", "value": "val", "domain": ".google.com"}, # Empty name - skipped
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(storage_state))
# Should load successfully but only include valid SID cookie
cookies = load_httpx_cookies()
assert cookies.get("SID", domain=".google.com") == "sid_val"
def test_explicit_path_overrides_env_var(self, tmp_path, monkeypatch):
"""Test that explicit path argument takes precedence over NOTEBOOKLM_AUTH_JSON."""
# Set env var with one value
env_storage = {
"cookies": [
{"name": "SID", "value": "from_env", "domain": ".google.com"},
]
}
monkeypatch.setenv("NOTEBOOKLM_AUTH_JSON", json.dumps(env_storage))
# Create file with different value
file_storage = {
"cookies": [
{"name": "SID", "value": "from_file", "domain": ".google.com"},
]
}
storage_file = tmp_path / "storage_state.json"
storage_file.write_text(json.dumps(file_storage))
# Explicit path should win
cookies = load_httpx_cookies(path=storage_file)
assert cookies.get("SID", domain=".google.com") == "from_file"
class TestExtractCSRFRedirect:
"""Test CSRF extraction redirect detection."""
def test_raises_on_redirect_to_accounts_in_url(self):
"""Test raises error when redirected to accounts.google.com (URL)."""
html = "<html><body>Login page</body></html>"
final_url = "https://accounts.google.com/signin"
with pytest.raises(ValueError, match="Authentication expired"):
extract_csrf_from_html(html, final_url)
def test_raises_on_redirect_to_accounts_in_html(self):
"""Test raises error when redirected to accounts.google.com (HTML content)."""
html = '<html><body><a href="https://accounts.google.com/signin">Sign in</a></body></html>'
with pytest.raises(ValueError, match="Authentication expired"):
extract_csrf_from_html(html)
class TestExtractSessionIdRedirect:
"""Test session ID extraction redirect detection."""
def test_raises_on_redirect_to_accounts_in_url(self):
"""Test raises error when redirected to accounts.google.com (URL)."""
html = "<html><body>Login page</body></html>"
final_url = "https://accounts.google.com/signin"
with pytest.raises(ValueError, match="Authentication expired"):
extract_session_id_from_html(html, final_url)
def test_raises_on_redirect_to_accounts_in_html(self):
"""Test raises error when redirected to accounts.google.com (HTML content)."""
html = '<html><body><a href="https://accounts.google.com/signin">Sign in</a></body></html>'
with pytest.raises(ValueError, match="Authentication expired"):
extract_session_id_from_html(html)
class TestExtractCookiesEdgeCases:
"""Test cookie extraction edge cases."""
def test_skips_cookies_without_name(self):
"""Test skips cookies without a name field."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_value", "domain": ".google.com"},
{"value": "no_name_value", "domain": ".google.com"}, # Missing name
{"name": "", "value": "empty_name", "domain": ".google.com"}, # Empty name
]
}
cookies = extract_cookies_from_storage(storage_state)
assert "SID" in cookies
assert len(cookies) == 1 # Only SID should be extracted
def test_handles_cookie_with_empty_value(self):
"""Test handles cookies with empty values."""
storage_state = {
"cookies": [
{"name": "SID", "value": "", "domain": ".google.com"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == ""
class TestFetchTokens:
"""Test fetch_tokens function with mocked HTTP."""
@pytest.mark.asyncio
async def test_fetch_tokens_success(self, httpx_mock: HTTPXMock):
"""Test successful token fetch."""
html = """
<html>
<script>
window.WIZ_global_data = {
"SNlM0e": "AF1_QpN-csrf_token_123",
"FdrFJe": "session_id_456"
};
</script>
</html>
"""
httpx_mock.add_response(
url="https://notebooklm.google.com/",
content=html.encode(),
)
cookies = {"SID": "test_sid"}
csrf, session_id = await fetch_tokens(cookies)
assert csrf == "AF1_QpN-csrf_token_123"
assert session_id == "session_id_456"
@pytest.mark.asyncio
async def test_fetch_tokens_redirect_to_login(self, httpx_mock: HTTPXMock):
"""Test raises error when redirected to login page."""
httpx_mock.add_response(
url="https://notebooklm.google.com/",
status_code=302,
headers={"Location": "https://accounts.google.com/signin"},
)
httpx_mock.add_response(
url="https://accounts.google.com/signin",
content=b"<html>Login</html>",
)
cookies = {"SID": "expired_sid"}
with pytest.raises(ValueError, match="Authentication expired"):
await fetch_tokens(cookies)
@pytest.mark.asyncio
async def test_fetch_tokens_includes_cookie_jar_cookies(self, httpx_mock: HTTPXMock):
"""Test that fetch_tokens sends cookies via the client cookie jar."""
html = '"SNlM0e":"csrf" "FdrFJe":"sess"'
httpx_mock.add_response(content=html.encode())
cookies = {"SID": "sid_value", "HSID": "hsid_value"}
await fetch_tokens(cookies)
request = httpx_mock.get_request()
cookie_header = request.headers.get("cookie", "")
assert "SID=sid_value" in cookie_header
assert "HSID=hsid_value" in cookie_header
class TestAuthTokensFromStorage:
"""Test AuthTokens.from_storage class method."""
@pytest.mark.asyncio
async def test_from_storage_success(self, tmp_path, httpx_mock: HTTPXMock):
"""Test loading AuthTokens from storage file."""
# Create storage file
storage_file = tmp_path / "storage_state.json"
storage_state = {
"cookies": [
{"name": "SID", "value": "sid", "domain": ".google.com"},
]
}
storage_file.write_text(json.dumps(storage_state))
# Mock token fetch
html = '"SNlM0e":"csrf_token" "FdrFJe":"session_id"'
httpx_mock.add_response(content=html.encode())
tokens = await AuthTokens.from_storage(storage_file)
assert tokens.cookies["SID"] == "sid"
assert tokens.csrf_token == "csrf_token"
assert tokens.session_id == "session_id"
@pytest.mark.asyncio
async def test_from_storage_file_not_found(self, tmp_path):
"""Test raises error when storage file doesn't exist."""
with pytest.raises(FileNotFoundError):
await AuthTokens.from_storage(tmp_path / "nonexistent.json")
# =============================================================================
# COOKIE DOMAIN VALIDATION TESTS
# =============================================================================
class TestIsAllowedCookieDomain:
"""Test cookie domain validation security."""
def test_accepts_exact_matches_from_allowlist(self):
"""Test accepts domains in ALLOWED_COOKIE_DOMAINS."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain(".google.com") is True
assert _is_allowed_cookie_domain("notebooklm.google.com") is True
assert _is_allowed_cookie_domain(".googleusercontent.com") is True
def test_accepts_valid_google_subdomains(self):
"""Test accepts legitimate Google subdomains."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain("lh3.google.com") is True
assert _is_allowed_cookie_domain("accounts.google.com") is True
assert _is_allowed_cookie_domain("www.google.com") is True
def test_accepts_googleusercontent_subdomains(self):
"""Test accepts googleusercontent.com subdomains."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain("lh3.googleusercontent.com") is True
assert _is_allowed_cookie_domain("drum.usercontent.google.com") is True
def test_rejects_malicious_lookalike_domains(self):
"""Test rejects domains like 'evil-google.com' that end with google.com."""
from notebooklm.auth import _is_allowed_cookie_domain
# These domains end with ".google.com" but are NOT subdomains
assert _is_allowed_cookie_domain("evil-google.com") is False
assert _is_allowed_cookie_domain("malicious-google.com") is False
assert _is_allowed_cookie_domain("fakegoogle.com") is False
def test_rejects_fake_googleusercontent_domains(self):
"""Test rejects fake googleusercontent domains."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain("evil-googleusercontent.com") is False
assert _is_allowed_cookie_domain("fakegoogleusercontent.com") is False
def test_rejects_unrelated_domains(self):
"""Test rejects completely unrelated domains."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain("example.com") is False
assert _is_allowed_cookie_domain("evil.com") is False
assert _is_allowed_cookie_domain("google.evil.com") is False
# =============================================================================
# CONSTANT TESTS
# =============================================================================
class TestDefaultStoragePath:
"""Test default storage path constant (deprecated, now via __getattr__)."""
def test_default_storage_path_via_package(self):
"""Test DEFAULT_STORAGE_PATH is available via notebooklm package with deprecation warning."""
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
from notebooklm import DEFAULT_STORAGE_PATH
assert DEFAULT_STORAGE_PATH is not None
assert isinstance(DEFAULT_STORAGE_PATH, Path)
assert DEFAULT_STORAGE_PATH.name == "storage_state.json"
# Should have emitted a deprecation warning
deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)]
assert len(deprecation_warnings) >= 1
assert "deprecated" in str(deprecation_warnings[0].message).lower()
class TestMinimumRequiredCookies:
"""Test minimum required cookies constant."""
def test_minimum_required_cookies_contains_sid(self):
"""Test MINIMUM_REQUIRED_COOKIES contains SID."""
from notebooklm.auth import MINIMUM_REQUIRED_COOKIES
assert "SID" in MINIMUM_REQUIRED_COOKIES
class TestAllowedCookieDomains:
"""Test allowed cookie domains constant."""
def test_allowed_cookie_domains(self):
"""Test ALLOWED_COOKIE_DOMAINS contains expected domains."""
from notebooklm.auth import ALLOWED_COOKIE_DOMAINS
assert ".google.com" in ALLOWED_COOKIE_DOMAINS
assert "notebooklm.google.com" in ALLOWED_COOKIE_DOMAINS
# =============================================================================
# REGIONAL GOOGLE DOMAIN TESTS (Issue #20 fix)
# =============================================================================
class TestIsGoogleDomain:
"""Test the unified _is_google_domain function (whitelist approach)."""
@pytest.mark.parametrize(
"domain,expected",
[
# Base Google domain
(".google.com", True),
# .google.com.XX pattern (country-code second-level domains)
(".google.com.sg", True), # Singapore
(".google.com.au", True), # Australia
(".google.com.br", True), # Brazil
(".google.com.hk", True), # Hong Kong
(".google.com.tw", True), # Taiwan
(".google.com.mx", True), # Mexico
(".google.com.ar", True), # Argentina
(".google.com.tr", True), # Turkey
(".google.com.ua", True), # Ukraine
# .google.co.XX pattern (countries using .co)
(".google.co.uk", True), # United Kingdom
(".google.co.jp", True), # Japan
(".google.co.in", True), # India
(".google.co.kr", True), # South Korea
(".google.co.za", True), # South Africa
(".google.co.nz", True), # New Zealand
(".google.co.id", True), # Indonesia
(".google.co.th", True), # Thailand
# .google.XX pattern (single ccTLD)
(".google.cn", True), # China
(".google.de", True), # Germany
(".google.fr", True), # France
(".google.it", True), # Italy
(".google.es", True), # Spain
(".google.nl", True), # Netherlands
(".google.pl", True), # Poland
(".google.ru", True), # Russia
(".google.ca", True), # Canada
(".google.cat", True), # Catalonia (3-letter special case)
# Invalid domains that should be rejected
(".google.zz", False), # Invalid ccTLD
(".google.xyz", False), # Not in whitelist
(".google.com.fake", False), # Not in whitelist
(".notgoogle.com", False),
(".evil-google.com", False),
("google.com", False), # Missing leading dot
("google.com.sg", False), # Missing leading dot
(".youtube.com", False),
(".google.", False), # Incomplete
("", False), # Empty
],
)
def test_is_google_domain(self, domain, expected):
"""Test _is_google_domain with various domain patterns."""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is expected
@pytest.mark.parametrize(
"domain",
[
# Case sensitivity - cookie domains per RFC should be lowercase
".GOOGLE.COM",
".Google.Com",
".google.COM.SG",
".GOOGLE.CO.UK",
".GOOGLE.DE",
],
)
def test_rejects_uppercase_domains(self, domain):
"""Test that uppercase domains are rejected (case-sensitive matching).
Per RFC 6265, cookie domains SHOULD be lowercase. Playwright and browsers
normalize domains to lowercase, so we don't need case-insensitive matching.
"""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is False
@pytest.mark.parametrize(
"domain",
[
" .google.com", # Leading space
".google.com ", # Trailing space
"\t.google.com", # Tab
".google.com\n", # Newline
],
)
def test_rejects_domains_with_whitespace(self, domain):
"""Test that domains with whitespace are rejected."""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is False
@pytest.mark.parametrize(
"domain",
[
".google..com", # Double dot
"..google.com", # Leading double dot
".google.com.", # Trailing dot
],
)
def test_rejects_malformed_domains(self, domain):
"""Test that malformed domains with extra dots are rejected."""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is False
@pytest.mark.parametrize(
"domain",
[
# Subdomains are not matched by _is_google_domain
"accounts.google.com",
"lh3.google.com",
"accounts.google.de", # Subdomain of regional
"lh3.google.co.uk", # Subdomain of regional
".accounts.google.de", # With leading dot
],
)
def test_rejects_subdomains(self, domain):
"""Test that subdomains are rejected by _is_google_domain.
_is_google_domain only matches domain-level cookies (with leading dot).
Subdomain matching is handled by _is_allowed_cookie_domain's suffix matching.
"""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is False
@pytest.mark.parametrize(
"domain",
[
".google.com.sg.fake", # Extra suffix
".fake.google.com.sg", # Prefix on regional
".google.com.sgx", # Extended TLD
".google.co.ukx", # Extended co.XX
".google.dex", # Extended ccTLD
],
)
def test_rejects_suffix_exploits(self, domain):
"""Test that attempts to exploit suffix matching are rejected."""
from notebooklm.auth import _is_google_domain
assert _is_google_domain(domain) is False
class TestIsAllowedAuthDomain:
"""Test auth cookie domain validation including regional Google domains."""
def test_accepts_primary_google_domains(self):
"""Test accepts domains in ALLOWED_COOKIE_DOMAINS."""
from notebooklm.auth import _is_allowed_auth_domain
assert _is_allowed_auth_domain(".google.com") is True
assert _is_allowed_auth_domain("notebooklm.google.com") is True
assert _is_allowed_auth_domain(".googleusercontent.com") is True
def test_accepts_all_regional_patterns(self):
"""Test accepts all three regional Google domain patterns (Issue #20)."""
from notebooklm.auth import _is_allowed_auth_domain
# .google.com.XX pattern
assert _is_allowed_auth_domain(".google.com.sg") is True # Singapore
assert _is_allowed_auth_domain(".google.com.au") is True # Australia
# .google.co.XX pattern
assert _is_allowed_auth_domain(".google.co.uk") is True # UK
assert _is_allowed_auth_domain(".google.co.jp") is True # Japan
# .google.XX pattern
assert _is_allowed_auth_domain(".google.de") is True # Germany
assert _is_allowed_auth_domain(".google.fr") is True # France
def test_rejects_unrelated_domains(self):
"""Test rejects non-Google domains."""
from notebooklm.auth import _is_allowed_auth_domain
assert _is_allowed_auth_domain(".youtube.com") is False
assert _is_allowed_auth_domain("evil.com") is False
assert _is_allowed_auth_domain(".evil-google.com") is False
def test_rejects_malicious_google_lookalikes(self):
"""Test rejects domains that look like Google but aren't."""
from notebooklm.auth import _is_allowed_auth_domain
assert _is_allowed_auth_domain("google.com.evil.sg") is False
assert _is_allowed_auth_domain(".not-google.com.sg") is False
assert _is_allowed_auth_domain(".google.zz") is False # Invalid ccTLD
def test_requires_leading_dot_for_regional(self):
"""Test regional domains must have leading dot."""
from notebooklm.auth import _is_allowed_auth_domain
assert _is_allowed_auth_domain("google.com.sg") is False
assert _is_allowed_auth_domain("google.co.uk") is False
assert _is_allowed_auth_domain("google.de") is False
class TestIsAllowedCookieDomainRegional:
"""Test _is_allowed_cookie_domain with regional Google domains."""
def test_accepts_regional_google_domains_for_downloads(self):
"""Test that download cookie validation accepts regional domains."""
from notebooklm.auth import _is_allowed_cookie_domain
# .google.com.XX pattern
assert _is_allowed_cookie_domain(".google.com.sg") is True
assert _is_allowed_cookie_domain(".google.com.au") is True
# .google.co.XX pattern
assert _is_allowed_cookie_domain(".google.co.uk") is True
assert _is_allowed_cookie_domain(".google.co.jp") is True
# .google.XX pattern
assert _is_allowed_cookie_domain(".google.de") is True
assert _is_allowed_cookie_domain(".google.fr") is True
def test_still_accepts_subdomains(self):
"""Test that subdomain suffix matching still works."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain("lh3.google.com") is True
assert _is_allowed_cookie_domain("accounts.google.com") is True
assert _is_allowed_cookie_domain("lh3.googleusercontent.com") is True
def test_rejects_invalid_domains(self):
"""Test rejects invalid domains."""
from notebooklm.auth import _is_allowed_cookie_domain
assert _is_allowed_cookie_domain(".google.zz") is False
assert _is_allowed_cookie_domain("evil-google.com") is False
assert _is_allowed_cookie_domain(".youtube.com") is False
class TestExtractCookiesRegionalDomains:
"""Test cookie extraction from regional Google domains (Issue #20, #27)."""
@pytest.mark.parametrize(
"domain,sid_value,description",
[
(".google.com.sg", "sid_from_singapore", "Issue #20 - Singapore"),
(".google.cn", "sid_from_china", "Issue #27 - China"),
(".google.co.uk", "sid_from_uk", "UK regional domain"),
(".google.de", "sid_from_de", "Germany regional domain"),
],
)
def test_extracts_sid_from_regional_domain(self, domain, sid_value, description):
"""Test extracts SID cookie from regional Google domains."""
storage_state = {
"cookies": [
{"name": "SID", "value": sid_value, "domain": domain},
{"name": "OSID", "value": "osid_value", "domain": "notebooklm.google.com"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == sid_value
assert cookies["OSID"] == "osid_value"
def test_extracts_sid_from_all_regional_patterns(self):
"""Test extracts SID from all three regional domain patterns."""
# Test .google.com.XX
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_sg", "domain": ".google.com.sg"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == "sid_sg"
# Test .google.co.XX
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_uk", "domain": ".google.co.uk"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == "sid_uk"
# Test .google.XX
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_de", "domain": ".google.de"},
]
}
cookies = extract_cookies_from_storage(storage_state)
assert cookies["SID"] == "sid_de"
def test_extracts_multiple_regional_cookies(self):
"""Test extracts cookies from multiple regional domains."""
storage_state = {
"cookies": [
{"name": "SID", "value": "sid_au", "domain": ".google.com.au"},
{"name": "HSID", "value": "hsid_jp", "domain": ".google.co.jp"},
{"name": "SSID", "value": "ssid_de", "domain": ".google.de"},
]
}