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
|
package project
import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/server/auth"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/db/cluster"
deviceconfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/idmap"
"github.com/lxc/incus/v6/shared/units"
"github.com/lxc/incus/v6/shared/util"
)
// HiddenStoragePools returns a list of storage pools that should be hidden from users of the project.
func HiddenStoragePools(ctx context.Context, tx *db.ClusterTx, projectName string) ([]string, error) {
dbProject, err := cluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return nil, fmt.Errorf("Failed getting project: %w", err)
}
project, err := dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return nil, err
}
hiddenPools := []string{}
for k, v := range project.Config {
if !strings.HasPrefix(k, projectLimitDiskPool) || v != "0" {
continue
}
fields := strings.SplitN(k, projectLimitDiskPool, 2)
if len(fields) == 2 {
hiddenPools = append(hiddenPools, fields[1])
}
}
return hiddenPools, nil
}
// AllowInstanceCreation returns an error if any project-specific limit or
// restriction is violated when creating a new instance.
func AllowInstanceCreation(tx *db.ClusterTx, projectName string, req api.InstancesPost) error {
info, err := fetchProject(tx, projectName, true)
if err != nil {
return err
}
if info == nil {
return nil
}
var instanceType instancetype.Type
switch req.Type {
case api.InstanceTypeContainer:
instanceType = instancetype.Container
case api.InstanceTypeVM:
instanceType = instancetype.VM
default:
return fmt.Errorf("Unexpected instance type %q", req.Type)
}
if req.Profiles == nil {
req.Profiles = []string{"default"}
}
err = checkInstanceCountLimit(info, instanceType)
if err != nil {
return err
}
err = checkTotalInstanceCountLimit(info)
if err != nil {
return err
}
// Add the instance being created.
info.Instances = append(info.Instances, api.Instance{
Name: req.Name,
Project: projectName,
InstancePut: req.InstancePut,
Type: string(req.Type),
})
// Special case restriction checks on volatile.* keys.
strip := false
if slices.Contains([]string{"copy", "migration"}, req.Source.Type) {
// Allow stripping volatile keys if dealing with a copy or migration.
strip = true
}
err = checkRestrictionsOnVolatileConfig(
info.Project, instanceType, req.Name, req.Config, map[string]string{}, strip)
if err != nil {
return err
}
err = checkRestrictionsAndAggregateLimits(tx, info)
if err != nil {
return fmt.Errorf("Failed checking if instance creation allowed: %w", err)
}
return nil
}
// Check that we have not exceeded the maximum total allotted number of instances for both containers and vms.
func checkTotalInstanceCountLimit(info *projectInfo) error {
count, limit, err := getTotalInstanceCountLimit(info)
if err != nil {
return err
}
if limit >= 0 && count >= limit {
return fmt.Errorf("Reached maximum number of instances in project %q", info.Project.Name)
}
return nil
}
func getTotalInstanceCountLimit(info *projectInfo) (int, int, error) {
overallValue, ok := info.Project.Config["limits.instances"]
if ok {
limit, err := strconv.Atoi(overallValue)
if err != nil {
return -1, -1, err
}
return len(info.Instances), limit, nil
}
return len(info.Instances), -1, nil
}
// Check that we have not reached the maximum number of instances for this type.
func checkInstanceCountLimit(info *projectInfo, instanceType instancetype.Type) error {
count, limit, err := getInstanceCountLimit(info, instanceType)
if err != nil {
return err
}
if limit >= 0 && count >= limit {
return fmt.Errorf("Reached maximum number of instances of type %q in project %q", instanceType, info.Project.Name)
}
return nil
}
func getInstanceCountLimit(info *projectInfo, instanceType instancetype.Type) (int, int, error) {
var key string
switch instanceType {
case instancetype.Container:
key = "limits.containers"
case instancetype.VM:
key = "limits.virtual-machines"
default:
return -1, -1, fmt.Errorf("Unexpected instance type %q", instanceType)
}
instanceCount := 0
for _, inst := range info.Instances {
if inst.Type == instanceType.String() {
instanceCount++
}
}
value, ok := info.Project.Config[key]
if ok {
limit, err := strconv.Atoi(value)
if err != nil || limit < 0 {
return -1, -1, fmt.Errorf("Unexpected %q value: %q", key, value)
}
return instanceCount, limit, nil
}
return instanceCount, -1, nil
}
// Check restrictions on setting volatile.* keys.
func checkRestrictionsOnVolatileConfig(project api.Project, instanceType instancetype.Type, instanceName string, config, currentConfig map[string]string, strip bool) error {
if project.Config["restrict"] == "false" {
return nil
}
var restrictedLowLevel string
switch instanceType {
case instancetype.Container:
restrictedLowLevel = "restricted.containers.lowlevel"
case instancetype.VM:
restrictedLowLevel = "restricted.virtual-machines.lowlevel"
}
if project.Config[restrictedLowLevel] == "allow" {
return nil
}
// Checker for safe volatile keys.
isSafeKey := func(key string) bool {
if slices.Contains([]string{"volatile.apply_template", "volatile.base_image", "volatile.last_state.power"}, key) {
return true
}
if strings.HasPrefix(key, instance.ConfigVolatilePrefix) {
if strings.HasSuffix(key, ".apply_quota") {
return true
}
if strings.HasSuffix(key, ".hwaddr") {
return true
}
}
return false
}
for key, value := range config {
if !strings.HasPrefix(key, instance.ConfigVolatilePrefix) {
continue
}
// Allow given safe volatile keys to be set
if isSafeKey(key) {
continue
}
if strip {
delete(config, key)
continue
}
currentValue, ok := currentConfig[key]
if !ok {
return fmt.Errorf("Setting %q on %s %q in project %q is forbidden", key, instanceType, instanceName, project.Name)
}
if currentValue != value {
return fmt.Errorf("Changing %q on %s %q in project %q is forbidden", key, instanceType, instanceName, project.Name)
}
}
return nil
}
// AllowVolumeCreation returns an error if any project-specific limit or
// restriction is violated when creating a new custom volume in a project.
func AllowVolumeCreation(tx *db.ClusterTx, projectName string, poolName string, req api.StorageVolumesPost) error {
info, err := fetchProject(tx, projectName, true)
if err != nil {
return err
}
if info == nil {
return nil
}
// If "limits.disk" is not set, there's nothing to do.
if info.Project.Config["limits.disk"] == "" {
return nil
}
// Add the volume being created.
info.Volumes = append(info.Volumes, db.StorageVolumeArgs{
Name: req.Name,
Config: req.Config,
PoolName: poolName,
})
err = checkRestrictionsAndAggregateLimits(tx, info)
if err != nil {
return fmt.Errorf("Failed checking if volume creation allowed: %w", err)
}
return nil
}
// GetImageSpaceBudget returns how much disk space is left in the given project
// for writing images.
//
// If no limit is in place, return -1.
func GetImageSpaceBudget(tx *db.ClusterTx, projectName string) (int64, error) {
info, err := fetchProject(tx, projectName, true)
if err != nil {
return -1, err
}
if info == nil {
return -1, nil
}
// If "features.images" is not enabled, the budget is unlimited.
if util.IsFalse(info.Project.Config["features.images"]) {
return -1, nil
}
// If "limits.disk" is not set, the budget is unlimited.
if info.Project.Config["limits.disk"] == "" {
return -1, nil
}
parser := aggregateLimitConfigValueParsers["limits.disk"]
quota, err := parser(info.Project.Config["limits.disk"])
if err != nil {
return -1, err
}
instances, err := expandInstancesConfigAndDevices(info.Instances, info.Profiles)
if err != nil {
return -1, err
}
info.Instances = instances
totals, err := getTotalsAcrossProjectEntities(info, []string{"limits.disk"}, false)
if err != nil {
return -1, err
}
if totals["limits.disk"] < quota {
return quota - totals["limits.disk"], nil
}
return 0, nil
}
// Check that we would not violate the project limits or restrictions if we
// were to commit the given instances and profiles.
func checkRestrictionsAndAggregateLimits(tx *db.ClusterTx, info *projectInfo) error {
// List of config keys for which we need to check aggregate values
// across all project instances.
aggregateKeys := []string{}
isRestricted := false
for key, value := range info.Project.Config {
if slices.Contains(allAggregateLimits, key) || strings.HasPrefix(key, projectLimitDiskPool) {
aggregateKeys = append(aggregateKeys, key)
continue
}
if key == "restricted" && util.IsTrue(value) {
isRestricted = true
continue
}
}
if len(aggregateKeys) == 0 && !isRestricted {
return nil
}
instances, err := expandInstancesConfigAndDevices(info.Instances, info.Profiles)
if err != nil {
return err
}
info.Instances = instances
err = checkAggregateLimits(info, aggregateKeys)
if err != nil {
return err
}
if isRestricted {
err = checkRestrictions(info.Project, info.Instances, info.Profiles)
if err != nil {
return err
}
}
return nil
}
func getAggregateLimits(info *projectInfo, aggregateKeys []string) (map[string]api.ProjectStateResource, error) {
result := map[string]api.ProjectStateResource{}
if len(aggregateKeys) == 0 {
return result, nil
}
totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, true)
if err != nil {
return nil, err
}
for _, key := range aggregateKeys {
max := int64(-1)
limit := info.Project.Config[key]
if limit != "" {
keyName := key
// Handle pool-specific limits.
if strings.HasPrefix(key, projectLimitDiskPool) {
keyName = "limits.disk"
}
parser := aggregateLimitConfigValueParsers[keyName]
max, err = parser(info.Project.Config[key])
if err != nil {
return nil, err
}
}
resource := api.ProjectStateResource{
Usage: totals[key],
Limit: max,
}
result[key] = resource
}
return result, nil
}
func checkAggregateLimits(info *projectInfo, aggregateKeys []string) error {
if len(aggregateKeys) == 0 {
return nil
}
totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, false)
if err != nil {
return fmt.Errorf("Failed getting usage of project entities: %w", err)
}
for _, key := range aggregateKeys {
keyName := key
// Handle pool-specific limits.
if strings.HasPrefix(key, projectLimitDiskPool) {
keyName = "limits.disk"
}
parser := aggregateLimitConfigValueParsers[keyName]
max, err := parser(info.Project.Config[key])
if err != nil {
return err
}
if totals[key] > max {
return fmt.Errorf("Reached maximum aggregate value %q for %q in project %q", info.Project.Config[key], key, info.Project.Name)
}
}
return nil
}
// parseHostIDMapRange parse the supplied list of host ID map ranges into a idmap.Entry slice.
func parseHostIDMapRange(isUID bool, isGID bool, listValue string) ([]idmap.Entry, error) {
var idmaps []idmap.Entry
for _, listItem := range util.SplitNTrimSpace(listValue, ",", -1, true) {
rangeStart, rangeSize, err := util.ParseUint32Range(listItem)
if err != nil {
return nil, err
}
idmaps = append(idmaps, idmap.Entry{
HostID: int64(rangeStart),
MapRange: int64(rangeSize),
IsUID: isUID,
IsGID: isGID,
NSID: -1, // We don't have this as we are just parsing host IDs.
})
}
return idmaps, nil
}
// Check that the project's restrictions are not violated across the given
// instances and profiles.
func checkRestrictions(project api.Project, instances []api.Instance, profiles []api.Profile) error {
containerConfigChecks := map[string]func(value string) error{}
devicesChecks := map[string]func(value map[string]string) error{}
allowContainerLowLevel := false
allowVMLowLevel := false
var allowedIDMapHostUIDs, allowedIDMapHostGIDs []idmap.Entry
for i := range allRestrictions {
// Check if this particular restriction is defined explicitly in the project config.
// If not, use the default value. Assign to local var so it doesn't change to the default value of
// another restriction by time check functions run.
restrictionKey := i
restrictionValue, ok := project.Config[restrictionKey]
if !ok {
restrictionValue = allRestrictions[restrictionKey]
}
switch restrictionKey {
case "restricted.containers.interception":
for _, key := range allowableIntercept {
containerConfigChecks[key] = func(instanceValue string) error {
disabled := util.IsFalseOrEmpty(instanceValue)
if restrictionValue != "allow" && !disabled {
return errors.New("Container syscall interception is forbidden")
}
return nil
}
}
case "restricted.containers.nesting":
containerConfigChecks["security.nesting"] = func(instanceValue string) error {
if restrictionValue == "block" && util.IsTrue(instanceValue) {
return errors.New("Container nesting is forbidden")
}
return nil
}
case "restricted.containers.lowlevel":
if restrictionValue == "allow" {
allowContainerLowLevel = true
}
case "restricted.containers.privilege":
containerConfigChecks["security.privileged"] = func(instanceValue string) error {
if restrictionValue != "allow" && util.IsTrue(instanceValue) {
return errors.New("Privileged containers are forbidden")
}
return nil
}
containerConfigChecks["security.idmap.isolated"] = func(instanceValue string) error {
if restrictionValue == "isolated" && util.IsFalseOrEmpty(instanceValue) {
return errors.New("Non-isolated containers are forbidden")
}
return nil
}
case "restricted.virtual-machines.lowlevel":
if restrictionValue == "allow" {
allowVMLowLevel = true
}
case "restricted.devices.unix-char":
devicesChecks["unix-char"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("Unix character devices are forbidden")
}
return nil
}
case "restricted.devices.unix-block":
devicesChecks["unix-block"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("Unix block devices are forbidden")
}
return nil
}
case "restricted.devices.unix-hotplug":
devicesChecks["unix-hotplug"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("Unix hotplug devices are forbidden")
}
return nil
}
case "restricted.devices.infiniband":
devicesChecks["infiniband"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("Infiniband devices are forbidden")
}
return nil
}
case "restricted.devices.gpu":
devicesChecks["gpu"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("GPU devices are forbidden")
}
return nil
}
case "restricted.devices.usb":
devicesChecks["usb"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("USB devices are forbidden")
}
return nil
}
case "restricted.devices.pci":
devicesChecks["pci"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("PCI devices are forbidden")
}
return nil
}
case "restricted.devices.proxy":
devicesChecks["proxy"] = func(device map[string]string) error {
if restrictionValue != "allow" {
return errors.New("Proxy devices are forbidden")
}
return nil
}
case "restricted.devices.nic":
devicesChecks["nic"] = func(device map[string]string) error {
// Check if the NICs are allowed at all.
switch restrictionValue {
case "block":
return errors.New("Network devices are forbidden")
case "managed":
if device["network"] == "" {
return errors.New("Only managed network devices are allowed")
}
}
// Check if the NIC's parent/network setting is allowed based on the
// restricted.devices.nic and restricted.networks.access settings.
if device["network"] != "" {
if !NetworkAllowed(project.Config, device["network"], true) {
return errors.New("Network not allowed in project")
}
} else if device["parent"] != "" {
if !NetworkAllowed(project.Config, device["parent"], false) {
return errors.New("Network not allowed in project")
}
}
return nil
}
case "restricted.devices.disk":
devicesChecks["disk"] = func(device map[string]string) error {
// The root device is always allowed.
if device["path"] == "/" && device["pool"] != "" {
return nil
}
// Always allow the cloud-init config drive.
if device["path"] == "" && device["source"] == "cloud-init:config" {
return nil
}
// Always allow the agent config drive.
if device["path"] == "" && device["source"] == "agent:config" {
return nil
}
switch restrictionValue {
case "block":
return errors.New("Disk devices are forbidden")
case "managed":
if device["pool"] == "" {
return errors.New("Attaching disks not backed by a pool is forbidden")
}
case "allow":
if device["pool"] == "" {
allowed, _ := CheckRestrictedDevicesDiskPaths(project.Config, device["source"])
if !allowed {
return fmt.Errorf("Disk source path %q not allowed", device["source"])
}
}
}
return nil
}
case "restricted.idmap.uid":
var err error
allowedIDMapHostUIDs, err = parseHostIDMapRange(true, false, restrictionValue)
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", "restricted.idmap.uid", err)
}
case "restricted.idmap.gid":
var err error
allowedIDMapHostGIDs, err = parseHostIDMapRange(false, true, restrictionValue)
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", "restricted.idmap.uid", err)
}
}
}
// Common config check logic between instances and profiles.
entityConfigChecker := func(instType instancetype.Type, entityName string, config map[string]string) error {
entityTypeLabel := instType.String()
if instType == instancetype.Any {
entityTypeLabel = "profile"
}
isContainerOrProfile := instType == instancetype.Container || instType == instancetype.Any
isVMOrProfile := instType == instancetype.VM || instType == instancetype.Any
for key, value := range config {
if ((isContainerOrProfile && !allowContainerLowLevel) || (isVMOrProfile && !allowVMLowLevel)) && key == "raw.idmap" {
// If the low-level raw.idmap is used check whether the raw.idmap host IDs
// are allowed based on the project's allowed ID map Host UIDs and GIDs.
idmaps, err := idmap.NewSetFromIncusIDMap(value)
if err != nil {
return err
}
for i, entry := range idmaps.Entries {
if !entry.HostIDsCoveredBy(allowedIDMapHostUIDs, allowedIDMapHostGIDs) {
return fmt.Errorf(`Use of low-level "raw.idmap" element %d on %s %q of project %q is forbidden`, i, entityTypeLabel, entityName, project.Name)
}
}
// Skip the other checks.
continue
}
if isContainerOrProfile && !allowContainerLowLevel && isContainerLowLevelOptionForbidden(key) {
return fmt.Errorf("Use of low-level config %q on %s %q of project %q is forbidden", key, entityTypeLabel, entityName, project.Name)
}
if isVMOrProfile && !allowVMLowLevel && isVMLowLevelOptionForbidden(key) {
return fmt.Errorf("Use of low-level config %q on %s %q of project %q is forbidden", key, entityTypeLabel, entityName, project.Name)
}
var checker func(value string) error
if isContainerOrProfile {
checker = containerConfigChecks[key]
}
if checker == nil {
continue
}
err := checker(value)
if err != nil {
return fmt.Errorf("Invalid value %q for config %q on %s %q of project %q: %w", value, key, instType, entityName, project.Name, err)
}
}
return nil
}
// Common devices check logic between instances and profiles.
entityDevicesChecker := func(instType instancetype.Type, entityName string, devices map[string]map[string]string) error {
entityTypeLabel := instType.String()
if instType == instancetype.Any {
entityTypeLabel = "profile"
}
for name, device := range devices {
check, ok := devicesChecks[device["type"]]
if !ok {
continue
}
err := check(device)
if err != nil {
return fmt.Errorf("Invalid device %q on %s %q of project %q: %w", name, entityTypeLabel, entityName, project.Name, err)
}
}
return nil
}
for _, instance := range instances {
instType, err := instancetype.New(instance.Type)
if err != nil {
return err
}
err = entityConfigChecker(instType, instance.Name, instance.Config)
if err != nil {
return err
}
err = entityDevicesChecker(instType, instance.Name, instance.Devices)
if err != nil {
return err
}
}
for _, profile := range profiles {
err := entityConfigChecker(instancetype.Any, profile.Name, profile.Config)
if err != nil {
return err
}
err = entityDevicesChecker(instancetype.Any, profile.Name, profile.Devices)
if err != nil {
return err
}
}
return nil
}
// CheckRestrictedDevicesDiskPaths checks whether the disk's source path is within the allowed paths specified in
// the project's restricted.devices.disk.paths config setting.
// If no allowed paths are specified in project, then it allows all paths, and returns true and empty string.
// If allowed paths are specified, and one matches, returns true and the matching allowed parent source path.
// Otherwise if sourcePath not allowed returns false and empty string.
func CheckRestrictedDevicesDiskPaths(projectConfig map[string]string, sourcePath string) (bool, string) {
if projectConfig["restricted.devices.disk.paths"] == "" {
return true, ""
}
// Clean, then add trailing slash, to ensure we are prefix matching on whole path.
sourcePath = fmt.Sprintf("%s/", filepath.Clean(sourcePath))
for _, parentSourcePath := range strings.SplitN(projectConfig["restricted.devices.disk.paths"], ",", -1) {
// Clean, then add trailing slash, to ensure we are prefix matching on whole path.
parentSourcePathTrailing := fmt.Sprintf("%s/", filepath.Clean(parentSourcePath))
if strings.HasPrefix(sourcePath, parentSourcePathTrailing) {
return true, parentSourcePath
}
}
return false, ""
}
var allAggregateLimits = []string{
"limits.cpu",
"limits.disk",
"limits.memory",
"limits.processes",
}
// allRestrictions lists all available 'restrict.*' config keys along with their default setting.
var allRestrictions = map[string]string{
"restricted.backups": "block",
"restricted.cluster.groups": "",
"restricted.cluster.target": "block",
"restricted.containers.nesting": "block",
"restricted.containers.interception": "block",
"restricted.containers.lowlevel": "block",
"restricted.containers.privilege": "unprivileged",
"restricted.virtual-machines.lowlevel": "block",
"restricted.devices.unix-char": "block",
"restricted.devices.unix-block": "block",
"restricted.devices.unix-hotplug": "block",
"restricted.devices.infiniband": "block",
"restricted.devices.gpu": "block",
"restricted.devices.usb": "block",
"restricted.devices.pci": "block",
"restricted.devices.proxy": "block",
"restricted.devices.nic": "managed",
"restricted.devices.disk": "managed",
"restricted.devices.disk.paths": "",
"restricted.idmap.uid": "",
"restricted.idmap.gid": "",
"restricted.networks.access": "",
"restricted.snapshots": "block",
}
// allowableIntercept lists all syscall interception keys which may be allowed.
var allowableIntercept = []string{
"security.syscalls.intercept.bpf",
"security.syscalls.intercept.bpf.devices",
"security.syscalls.intercept.mknod",
"security.syscalls.intercept.mount",
"security.syscalls.intercept.mount.fuse",
"security.syscalls.intercept.setxattr",
"security.syscalls.intercept.sysinfo",
}
// Return true if a low-level container option is forbidden.
func isContainerLowLevelOptionForbidden(key string) bool {
if strings.HasPrefix(key, "security.syscalls.intercept") && !slices.Contains(allowableIntercept, key) {
return true
}
if slices.Contains([]string{
"boot.host_shutdown_action",
"boot.host_shutdown_timeout",
"linux.kernel_modules",
"limits.memory.swap",
"raw.apparmor",
"raw.idmap",
"raw.lxc",
"raw.seccomp",
"security.guestapi.images",
"security.idmap.base",
"security.idmap.size",
},
key) {
return true
}
return false
}
// Return true if a low-level VM option is forbidden.
func isVMLowLevelOptionForbidden(key string) bool {
return slices.Contains([]string{
"boot.host_shutdown_action",
"boot.host_shutdown_timeout",
"limits.memory.hugepages",
"raw.apparmor",
"raw.idmap",
"raw.qemu",
"raw.qemu.conf",
"raw.qemu.qmp.early",
"raw.qemu.qmp.post-start",
"raw.qemu.qmp.pre-start",
"raw.qemu.scriptlet",
},
key)
}
// AllowInstanceUpdate returns an error if any project-specific limit or
// restriction is violated when updating an existing instance.
func AllowInstanceUpdate(tx *db.ClusterTx, projectName, instanceName string, req api.InstancePut, currentConfig map[string]string) error {
var updatedInstance *api.Instance
info, err := fetchProject(tx, projectName, true)
if err != nil {
return err
}
if info == nil {
return nil
}
// Change the instance being updated.
for i, instance := range info.Instances {
if instance.Name != instanceName {
continue
}
info.Instances[i].Profiles = req.Profiles
info.Instances[i].Config = req.Config
info.Instances[i].Devices = req.Devices
updatedInstance = &info.Instances[i]
}
instType, err := instancetype.New(updatedInstance.Type)
if err != nil {
return err
}
// Special case restriction checks on volatile.* keys, since we want to
// detect if they were changed or added.
err = checkRestrictionsOnVolatileConfig(
info.Project, instType, updatedInstance.Name, req.Config, currentConfig, false)
if err != nil {
return err
}
err = checkRestrictionsAndAggregateLimits(tx, info)
if err != nil {
return fmt.Errorf("Failed checking if instance update allowed: %w", err)
}
return nil
}
// AllowVolumeUpdate returns an error if any project-specific limit or
// restriction is violated when updating an existing custom volume.
func AllowVolumeUpdate(tx *db.ClusterTx, projectName, volumeName string, req api.StorageVolumePut, currentConfig map[string]string) error {
info, err := fetchProject(tx, projectName, true)
if err != nil {
return err
}
if info == nil {
return nil
}
// If "limits.disk" is not set, there's nothing to do.
if info.Project.Config["limits.disk"] == "" {
return nil
}
// Change the volume being updated.
for i, volume := range info.Volumes {
if volume.Name != volumeName {
continue
}
info.Volumes[i].Config = req.Config
}
err = checkRestrictionsAndAggregateLimits(tx, info)
if err != nil {
return fmt.Errorf("Failed checking if volume update allowed: %w", err)
}
return nil
}
// AllowProfileUpdate checks that project limits and restrictions are not
// violated when changing a profile.
func AllowProfileUpdate(tx *db.ClusterTx, projectName, profileName string, req api.ProfilePut) error {
info, err := fetchProject(tx, projectName, true)
if err != nil {
return err
}
if info == nil {
return nil
}
// Change the profile being updated.
for i, profile := range info.Profiles {
if profile.Name != profileName {
continue
}
info.Profiles[i].Config = req.Config
info.Profiles[i].Devices = req.Devices
}
err = checkRestrictionsAndAggregateLimits(tx, info)
if err != nil {
return fmt.Errorf("Failed checking if profile update allowed: %w", err)
}
return nil
}
// AllowProjectUpdate checks the new config to be set on a project is valid.
func AllowProjectUpdate(tx *db.ClusterTx, projectName string, config map[string]string, changed []string) error {
info, err := fetchProject(tx, projectName, false)
if err != nil {
return err
}
info.Instances, err = expandInstancesConfigAndDevices(info.Instances, info.Profiles)
if err != nil {
return err
}
// List of keys that need to check aggregate values across all project
// instances.
aggregateKeys := []string{}
for _, key := range changed {
if strings.HasPrefix(key, "restricted.") {
project := api.Project{
Name: projectName,
ProjectPut: api.ProjectPut{
Config: config,
},
}
err := checkRestrictions(project, info.Instances, info.Profiles)
if err != nil {
return fmt.Errorf("Conflict detected when changing %q in project %q: %w", key, projectName, err)
}
continue
}
switch key {
case "limits.instances":
err := validateTotalInstanceCountLimit(info.Instances, config[key], projectName)
if err != nil {
return fmt.Errorf("Can't change limits.instances in project %q: %w", projectName, err)
}
case "limits.containers":
fallthrough
case "limits.virtual-machines":
err := validateInstanceCountLimit(info.Instances, key, config[key], projectName)
if err != nil {
return fmt.Errorf("Can't change %q in project %q: %w", key, projectName, err)
}
case "limits.processes":
fallthrough
case "limits.cpu":
fallthrough
case "limits.memory":
fallthrough
case "limits.disk":
aggregateKeys = append(aggregateKeys, key)
}
}
if len(aggregateKeys) > 0 {
totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, false)
if err != nil {
return err
}
for _, key := range aggregateKeys {
err := validateAggregateLimit(totals, key, config[key])
if err != nil {
return err
}
}
}
return nil
}
// Check that limits.instances, i.e. the total limit of containers/virtual machines allocated
// to the user is equal to or above the current count.
func validateTotalInstanceCountLimit(instances []api.Instance, value, project string) error {
if value == "" {
return nil
}
limit, err := strconv.Atoi(value)
if err != nil {
return err
}
count := len(instances)
if limit < count {
return fmt.Errorf(`"limits.instances" is too low: there currently are %d total instances in project %q`, count, project)
}
return nil
}
// Check that limits.containers or limits.virtual-machines is equal or above
// the current count.
func validateInstanceCountLimit(instances []api.Instance, key, value, project string) error {
if value == "" {
return nil
}
instanceType := countConfigInstanceType[key]
limit, err := strconv.Atoi(value)
if err != nil {
return err
}
dbType, err := instancetype.New(string(instanceType))
if err != nil {
return err
}
count := 0
for _, instance := range instances {
if instance.Type == dbType.String() {
count++
}
}
if limit < count {
return fmt.Errorf(`%q is too low: there currently are %d instances of type %s in project %q`, key, count, instanceType, project)
}
return nil
}
var countConfigInstanceType = map[string]api.InstanceType{
"limits.containers": api.InstanceTypeContainer,
"limits.virtual-machines": api.InstanceTypeVM,
}
// Validates an aggregate limit, checking that the new value is not below the
// current total amount.
func validateAggregateLimit(totals map[string]int64, key, value string) error {
if value == "" {
return nil
}
keyName := key
// Handle pool-specific limits.
if strings.HasPrefix(key, projectLimitDiskPool) {
keyName = "limits.disk"
}
parser := aggregateLimitConfigValueParsers[keyName]
limit, err := parser(value)
if err != nil {
return fmt.Errorf("Invalid value %q for limit %q: %w", value, key, err)
}
total := totals[key]
if limit < total {
keyName := key
// Handle pool-specific limits.
if strings.HasPrefix(key, projectLimitDiskPool) {
keyName = "limits.disk"
}
printer := aggregateLimitConfigValuePrinters[keyName]
return fmt.Errorf("%q is too low: current total is %q", key, printer(total))
}
return nil
}
// Return true if the project has some limits or restrictions set.
func projectHasLimitsOrRestrictions(project api.Project) bool {
for k, v := range project.Config {
if strings.HasPrefix(k, "limits.") {
return true
}
if k == "restricted" && util.IsTrue(v) {
return true
}
}
return false
}
// Hold information associated with the project, such as profiles and
// instances.
type projectInfo struct {
Project api.Project
Profiles []api.Profile
Instances []api.Instance
Volumes []db.StorageVolumeArgs
}
// Fetch the given project from the database along with its profiles, instances
// and possibly custom volumes.
//
// If the skipIfNoLimits flag is true, then profiles, instances and volumes
// won't be loaded if the profile has no limits set on it, and nil will be
// returned.
func fetchProject(tx *db.ClusterTx, projectName string, skipIfNoLimits bool) (*projectInfo, error) {
ctx := context.Background()
dbProject, err := cluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return nil, fmt.Errorf("Fetch project database object: %w", err)
}
project, err := dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return nil, err
}
if skipIfNoLimits && !projectHasLimitsOrRestrictions(*project) {
return nil, nil
}
profilesFilter := cluster.ProfileFilter{}
// If the project has the profiles feature enabled, we use its own
// profiles to expand the instances configs, otherwise we use the
// profiles from the default project.
defaultProject := api.ProjectDefaultName
if projectName == api.ProjectDefaultName || util.IsTrue(project.Config["features.profiles"]) {
profilesFilter.Project = &projectName
} else {
profilesFilter.Project = &defaultProject
}
dbProfiles, err := cluster.GetProfiles(ctx, tx.Tx(), profilesFilter)
if err != nil {
return nil, fmt.Errorf("Fetch profiles from database: %w", err)
}
dbProfileConfigs, err := cluster.GetAllProfileConfigs(ctx, tx.Tx())
if err != nil {
return nil, fmt.Errorf("Fetch profile configs from database: %w", err)
}
dbProfileDevices, err := cluster.GetAllProfileDevices(ctx, tx.Tx())
if err != nil {
return nil, fmt.Errorf("Fetch profile devices from database: %w", err)
}
profiles := make([]api.Profile, 0, len(dbProfiles))
for _, profile := range dbProfiles {
apiProfile, err := profile.ToAPI(ctx, tx.Tx(), dbProfileConfigs, dbProfileDevices)
if err != nil {
return nil, err
}
profiles = append(profiles, *apiProfile)
}
dbInstances, err := cluster.GetInstances(ctx, tx.Tx(), cluster.InstanceFilter{Project: &projectName})
if err != nil {
return nil, fmt.Errorf("Fetch project instances from database: %w", err)
}
dbInstanceDevices, err := cluster.GetAllInstanceDevices(ctx, tx.Tx())
if err != nil {
return nil, fmt.Errorf("Fetch instance devices from database: %w", err)
}
instances := make([]api.Instance, 0, len(dbInstances))
for _, instance := range dbInstances {
apiInstance, err := instance.ToAPI(ctx, tx.Tx(), dbInstanceDevices, dbProfileConfigs, dbProfileDevices)
if err != nil {
return nil, fmt.Errorf("Failed to get API data for instance %q in project %q: %w", instance.Name, instance.Project, err)
}
instances = append(instances, *apiInstance)
}
volumes, err := tx.GetCustomVolumesInProject(ctx, projectName)
if err != nil {
return nil, fmt.Errorf("Fetch project custom volumes from database: %w", err)
}
info := &projectInfo{
Project: *project,
Profiles: profiles,
Instances: instances,
Volumes: volumes,
}
return info, nil
}
// Expand the configuration and devices of the given instances, taking the give
// project profiles into account.
func expandInstancesConfigAndDevices(instances []api.Instance, profiles []api.Profile) ([]api.Instance, error) {
expandedInstances := make([]api.Instance, len(instances))
// Index of all profiles by name.
profilesByName := map[string]api.Profile{}
for _, profile := range profiles {
profilesByName[profile.Name] = profile
}
for i, instance := range instances {
apiProfiles := make([]api.Profile, len(instance.Profiles))
for j, name := range instance.Profiles {
profile := profilesByName[name]
apiProfiles[j] = profile
}
expandedInstances[i] = instance
expandedInstances[i].Config = db.ExpandInstanceConfig(instance.Config, apiProfiles)
expandedInstances[i].Devices = db.ExpandInstanceDevices(deviceconfig.NewDevices(instance.Devices), apiProfiles).CloneNative()
}
return expandedInstances, nil
}
// Sum of the effective values for the given limits across all project
// entities (instances and custom volumes).
func getTotalsAcrossProjectEntities(info *projectInfo, keys []string, skipUnset bool) (map[string]int64, error) {
totals := map[string]int64{}
for _, key := range keys {
totals[key] = 0
if key == "limits.disk" || strings.HasPrefix(key, projectLimitDiskPool) {
poolName := ""
fields := strings.SplitN(key, projectLimitDiskPool, 2)
if len(fields) == 2 {
poolName = fields[1]
}
for _, volume := range info.Volumes {
if poolName != "" && volume.PoolName != poolName {
continue
}
value, ok := volume.Config["size"]
if !ok {
if skipUnset {
continue
}
return nil, fmt.Errorf(`Custom volume %q in project %q has no "size" config set`, volume.Name, info.Project.Name)
}
limit, err := units.ParseByteSizeString(value)
if err != nil {
return nil, fmt.Errorf(`Parse "size" for custom volume %q in project %q: %w`, volume.Name, info.Project.Name, err)
}
totals[key] += limit
}
}
}
for _, instance := range info.Instances {
limits, err := getInstanceLimits(instance, keys, skipUnset)
if err != nil {
return nil, err
}
for _, key := range keys {
totals[key] += limits[key]
}
}
return totals, nil
}
// Return the effective instance-level values for the limits with the given keys.
func getInstanceLimits(inst api.Instance, keys []string, skipUnset bool) (map[string]int64, error) {
var err error
limits := map[string]int64{}
for _, key := range keys {
var limit int64
keyName := key
// Handle pool-specific limits.
if strings.HasPrefix(key, projectLimitDiskPool) {
keyName = "limits.disk"
}
parser := aggregateLimitConfigValueParsers[keyName]
if key == "limits.disk" || strings.HasPrefix(key, projectLimitDiskPool) {
poolName := ""
fields := strings.SplitN(key, projectLimitDiskPool, 2)
if len(fields) == 2 {
poolName = fields[1]
}
_, device, err := instance.GetRootDiskDevice(inst.Devices)
if err != nil {
return nil, fmt.Errorf("Failed getting root disk device for instance %q in project %q: %w", inst.Name, inst.Project, err)
}
if poolName != "" && device["pool"] != poolName {
continue
}
value, ok := device["size"]
if !ok || value == "" {
if skipUnset {
continue
}
return nil, fmt.Errorf(`Instance %q in project %q has no "size" config set on the root device either directly or via a profile`, inst.Name, inst.Project)
}
limit, err = parser(value)
if err != nil {
if skipUnset {
continue
}
return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", key, inst.Name, inst.Project)
}
// Add size.state accounting for VM root disks.
if inst.Type == instancetype.VM.String() {
sizeStateValue, ok := device["size.state"]
if !ok {
// TODO: In case the VMs storage drivers config drive size isn't the default,
// the limits accounting will be incorrect.
sizeStateValue = deviceconfig.DefaultVMBlockFilesystemSize
}
sizeStateLimit, err := parser(sizeStateValue)
if err != nil {
if skipUnset {
continue
}
return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", "size.state", inst.Name, inst.Project)
}
limit += sizeStateLimit
}
} else {
// Skip processing for 'limits.processes' if the instance type is VM,
// as this limit is only applicable to containers.
if key == "limits.processes" && inst.Type == instancetype.VM.String() {
continue
}
value, ok := inst.Config[key]
if !ok || value == "" {
if skipUnset {
continue
}
return nil, fmt.Errorf("Instance %q in project %q has no %q config, either directly or via a profile", inst.Name, inst.Project, key)
}
limit, err = parser(value)
if err != nil {
if skipUnset {
continue
}
return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", key, inst.Name, inst.Project)
}
}
limits[key] = limit
}
return limits, nil
}
var aggregateLimitConfigValueParsers = map[string]func(string) (int64, error){
"limits.memory": func(value string) (int64, error) {
if strings.HasSuffix(value, "%") {
return -1, errors.New("Value can't be a percentage")
}
return units.ParseByteSizeString(value)
},
"limits.processes": func(value string) (int64, error) {
limit, err := strconv.Atoi(value)
if err != nil {
return -1, err
}
return int64(limit), nil
},
"limits.cpu": func(value string) (int64, error) {
if strings.Contains(value, ",") || strings.Contains(value, "-") {
return -1, errors.New("CPUs can't be pinned if project limits are used")
}
limit, err := strconv.Atoi(value)
if err != nil {
return -1, err
}
return int64(limit), nil
},
"limits.disk": func(value string) (int64, error) {
return units.ParseByteSizeString(value)
},
}
var aggregateLimitConfigValuePrinters = map[string]func(int64) string{
"limits.memory": func(limit int64) string {
return units.GetByteSizeStringIEC(limit, 1)
},
"limits.processes": func(limit int64) string {
return fmt.Sprintf("%d", limit)
},
"limits.cpu": func(limit int64) string {
return fmt.Sprintf("%d", limit)
},
"limits.disk": func(limit int64) string {
return units.GetByteSizeStringIEC(limit, 1)
},
}
// FilterUsedBy filters a UsedBy list based on project access.
func FilterUsedBy(authorizer auth.Authorizer, r *http.Request, entries []string) []string {
// Filter the entries.
usedBy := []string{}
for _, entry := range entries {
entityType, projectName, location, pathArgs, err := cluster.URLToEntityType(entry)
if err != nil {
continue
}
var object auth.Object
switch entityType {
case cluster.TypeImage:
object = auth.ObjectImage(projectName, pathArgs[0])
case cluster.TypeInstance:
object = auth.ObjectInstance(projectName, pathArgs[0])
case cluster.TypeNetwork:
object = auth.ObjectNetwork(projectName, pathArgs[0])
case cluster.TypeProfile:
object = auth.ObjectProfile(projectName, pathArgs[0])
case cluster.TypeStoragePool:
object = auth.ObjectStoragePool(pathArgs[0])
case cluster.TypeStorageVolume:
object = auth.ObjectStorageVolume(projectName, pathArgs[0], pathArgs[1], pathArgs[2], location)
case cluster.TypeStorageBucket:
object = auth.ObjectStorageBucket(projectName, pathArgs[0], pathArgs[1], location)
default:
continue
}
err = authorizer.CheckPermission(r.Context(), r, object, auth.EntitlementCanView)
if err != nil {
continue
}
usedBy = append(usedBy, entry)
}
return usedBy
}
// Return true if particular restriction in project is violated.
func projectHasRestriction(project *api.Project, restrictionKey string, blockValue string) bool {
if util.IsFalseOrEmpty(project.Config["restricted"]) {
return false
}
restrictionValue, ok := project.Config[restrictionKey]
if !ok {
restrictionValue = allRestrictions[restrictionKey]
}
if restrictionValue == blockValue {
return true
}
return false
}
// CheckClusterTargetRestriction check if user is allowed to use cluster member targeting.
func CheckClusterTargetRestriction(authorizer auth.Authorizer, r *http.Request, project *api.Project, targetFlag string) error {
if projectHasRestriction(project, "restricted.cluster.target", "block") && targetFlag != "" {
// Allow server administrators to move instances around even when restricted (node evacuation, ...)
err := authorizer.CheckPermission(r.Context(), r, auth.ObjectServer(), auth.EntitlementCanOverrideClusterTargetRestriction)
if err != nil && api.StatusErrorCheck(err, http.StatusForbidden) {
return api.StatusErrorf(http.StatusForbidden, "This project doesn't allow cluster member targeting")
} else if err != nil {
return err
}
}
return nil
}
// AllowBackupCreation returns an error if any project-specific restriction is violated
// when creating a new backup in a project.
func AllowBackupCreation(tx *db.ClusterTx, projectName string) error {
ctx := context.Background()
dbProject, err := cluster.GetProject(ctx, tx.Tx(), projectName)
if err != nil {
return err
}
project, err := dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
if projectHasRestriction(project, "restricted.backups", "block") {
return fmt.Errorf("Project %q doesn't allow for backup creation", projectName)
}
return nil
}
// AllowSnapshotCreation returns an error if any project-specific restriction is violated
// when creating a new snapshot in a project.
func AllowSnapshotCreation(p *api.Project) error {
if projectHasRestriction(p, "restricted.snapshots", "block") {
return fmt.Errorf("Project %q doesn't allow for snapshot creation", p.Name)
}
return nil
}
// GetRestrictedClusterGroups returns a slice of restricted cluster groups for the given project.
func GetRestrictedClusterGroups(p *api.Project) []string {
return util.SplitNTrimSpace(p.Config["restricted.cluster.groups"], ",", -1, true)
}
// AllowClusterMember returns nil if the given project is allowed to use the cluster member.
func AllowClusterMember(p *api.Project, member *db.NodeInfo) error {
clusterGroupsAllowed := GetRestrictedClusterGroups(p)
if util.IsTrue(p.Config["restricted"]) && len(clusterGroupsAllowed) > 0 {
for _, memberGroupName := range member.Groups {
if slices.Contains(clusterGroupsAllowed, memberGroupName) {
return nil
}
}
return fmt.Errorf("Project isn't allowed to use this cluster member: %q", member.Name)
}
return nil
}
// AllowClusterGroup returns nil if the given project is allowed to use the cluster groupName.
func AllowClusterGroup(p *api.Project, groupName string) error {
clusterGroupsAllowed := GetRestrictedClusterGroups(p)
// Skip the check if the project is not restricted
if util.IsFalseOrEmpty(p.Config["restricted"]) {
return nil
}
if len(clusterGroupsAllowed) > 0 && !slices.Contains(clusterGroupsAllowed, groupName) {
return fmt.Errorf("Project isn't allowed to use this cluster group: %q", groupName)
}
return nil
}
// CheckTargetMember checks if the given targetMemberName is present in allMembers
// and is allowed for the project.
// If the target member is allowed it returns the resolved node information.
func CheckTargetMember(p *api.Project, targetMemberName string, allMembers []db.NodeInfo) (*db.NodeInfo, error) {
// Find target member.
for _, potentialMember := range allMembers {
if potentialMember.Name == targetMemberName {
// If restricted groups are specified then check member is in at least one of them.
err := AllowClusterMember(p, &potentialMember)
if err != nil {
return nil, api.StatusErrorf(http.StatusForbidden, "%s", err.Error())
}
return &potentialMember, nil
}
}
return nil, api.StatusErrorf(http.StatusNotFound, "Cluster member %q not found", targetMemberName)
}
// CheckTargetGroup checks if the given groupName is allowed for the project.
func CheckTargetGroup(ctx context.Context, tx *db.ClusterTx, p *api.Project, groupName string) error {
// If restricted groups are specified then check the requested group is in the list.
err := AllowClusterGroup(p, groupName)
if err != nil {
return api.StatusErrorf(http.StatusForbidden, "%s", err.Error())
}
// Check if the target group exists.
targetGroupExists, err := cluster.ClusterGroupExists(ctx, tx.Tx(), groupName)
if err != nil {
return err
}
if !targetGroupExists {
return api.StatusErrorf(http.StatusBadRequest, "Cluster group %q doesn't exist", groupName)
}
return nil
}
// CheckTarget checks if the given cluster target (member or group) is allowed.
// If target is a cluster member and is found in allMembers it returns the resolved node information object.
// If target is a cluster group it returns the cluster group name.
// In case of error, neither node information nor cluster group name gets returned.
func CheckTarget(ctx context.Context, authorizer auth.Authorizer, r *http.Request, tx *db.ClusterTx, p *api.Project, target string, allMembers []db.NodeInfo) (*db.NodeInfo, string, error) {
// Extract the target.
var targetGroupName string
var targetMemberName string
after, ok := strings.CutPrefix(target, "@")
if ok {
targetGroupName = after
} else {
targetMemberName = target
}
// Check manual cluster member targeting restrictions.
err := CheckClusterTargetRestriction(authorizer, r, p, target)
if err != nil {
return nil, "", err
}
if targetMemberName != "" {
member, err := CheckTargetMember(p, targetMemberName, allMembers)
if err != nil {
return nil, "", err
}
return member, "", nil
} else if targetGroupName != "" {
err := CheckTargetGroup(ctx, tx, p, targetGroupName)
if err != nil {
return nil, "", err
}
return nil, targetGroupName, nil
}
return nil, "", nil
}
|