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
|
// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package api
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/d4l3k/messagediff"
"github.com/thejerf/suture/v4"
"github.com/syncthing/syncthing/lib/assets"
"github.com/syncthing/syncthing/lib/build"
"github.com/syncthing/syncthing/lib/config"
connmocks "github.com/syncthing/syncthing/lib/connections/mocks"
"github.com/syncthing/syncthing/lib/db"
"github.com/syncthing/syncthing/lib/db/backend"
discovermocks "github.com/syncthing/syncthing/lib/discover/mocks"
"github.com/syncthing/syncthing/lib/events"
eventmocks "github.com/syncthing/syncthing/lib/events/mocks"
"github.com/syncthing/syncthing/lib/fs"
"github.com/syncthing/syncthing/lib/locations"
"github.com/syncthing/syncthing/lib/logger"
loggermocks "github.com/syncthing/syncthing/lib/logger/mocks"
"github.com/syncthing/syncthing/lib/model"
modelmocks "github.com/syncthing/syncthing/lib/model/mocks"
"github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/rand"
"github.com/syncthing/syncthing/lib/svcutil"
"github.com/syncthing/syncthing/lib/sync"
"github.com/syncthing/syncthing/lib/tlsutil"
"github.com/syncthing/syncthing/lib/ur"
)
var (
confDir = filepath.Join("testdata", "config")
dev1 protocol.DeviceID
apiCfg = newMockedConfig()
testAPIKey = "foobarbaz"
)
func init() {
dev1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
apiCfg.GUIReturns(config.GUIConfiguration{APIKey: testAPIKey, RawAddress: "127.0.0.1:0"})
}
func TestMain(m *testing.M) {
orig := locations.GetBaseDir(locations.ConfigBaseDir)
locations.SetBaseDir(locations.ConfigBaseDir, confDir)
exitCode := m.Run()
locations.SetBaseDir(locations.ConfigBaseDir, orig)
os.Exit(exitCode)
}
func TestStopAfterBrokenConfig(t *testing.T) {
t.Parallel()
cfg := config.Configuration{
GUI: config.GUIConfiguration{
RawAddress: "127.0.0.1:0",
RawUseTLS: false,
},
}
w := config.Wrap("/dev/null", cfg, protocol.LocalDeviceID, events.NoopLogger)
mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
kdb := db.NewMiscDataNamespace(mdb)
srv := New(protocol.LocalDeviceID, w, "", "syncthing", nil, nil, nil, events.NoopLogger, nil, nil, nil, nil, nil, nil, false, kdb).(*service)
srv.started = make(chan string)
sup := suture.New("test", svcutil.SpecWithDebugLogger(l))
sup.Add(srv)
ctx, cancel := context.WithCancel(context.Background())
sup.ServeBackground(ctx)
<-srv.started
// Service is now running, listening on a random port on localhost. Now we
// request a config change to a completely invalid listen address. The
// commit will fail and the service will be in a broken state.
newCfg := config.Configuration{
GUI: config.GUIConfiguration{
RawAddress: "totally not a valid address",
RawUseTLS: false,
},
}
if err := srv.VerifyConfiguration(cfg, newCfg); err == nil {
t.Fatal("Verify config should have failed")
}
cancel()
}
func TestAssetsDir(t *testing.T) {
t.Parallel()
// For any given request to $FILE, we should return the first found of
// - assetsdir/$THEME/$FILE
// - compiled in asset $THEME/$FILE
// - assetsdir/default/$FILE
// - compiled in asset default/$FILE
// The asset map contains compressed assets, so create a couple of gzip compressed assets here.
buf := new(bytes.Buffer)
gw := gzip.NewWriter(buf)
gw.Write([]byte("default"))
gw.Close()
def := assets.Asset{
Content: buf.String(),
Gzipped: true,
}
buf = new(bytes.Buffer)
gw = gzip.NewWriter(buf)
gw.Write([]byte("foo"))
gw.Close()
foo := assets.Asset{
Content: buf.String(),
Gzipped: true,
}
e := &staticsServer{
theme: "foo",
mut: sync.NewRWMutex(),
assetDir: "testdata",
assets: map[string]assets.Asset{
"foo/a": foo, // overridden in foo/a
"foo/b": foo,
"default/a": def, // overridden in default/a (but foo/a takes precedence)
"default/b": def, // overridden in default/b (but foo/b takes precedence)
"default/c": def,
},
}
s := httptest.NewServer(e)
defer s.Close()
// assetsdir/foo/a exists, overrides compiled in
expectURLToContain(t, s.URL+"/a", "overridden-foo")
// foo/b is compiled in, default/b is overridden, return compiled in
expectURLToContain(t, s.URL+"/b", "foo")
// only exists as compiled in default/c so use that
expectURLToContain(t, s.URL+"/c", "default")
// only exists as overridden default/d so use that
expectURLToContain(t, s.URL+"/d", "overridden-default")
}
func expectURLToContain(t *testing.T, url, exp string) {
res, err := http.Get(url)
if err != nil {
t.Error(err)
return
}
if res.StatusCode != 200 {
t.Errorf("Got %s instead of 200 OK", res.Status)
return
}
data, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Error(err)
return
}
if string(data) != exp {
t.Errorf("Got %q instead of %q on %q", data, exp, url)
return
}
}
func TestDirNames(t *testing.T) {
t.Parallel()
names := dirNames("testdata")
expected := []string{"config", "default", "foo", "testfolder"}
if diff, equal := messagediff.PrettyDiff(expected, names); !equal {
t.Errorf("Unexpected dirNames return: %#v\n%s", names, diff)
}
}
type httpTestCase struct {
URL string // URL to check
Code int // Expected result code
Type string // Expected content type
Prefix string // Expected result prefix
Timeout time.Duration // Defaults to a second
}
func TestAPIServiceRequests(t *testing.T) {
t.Parallel()
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(cancel)
cases := []httpTestCase{
// /rest/db
{
URL: "/rest/db/completion?device=" + protocol.LocalDeviceID.String() + "&folder=default",
Code: 200,
Type: "application/json",
Prefix: "{",
Timeout: 15 * time.Second,
},
{
URL: "/rest/db/file?folder=default&file=something",
Code: 404,
},
{
URL: "/rest/db/ignores?folder=default",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/db/need?folder=default",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/db/status?folder=default",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/db/browse?folder=default",
Code: 200,
Type: "application/json",
Prefix: "null",
},
{
URL: "/rest/db/status?folder=default",
Code: 200,
Type: "application/json",
Prefix: "",
},
// /rest/stats
{
URL: "/rest/stats/device",
Code: 200,
Type: "application/json",
Prefix: "null",
},
{
URL: "/rest/stats/folder",
Code: 200,
Type: "application/json",
Prefix: "null",
},
// /rest/svc
{
URL: "/rest/svc/deviceid?id=" + protocol.LocalDeviceID.String(),
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/svc/lang",
Code: 200,
Type: "application/json",
Prefix: "[",
},
{
URL: "/rest/svc/report",
Code: 200,
Type: "application/json",
Prefix: "{",
Timeout: 5 * time.Second,
},
// /rest/system
{
URL: "/rest/system/browse?current=~",
Code: 200,
Type: "application/json",
Prefix: "[",
},
{
URL: "/rest/system/config",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/config/insync",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/connections",
Code: 200,
Type: "application/json",
Prefix: "null",
},
{
URL: "/rest/system/discovery",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/error?since=0",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/ping",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/status",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/version",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/debug",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/log?since=0",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/system/log.txt?since=0",
Code: 200,
Type: "text/plain",
Prefix: "",
},
// /rest/config
{
URL: "/rest/config",
Code: 200,
Type: "application/json",
Prefix: "",
},
{
URL: "/rest/config/folders",
Code: 200,
Type: "application/json",
Prefix: "",
},
{
URL: "/rest/config/folders/missing",
Code: 404,
Type: "text/plain",
Prefix: "",
},
{
URL: "/rest/config/devices",
Code: 200,
Type: "application/json",
Prefix: "",
},
{
URL: "/rest/config/devices/illegalid",
Code: 400,
Type: "text/plain",
Prefix: "",
},
{
URL: "/rest/config/devices/" + protocol.GlobalDeviceID.String(),
Code: 404,
Type: "text/plain",
Prefix: "",
},
{
URL: "/rest/config/options",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/config/gui",
Code: 200,
Type: "application/json",
Prefix: "{",
},
{
URL: "/rest/config/ldap",
Code: 200,
Type: "application/json",
Prefix: "{",
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.URL, func(t *testing.T) {
t.Parallel()
testHTTPRequest(t, baseURL, tc, testAPIKey)
})
}
}
// testHTTPRequest tries the given test case, comparing the result code,
// content type, and result prefix.
func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) {
// Since running tests in parallel, the previous 1s timeout proved to be too short.
// https://github.com/syncthing/syncthing/issues/9455
timeout := 10 * time.Second
if tc.Timeout > 0 {
timeout = tc.Timeout
}
cli := &http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("GET", baseURL+tc.URL, nil)
if err != nil {
t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
return
}
req.Header.Set("X-API-Key", apikey)
resp, err := cli.Do(req)
if err != nil {
t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
return
}
defer resp.Body.Close()
if resp.StatusCode != tc.Code {
t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status)
return
}
ct := resp.Header.Get("Content-Type")
if !strings.HasPrefix(ct, tc.Type) {
t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct)
return
}
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Unexpected error reading %s: %v", tc.URL, err)
return
}
if !bytes.HasPrefix(data, []byte(tc.Prefix)) {
t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data)
return
}
}
func getSessionCookie(cookies []*http.Cookie) (*http.Cookie, bool) {
for _, cookie := range cookies {
if cookie.MaxAge >= 0 && strings.HasPrefix(cookie.Name, "sessionid") {
return cookie, true
}
}
return nil, false
}
func hasSessionCookie(cookies []*http.Cookie) bool {
_, ok := getSessionCookie(cookies)
return ok
}
func hasDeleteSessionCookie(cookies []*http.Cookie) bool {
for _, cookie := range cookies {
if cookie.MaxAge < 0 && strings.HasPrefix(cookie.Name, "sessionid") {
return true
}
}
return false
}
func httpRequest(method string, url string, body any, basicAuthUsername, basicAuthPassword, xapikeyHeader, authorizationBearer, csrfTokenName, csrfTokenValue string, cookies []*http.Cookie, t *testing.T) *http.Response {
t.Helper()
var bodyReader io.Reader = nil
if body != nil {
bodyBytes, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
bodyReader = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
t.Fatal(err)
}
if basicAuthUsername != "" || basicAuthPassword != "" {
req.SetBasicAuth(basicAuthUsername, basicAuthPassword)
}
if xapikeyHeader != "" {
req.Header.Set("X-API-Key", xapikeyHeader)
}
if authorizationBearer != "" {
req.Header.Set("Authorization", "Bearer "+authorizationBearer)
}
if csrfTokenName != "" && csrfTokenValue != "" {
req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
}
for _, cookie := range cookies {
req.AddCookie(cookie)
}
client := http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func httpGet(url string, basicAuthUsername, basicAuthPassword, xapikeyHeader, authorizationBearer string, cookies []*http.Cookie, t *testing.T) *http.Response {
t.Helper()
return httpRequest(http.MethodGet, url, nil, basicAuthUsername, basicAuthPassword, xapikeyHeader, authorizationBearer, "", "", cookies, t)
}
func httpPost(url string, body map[string]string, cookies []*http.Cookie, t *testing.T) *http.Response {
t.Helper()
return httpRequest(http.MethodPost, url, body, "", "", "", "", "", "", cookies, t)
}
func TestHTTPLogin(t *testing.T) {
t.Parallel()
httpGetBasicAuth := func(url string, username string, password string) *http.Response {
t.Helper()
return httpGet(url, username, password, "", "", nil, t)
}
httpGetXapikey := func(url string, xapikeyHeader string) *http.Response {
t.Helper()
return httpGet(url, "", "", xapikeyHeader, "", nil, t)
}
httpGetAuthorizationBearer := func(url string, bearer string) *http.Response {
t.Helper()
return httpGet(url, "", "", "", bearer, nil, t)
}
testWith := func(sendBasicAuthPrompt bool, expectedOkStatus int, expectedFailStatus int, path string) {
cfg := newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
User: "üser",
Password: "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq", // bcrypt of "räksmörgås" in UTF-8
RawAddress: "127.0.0.1:0",
APIKey: testAPIKey,
SendBasicAuthPrompt: sendBasicAuthPrompt,
})
baseURL, cancel, err := startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(cancel)
url := baseURL + path
t.Run(fmt.Sprintf("%d path", expectedOkStatus), func(t *testing.T) {
t.Run("no auth is rejected", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "", "")
if resp.StatusCode != expectedFailStatus {
t.Errorf("Unexpected non-%d return code %d for unauthed request", expectedFailStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for unauthed request")
}
})
t.Run("incorrect password is rejected", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "üser", "rksmrgs")
if resp.StatusCode != expectedFailStatus {
t.Errorf("Unexpected non-%d return code %d for incorrect password", expectedFailStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for incorrect password")
}
})
t.Run("incorrect username is rejected", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "user", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != expectedFailStatus {
t.Errorf("Unexpected non-%d return code %d for incorrect username", expectedFailStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for incorrect username")
}
})
t.Run("UTF-8 auth works", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
}
if !hasSessionCookie(resp.Cookies()) {
t.Errorf("Expected session cookie for authed request (UTF-8)")
}
})
t.Run("Logout removes the session cookie", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
}
if !hasSessionCookie(resp.Cookies()) {
t.Errorf("Expected session cookie for authed request (UTF-8)")
}
logoutResp := httpPost(baseURL+"/rest/noauth/auth/logout", nil, resp.Cookies(), t)
if !hasDeleteSessionCookie(logoutResp.Cookies()) {
t.Errorf("Expected session cookie to be deleted for logout request")
}
})
t.Run("Session cookie is invalid after logout", func(t *testing.T) {
t.Parallel()
loginResp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
if loginResp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, loginResp.StatusCode)
}
if !hasSessionCookie(loginResp.Cookies()) {
t.Errorf("Expected session cookie for authed request (UTF-8)")
}
resp := httpGet(url, "", "", "", "", loginResp.Cookies(), t)
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for cookie-authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
}
httpPost(baseURL+"/rest/noauth/auth/logout", nil, loginResp.Cookies(), t)
resp = httpGet(url, "", "", "", "", loginResp.Cookies(), t)
if resp.StatusCode != expectedFailStatus {
t.Errorf("Expected session to be invalid (status %d) after logout, got status: %d", expectedFailStatus, resp.StatusCode)
}
})
t.Run("ISO-8859-1 auth works", func(t *testing.T) {
t.Parallel()
resp := httpGetBasicAuth(url, "\xfcser", "r\xe4ksm\xf6rg\xe5s") // escaped ISO-8859-1
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for authed request (ISO-8859-1)", expectedOkStatus, resp.StatusCode)
}
if !hasSessionCookie(resp.Cookies()) {
t.Errorf("Expected session cookie for authed request (ISO-8859-1)")
}
})
t.Run("bad X-API-Key is rejected", func(t *testing.T) {
t.Parallel()
resp := httpGetXapikey(url, testAPIKey+"X")
if resp.StatusCode != expectedFailStatus {
t.Errorf("Unexpected non-%d return code %d for bad API key", expectedFailStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for bad API key")
}
})
t.Run("good X-API-Key is accepted", func(t *testing.T) {
t.Parallel()
resp := httpGetXapikey(url, testAPIKey)
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for API key", expectedOkStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for API key")
}
})
t.Run("bad Bearer is rejected", func(t *testing.T) {
t.Parallel()
resp := httpGetAuthorizationBearer(url, testAPIKey+"X")
if resp.StatusCode != expectedFailStatus {
t.Errorf("Unexpected non-%d return code %d for bad Authorization: Bearer", expectedFailStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for bad Authorization: Bearer")
}
})
t.Run("good Bearer is accepted", func(t *testing.T) {
t.Parallel()
resp := httpGetAuthorizationBearer(url, testAPIKey)
if resp.StatusCode != expectedOkStatus {
t.Errorf("Unexpected non-%d return code %d for Authorization: Bearer", expectedOkStatus, resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for bad Authorization: Bearer")
}
})
})
}
testWith(true, http.StatusOK, http.StatusOK, "/")
testWith(true, http.StatusOK, http.StatusUnauthorized, "/meta.js")
testWith(true, http.StatusNotFound, http.StatusUnauthorized, "/any-path/that/does/nooooooot/match-any/noauth-pattern")
testWith(false, http.StatusOK, http.StatusOK, "/")
testWith(false, http.StatusOK, http.StatusForbidden, "/meta.js")
testWith(false, http.StatusNotFound, http.StatusForbidden, "/any-path/that/does/nooooooot/match-any/noauth-pattern")
t.Run("Password change invalidates old and enables new password", func(t *testing.T) {
t.Parallel()
// This test needs a longer-than-default shutdown timeout to finish saving
// config changes when running on GitHub Actions
shutdownTimeout := time.Second
initConfig := func(password string, t *testing.T) config.Wrapper {
gui := config.GUIConfiguration{
RawAddress: "127.0.0.1:0",
APIKey: testAPIKey,
User: "user",
}
if err := gui.SetPassword(password); err != nil {
t.Fatal(err, "Failed to set initial password")
}
cfg := config.Configuration{
GUI: gui,
}
tmpFile, err := os.CreateTemp("", "syncthing-testConfig-Password-*")
if err != nil {
t.Fatal(err, "Failed to create tmpfile for test")
}
w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
tmpFile.Close()
cfgCtx, cfgCancel := context.WithCancel(context.Background())
go w.Serve(cfgCtx)
t.Cleanup(func() {
os.Remove(tmpFile.Name())
cfgCancel()
})
return w
}
initialPassword := "Asdf123!"
newPassword := "123!asdF"
t.Run("when done via /rest/config", func(t *testing.T) {
t.Parallel()
w := initConfig(initialPassword, t)
{
baseURL, cancel, err := startHTTPWithShutdownTimeout(w, shutdownTimeout)
cfgPath := baseURL + "/rest/config"
path := baseURL + "/meta.js"
t.Cleanup(cancel)
if err != nil {
t.Fatal(err)
}
resp := httpGetBasicAuth(path, "user", initialPassword)
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected non-200 return code %d for auth with initial password", resp.StatusCode)
}
cfg := w.RawCopy()
cfg.GUI.Password = newPassword
httpRequest(http.MethodPut, cfgPath, cfg, "", "", testAPIKey, "", "", "", nil, t)
}
{
baseURL, cancel, err := startHTTP(w)
path := baseURL + "/meta.js"
t.Cleanup(cancel)
if err != nil {
t.Fatal(err)
}
resp := httpGetBasicAuth(path, "user", initialPassword)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for request authed with old password", resp.StatusCode)
}
resp2 := httpGetBasicAuth(path, "user", newPassword)
if resp2.StatusCode != http.StatusOK {
t.Errorf("Unexpected non-200 return code %d for request authed with new password", resp2.StatusCode)
}
}
})
t.Run("when done via /rest/config/gui", func(t *testing.T) {
t.Parallel()
w := initConfig(initialPassword, t)
{
baseURL, cancel, err := startHTTPWithShutdownTimeout(w, shutdownTimeout)
cfgPath := baseURL + "/rest/config/gui"
path := baseURL + "/meta.js"
t.Cleanup(cancel)
if err != nil {
t.Fatal(err)
}
resp := httpGetBasicAuth(path, "user", initialPassword)
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected non-200 return code %d for auth with initial password", resp.StatusCode)
}
cfg := w.RawCopy()
cfg.GUI.Password = newPassword
httpRequest(http.MethodPut, cfgPath, cfg.GUI, "", "", testAPIKey, "", "", "", nil, t)
}
{
baseURL, cancel, err := startHTTP(w)
path := baseURL + "/meta.js"
t.Cleanup(cancel)
if err != nil {
t.Fatal(err)
}
resp := httpGetBasicAuth(path, "user", initialPassword)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for request authed with old password", resp.StatusCode)
}
resp2 := httpGetBasicAuth(path, "user", newPassword)
if resp2.StatusCode != http.StatusOK {
t.Errorf("Unexpected non-200 return code %d for request authed with new password", resp2.StatusCode)
}
}
})
})
}
func TestHtmlFormLogin(t *testing.T) {
t.Parallel()
cfg := newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
User: "üser",
Password: "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq", // bcrypt of "räksmörgås" in UTF-8
SendBasicAuthPrompt: false,
})
baseURL, cancel, err := startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(cancel)
loginUrl := baseURL + "/rest/noauth/auth/password"
resourceUrl := baseURL + "/meta.js"
resourceUrl404 := baseURL + "/any-path/that/does/nooooooot/match-any/noauth-pattern"
performLogin := func(username string, password string) *http.Response {
t.Helper()
return httpPost(loginUrl, map[string]string{"username": username, "password": password}, nil, t)
}
performResourceRequest := func(url string, cookies []*http.Cookie) *http.Response {
t.Helper()
return httpGet(url, "", "", "", "", cookies, t)
}
testNoAuthPath := func(noAuthPath string) {
t.Run("auth is not needed for "+noAuthPath, func(t *testing.T) {
t.Parallel()
resp := httpGet(baseURL+noAuthPath, "", "", "", "", nil, t)
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected non-200 return code %d at %s", resp.StatusCode, noAuthPath)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie at " + noAuthPath)
}
})
}
testNoAuthPath("/index.html")
testNoAuthPath("/rest/svc/lang")
t.Run("incorrect password is rejected with 403", func(t *testing.T) {
t.Parallel()
resp := performLogin("üser", "rksmrgs") // string literals in Go source code are in UTF-8
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for incorrect password", resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for incorrect password")
}
resp = performResourceRequest(resourceUrl, resp.Cookies())
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for incorrect password", resp.StatusCode)
}
})
t.Run("incorrect username is rejected with 403", func(t *testing.T) {
t.Parallel()
resp := performLogin("user", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for incorrect username", resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for incorrect username")
}
resp = performResourceRequest(resourceUrl, resp.Cookies())
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for incorrect username", resp.StatusCode)
}
})
t.Run("UTF-8 auth works", func(t *testing.T) {
t.Parallel()
// JSON is always UTF-8, so ISO-8859-1 case is not applicable
resp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != http.StatusNoContent {
t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", resp.StatusCode)
}
resp = performResourceRequest(resourceUrl, resp.Cookies())
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
}
})
t.Run("Logout removes the session cookie", func(t *testing.T) {
t.Parallel()
// JSON is always UTF-8, so ISO-8859-1 case is not applicable
resp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
if resp.StatusCode != http.StatusNoContent {
t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", resp.StatusCode)
}
logoutResp := httpPost(baseURL+"/rest/noauth/auth/logout", nil, resp.Cookies(), t)
if !hasDeleteSessionCookie(logoutResp.Cookies()) {
t.Errorf("Expected session cookie to be deleted for logout request")
}
})
t.Run("Session cookie is invalid after logout", func(t *testing.T) {
t.Parallel()
// JSON is always UTF-8, so ISO-8859-1 case is not applicable
loginResp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
if loginResp.StatusCode != http.StatusNoContent {
t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", loginResp.StatusCode)
}
resp := performResourceRequest(resourceUrl, loginResp.Cookies())
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
}
httpPost(baseURL+"/rest/noauth/auth/logout", nil, loginResp.Cookies(), t)
resp = performResourceRequest(resourceUrl, loginResp.Cookies())
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Expected session to be invalid (status 403) after logout, got status: %d", resp.StatusCode)
}
})
t.Run("form login is not applicable to other URLs", func(t *testing.T) {
t.Parallel()
resp := httpPost(baseURL+"/meta.js", map[string]string{"username": "üser", "password": "räksmörgås"}, nil, t)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for incorrect form login URL", resp.StatusCode)
}
if hasSessionCookie(resp.Cookies()) {
t.Errorf("Unexpected session cookie for incorrect form login URL")
}
})
t.Run("invalid URL returns 403 before auth and 404 after auth", func(t *testing.T) {
t.Parallel()
resp := performResourceRequest(resourceUrl404, nil)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Unexpected non-403 return code %d for unauthed request", resp.StatusCode)
}
resp = performLogin("üser", "räksmörgås")
if resp.StatusCode != http.StatusNoContent {
t.Errorf("Unexpected non-204 return code %d for authed request", resp.StatusCode)
}
resp = performResourceRequest(resourceUrl404, resp.Cookies())
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Unexpected non-404 return code %d for authed request", resp.StatusCode)
}
})
}
func TestApiCache(t *testing.T) {
t.Parallel()
cfg := newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
RawAddress: "127.0.0.1:0",
APIKey: testAPIKey,
})
baseURL, cancel, err := startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(cancel)
httpGet := func(url string, bearer string) *http.Response {
return httpGet(url, "", "", "", bearer, nil, t)
}
t.Run("meta.js has no-cache headers", func(t *testing.T) {
t.Parallel()
url := baseURL + "/meta.js"
resp := httpGet(url, testAPIKey)
if resp.Header.Get("Cache-Control") != "max-age=0, no-cache, no-store" {
t.Errorf("Expected no-cache headers at %s", url)
}
})
t.Run("/rest/ has no-cache headers", func(t *testing.T) {
t.Parallel()
url := baseURL + "/rest/system/version"
resp := httpGet(url, testAPIKey)
if resp.Header.Get("Cache-Control") != "max-age=0, no-cache, no-store" {
t.Errorf("Expected no-cache headers at %s", url)
}
})
}
func startHTTP(cfg config.Wrapper) (string, context.CancelFunc, error) {
return startHTTPWithShutdownTimeout(cfg, 0)
}
func startHTTPWithShutdownTimeout(cfg config.Wrapper, shutdownTimeout time.Duration) (string, context.CancelFunc, error) {
m := new(modelmocks.Model)
assetDir := "../../gui"
eventSub := new(eventmocks.BufferedSubscription)
diskEventSub := new(eventmocks.BufferedSubscription)
discoverer := new(discovermocks.Manager)
connections := new(connmocks.Service)
errorLog := new(loggermocks.Recorder)
systemLog := new(loggermocks.Recorder)
for _, l := range []*loggermocks.Recorder{errorLog, systemLog} {
l.SinceReturns([]logger.Line{
{
When: time.Now(),
Message: "Test message",
},
})
}
addrChan := make(chan string)
mockedSummary := &modelmocks.FolderSummaryService{}
mockedSummary.SummaryReturns(new(model.FolderSummary), nil)
// Instantiate the API service
urService := ur.New(cfg, m, connections, false)
mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
kdb := db.NewMiscDataNamespace(mdb)
svc := New(protocol.LocalDeviceID, cfg, assetDir, "syncthing", m, eventSub, diskEventSub, events.NoopLogger, discoverer, connections, urService, mockedSummary, errorLog, systemLog, false, kdb).(*service)
svc.started = addrChan
if shutdownTimeout > 0*time.Millisecond {
svc.shutdownTimeout = shutdownTimeout
}
// Actually start the API service
supervisor := suture.New("API test", suture.Spec{
PassThroughPanics: true,
})
supervisor.Add(svc)
ctx, cancel := context.WithCancel(context.Background())
supervisor.ServeBackground(ctx)
// Make sure the API service is listening, and get the URL to use.
addr := <-addrChan
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
cancel()
return "", cancel, fmt.Errorf("weird address from API service: %w", err)
}
host, _, _ := net.SplitHostPort(cfg.GUI().RawAddress)
if host == "" || host == "0.0.0.0" {
host = "127.0.0.1"
}
baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
return baseURL, cancel, nil
}
func TestCSRFRequired(t *testing.T) {
t.Parallel()
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
t.Fatal("Unexpected error from getting base URL:", err)
}
t.Cleanup(cancel)
cli := &http.Client{
Timeout: time.Minute,
}
// Getting the base URL (i.e. "/") should succeed.
resp, err := cli.Get(baseURL)
if err != nil {
t.Fatal("Unexpected error from getting base URL:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal("Getting base URL should succeed, not", resp.Status)
}
// Find the returned CSRF token for future use
var csrfTokenName, csrfTokenValue string
for _, cookie := range resp.Cookies() {
if strings.HasPrefix(cookie.Name, "CSRF-Token") {
csrfTokenName = cookie.Name
csrfTokenValue = cookie.Value
break
}
}
if csrfTokenValue == "" {
t.Fatal("Failed to initialize CSRF test: no CSRF cookie returned from " + baseURL)
}
t.Run("/rest without a token should fail", func(t *testing.T) {
t.Parallel()
resp, err := cli.Get(baseURL + "/rest/system/config")
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
}
})
t.Run("/rest with a token should succeed", func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
resp, err := cli.Do(req)
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
}
})
t.Run("/rest with an incorrect API key should fail, X-API-Key version", func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
req.Header.Set("X-API-Key", testAPIKey+"X")
resp, err := cli.Do(req)
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
}
})
t.Run("/rest with an incorrect API key should fail, Bearer auth version", func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
req.Header.Set("Authorization", "Bearer "+testAPIKey+"X")
resp, err := cli.Do(req)
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
}
})
t.Run("/rest with the API key should succeed", func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
req.Header.Set("X-API-Key", testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
}
})
t.Run("/rest with the API key as a bearer token should succeed", func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
req.Header.Set("Authorization", "Bearer "+testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal("Unexpected error from getting /rest/system/config:", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
}
})
}
func TestRandomString(t *testing.T) {
t.Parallel()
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
cli := &http.Client{
Timeout: time.Second,
}
// The default should be to return a 32 character random string
for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
req, _ := http.NewRequest("GET", baseURL+url, nil)
req.Header.Set("X-API-Key", testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal(err)
}
var res map[string]string
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
t.Fatal(err)
}
if len(res["random"]) != 32 {
t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
}
}
// We can ask for a different length if we like
req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
req.Header.Set("X-API-Key", testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal(err)
}
var res map[string]string
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
t.Fatal(err)
}
if len(res["random"]) != 27 {
t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
}
}
func TestConfigPostOK(t *testing.T) {
t.Parallel()
cfg := bytes.NewBuffer([]byte(`{
"version": 15,
"folders": [
{
"id": "foo",
"path": "TestConfigPostOK"
}
]
}`))
resp, err := testConfigPost(cfg)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Error("Expected 200 OK, not", resp.Status)
}
os.RemoveAll("TestConfigPostOK")
}
func TestConfigPostDupFolder(t *testing.T) {
t.Parallel()
cfg := bytes.NewBuffer([]byte(`{
"version": 15,
"folders": [
{"id": "foo"},
{"id": "foo"}
]
}`))
resp, err := testConfigPost(cfg)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusBadRequest {
t.Error("Expected 400 Bad Request, not", resp.Status)
}
}
func testConfigPost(data io.Reader) (*http.Response, error) {
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
return nil, err
}
defer cancel()
cli := &http.Client{
Timeout: time.Second,
}
req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
req.Header.Set("X-API-Key", testAPIKey)
return cli.Do(req)
}
func TestHostCheck(t *testing.T) {
t.Skip()
t.Parallel()
// An API service bound to localhost should reject non-localhost host Headers
cfg := newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{RawAddress: "127.0.0.1:0"})
baseURL, cancel, err := startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
// A normal HTTP get to the localhost-bound service should succeed
resp, err := http.Get(baseURL)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
}
// A request with a suspicious Host header should fail
req, _ := http.NewRequest("GET", baseURL, nil)
req.Host = "example.com"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
}
// A request with an explicit "localhost:8384" Host header should pass
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "localhost:8384"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
}
// A request with an explicit "localhost" Host header (no port) should pass
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "localhost"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
}
// A server with InsecureSkipHostCheck set behaves differently
cfg = newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
RawAddress: "127.0.0.1:0",
InsecureSkipHostCheck: true,
})
baseURL, cancel, err = startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
// A request with a suspicious Host header should be allowed
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "example.com"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
}
if !testing.Short() {
// A server bound to a wildcard address also doesn't do the check
cfg = newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
RawAddress: "0.0.0.0:0",
})
baseURL, cancel, err = startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
// A request with a suspicious Host header should be allowed
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "example.com"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
}
}
// This should all work over IPv6 as well
if runningInContainer() {
// Working IPv6 in Docker can't be taken for granted.
return
}
cfg = newMockedConfig()
cfg.GUIReturns(config.GUIConfiguration{
RawAddress: "[::1]:0",
})
baseURL, cancel, err = startHTTP(cfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
// A normal HTTP get to the localhost-bound service should succeed
resp, err = http.Get(baseURL)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
}
// A request with a suspicious Host header should fail
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "example.com"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
}
// A request with an explicit "localhost:8384" Host header should pass
req, _ = http.NewRequest("GET", baseURL, nil)
req.Host = "localhost:8384"
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
}
}
func TestAddressIsLocalhost(t *testing.T) {
t.Parallel()
testcases := []struct {
address string
result bool
}{
// These are all valid localhost addresses
{"localhost", true},
{"LOCALHOST", true},
{"localhost.", true},
{"::1", true},
{"127.0.0.1", true},
{"127.23.45.56", true},
{"localhost:8080", true},
{"LOCALHOST:8000", true},
{"localhost.:8080", true},
{"[::1]:8080", true},
{"127.0.0.1:8080", true},
{"127.23.45.56:8080", true},
{"www.localhost", true},
{"www.localhost:8080", true},
// These are all non-localhost addresses
{"example.com", false},
{"example.com:8080", false},
{"localhost.com", false},
{"localhost.com:8080", false},
{"192.0.2.10", false},
{"192.0.2.10:8080", false},
{"0.0.0.0", false},
{"0.0.0.0:8080", false},
{"::", false},
{"[::]:8080", false},
{":8080", false},
}
for _, tc := range testcases {
result := addressIsLocalhost(tc.address)
if result != tc.result {
t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
}
}
}
func TestAccessControlAllowOriginHeader(t *testing.T) {
t.Parallel()
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
cli := &http.Client{
Timeout: time.Second,
}
req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
req.Header.Set("X-API-Key", testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
}
if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
}
}
func TestOptionsRequest(t *testing.T) {
t.Parallel()
baseURL, cancel, err := startHTTP(apiCfg)
if err != nil {
t.Fatal(err)
}
defer cancel()
cli := &http.Client{
Timeout: time.Second,
}
req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
resp, err := cli.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
}
if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
}
if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, PATCH, DELETE, OPTIONS" {
t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' header")
}
if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
}
}
func TestEventMasks(t *testing.T) {
t.Parallel()
cfg := newMockedConfig()
defSub := new(eventmocks.BufferedSubscription)
diskSub := new(eventmocks.BufferedSubscription)
mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
kdb := db.NewMiscDataNamespace(mdb)
svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, events.NoopLogger, nil, nil, nil, nil, nil, nil, false, kdb).(*service)
if mask := svc.getEventMask(""); mask != DefaultEventMask {
t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
}
expected := events.FolderSummary | events.LocalChangeDetected
if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
}
expected = 0
if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
}
if res := svc.getEventSub(DefaultEventMask); res != defSub {
t.Errorf("should have returned the given default event sub")
}
if res := svc.getEventSub(DiskEventMask); res != diskSub {
t.Errorf("should have returned the given disk event sub")
}
if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
t.Errorf("should have returned a valid, non-default event sub")
}
}
func TestBrowse(t *testing.T) {
t.Parallel()
pathSep := string(os.PathSeparator)
ffs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?nostfolder=true")
_ = ffs.Mkdir("dir", 0o755)
_ = fs.WriteFile(ffs, "file", []byte("hello"), 0o644)
_ = ffs.Mkdir("MiXEDCase", 0o755)
// We expect completion to return the full path to the completed
// directory, with an ending slash.
dirPath := "dir" + pathSep
mixedCaseDirPath := "MiXEDCase" + pathSep
cases := []struct {
current string
returns []string
}{
// The directory without slash is completed to one with slash.
{"dir", []string{"dir" + pathSep}},
// With slash it's completed to its contents.
// Dirs are given pathSeps.
// Files are not returned.
{"", []string{mixedCaseDirPath, dirPath}},
// Globbing is automatic based on prefix.
{"d", []string{dirPath}},
{"di", []string{dirPath}},
{"dir", []string{dirPath}},
{"f", nil},
{"q", nil},
// Globbing is case-insensitive
{"mixed", []string{mixedCaseDirPath}},
}
for _, tc := range cases {
ret := browseFiles(ffs, tc.current)
if !slices.Equal(ret, tc.returns) {
t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
}
}
}
func TestPrefixMatch(t *testing.T) {
t.Parallel()
cases := []struct {
s string
prefix string
expected int
}{
{"aaaA", "aaa", matchExact},
{"AAAX", "BBB", noMatch},
{"AAAX", "aAa", matchCaseIns},
{"äÜX", "äü", matchCaseIns},
}
for _, tc := range cases {
ret := checkPrefixMatch(tc.s, tc.prefix)
if ret != tc.expected {
t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
}
}
}
func TestShouldRegenerateCertificate(t *testing.T) {
// Self signed certificates expiring in less than a month are errored so we
// can regenerate in time.
crt, err := tlsutil.NewCertificateInMemory("foo.example.com", 29)
if err != nil {
t.Fatal(err)
}
if err := shouldRegenerateCertificate(crt); err == nil {
t.Error("expected expiry error")
}
// Certificates with at least 31 days of life left are fine.
crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 31)
if err != nil {
t.Fatal(err)
}
if err := shouldRegenerateCertificate(crt); err != nil {
t.Error("expected no error:", err)
}
if build.IsDarwin {
// Certificates with too long an expiry time are not allowed on macOS
crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 1000)
if err != nil {
t.Fatal(err)
}
if err := shouldRegenerateCertificate(crt); err == nil {
t.Error("expected expiry error")
}
}
}
func TestConfigChanges(t *testing.T) {
t.Parallel()
const testAPIKey = "foobarbaz"
cfg := config.Configuration{
GUI: config.GUIConfiguration{
RawAddress: "127.0.0.1:0",
RawUseTLS: false,
APIKey: testAPIKey,
},
}
tmpFile, err := os.CreateTemp("", "syncthing-testConfig-")
if err != nil {
panic(err)
}
defer os.Remove(tmpFile.Name())
w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
tmpFile.Close()
cfgCtx, cfgCancel := context.WithCancel(context.Background())
go w.Serve(cfgCtx)
defer cfgCancel()
baseURL, cancel, err := startHTTP(w)
if err != nil {
t.Fatal("Unexpected error from getting base URL:", err)
}
defer cancel()
cli := &http.Client{
Timeout: time.Minute,
}
do := func(req *http.Request, status int) *http.Response {
t.Helper()
req.Header.Set("X-API-Key", testAPIKey)
resp, err := cli.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != status {
t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
}
return resp
}
mod := func(method, path string, data interface{}) {
t.Helper()
bs, err := json.Marshal(data)
if err != nil {
t.Fatal(err)
}
req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
do(req, http.StatusOK).Body.Close()
}
get := func(path string) *http.Response {
t.Helper()
req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
return do(req, http.StatusOK)
}
dev1Path := "/rest/config/devices/" + dev1.String()
// Create device
mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
// Check its there
get(dev1Path).Body.Close()
// Modify just a single attribute
mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
// Check that attribute
resp := get(dev1Path)
var dev config.DeviceConfiguration
if err := unmarshalTo(resp.Body, &dev); err != nil {
t.Fatal(err)
}
if !dev.Paused {
t.Error("Expected device to be paused")
}
folder2Path := "/rest/config/folders/folder2"
// Create a folder and add another
mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
// Check they are there
get("/rest/config/folders/folder1").Body.Close()
get(folder2Path).Body.Close()
// Modify just a single attribute
mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
// Check that attribute
resp = get(folder2Path)
var folder config.FolderConfiguration
if err := unmarshalTo(resp.Body, &folder); err != nil {
t.Fatal(err)
}
if !dev.Paused {
t.Error("Expected folder to be paused")
}
// Delete folder2
req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
do(req, http.StatusOK)
// Check folder1 is still there and folder2 gone
get("/rest/config/folders/folder1").Body.Close()
req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
do(req, http.StatusNotFound)
mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
resp = get("/rest/config/options")
var opts config.OptionsConfiguration
if err := unmarshalTo(resp.Body, &opts); err != nil {
t.Fatal(err)
}
if opts.MaxSendKbps != 50 {
t.Error("Expected 50 for MaxSendKbps, got", opts.MaxSendKbps)
}
}
func TestSanitizedHostname(t *testing.T) {
cases := []struct {
in, out string
}{
{"foo.BAR-baz", "foo.bar-baz"},
{"~.~-Min 1:a Räksmörgås-dator 😀😎 ~.~-", "min1araksmorgas-dator"},
{"Vicenç-PC", "vicenc-pc"},
{"~.~-~.~-", ""},
{"", ""},
}
for _, tc := range cases {
res, err := sanitizedHostname(tc.in)
if tc.out == "" && err == nil {
t.Errorf("%q should cause error", tc.in)
} else if res != tc.out {
t.Errorf("%q => %q, expected %q", tc.in, res, tc.out)
}
}
}
// runningInContainer returns true if we are inside Docker or LXC. It might
// be prone to false negatives if things change in the future, but likely
// not false positives.
func runningInContainer() bool {
if !build.IsLinux {
return false
}
bs, err := os.ReadFile("/proc/1/cgroup")
if err != nil {
return false
}
if bytes.Contains(bs, []byte("/docker/")) {
return true
}
if bytes.Contains(bs, []byte("/lxc/")) {
return true
}
return false
}
|