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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
|
import urllib.parse
import time
import warnings
import pprint
from openid.message import Message, OPENID_NS, OPENID2_NS, IDENTIFIER_SELECT, \
OPENID1_NS, BARE_NS
from openid import cryptutil, oidutil, kvform
from openid.store.nonce import mkNonce, split as splitNonce
from openid.consumer.discover import OpenIDServiceEndpoint, OPENID_2_0_TYPE, \
OPENID_1_1_TYPE
from openid.consumer.consumer import \
AuthRequest, GenericConsumer, SUCCESS, FAILURE, CANCEL, SETUP_NEEDED, \
SuccessResponse, FailureResponse, SetupNeededResponse, CancelResponse, \
DiffieHellmanSHA1ConsumerSession, Consumer, PlainTextConsumerSession, \
SetupNeededError, DiffieHellmanSHA256ConsumerSession, ServerError, \
ProtocolError, _httpResponseToMessage
from openid import association
from openid.server.server import \
PlainTextServerSession, DiffieHellmanSHA1ServerSession
from openid.yadis.manager import Discovery
from openid.yadis.discover import DiscoveryFailure
from openid.dh import DiffieHellman
from openid.fetchers import HTTPResponse, HTTPFetchingError
from openid import fetchers
from openid.store import memstore
from .support import CatchLogs
assocs = [
('another 20-byte key.', 'Snarky'),
('\x00' * 20, 'Zeros'),
]
def mkSuccess(endpoint, q):
"""Convenience function to create a SuccessResponse with the given
arguments, all signed."""
signed_list = ['openid.' + k for k in list(q.keys())]
return SuccessResponse(endpoint, Message.fromOpenIDArgs(q), signed_list)
def parseQuery(qs):
q = {}
for (k, v) in urllib.parse.parse_qsl(qs):
assert k not in q
q[k] = v
return q
def associate(qs, assoc_secret, assoc_handle):
"""Do the server's half of the associate call, using the given
secret and handle."""
q = parseQuery(qs)
assert q['openid.mode'] == 'associate'
assert q['openid.assoc_type'] == 'HMAC-SHA1'
reply_dict = {
'assoc_type': 'HMAC-SHA1',
'assoc_handle': assoc_handle,
'expires_in': '600',
}
if q.get('openid.session_type') == 'DH-SHA1':
assert len(q) == 6 or len(q) == 4
message = Message.fromPostArgs(q)
session = DiffieHellmanSHA1ServerSession.fromMessage(message)
reply_dict['session_type'] = 'DH-SHA1'
else:
assert len(q) == 2
session = PlainTextServerSession.fromQuery(q)
reply_dict.update(session.answer(assoc_secret))
return kvform.dictToKV(reply_dict)
GOODSIG = "[A Good Signature]"
class GoodAssociation:
expiresIn = 3600
handle = "-blah-"
def checkMessageSignature(self, message):
return message.getArg(OPENID_NS, 'sig') == GOODSIG
class GoodAssocStore(memstore.MemoryStore):
def getAssociation(self, server_url, handle=None):
return GoodAssociation()
class TestFetcher(object):
def __init__(self, user_url, user_page, xxx_todo_changeme):
(assoc_secret, assoc_handle) = xxx_todo_changeme
self.get_responses = {
user_url: self.response(user_url, 200, user_page)
}
self.assoc_secret = assoc_secret
self.assoc_handle = assoc_handle
self.num_assocs = 0
def response(self, url, status, body):
return HTTPResponse(
final_url=url, status=status, headers={}, body=body)
def fetch(self, url, body=None, headers=None):
if body is None:
if url in self.get_responses:
return self.get_responses[url]
else:
try:
body.index('openid.mode=associate')
except ValueError:
pass # fall through
else:
assert body.find('DH-SHA1') != -1
response = associate(
body, self.assoc_secret, self.assoc_handle)
self.num_assocs += 1
return self.response(url, 200, response)
return self.response(url, 404, 'Not found')
def makeFastConsumerSession():
"""
Create custom DH object so tests run quickly.
"""
dh = DiffieHellman(100389557, 2)
return DiffieHellmanSHA1ConsumerSession(dh)
def setConsumerSession(con):
con.session_types = {'DH-SHA1': makeFastConsumerSession}
def _test_success(server_url, user_url, delegate_url, links, immediate=False):
if isinstance(server_url, bytes):
server_url = str(server_url, encoding="utf-8")
if isinstance(user_url, bytes):
user_url = str(user_url, encoding="utf-8")
if isinstance(delegate_url, bytes):
delegate_url = str(delegate_url, encoding="utf-8")
if isinstance(links, bytes):
links = str(links, encoding="utf-8")
store = memstore.MemoryStore()
if immediate:
mode = 'checkid_immediate'
else:
mode = 'checkid_setup'
endpoint = OpenIDServiceEndpoint()
endpoint.claimed_id = user_url
endpoint.server_url = server_url
endpoint.local_id = delegate_url
endpoint.type_uris = [OPENID_1_1_TYPE]
fetcher = TestFetcher(None, None, assocs[0])
fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)
def run():
trust_root = str(consumer_url, encoding="utf-8")
consumer = GenericConsumer(store)
setConsumerSession(consumer)
request = consumer.begin(endpoint)
return_to = str(consumer_url, encoding="utf-8")
m = request.getMessage(trust_root, return_to, immediate)
redirect_url = request.redirectURL(trust_root, return_to, immediate)
if isinstance(redirect_url, bytes):
redirect_url = str(redirect_url, encoding="utf-8")
parsed = urllib.parse.urlparse(redirect_url)
qs = parsed[4]
q = parseQuery(qs)
new_return_to = q['openid.return_to']
del q['openid.return_to']
expected = {
'openid.mode': mode,
'openid.identity': delegate_url,
'openid.trust_root': trust_root,
'openid.assoc_handle': fetcher.assoc_handle,
}
assert q == expected, pprint.pformat((q, expected))
# (q, user_url, delegate_url, mode, expected)
assert new_return_to.startswith(return_to)
assert redirect_url.startswith(server_url)
parsed = urllib.parse.urlparse(new_return_to)
query = parseQuery(parsed[4])
query.update({
'openid.mode': 'id_res',
'openid.return_to': new_return_to,
'openid.identity': delegate_url,
'openid.assoc_handle': fetcher.assoc_handle,
})
assoc = store.getAssociation(server_url, fetcher.assoc_handle)
message = Message.fromPostArgs(query)
message = assoc.signMessage(message)
info = consumer.complete(message, request.endpoint, new_return_to)
assert info.status == SUCCESS, info.message
assert info.identity_url == user_url
assert fetcher.num_assocs == 0
run()
assert fetcher.num_assocs == 1
# Test that doing it again uses the existing association
run()
assert fetcher.num_assocs == 1
# Another association is created if we remove the existing one
store.removeAssociation(server_url, fetcher.assoc_handle)
run()
assert fetcher.num_assocs == 2
# Test that doing it again uses the existing association
run()
assert fetcher.num_assocs == 2
import unittest
http_server_url = b'http://server.example.com/'
consumer_url = b'http://consumer.example.com/'
https_server_url = b'https://server.example.com/'
class TestSuccess(unittest.TestCase, CatchLogs):
server_url = http_server_url
user_url = b'http://www.example.com/user.html'
delegate_url = b'http://consumer.example.com/user'
def setUp(self):
CatchLogs.setUp(self)
self.links = '<link rel="openid.server" href="%s" />' % (
self.server_url,)
self.delegate_links = ('<link rel="openid.server" href="%s" />'
'<link rel="openid.delegate" href="%s" />') % (
self.server_url, self.delegate_url)
def tearDown(self):
CatchLogs.tearDown(self)
def test_nodelegate(self):
_test_success(self.server_url, self.user_url,
self.user_url, self.links)
def test_nodelegateImmediate(self):
_test_success(self.server_url, self.user_url,
self.user_url, self.links, True)
def test_delegate(self):
_test_success(self.server_url, self.user_url,
self.delegate_url, self.delegate_links)
def test_delegateImmediate(self):
_test_success(self.server_url, self.user_url,
self.delegate_url, self.delegate_links, True)
class TestSuccessHTTPS(TestSuccess):
server_url = https_server_url
class TestConstruct(unittest.TestCase):
def setUp(self):
self.store_sentinel = object()
def test_construct(self):
oidc = GenericConsumer(self.store_sentinel)
self.assertTrue(oidc.store is self.store_sentinel)
def test_nostore(self):
self.assertRaises(TypeError, GenericConsumer)
class TestIdRes(unittest.TestCase, CatchLogs):
consumer_class = GenericConsumer
def setUp(self):
CatchLogs.setUp(self)
self.store = memstore.MemoryStore()
self.consumer = self.consumer_class(self.store)
self.return_to = "nonny"
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.claimed_id = self.consumer_id = "consu"
self.endpoint.server_url = self.server_url = "serlie"
self.endpoint.local_id = self.server_id = "sirod"
self.endpoint.type_uris = [OPENID_1_1_TYPE]
def disableDiscoveryVerification(self):
"""Set the discovery verification to a no-op for test cases in
which we don't care."""
def dummyVerifyDiscover(_, endpoint):
return endpoint
self.consumer._verifyDiscoveryResults = dummyVerifyDiscover
def disableReturnToChecking(self):
def checkReturnTo(unused1, unused2):
return True
self.consumer._checkReturnTo = checkReturnTo
complete = self.consumer.complete
def callCompleteWithoutReturnTo(message, endpoint):
return complete(message, endpoint, None)
self.consumer.complete = callCompleteWithoutReturnTo
class TestIdResCheckSignature(TestIdRes):
def setUp(self):
TestIdRes.setUp(self)
self.assoc = GoodAssociation()
self.assoc.handle = "{not_dumb}"
self.store.storeAssociation(self.endpoint.server_url, self.assoc)
self.message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.identity': '=example',
'openid.sig': GOODSIG,
'openid.assoc_handle': self.assoc.handle,
'openid.signed': 'mode,identity,assoc_handle,signed',
'frobboz': 'banzit',
})
def test_sign(self):
# assoc_handle to assoc with good sig
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_signFailsWithBadSig(self):
self.message.setArg(OPENID_NS, 'sig', 'BAD SIGNATURE')
self.assertRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
def test_stateless(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._processCheckAuthResponse = (
lambda response, server_url: True)
self.consumer._makeKVPost = lambda args, server_url: {}
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_statelessRaisesError(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._checkAuth = lambda unused1, unused2: False
self.assertRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
def test_stateless_noStore(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer.store = None
self.consumer._processCheckAuthResponse = (
lambda response, server_url: True)
self.consumer._makeKVPost = lambda args, server_url: {}
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_statelessRaisesError_noStore(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._checkAuth = lambda unused1, unused2: False
self.consumer.store = None
self.assertRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
class TestQueryFormat(TestIdRes):
def test_notAList(self):
# XXX: should be a Message object test, not a consumer test
# Value should be a single string. If it's a list, it should generate
# an exception.
query = {'openid.mode': ['cancel']}
try:
r = Message.fromPostArgs(query)
except TypeError as err:
self.assertTrue(str(err).find('values') != -1, err)
else:
self.fail("expected TypeError, got this instead: %s" % (r,))
class TestComplete(TestIdRes):
"""Testing GenericConsumer.complete.
Other TestIdRes subclasses test more specific aspects.
"""
def test_setupNeededIdRes(self):
message = Message.fromOpenIDArgs({'mode': 'id_res'})
setup_url_sentinel = object()
def raiseSetupNeeded(msg):
self.assertTrue(msg is message)
raise SetupNeededError(setup_url_sentinel)
self.consumer._checkSetupNeeded = raiseSetupNeeded
response = self.consumer.complete(message, None, None)
self.assertEqual(SETUP_NEEDED, response.status)
self.assertTrue(setup_url_sentinel is response.setup_url)
def test_cancel(self):
message = Message.fromPostArgs({'openid.mode': 'cancel'})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.assertEqual(r.status, CANCEL)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
def test_cancel_with_return_to(self):
message = Message.fromPostArgs({'openid.mode': 'cancel'})
r = self.consumer.complete(message, self.endpoint, self.return_to)
self.assertEqual(r.status, CANCEL)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
def test_error(self):
msg = 'an error message'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg,
})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.assertEqual(r.status, FAILURE)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
self.assertEqual(r.message, msg)
def test_errorWithNoOptionalKeys(self):
msg = 'an error message'
contact = 'some contact info here'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg,
'openid.contact': contact,
})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.assertEqual(r.status, FAILURE)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
self.assertTrue(r.contact == contact)
self.assertTrue(r.reference is None)
self.assertEqual(r.message, msg)
def test_errorWithOptionalKeys(self):
msg = 'an error message'
contact = 'me'
reference = 'support ticket'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg, 'openid.reference': reference,
'openid.contact': contact, 'openid.ns': OPENID2_NS,
})
r = self.consumer.complete(message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
self.assertTrue(r.contact == contact)
self.assertTrue(r.reference == reference)
self.assertEqual(r.message, msg)
def test_noMode(self):
message = Message.fromPostArgs({})
r = self.consumer.complete(message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
self.assertTrue(r.identity_url == self.endpoint.claimed_id)
def test_idResMissingField(self):
# XXX - this test is passing, but not necessarily by what it
# is supposed to test for. status in FAILURE, but it's because
# *check_auth* failed, not because it's missing an arg, exactly.
message = Message.fromPostArgs({'openid.mode': 'id_res'})
self.assertRaises(ProtocolError, self.consumer._doIdRes,
message, self.endpoint, None)
def test_idResURLMismatch(self):
class VerifiedError(Exception):
pass
def discoverAndVerify(claimed_id, _to_match_endpoints):
raise VerifiedError
self.consumer._discoverAndVerify = discoverAndVerify
self.disableReturnToChecking()
message = Message.fromPostArgs(
{'openid.mode': 'id_res',
'openid.return_to': 'return_to (just anything)',
'openid.identity': 'something wrong (not self.consumer_id)',
'openid.assoc_handle': 'does not matter',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
self.consumer.store = GoodAssocStore()
self.assertRaises(VerifiedError,
self.consumer.complete,
message, self.endpoint)
self.failUnlessLogMatches('Error attempting to use stored',
'Attempting discovery')
class TestCompleteMissingSig(unittest.TestCase, CatchLogs):
def setUp(self):
self.store = GoodAssocStore()
self.consumer = GenericConsumer(self.store)
self.server_url = "http://idp.unittest/"
CatchLogs.setUp(self)
claimed_id = 'bogus.claimed'
self.message = Message.fromOpenIDArgs(
{'mode': 'id_res',
'return_to': 'return_to (just anything)',
'identity': claimed_id,
'assoc_handle': 'does not matter',
'sig': GOODSIG,
'response_nonce': mkNonce(),
'signed': 'identity,return_to,response_nonce,assoc_handle,claimed_id,op_endpoint',
'claimed_id': claimed_id,
'op_endpoint': self.server_url,
'ns': OPENID2_NS,
})
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.server_url = self.server_url
self.endpoint.claimed_id = claimed_id
self.consumer._checkReturnTo = lambda unused1, unused2: True
def tearDown(self):
CatchLogs.tearDown(self)
def test_idResMissingNoSigs(self):
def _vrfy(resp_msg, endpoint=None):
return endpoint
self.consumer._verifyDiscoveryResults = _vrfy
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessSuccess(r)
def test_idResNoIdentity(self):
self.message.delArg(OPENID_NS, 'identity')
self.message.delArg(OPENID_NS, 'claimed_id')
self.endpoint.claimed_id = None
self.message.setArg(
OPENID_NS,
'signed',
'return_to,response_nonce,assoc_handle,op_endpoint')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessSuccess(r)
def test_idResMissingIdentitySig(self):
self.message.setArg(
OPENID_NS, 'signed',
'return_to,response_nonce,assoc_handle,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
def test_idResMissingReturnToSig(self):
self.message.setArg(
OPENID_NS, 'signed',
'identity,response_nonce,assoc_handle,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
def test_idResMissingAssocHandleSig(self):
self.message.setArg(
OPENID_NS, 'signed',
'identity,response_nonce,return_to,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
def test_idResMissingClaimedIDSig(self):
self.message.setArg(
OPENID_NS, 'signed',
'identity,response_nonce,return_to,assoc_handle')
r = self.consumer.complete(self.message, self.endpoint, None)
self.assertEqual(r.status, FAILURE)
def failUnlessSuccess(self, response):
if response.status != SUCCESS:
self.fail("Non-successful response: %s" % (response,))
class TestCheckAuthResponse(TestIdRes, CatchLogs):
def setUp(self):
CatchLogs.setUp(self)
TestIdRes.setUp(self)
def tearDown(self):
CatchLogs.tearDown(self)
def _createAssoc(self):
issued = time.time()
lifetime = 1000
assoc = association.Association(
'handle', 'secret', issued, lifetime, 'HMAC-SHA1')
store = self.consumer.store
store.storeAssociation(self.server_url, assoc)
assoc2 = store.getAssociation(self.server_url)
self.assertEqual(assoc, assoc2)
def test_goodResponse(self):
"""successful response to check_authentication"""
response = Message.fromOpenIDArgs({'is_valid': 'true'})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertTrue(r)
def test_missingAnswer(self):
"""check_authentication returns false when server sends no answer"""
response = Message.fromOpenIDArgs({})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertFalse(r)
def test_badResponse(self):
"""check_authentication returns false when is_valid is false"""
response = Message.fromOpenIDArgs({'is_valid': 'false'})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertFalse(r)
def test_badResponseInvalidate(self):
"""Make sure that the handle is invalidated when is_valid is false
From "Verifying directly with the OpenID Provider"::
If the OP responds with "is_valid" set to "true", and
"invalidate_handle" is present, the Relying Party SHOULD
NOT send further authentication requests with that handle.
"""
self._createAssoc()
response = Message.fromOpenIDArgs({
'is_valid': 'false',
'invalidate_handle': 'handle',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertFalse(r)
self.assertTrue(
self.consumer.store.getAssociation(self.server_url) is None)
def test_invalidateMissing(self):
"""invalidate_handle with a handle that is not present"""
response = Message.fromOpenIDArgs({
'is_valid': 'true',
'invalidate_handle': 'missing',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertTrue(r)
self.failUnlessLogMatches(
'Received "invalidate_handle"'
)
def test_invalidateMissing_noStore(self):
"""invalidate_handle with a handle that is not present"""
response = Message.fromOpenIDArgs({
'is_valid': 'true',
'invalidate_handle': 'missing',
})
self.consumer.store = None
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertTrue(r)
self.failUnlessLogMatches(
'Received "invalidate_handle"',
'Unexpectedly got invalidate_handle without a store')
def test_invalidatePresent(self):
"""invalidate_handle with a handle that exists
From "Verifying directly with the OpenID Provider"::
If the OP responds with "is_valid" set to "true", and
"invalidate_handle" is present, the Relying Party SHOULD
NOT send further authentication requests with that handle.
"""
self._createAssoc()
response = Message.fromOpenIDArgs({
'is_valid': 'true',
'invalidate_handle': 'handle',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.assertTrue(r)
self.assertTrue(
self.consumer.store.getAssociation(self.server_url) is None)
class TestSetupNeeded(TestIdRes):
def failUnlessSetupNeeded(self, expected_setup_url, message):
try:
self.consumer._checkSetupNeeded(message)
except SetupNeededError as why:
self.assertEqual(expected_setup_url, why.user_setup_url)
else:
self.fail("Expected to find an immediate-mode response")
def test_setupNeededOpenID1(self):
"""The minimum conditions necessary to trigger Setup Needed"""
setup_url = 'http://unittest/setup-here'
message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.user_setup_url': setup_url,
})
self.assertTrue(message.isOpenID1())
self.failUnlessSetupNeeded(setup_url, message)
def test_setupNeededOpenID1_extra(self):
"""Extra stuff along with setup_url still trigger Setup Needed"""
setup_url = 'http://unittest/setup-here'
message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.user_setup_url': setup_url,
'openid.identity': 'bogus',
})
self.assertTrue(message.isOpenID1())
self.failUnlessSetupNeeded(setup_url, message)
def test_noSetupNeededOpenID1(self):
"""When the user_setup_url is missing on an OpenID 1 message,
we assume that it's not a cancel response to checkid_immediate"""
message = Message.fromOpenIDArgs({'mode': 'id_res'})
self.assertTrue(message.isOpenID1())
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
def test_setupNeededOpenID2(self):
message = Message.fromOpenIDArgs({
'mode': 'setup_needed',
'ns': OPENID2_NS,
})
self.assertTrue(message.isOpenID2())
response = self.consumer.complete(message, None, None)
self.assertEqual('setup_needed', response.status)
self.assertEqual(None, response.setup_url)
def test_setupNeededDoesntWorkForOpenID1(self):
message = Message.fromOpenIDArgs({
'mode': 'setup_needed',
})
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
response = self.consumer.complete(message, None, None)
self.assertEqual('failure', response.status)
self.assertTrue(response.message.startswith('Invalid openid.mode'))
def test_noSetupNeededOpenID2(self):
message = Message.fromOpenIDArgs({
'mode': 'id_res',
'game': 'puerto_rico',
'ns': OPENID2_NS,
})
self.assertTrue(message.isOpenID2())
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
class IdResCheckForFieldsTest(TestIdRes):
def setUp(self):
self.consumer = GenericConsumer(None)
def mkSuccessTest(openid_args, signed_list):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
message.setArg(OPENID_NS, 'signed', ','.join(signed_list))
self.consumer._idResCheckForFields(message)
return test
test_openid1Success = mkSuccessTest(
{'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'identity': 'someone',
},
['return_to', 'identity'])
test_openid2Success = mkSuccessTest(
{'ns': OPENID2_NS,
'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'op_endpoint': 'my favourite server',
'response_nonce': 'use only once',
},
['return_to', 'response_nonce', 'assoc_handle', 'op_endpoint'])
test_openid2Success_identifiers = mkSuccessTest(
{'ns': OPENID2_NS,
'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'claimed_id': 'i claim to be me',
'identity': 'my server knows me as me',
'op_endpoint': 'my favourite server',
'response_nonce': 'use only once',
},
['return_to', 'response_nonce', 'identity',
'claimed_id', 'assoc_handle', 'op_endpoint'])
def mkMissingFieldTest(openid_args):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
try:
self.consumer._idResCheckForFields(message)
except ProtocolError as why:
self.assertTrue(str(why).startswith('Missing required'))
else:
self.fail('Expected an error, but none occurred')
return test
def mkMissingSignedTest(openid_args):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
try:
self.consumer._idResCheckForFields(message)
except ProtocolError as why:
self.assertTrue(str(why).endswith('not signed'))
else:
self.fail('Expected an error, but none occurred')
return test
test_openid1Missing_returnToSig = mkMissingSignedTest(
{'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'identity': 'someone',
'signed': 'identity',
})
test_openid1Missing_identitySig = mkMissingSignedTest(
{'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'identity': 'someone',
'signed': 'return_to'
})
test_openid2Missing_opEndpointSig = mkMissingSignedTest(
{'ns': OPENID2_NS,
'return_to': 'return',
'assoc_handle': 'assoc handle',
'sig': 'a signature',
'identity': 'someone',
'op_endpoint': 'the endpoint',
'signed': 'return_to,identity,assoc_handle'
})
test_openid1MissingReturnTo = mkMissingFieldTest(
{'assoc_handle': 'assoc handle',
'sig': 'a signature',
'identity': 'someone',
})
test_openid1MissingAssocHandle = mkMissingFieldTest(
{'return_to': 'return',
'sig': 'a signature',
'identity': 'someone',
})
# XXX: I could go on...
class CheckAuthHappened(Exception):
pass
class CheckNonceVerifyTest(TestIdRes, CatchLogs):
def setUp(self):
CatchLogs.setUp(self)
TestIdRes.setUp(self)
self.consumer.openid1_nonce_query_arg_name = 'nonce'
def tearDown(self):
CatchLogs.tearDown(self)
def test_openid1Success(self):
"""use consumer-generated nonce"""
nonce_value = mkNonce()
self.return_to = 'http://rt.unittest/?nonce=%s' % (nonce_value,)
self.response = Message.fromOpenIDArgs({'return_to': self.return_to})
self.response.setArg(BARE_NS, 'nonce', nonce_value)
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_openid1Missing(self):
"""use consumer-generated nonce"""
self.response = Message.fromOpenIDArgs({})
n = self.consumer._idResGetNonceOpenID1(self.response, self.endpoint)
self.assertTrue(n is None, n)
self.failUnlessLogEmpty()
def test_consumerNonceOpenID2(self):
"""OpenID 2 does not use consumer-generated nonce"""
self.return_to = 'http://rt.unittest/?nonce=%s' % (mkNonce(),)
self.response = Message.fromOpenIDArgs(
{'return_to': self.return_to, 'ns': OPENID2_NS})
self.assertRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_serverNonce(self):
"""use server-generated nonce"""
self.response = Message.fromOpenIDArgs(
{'ns': OPENID2_NS, 'response_nonce': mkNonce()})
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_serverNonceOpenID1(self):
"""OpenID 1 does not use server-generated nonce"""
self.response = Message.fromOpenIDArgs(
{'ns': OPENID1_NS,
'return_to': 'http://return.to/',
'response_nonce': mkNonce()})
self.assertRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_badNonce(self):
"""remove the nonce from the store
From "Checking the Nonce"::
When the Relying Party checks the signature on an assertion, the
Relying Party SHOULD ensure that an assertion has not yet
been accepted with the same value for "openid.response_nonce"
from the same OP Endpoint URL.
"""
nonce = mkNonce()
stamp, salt = splitNonce(nonce)
self.store.useNonce(self.server_url, stamp, salt)
self.response = Message.fromOpenIDArgs(
{'response_nonce': nonce,
'ns': OPENID2_NS,
})
self.assertRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
def test_successWithNoStore(self):
"""When there is no store, checking the nonce succeeds"""
self.consumer.store = None
self.response = Message.fromOpenIDArgs(
{'response_nonce': mkNonce(),
'ns': OPENID2_NS,
})
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_tamperedNonce(self):
"""Malformed nonce"""
self.response = Message.fromOpenIDArgs(
{'ns': OPENID2_NS,
'response_nonce': 'malformed'})
self.assertRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
def test_missingNonce(self):
"""no nonce parameter on the return_to"""
self.response = Message.fromOpenIDArgs(
{'return_to': self.return_to})
self.assertRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
class CheckAuthDetectingConsumer(GenericConsumer):
def _checkAuth(self, *args):
raise CheckAuthHappened(args)
def _idResCheckNonce(self, *args):
"""We're not testing nonce-checking, so just return success
when it asks."""
return True
class TestCheckAuthTriggered(TestIdRes, CatchLogs):
consumer_class = CheckAuthDetectingConsumer
def setUp(self):
TestIdRes.setUp(self)
CatchLogs.setUp(self)
self.disableDiscoveryVerification()
def test_checkAuthTriggered(self):
message = Message.fromPostArgs({
'openid.return_to': self.return_to,
'openid.identity': self.server_id,
'openid.assoc_handle': 'not_found',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
self.disableReturnToChecking()
try:
result = self.consumer._doIdRes(message, self.endpoint, None)
except CheckAuthHappened:
pass
else:
self.fail('_checkAuth did not happen. Result was: %r %s' %
(result, self.messages))
def test_checkAuthTriggeredWithAssoc(self):
# Store an association for this server that does not match the
# handle that is in the message
issued = time.time()
lifetime = 1000
assoc = association.Association(
'handle', 'secret', issued, lifetime, 'HMAC-SHA1')
self.store.storeAssociation(self.server_url, assoc)
self.disableReturnToChecking()
message = Message.fromPostArgs({
'openid.return_to': self.return_to,
'openid.identity': self.server_id,
'openid.assoc_handle': 'not_found',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
try:
result = self.consumer._doIdRes(message, self.endpoint, None)
except CheckAuthHappened:
pass
else:
self.fail('_checkAuth did not happen. Result was: %r' % (result,))
def test_expiredAssoc(self):
# Store an expired association for the server with the handle
# that is in the message
issued = time.time() - 10
lifetime = 0
handle = 'handle'
assoc = association.Association(
handle, 'secret', issued, lifetime, 'HMAC-SHA1')
self.assertTrue(assoc.expiresIn <= 0)
self.store.storeAssociation(self.server_url, assoc)
message = Message.fromPostArgs({
'openid.return_to': self.return_to,
'openid.identity': self.server_id,
'openid.assoc_handle': handle,
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
self.disableReturnToChecking()
self.assertRaises(ProtocolError, self.consumer._doIdRes,
message, self.endpoint, None)
def test_newerAssoc(self):
lifetime = 1000
good_issued = time.time() - 10
good_handle = 'handle'
good_assoc = association.Association(
good_handle, 'secret', good_issued, lifetime, 'HMAC-SHA1')
self.store.storeAssociation(self.server_url, good_assoc)
bad_issued = time.time() - 5
bad_handle = 'handle2'
bad_assoc = association.Association(
bad_handle, 'secret', bad_issued, lifetime, 'HMAC-SHA1')
self.store.storeAssociation(self.server_url, bad_assoc)
query = {
'return_to': self.return_to,
'identity': self.server_id,
'assoc_handle': good_handle,
}
message = Message.fromOpenIDArgs(query)
message = good_assoc.signMessage(message)
self.disableReturnToChecking()
info = self.consumer._doIdRes(message, self.endpoint, None)
self.assertEqual(info.status, SUCCESS, info.message)
self.assertEqual(self.consumer_id, info.identity_url)
class TestReturnToArgs(unittest.TestCase):
"""Verifying the Return URL paramaters.
From the specification "Verifying the Return URL"::
To verify that the "openid.return_to" URL matches the URL that is
processing this assertion:
- The URL scheme, authority, and path MUST be the same between the
two URLs.
- Any query parameters that are present in the "openid.return_to"
URL MUST also be present with the same values in the
accepting URL.
XXX: So far we have only tested the second item on the list above.
XXX: _verifyReturnToArgs is not invoked anywhere.
"""
def setUp(self):
store = object()
self.consumer = GenericConsumer(store)
def test_returnToArgsOkay(self):
query = {
'openid.mode': 'id_res',
'openid.return_to': 'http://example.com/?foo=bar',
'foo': 'bar',
}
# no return value, success is assumed if there are no exceptions.
self.consumer._verifyReturnToArgs(query)
def test_returnToArgsUnexpectedArg(self):
query = {
'openid.mode': 'id_res',
'openid.return_to': 'http://example.com/',
'foo': 'bar',
}
# no return value, success is assumed if there are no exceptions.
self.assertRaises(ProtocolError,
self.consumer._verifyReturnToArgs, query)
def test_returnToMismatch(self):
query = {
'openid.mode': 'id_res',
'openid.return_to': 'http://example.com/?foo=bar',
}
# fail, query has no key 'foo'.
self.assertRaises(ValueError,
self.consumer._verifyReturnToArgs, query)
query['foo'] = 'baz'
# fail, values for 'foo' do not match.
self.assertRaises(ValueError,
self.consumer._verifyReturnToArgs, query)
def test_noReturnTo(self):
query = {'openid.mode': 'id_res'}
self.assertRaises(ValueError,
self.consumer._verifyReturnToArgs, query)
def test_completeBadReturnTo(self):
"""Test GenericConsumer.complete()'s handling of bad return_to
values.
"""
return_to = "http://some.url/path?foo=bar"
# Scheme, authority, and path differences are checked by
# GenericConsumer._checkReturnTo. Query args checked by
# GenericConsumer._verifyReturnToArgs.
bad_return_tos = [
# Scheme only
"https://some.url/path?foo=bar",
# Authority only
"http://some.url.invalid/path?foo=bar",
# Path only
"http://some.url/path_extra?foo=bar",
# Query args differ
"http://some.url/path?foo=bar2",
"http://some.url/path?foo2=bar",
]
m = Message(OPENID1_NS)
m.setArg(OPENID_NS, 'mode', 'cancel')
m.setArg(BARE_NS, 'foo', 'bar')
endpoint = None
for bad in bad_return_tos:
m.setArg(OPENID_NS, 'return_to', bad)
self.assertFalse(self.consumer._checkReturnTo(m, return_to))
def test_completeGoodReturnTo(self):
"""Test GenericConsumer.complete()'s handling of good
return_to values.
"""
return_to = "http://some.url/path"
good_return_tos = [
(return_to, {}),
(return_to + "?another=arg", {(BARE_NS, 'another'): 'arg'}),
(return_to + "?another=arg#fragment",
{(BARE_NS, 'another'): 'arg'}),
("HTTP" + return_to[4:], {}),
(return_to.replace('url', 'URL'), {}),
("http://some.url:80/path", {}),
("http://some.url/p%61th", {}),
("http://some.url/./path", {}),
]
endpoint = None
for good, extra in good_return_tos:
m = Message(OPENID1_NS)
m.setArg(OPENID_NS, 'mode', 'cancel')
for ns, key in extra:
m.setArg(ns, key, extra[(ns, key)])
m.setArg(OPENID_NS, 'return_to', good)
result = self.consumer.complete(m, endpoint, return_to)
self.assertTrue(
isinstance(result, CancelResponse),
"Expected CancelResponse, got %r for %s" % (result, good))
class MockFetcher(object):
def __init__(self, response=None):
self.response = response or HTTPResponse()
self.fetches = []
def fetch(self, url, body=None, headers=None):
self.fetches.append((url, body, headers))
return self.response
class ExceptionRaisingMockFetcher(object):
class MyException(Exception):
pass
def fetch(self, url, body=None, headers=None):
raise self.MyException('mock fetcher exception')
class BadArgCheckingConsumer(GenericConsumer):
def _makeKVPost(self, args, _):
assert args == {
'openid.mode': 'check_authentication',
'openid.signed': 'foo',
'openid.ns': OPENID1_NS
}, args
return None
class TestCheckAuth(unittest.TestCase, CatchLogs):
consumer_class = GenericConsumer
def setUp(self):
CatchLogs.setUp(self)
self.store = memstore.MemoryStore()
self.consumer = self.consumer_class(self.store)
self._orig_fetcher = fetchers.getDefaultFetcher()
self.fetcher = MockFetcher()
fetchers.setDefaultFetcher(self.fetcher)
def tearDown(self):
CatchLogs.tearDown(self)
fetchers.setDefaultFetcher(self._orig_fetcher, wrap_exceptions=False)
def test_error(self):
self.fetcher.response = HTTPResponse(
"http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n')
query = {'openid.signed': 'stuff',
'openid.stuff': 'a value'}
r = self.consumer._checkAuth(Message.fromPostArgs(query),
http_server_url)
self.assertFalse(r)
self.assertTrue(self.messages)
def test_bad_args(self):
query = {
'openid.signed': 'foo',
'closid.foo': 'something',
}
consumer = BadArgCheckingConsumer(self.store)
consumer._checkAuth(Message.fromPostArgs(query), 'does://not.matter')
def test_signedList(self):
query = Message.fromOpenIDArgs({
'mode': 'id_res',
'sig': 'rabbits',
'identity': '=example',
'assoc_handle': 'munchkins',
'ns.sreg': 'urn:sreg',
'sreg.email': 'bogus@example.com',
'signed': 'identity,mode,ns.sreg,sreg.email',
'foo': 'bar',
})
args = self.consumer._createCheckAuthRequest(query)
self.assertTrue(args.isOpenID1())
for signed_arg in query.getArg(OPENID_NS, 'signed').split(','):
self.assertTrue(args.getAliasedArg(signed_arg), signed_arg)
def test_112(self):
args = {
'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8',
'openid.claimed_id': 'http://binkley.lan/user/test01',
'openid.identity': 'http://test01.binkley.lan/',
'openid.mode': 'id_res',
'openid.ns': 'http://specs.openid.net/auth/2.0',
'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0',
'openid.op_endpoint': 'http://binkley.lan/server',
'openid.pape.auth_policies': 'none',
'openid.pape.auth_time': '2008-01-28T20:42:36Z',
'openid.pape.nist_auth_level': '0',
'openid.response_nonce': '2008-01-28T21:07:04Z99Q=',
'openid.return_to': 'http://binkley.lan:8001/process?janrain_nonce=2008-01-28T21%3A07%3A02Z0tMIKx',
'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=',
'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,ns.pape,pape.nist_auth_level,pape.auth_policies'
}
self.assertEqual(OPENID2_NS, args['openid.ns'])
incoming = Message.fromPostArgs(args)
self.assertTrue(incoming.isOpenID2())
car = self.consumer._createCheckAuthRequest(incoming)
expected_args = args.copy()
expected_args['openid.mode'] = 'check_authentication'
expected = Message.fromPostArgs(expected_args)
self.assertTrue(expected.isOpenID2())
self.assertEqual(expected, car)
car_args = car.toPostArgs()
self.assertEqual(set(expected_args.keys()), set(car_args.keys()))
self.assertEqual(set(expected_args.values()), set(car_args.values()))
self.assertEqual(expected_args, car.toPostArgs())
class TestFetchAssoc(unittest.TestCase, CatchLogs):
consumer_class = GenericConsumer
def setUp(self):
CatchLogs.setUp(self)
self.store = memstore.MemoryStore()
self.fetcher = MockFetcher()
fetchers.setDefaultFetcher(self.fetcher)
self.consumer = self.consumer_class(self.store)
def test_error_404(self):
"""404 from a kv post raises HTTPFetchingError"""
self.fetcher.response = HTTPResponse(
"http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n')
self.assertRaises(
fetchers.HTTPFetchingError,
self.consumer._makeKVPost,
Message.fromPostArgs({'mode': 'associate'}),
"http://server_url")
def test_error_exception_unwrapped(self):
"""Ensure that exceptions are bubbled through from fetchers
when making associations
"""
self.fetcher = ExceptionRaisingMockFetcher()
fetchers.setDefaultFetcher(self.fetcher, wrap_exceptions=False)
self.assertRaises(self.fetcher.MyException,
self.consumer._makeKVPost,
Message.fromPostArgs({'mode': 'associate'}),
"http://server_url")
# exception fetching returns no association
e = OpenIDServiceEndpoint()
e.server_url = 'some://url'
self.assertRaises(self.fetcher.MyException,
self.consumer._getAssociation, e)
self.assertRaises(self.fetcher.MyException,
self.consumer._checkAuth,
Message.fromPostArgs({'openid.signed': ''}),
'some://url')
def test_error_exception_wrapped(self):
"""Ensure that openid.fetchers.HTTPFetchingError is caught by
the association creation stuff.
"""
self.fetcher = ExceptionRaisingMockFetcher()
# This will wrap exceptions!
fetchers.setDefaultFetcher(self.fetcher)
self.assertRaises(fetchers.HTTPFetchingError,
self.consumer._makeKVPost,
Message.fromOpenIDArgs({'mode': 'associate'}),
"http://server_url")
# exception fetching returns no association
e = OpenIDServiceEndpoint()
e.server_url = 'some://url'
self.assertTrue(self.consumer._getAssociation(e) is None)
msg = Message.fromPostArgs({'openid.signed': ''})
self.assertFalse(self.consumer._checkAuth(msg, 'some://url'))
class TestSuccessResponse(unittest.TestCase):
def setUp(self):
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.claimed_id = 'identity_url'
def test_extensionResponse(self):
resp = mkSuccess(self.endpoint, {
'ns.sreg': 'urn:sreg',
'ns.unittest': 'urn:unittest',
'unittest.one': '1',
'unittest.two': '2',
'sreg.nickname': 'j3h',
'return_to': 'return_to',
})
utargs = resp.extensionResponse('urn:unittest', False)
self.assertEqual(utargs, {'one': '1', 'two': '2'})
sregargs = resp.extensionResponse('urn:sreg', False)
self.assertEqual(sregargs, {'nickname': 'j3h'})
def test_extensionResponseSigned(self):
args = {
'ns.sreg': 'urn:sreg',
'ns.unittest': 'urn:unittest',
'unittest.one': '1',
'unittest.two': '2',
'sreg.nickname': 'j3h',
'sreg.dob': 'yesterday',
'return_to': 'return_to',
'signed': 'sreg.nickname,unittest.one,sreg.dob',
}
signed_list = ['openid.sreg.nickname',
'openid.unittest.one',
'openid.sreg.dob']
# Don't use mkSuccess because it creates an all-inclusive
# signed list.
msg = Message.fromOpenIDArgs(args)
resp = SuccessResponse(self.endpoint, msg, signed_list)
# All args in this NS are signed, so expect all.
sregargs = resp.extensionResponse('urn:sreg', True)
self.assertEqual(sregargs, {
'nickname': 'j3h',
'dob': 'yesterday'
})
# Not all args in this NS are signed, so expect None when
# asking for them.
utargs = resp.extensionResponse('urn:unittest', True)
self.assertEqual(utargs, None)
def test_noReturnTo(self):
resp = mkSuccess(self.endpoint, {})
self.assertTrue(resp.getReturnTo() is None)
def test_returnTo(self):
resp = mkSuccess(self.endpoint, {'return_to': 'return_to'})
self.assertEqual(resp.getReturnTo(), 'return_to')
def test_displayIdentifierClaimedId(self):
resp = mkSuccess(self.endpoint, {})
self.assertEqual(resp.getDisplayIdentifier(),
resp.endpoint.claimed_id)
def test_displayIdentifierOverride(self):
self.endpoint.display_identifier = "http://input.url/"
resp = mkSuccess(self.endpoint, {})
self.assertEqual(resp.getDisplayIdentifier(),
"http://input.url/")
class StubConsumer(object):
def __init__(self):
self.assoc = object()
self.response = None
self.endpoint = None
def begin(self, service):
auth_req = AuthRequest(service, self.assoc)
self.endpoint = service
return auth_req
def complete(self, message, endpoint, return_to):
assert endpoint is self.endpoint
return self.response
class ConsumerTest(unittest.TestCase):
"""Tests for high-level consumer.Consumer functions.
Its GenericConsumer component is stubbed out with StubConsumer.
"""
def setUp(self):
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.claimed_id = self.identity_url = 'http://identity.url/'
self.store = None
self.session = {}
self.consumer = Consumer(self.session, self.store)
self.consumer.consumer = StubConsumer()
self.discovery = Discovery(self.session,
self.identity_url,
self.consumer.session_key_prefix)
def test_setAssociationPreference(self):
self.consumer.setAssociationPreference([])
self.assertTrue(isinstance(self.consumer.consumer.negotiator,
association.SessionNegotiator))
self.assertEqual([],
self.consumer.consumer.negotiator.allowed_types)
self.consumer.setAssociationPreference([('HMAC-SHA1', 'DH-SHA1')])
self.assertEqual([('HMAC-SHA1', 'DH-SHA1')],
self.consumer.consumer.negotiator.allowed_types)
def withDummyDiscovery(self, callable, dummy_getNextService):
class DummyDisco(object):
def __init__(self, *ignored):
pass
getNextService = dummy_getNextService
import openid.consumer.consumer
old_discovery = openid.consumer.consumer.Discovery
try:
openid.consumer.consumer.Discovery = DummyDisco
callable()
finally:
openid.consumer.consumer.Discovery = old_discovery
def test_beginHTTPError(self):
"""Make sure that the discovery HTTP failure case behaves properly
"""
def getNextService(self, ignored):
raise HTTPFetchingError("Unit test")
def test():
try:
self.consumer.begin('unused in this test')
except DiscoveryFailure as why:
self.assertTrue(str(why).startswith('Error fetching'))
self.assertFalse(str(why).find('Unit test') == -1)
else:
self.fail('Expected DiscoveryFailure')
self.withDummyDiscovery(test, getNextService)
def test_beginNoServices(self):
def getNextService(self, ignored):
return None
url = 'http://a.user.url/'
def test():
try:
self.consumer.begin(url)
except DiscoveryFailure as why:
self.assertTrue(str(why).startswith('No usable OpenID'))
self.assertFalse(str(why).find(url) == -1)
else:
self.fail('Expected DiscoveryFailure')
self.withDummyDiscovery(test, getNextService)
def test_beginWithoutDiscovery(self):
# Does this really test anything non-trivial?
result = self.consumer.beginWithoutDiscovery(self.endpoint)
# The result is an auth request
self.assertTrue(isinstance(result, AuthRequest))
# Side-effect of calling beginWithoutDiscovery is setting the
# session value to the endpoint attribute of the result
self.assertTrue(
self.session[self.consumer._token_key] is result.endpoint)
# The endpoint that we passed in is the endpoint on the auth_request
self.assertTrue(result.endpoint is self.endpoint)
def test_completeEmptySession(self):
text = "failed complete"
def checkEndpoint(message, endpoint, return_to):
self.assertTrue(endpoint is None)
return FailureResponse(endpoint, text)
self.consumer.consumer.complete = checkEndpoint
response = self.consumer.complete({}, None)
self.assertEqual(response.status, FAILURE)
self.assertEqual(response.message, text)
self.assertTrue(response.identity_url is None)
def _doResp(self, auth_req, exp_resp):
"""complete a transaction, using the expected response from
the generic consumer."""
# response is an attribute of StubConsumer, returned by
# StubConsumer.complete.
self.consumer.consumer.response = exp_resp
# endpoint is stored in the session
self.assertTrue(self.session)
resp = self.consumer.complete({}, None)
# All responses should have the same identity URL, and the
# session should be cleaned out
if self.endpoint.claimed_id != IDENTIFIER_SELECT:
self.assertTrue(resp.identity_url is self.identity_url)
self.assertFalse(self.consumer._token_key in self.session)
# Expected status response
self.assertEqual(resp.status, exp_resp.status)
return resp
def _doRespNoDisco(self, exp_resp):
"""Set up a transaction without discovery"""
auth_req = self.consumer.beginWithoutDiscovery(self.endpoint)
resp = self._doResp(auth_req, exp_resp)
# There should be nothing left in the session once we have completed.
self.assertFalse(self.session)
return resp
def test_noDiscoCompleteSuccessWithToken(self):
self._doRespNoDisco(mkSuccess(self.endpoint, {}))
def test_noDiscoCompleteCancelWithToken(self):
self._doRespNoDisco(CancelResponse(self.endpoint))
def test_noDiscoCompleteFailure(self):
msg = 'failed!'
resp = self._doRespNoDisco(FailureResponse(self.endpoint, msg))
self.assertTrue(resp.message is msg)
def test_noDiscoCompleteSetupNeeded(self):
setup_url = 'http://setup.url/'
resp = self._doRespNoDisco(
SetupNeededResponse(self.endpoint, setup_url))
self.assertTrue(resp.setup_url is setup_url)
# To test that discovery is cleaned up, we need to initialize a
# Yadis manager, and have it put its values in the session.
def _doRespDisco(self, is_clean, exp_resp):
"""Set up and execute a transaction, with discovery"""
self.discovery.createManager([self.endpoint], self.identity_url)
auth_req = self.consumer.begin(self.identity_url)
resp = self._doResp(auth_req, exp_resp)
manager = self.discovery.getManager()
if is_clean:
self.assertTrue(self.discovery.getManager() is None, manager)
else:
self.assertFalse(self.discovery.getManager() is None, manager)
return resp
# Cancel and success DO clean up the discovery process
def test_completeSuccess(self):
self._doRespDisco(True, mkSuccess(self.endpoint, {}))
def test_completeCancel(self):
self._doRespDisco(True, CancelResponse(self.endpoint))
# Failure and setup_needed don't clean up the discovery process
def test_completeFailure(self):
msg = 'failed!'
resp = self._doRespDisco(False, FailureResponse(self.endpoint, msg))
self.assertTrue(resp.message is msg)
def test_completeSetupNeeded(self):
setup_url = 'http://setup.url/'
resp = self._doRespDisco(
False,
SetupNeededResponse(self.endpoint, setup_url))
self.assertTrue(resp.setup_url is setup_url)
def test_successDifferentURL(self):
"""
Be sure that the session gets cleaned up when the response is
successful and has a different URL than the one in the
request.
"""
# Set up a request endpoint describing an IDP URL
self.identity_url = 'http://idp.url/'
self.endpoint.claimed_id = self.endpoint.local_id = IDENTIFIER_SELECT
# Use a response endpoint with a different URL (asserted by
# the IDP)
resp_endpoint = OpenIDServiceEndpoint()
resp_endpoint.claimed_id = "http://user.url/"
resp = self._doRespDisco(True, mkSuccess(resp_endpoint, {}))
self.assertTrue(self.discovery.getManager(force=True) is None)
def test_begin(self):
self.discovery.createManager([self.endpoint], self.identity_url)
# Should not raise an exception
auth_req = self.consumer.begin(self.identity_url)
self.assertTrue(isinstance(auth_req, AuthRequest))
self.assertTrue(auth_req.endpoint is self.endpoint)
self.assertTrue(auth_req.endpoint is self.consumer.consumer.endpoint)
self.assertTrue(auth_req.assoc is self.consumer.consumer.assoc)
class IDPDrivenTest(unittest.TestCase):
def setUp(self):
self.store = GoodAssocStore()
self.consumer = GenericConsumer(self.store)
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.server_url = "http://idp.unittest/"
def test_idpDrivenBegin(self):
# Testing here that the token-handling doesn't explode...
self.consumer.begin(self.endpoint)
def test_idpDrivenComplete(self):
identifier = '=directed_identifier'
message = Message.fromPostArgs({
'openid.identity': '=directed_identifier',
'openid.return_to': 'x',
'openid.assoc_handle': 'z',
'openid.signed': 'identity,return_to',
'openid.sig': GOODSIG,
})
discovered_endpoint = OpenIDServiceEndpoint()
discovered_endpoint.claimed_id = identifier
discovered_endpoint.server_url = self.endpoint.server_url
discovered_endpoint.local_id = identifier
iverified = []
def verifyDiscoveryResults(identifier, endpoint):
self.assertTrue(endpoint is self.endpoint)
iverified.append(discovered_endpoint)
return discovered_endpoint
self.consumer._verifyDiscoveryResults = verifyDiscoveryResults
self.consumer._idResCheckNonce = lambda *args: True
self.consumer._checkReturnTo = lambda unused1, unused2: True
response = self.consumer._doIdRes(message, self.endpoint, None)
self.failUnlessSuccess(response)
self.assertEqual(response.identity_url, "=directed_identifier")
# assert that discovery attempt happens and returns good
self.assertEqual(iverified, [discovered_endpoint])
def test_idpDrivenCompleteFraud(self):
# crap with an identifier that doesn't match discovery info
message = Message.fromPostArgs({
'openid.identity': '=directed_identifier',
'openid.return_to': 'x',
'openid.assoc_handle': 'z',
'openid.signed': 'identity,return_to',
'openid.sig': GOODSIG,
})
def verifyDiscoveryResults(identifier, endpoint):
raise DiscoveryFailure("PHREAK!", None)
self.consumer._verifyDiscoveryResults = verifyDiscoveryResults
self.consumer._checkReturnTo = lambda unused1, unused2: True
self.assertRaises(DiscoveryFailure, self.consumer._doIdRes,
message, self.endpoint, None)
def failUnlessSuccess(self, response):
if response.status != SUCCESS:
self.fail("Non-successful response: %s" % (response,))
class TestDiscoveryVerification(unittest.TestCase):
services = []
def setUp(self):
self.store = GoodAssocStore()
self.consumer = GenericConsumer(self.store)
self.consumer._discover = self.discoveryFunc
self.identifier = "http://idp.unittest/1337"
self.server_url = "http://endpoint.unittest/"
self.message = Message.fromPostArgs({
'openid.ns': OPENID2_NS,
'openid.identity': self.identifier,
'openid.claimed_id': self.identifier,
'openid.op_endpoint': self.server_url,
})
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.server_url = self.server_url
def test_theGoodStuff(self):
endpoint = OpenIDServiceEndpoint()
endpoint.type_uris = [OPENID_2_0_TYPE]
endpoint.claimed_id = self.identifier
endpoint.server_url = self.server_url
endpoint.local_id = self.identifier
self.services = [endpoint]
r = self.consumer._verifyDiscoveryResults(self.message, endpoint)
self.assertEqual(r, endpoint)
def test_otherServer(self):
text = "verify failed"
def discoverAndVerify(claimed_id, to_match_endpoints):
self.assertEqual(claimed_id, self.identifier)
for to_match in to_match_endpoints:
self.assertEqual(claimed_id, to_match.claimed_id)
raise ProtocolError(text)
self.consumer._discoverAndVerify = discoverAndVerify
# a set of things without the stuff
endpoint = OpenIDServiceEndpoint()
endpoint.type_uris = [OPENID_2_0_TYPE]
endpoint.claimed_id = self.identifier
endpoint.server_url = "http://the-MOON.unittest/"
endpoint.local_id = self.identifier
self.services = [endpoint]
try:
r = self.consumer._verifyDiscoveryResults(self.message, endpoint)
except ProtocolError as e:
# Should we make more ProtocolError subclasses?
self.assertTrue(str(e), text)
else:
self.fail("expected ProtocolError, %r returned." % (r,))
def test_foreignDelegate(self):
text = "verify failed"
def discoverAndVerify(claimed_id, to_match_endpoints):
self.assertEqual(claimed_id, self.identifier)
for to_match in to_match_endpoints:
self.assertEqual(claimed_id, to_match.claimed_id)
raise ProtocolError(text)
self.consumer._discoverAndVerify = discoverAndVerify
# a set of things with the server stuff but other delegate
endpoint = OpenIDServiceEndpoint()
endpoint.type_uris = [OPENID_2_0_TYPE]
endpoint.claimed_id = self.identifier
endpoint.server_url = self.server_url
endpoint.local_id = "http://unittest/juan-carlos"
try:
r = self.consumer._verifyDiscoveryResults(self.message, endpoint)
except ProtocolError as e:
self.assertEqual(str(e), text)
else:
self.fail("Exepected ProtocolError, %r returned" % (r,))
def test_nothingDiscovered(self):
# a set of no things.
self.services = []
self.assertRaises(DiscoveryFailure,
self.consumer._verifyDiscoveryResults,
self.message, self.endpoint)
def discoveryFunc(self, identifier):
return identifier, self.services
class TestCreateAssociationRequest(unittest.TestCase):
def setUp(self):
class DummyEndpoint(object):
use_compatibility = False
def compatibilityMode(self):
return self.use_compatibility
self.endpoint = DummyEndpoint()
self.consumer = GenericConsumer(store=None)
self.assoc_type = 'HMAC-SHA1'
def test_noEncryptionSendsType(self):
session_type = 'no-encryption'
session, args = self.consumer._createAssociateRequest(
self.endpoint, self.assoc_type, session_type)
self.assertTrue(isinstance(session, PlainTextConsumerSession))
expected = Message.fromOpenIDArgs(
{'ns': OPENID2_NS,
'session_type': session_type,
'mode': 'associate',
'assoc_type': self.assoc_type,
})
self.assertEqual(expected, args)
def test_noEncryptionCompatibility(self):
self.endpoint.use_compatibility = True
session_type = 'no-encryption'
session, args = self.consumer._createAssociateRequest(
self.endpoint, self.assoc_type, session_type)
self.assertTrue(isinstance(session, PlainTextConsumerSession))
self.assertEqual(Message.fromOpenIDArgs({
'mode': 'associate',
'assoc_type': self.assoc_type,
}), args)
def test_dhSHA1Compatibility(self):
# Set the consumer's session type to a fast session since we
# need it here.
setConsumerSession(self.consumer)
self.endpoint.use_compatibility = True
session_type = 'DH-SHA1'
session, args = self.consumer._createAssociateRequest(
self.endpoint, self.assoc_type, session_type)
self.assertTrue(isinstance(session, DiffieHellmanSHA1ConsumerSession))
# This is a random base-64 value, so just check that it's
# present.
self.assertTrue(args.getArg(OPENID1_NS, 'dh_consumer_public'))
args.delArg(OPENID1_NS, 'dh_consumer_public')
# OK, session_type is set here and not for no-encryption
# compatibility
expected = Message.fromOpenIDArgs({
'mode': 'associate',
'session_type': 'DH-SHA1',
'assoc_type': self.assoc_type,
# DH does byte-manipulation and returns bytes
'dh_modulus': b'BfvStQ==',
'dh_gen': b'Ag==',
})
self.assertEqual(expected, args)
# XXX: test the other types
class _TestingDiffieHellmanResponseParameters(object):
session_cls = None
message_namespace = None
def setUp(self):
# Pre-compute DH with small prime so tests run quickly.
self.server_dh = DiffieHellman(100389557, 2)
self.consumer_dh = DiffieHellman(100389557, 2)
# base64(btwoc(g ^ xb mod p))
self.dh_server_public = cryptutil.longToBase64(self.server_dh.public)
self.secret = cryptutil.randomString(self.session_cls.secret_size)
self.enc_mac_key = oidutil.toBase64(
self.server_dh.xorSecret(self.consumer_dh.public,
self.secret,
self.session_cls.hash_func))
self.consumer_session = self.session_cls(self.consumer_dh)
self.msg = Message(self.message_namespace)
def testExtractSecret(self):
self.msg.setArg(OPENID_NS, 'dh_server_public', self.dh_server_public)
self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key)
extracted = self.consumer_session.extractSecret(self.msg)
self.assertEqual(extracted, self.secret)
def testAbsentServerPublic(self):
self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key)
self.assertRaises(KeyError, self.consumer_session.extractSecret,
self.msg)
def testAbsentMacKey(self):
self.msg.setArg(OPENID_NS, 'dh_server_public', self.dh_server_public)
self.assertRaises(KeyError, self.consumer_session.extractSecret,
self.msg)
def testInvalidBase64Public(self):
self.msg.setArg(OPENID_NS, 'dh_server_public', 'n o t b a s e 6 4.')
self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key)
self.assertRaises(ValueError,
self.consumer_session.extractSecret,
self.msg)
def testInvalidBase64MacKey(self):
self.msg.setArg(OPENID_NS, 'dh_server_public', self.dh_server_public)
self.msg.setArg(OPENID_NS, 'enc_mac_key', 'n o t base 64')
self.assertRaises(ValueError,
self.consumer_session.extractSecret,
self.msg)
class TestOpenID1SHA1(_TestingDiffieHellmanResponseParameters,
unittest.TestCase):
session_cls = DiffieHellmanSHA1ConsumerSession
message_namespace = OPENID1_NS
class TestOpenID2SHA1(_TestingDiffieHellmanResponseParameters,
unittest.TestCase):
session_cls = DiffieHellmanSHA1ConsumerSession
message_namespace = OPENID2_NS
if cryptutil.SHA256_AVAILABLE:
class TestOpenID2SHA256(_TestingDiffieHellmanResponseParameters,
unittest.TestCase):
session_cls = DiffieHellmanSHA256ConsumerSession
message_namespace = OPENID2_NS
else:
warnings.warn("Not running SHA256 association session tests.")
class TestNoStore(unittest.TestCase):
def setUp(self):
self.consumer = GenericConsumer(None)
def test_completeNoGetAssoc(self):
"""_getAssociation is never called when the store is None"""
def notCalled(unused):
self.fail('This method was unexpectedly called')
endpoint = OpenIDServiceEndpoint()
endpoint.claimed_id = 'identity_url'
self.consumer._getAssociation = notCalled
auth_request = self.consumer.begin(endpoint)
# _getAssociation was not called
class NonAnonymousAuthRequest(object):
endpoint = 'unused'
def setAnonymous(self, unused):
raise ValueError('Should trigger ProtocolError')
class TestConsumerAnonymous(unittest.TestCase):
def test_beginWithoutDiscoveryAnonymousFail(self):
"""Make sure that ValueError for setting an auth request
anonymous gets converted to a ProtocolError
"""
sess = {}
consumer = Consumer(sess, None)
def bogusBegin(unused):
return NonAnonymousAuthRequest()
consumer.consumer.begin = bogusBegin
self.assertRaises(
ProtocolError,
consumer.beginWithoutDiscovery, None)
class TestDiscoverAndVerify(unittest.TestCase):
def setUp(self):
self.consumer = GenericConsumer(None)
self.discovery_result = None
def dummyDiscover(unused_identifier):
return self.discovery_result
self.consumer._discover = dummyDiscover
self.to_match = OpenIDServiceEndpoint()
def failUnlessDiscoveryFailure(self):
self.assertRaises(
DiscoveryFailure,
self.consumer._discoverAndVerify,
'http://claimed-id.com/',
[self.to_match])
def test_noServices(self):
"""Discovery returning no results results in a
DiscoveryFailure exception"""
self.discovery_result = (None, [])
self.failUnlessDiscoveryFailure()
def test_noMatches(self):
"""If no discovered endpoint matches the values from the
assertion, then we end up raising a ProtocolError
"""
self.discovery_result = (None, ['unused'])
def raiseProtocolError(unused1, unused2):
raise ProtocolError('unit test')
self.consumer._verifyDiscoverySingle = raiseProtocolError
self.failUnlessDiscoveryFailure()
def test_matches(self):
"""If an endpoint matches, we return it
"""
# Discovery returns a single "endpoint" object
matching_endpoint = 'matching endpoint'
self.discovery_result = (None, [matching_endpoint])
# Make verifying discovery return True for this endpoint
def returnTrue(unused1, unused2):
return True
self.consumer._verifyDiscoverySingle = returnTrue
# Since _verifyDiscoverySingle returns True, we should get the
# first endpoint that we passed in as a result.
result = self.consumer._discoverAndVerify(
'http://claimed.id/', [self.to_match])
self.assertEqual(matching_endpoint, result)
from openid.extension import Extension
class SillyExtension(Extension):
ns_uri = 'http://silly.example.com/'
ns_alias = 'silly'
def getExtensionArgs(self):
return {'i_am': 'silly'}
class TestAddExtension(unittest.TestCase):
def test_SillyExtension(self):
ext = SillyExtension()
ar = AuthRequest(OpenIDServiceEndpoint(), None)
ar.addExtension(ext)
ext_args = ar.message.getArgs(ext.ns_uri)
self.assertEqual(ext.getExtensionArgs(), ext_args)
class TestKVPost(unittest.TestCase):
def setUp(self):
self.server_url = 'http://unittest/%s' % (self.id(),)
def test_200(self):
from openid.fetchers import HTTPResponse
response = HTTPResponse()
response.status = 200
response.body = "foo:bar\nbaz:quux\n"
r = _httpResponseToMessage(response, self.server_url)
expected_msg = Message.fromOpenIDArgs({'foo': 'bar', 'baz': 'quux'})
self.assertEqual(expected_msg, r)
def test_400(self):
response = HTTPResponse()
response.status = 400
response.body = "error:bonk\nerror_code:7\n"
try:
r = _httpResponseToMessage(response, self.server_url)
except ServerError as e:
self.assertEqual(e.error_text, 'bonk')
self.assertEqual(e.error_code, '7')
else:
self.fail("Expected ServerError, got return %r" % (r,))
def test_500(self):
# 500 as an example of any non-200, non-400 code.
response = HTTPResponse()
response.status = 500
response.body = "foo:bar\nbaz:quux\n"
self.assertRaises(fetchers.HTTPFetchingError,
_httpResponseToMessage, response,
self.server_url)
if __name__ == '__main__':
unittest.main()
|